content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def arg_return_greetings(name):
"""
This is greeting function with arguments and return greeting message
:param name:
:return:
"""
message = F"hello {name}"
return message | 23bab521832358692c3aa653c6138ffee13c4e7a | 6,636 |
from typing import Any
def basic_usage(card_id: str, parent: Any = None):
"""Basic usage of the application, minus the card recognition bits"""
data = pull_card_data(card_id)
qt_window = Card(parent, data)
qt_window.setWindowTitle("YGO Scanner")
qt_window.show()
return qt_window | 6960697ef12959a7aaaf47607c3026d0925b0a88 | 6,637 |
from typing import Dict
from typing import Optional
from pathlib import Path
import json
def get_abi(
contract_sources: Dict[str, str],
allow_paths: Optional[str] = None,
remappings: Optional[list] = None,
silent: bool = True,
) -> Dict:
"""
Generate ABIs from contract interfaces.
Argumen... | bd9eb4959796d549950f8dd0372ee42c95cd0dd6 | 6,638 |
def predict(w , b , X ):
"""
使用学习逻辑回归参数logistic (w,b)预测标签是0还是1,
参数:
w - 权重,大小不等的数组(num_px * num_px * 3,1)
b - 偏差,一个标量
X - 维度为(num_px * num_px * 3,训练数据的数量)的数据
返回:
Y_prediction - 包含X中所有图片的所有预测【0 | 1】的一个numpy数组(向量)
"""
m = X.shape[1] #图片的数量
Y_prediction ... | 4e258d7de1788d6da5c8a832ff11a5e8718b5d84 | 6,639 |
def delta_C(parcels_old, parcels_new, normed=False):
"""
Compute the number of vertices that change connected component from
old parcellation to new parcellation.
Parameters:
- - - - -
parcels_old : dictionary
old connected component sample assignments
parcels_new : dictionary
... | 07f48d30fbaa4b0278871b199d7768c6f2d49508 | 6,640 |
def increment(number):
"""Increases a given number by 1"""
return number + 1 | ad10a887ee571182247e76fe41fddd6d53b2dc6a | 6,641 |
def get_recent_added_companies(parser, token):
"""
Gets any number of the recent added comapnies.
Syntax::
{% get_recent_added_companies [limit] as [var_name] %}
"""
return base_tag(parser, token, RecentCreatedCompanies) | 73c7c0f12951ba9d6b6a3220c2f88055ea027624 | 6,642 |
import glob
def search_data(templates, pols, matched_pols=False, reverse_nesting=False, flatten=False):
"""
Glob-parse data templates to search for data files.
Parameters
----------
templates : str or list
A glob-parsable search string, or list of such strings, with a {pol}
spot f... | 9f8018de15db0659928e28779ebf4acda0ddba74 | 6,643 |
import re
def normalize_word(word):
"""
:type word: str
:rtype: str
"""
acronym_pattern = r'^(?:[A-Z]\.)+$'
if re.match(pattern=acronym_pattern, string=word):
word = word.replace('.', '')
if word.lower() in _REPLACE_WORDS:
replacement = _REPLACE_WORDS[word.lower()]
if word.islower():
return replaceme... | e2c96d456cc8b555b68f2c7498a6d2898ce5990e | 6,644 |
def _ggm_qsize_prob_gt_0_whitt_5_2(arr_rate, svc_rate, c, ca2, cs2):
"""
Return the approximate P(Q>0) in G/G/m queue using Whitt's simple
approximation involving rho and P(W>0).
This approximation is exact for M/M/m and has strong theoretical
support for GI/M/m. It's described by Whitt as "crude" ... | 3eded5597dc199e61c4d79187369e1a84531ac3d | 6,645 |
def pds3_label_gen_date(file):
"""Returns the creation date of a given PDS3 label.
:param path: File path
:type path: str
:return: Creation date
:rtype: str
"""
generation_date = "N/A"
with open(file, "r") as f:
for line in f:
if "PRODUCT_CREATION_TIME" in line:
... | c2877fa9246dd0c12c6ea47635ab248dc038b179 | 6,646 |
def harmony(*args):
"""
Takes an arbitrary number of floats and prints their harmonic
medium value. Calculation is done with formula:
number_of_args \ (1 \ item1 + 1 \ item2 + ...)
Args:
*args (tuple): number of arguments with a type: float, integer
Returns:
float: harmonic... | bc66276b3ef27ef0bfd059afa8ca7afd5d9cbb82 | 6,647 |
def node_gdf_from_graph(G, crs = 'epsg:4326', attr_list = None, geometry_tag = 'geometry', xCol='x', yCol='y'):
"""
Function for generating GeoDataFrame from Graph
:param G: a graph object G
:param crs: projection of format {'init' :'epsg:4326'}. Defaults to WGS84. note: here we are defining the crs of... | cf5849c672877010aae7b1fb841a6993a53d232f | 6,648 |
def views():
""" Used for the creation of Orientation objects with
`Orientations.from_view_up`
"""
return [[1, 0, 0], [2, 0, 0], [-1, 0, 0]] | 21ffce8e8a56cf31e2d03a6384d584bcb4bfb2c8 | 6,649 |
def check_closed(f):
"""Decorator that checks if connection/cursor is closed."""
def g(self, *args, **kwargs):
if self.closed:
raise exceptions.Error(f'{self.__class__.__name__} already closed')
return f(self, *args, **kwargs)
return g | 4772de94c28022266ee01f0c900e8937859cc58c | 6,651 |
def get_diff_comparison_score(git_commit, review_url, git_checkout_path,
cc): # pragma: no cover
"""Reads the diff for a specified commit
Args:
git_commit(str): a commit hash
review_url(str): a rietveld review url
git_checkout_path(str): path to a local git checkout
c... | b68904a62d1e42b8e147705984c9455ff0f5d6fc | 6,653 |
def pack(pieces=()):
"""
Join a sequence of strings together.
:param list pieces: list of strings
:rtype: bytes
"""
return b''.join(pieces) | ffd0852a16c6292f921e5cf205301171e3a96fd3 | 6,654 |
def compte_var(f, var):
"""compte le nombre d'apparition de la variable var dans f"""
n = f.nb_operandes()
if n == 0:
v = f.get_val()
if v == var:
return 1
else:
return 0
elif n == 1:
f2 = (f.decompose())[0]
return compte_var(f2, var)
e... | 002051e3bf723cfcc1a2cb3d094b58980591adc5 | 6,656 |
from watchlist.models import User
def inject_vars(): # 函数名可以随意修改
"""模板上下文处理函数"""
user = User.query.first() # 用户对象
if not user:
user = User()
user.name = 'BL00D'
return locals() | edf9126fb919cb825acac3f951f481575fe2ef57 | 6,657 |
def try_parse_section(text: str, section_name: str) -> str:
"""
Parse a section. Return an empty string if section not found.
Args:
text (str): text
section_name (str): section's name
Returns:
(str): section
"""
try:
return parse_section(text, section_name)
... | 26c8d6d3f8475954fcf742e662981ad5f1223e53 | 6,658 |
from bs4 import BeautifulSoup
def get_location_based_lifers(web_page):
"""
a method that takes in a web page and returns back location frequency for lifers and lifer details.
"""
bs4_object = BeautifulSoup(web_page, html_parser)
table_list = bs4_object.find_all('li', class_=myebird_species_li_clas... | 1c6b85962f6c142ab816255a1fe5c98f272dfebb | 6,659 |
def parse_show_qos_queue_profile(raw_result):
"""
Parse the show command raw output.
:param str raw_result: vtysh raw result string.
:rtype: dict
:return: The parsed result of the 'show qos queue-profile' command in a \
dictionary:
for 'show qos queue-profile':
::
{
... | 2a883a50663607356e0edadeb2d4cf17d34ab028 | 6,660 |
import random
import io
def plot_png(num_x_points=50):
""" renders the plot on the fly.
"""
fig = Figure()
axis = fig.add_subplot(1, 1, 1)
x_points = range(num_x_points)
axis.plot(x_points, [random.randint(1, 30) for x in x_points])
output = io.BytesIO()
FigureCanvasAgg(fig).print_png... | bac5e9146bf0b60d943e5d58376a84eddebd21ec | 6,661 |
def render_message(session, window, msg, x, y):
"""Render a message glyph.
Clears the area beneath the message first
and assumes the display will be paused
afterwards.
"""
# create message box
msg = GlyphCoordinate(session, msg, x, y)
# clear existing glyphs which intersect
for gl... | 2f0362dfa1f884571339456b0a610e0f6cdd75a6 | 6,662 |
from pathlib import Path
def part_one(filename='input.txt', target=2020):
"""Satisfies part one of day one by first sorting the input rows so we can
avoid the worst case O(n**2). We incur O(n log n) to do the sort followed by
a brute force search with short circuiting if the sum exceeds our target.
Th... | d9c6790f9c5b5de7fbd9555a8483f2cb0e156b3b | 6,663 |
def get_urls(name, version=None, platform=None):
"""
Return a mapping of standard URLs
"""
dnlu = rubygems_download_url(name, version, platform)
return dict(
repository_homepage_url=rubygems_homepage_url(name, version),
repository_download_url=dnlu,
api_data_url=rubygems_api_... | d11666a72771187166a6b9f620237639fd8422f3 | 6,664 |
def getEHfields(m1d, sigma, freq, zd, scaleUD=True, scaleValue=1):
"""Analytic solution for MT 1D layered earth. Returns E and H fields.
:param discretize.base.BaseMesh, object m1d: Mesh object with the 1D spatial information.
:param numpy.ndarray, vector sigma: Physical property of conductivity correspond... | e850762955ff513adef7099b61eb285d059c1ffe | 6,665 |
def repeated(f, n):
"""Returns a function that takes in an integer and computes
the nth application of f on that integer.
Implement using recursion!
>>> add_three = repeated(lambda x: x + 1, 3)
>>> add_three(5)
8
>>> square = lambda x: x ** 2
>>> repeated(square, 2)(5) # square(square(... | dd2024ffa7c5abbcfb43b1a6a8d6ea00c3fb42c4 | 6,666 |
def method_functions():
"""
Returns a dictionary containing the valid method keys and their
corresponding dispersion measure functions.
"""
return _available | 6d9ea23e4c0449b4b2d0a27b5117be30400a7d43 | 6,667 |
def generate_auth_token():
"""Generate a token using jwt.
Returns:
token.
"""
key = PRIVATE_KEY
data = {'appId': APPLICATION_ID}
token = jwt.encode(data, key, algorithm='RS256')
return token | a2e9307f392a8a6c0d83e9f1064475c11fc4eeec | 6,669 |
from typing import Dict
from typing import Any
from typing import List
def dict_expand(d: Dict[Any, Any]) -> List[Dict[Any, Any]]:
"""Converts a dictionary of lists to a list of dictionaries.
The resulting list will be of the same length as the longest dictionary
value. If any values are not lists then t... | 6ca2c25318a3b6bc0b2a45bf3aeec7187ad78e5c | 6,670 |
def get_asexual_lineage_num_discrete_state_changes(lineage, attribute_list):
"""Get the number of discrete state changes from an asexual lineage.
State is described by the aggregation of all attributes give by attribute list.
Args:
lineage (networkx.DiGraph): an asexual lineage
attribute_l... | 9c0d4badc7b4fea70c56ce69727e48eb991a96e1 | 6,671 |
def check_downloaded(dataset: str,
directory: str = None) -> bool:
"""
Check whether dataset is downloaded
Args:
dataset (str): String of dataset's name, e.g. ml-100k, bx
directory (str, optional): String of directory of downloaded data.
Defaults to None... | bf3342e7da11b34918bc2cb9939c95145d2f4feb | 6,672 |
from pathlib import Path
def enterprise_1_9_installer() -> Path:
"""
Return the path to an installer for DC/OS Enterprise 1.9.
"""
return Path('/tmp/dcos_generate_config_1_9.ee.sh') | 857b5d339e05cbb225189d7ee47d0415fc539c54 | 6,673 |
def Laplacian(n):
"""
Create Laplacian on 2-dimensional grid with n*n nodes
"""
B = forward_diff_matrix(n)
D = -B.T @ B
Dx = sparse.kron(sparse.eye(n), D).tocsr()
Dy = sparse.kron(D, sparse.eye(n)).tocsr()
return Dx + Dy | 47d70e635dc8e7d722e069435d17214a6ea3c6de | 6,674 |
import re
def LookupGitSVNRevision(directory, depth):
"""
Fetch the Git-SVN identifier for the local tree.
Parses first |depth| commit messages.
Errors are swallowed.
"""
if not IsGitSVN(directory):
return None
git_re = re.compile(r'^\s*git-svn-id:\s+(\S+)@(\d+)')
proc = RunGitCommand(directory, ... | 664da44ee6057a62eb8ece161ade5cabac15bc7b | 6,675 |
def collect_jars(
dep_targets,
dependency_analyzer_is_off = True,
unused_dependency_checker_is_off = True,
plus_one_deps_is_off = True):
"""Compute the runtime and compile-time dependencies from the given targets""" # noqa
if dependency_analyzer_is_off:
return _collect_... | 10203c31bb2d1b5df9336d606355b497f7dd755a | 6,676 |
def _cred1_adapter(user=None, password=None):
"""Just a sample adapter from one user/pw type to another"""
return dict(user=user + "_1", password=password + "_2") | 9e7c218d2dc01793cba232ba1f6d69a54bf21fee | 6,677 |
def acc_metric(y_true, y_pred):
"""
Accuracy
"""
diff = K.abs(y_pred - y_true) * 5000
return K.mean(diff, axis=-1) | 0722791db5546f16648f74b8927590de8696e3d5 | 6,678 |
async def confirm(message: discord.Message, fallback: str = None) -> bool:
"""
Helper function to send a checkmark reaction on a message. This would be
used for responding to a user that an action completed successfully,
without sending a whole other message. If a checkmark reaction cannot
be added,... | 2567957d4239605072bd4f707c12e2b265b8cfbe | 6,679 |
def get_layer_version(
lambda_client: BaseClient,
layer_name: str,
version: int,
) -> "definitions.LambdaLayer":
"""Retrieve the configuration for the specified lambda layer."""
return definitions.LambdaLayer(
lambda_client.get_layer_version(
LayerName=layer_name,
Ver... | cfa2121ac757ae24b67bb25f7fd3046f017df85d | 6,680 |
import requests
def get_detail_msg(detail_url):
"""
2.获取某个职位的详细数据
:param detail_url: 职位详细页面的url
:return: 职位数据
"""
# print('请求的详细地址是:' + detail_url)
response = requests.get(detail_url, headers=HEADERS)
html_element = etree.HTML(response.text)
position = {}
# 【数据】获取职位标题
title = html_element.xpath('//tr[@cl... | 2fc5b316abed9eb9aeff99ae87cdd8e5e59a5e70 | 6,681 |
def wizard_process_received_form(form):
""" Processing of form received during the time measure
Expected result example: {1: '00:43.42', 2: '00:41.35', 3: '00:39.14', 4: '00:27.54'}
"""
lines = {key.split('_')[1]: value.split('_')[1] for key, value in form.items() if key.startswith("line")}
# print(... | 54b10589cab7ce689b64f5373d2f0a998044db82 | 6,682 |
import inspect
def getsource(obj,is_binary=False):
"""Wrapper around inspect.getsource.
This can be modified by other projects to provide customized source
extraction.
Inputs:
- obj: an object whose source code we will attempt to extract.
Optional inputs:
- is_binary: whether the obje... | 9e97a030c695b9ea50d27abc5253e47be7d4c06a | 6,683 |
import re
def extract_sector_id(room):
"""Given a room identifier of the form:
'aaa-bbb-cc-d-e-123[abcde]'
Return the sector id:
'123'
"""
m = re.search(r'(?P<sector_id>\d+)', room)
return m.group('sector_id') if m else None | f5bfb64d32769cd4b6c2b7309d41450fa807d7a2 | 6,684 |
def splitext_all(_filename):
"""split all extensions (after the first .) from the filename
should work similar to os.path.splitext (but that splits only the last extension)
"""
_name, _extensions = _filename.split('.')[0], '.'.join(_filename.split('.')[1:])
return(_name, "."+ _extensions) | bf9e4ee06eb30dfeb7898ce6e34607bef20b290b | 6,685 |
def tag_in_tags(entity, attribute, value):
"""
Return true if the provided entity has
a tag of value in its tag list.
"""
return value in entity.tags | ad88be5f8848b387f2a261ce5506dffde285a1d8 | 6,687 |
def generate_finding_title(title):
"""
Generate a consistent title for a finding in AWS Security Hub
* Setup as a function for consistency
"""
return "Trend Micro: {}".format(title) | 0cf390c2579e06c2166b086332035b864d3db1e3 | 6,688 |
def makeHexagon(x,y,w,h):
"""Return hexagonal QPolygon. (x,y) is top left coner"""
points=[]
cos=[1.,0.5,-0.5,-1,-0.5,0.5]
sin=[0,0.866025,0.866025,0,-0.866025,-0.866025]
for i in range(len (cos)):
points.append(QPoint(x+w*cos[i],y+h*sin[i]))
return QPolygonF(points) | 7310e0313130f54b125c81f332a541b2b2b9b9a9 | 6,689 |
def save_conv_output(activations, name):
"""
Saves layer output in activations dict with name key
"""
def get_activation(m, i, o):
activations[name] = F.relu(o).data.cpu().numpy()
return get_activation | 13034128234ea6a9633ae144ac02788f2d49986a | 6,690 |
async def get_profile_xp(user_id: int):
"""
Get a user's profile xp.
:param user_id: Discord User ID
"""
return (await self.conn.fetchrow("SELECT profilexp FROM currency.levels WHERE userid = $1", user_id))[0] | d029bb335442aa3ba5ef02b143351e8ccc6b6434 | 6,691 |
from typing import Optional
def validate_raw_data(data: Optional[UserPackage]) -> bool:
"""Returns False if invalid data"""
# NOTE: add more validation as more fields are required
if data is None or data.contribs is None:
return False
if (
data.contribs.total_stats.commits_count > 0
... | 22185bc2691b6a5fce98749c119ea14649c0d676 | 6,693 |
def extractTheSunIsColdTranslations(item):
"""
Parser for 'The Sun Is Cold Translations'
"""
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
if not (chp or vol) or 'preview' in item['title'].lower():
return None
if '108 maidens' in item['tags']:
return buildReleaseMessageWithType(ite... | 94ef69f42dd183a2155a02c8035c12da30eb34e2 | 6,694 |
import torch
def to_device(x, device):
"""Cast a hierarchical object to pytorch device"""
if isinstance(x, torch.Tensor):
return x.to(device)
elif isinstance(x, dict):
for k in list(x.keys()):
x[k] = to_device(x[k], device)
return x
elif isinstance(x, list) or isins... | a315905fb0cf6d6720103c0d22440418ebd41bf1 | 6,695 |
def git_show_oneline(obj):
"""Returns: One-line description of a git object `obj`, which is typically a commit.
https://git-scm.com/docs/git-show
"""
return exec_headline(['git', 'show', '--oneline', '--quiet', obj]) | 77427786a8d1b9e3b01d5194387f047c1c9ce505 | 6,696 |
from operator import and_
import logging
def like_post():
""" Like a post """
try:
# This will prevent old code from adding invalid post_ids
post_id = int(request.args.get('post_id', '-1'))
if post_id < 0:
return "No Post Found to like!"
vote = (db_session.query(Vot... | 8cdde2ec6f71104178c49661a9e3fdf5c62bb67d | 6,697 |
def login_post():
"""Obdelaj izpolnjeno formo za prijavo"""
# Uporabniško ime, ki ga je uporabnik vpisal v formo
username = bottle.request.forms.user
# Izračunamo MD5 hash geslo, ki ga bomo spravili
password = password_md5(bottle.request.forms.psw)
# Preverimo, ali se je uporabnik pravilno prij... | 9b2243f7e618833d59a7d07454ed8fe86d4b18fc | 6,698 |
def parse_symbol_file(filepath, fapi=None):
"""Read in stock symbol list from a text file.
Args:
filepath: Path to file containing stock symbols, one per line.
fapi: If this is supplied, the symbols read will be conformed
to a financial API; currently 'google' or 'yahoo'.
Retur... | af0f085fd5424045c71dee6a290a07645f242ff8 | 6,699 |
def trader_tactic_snapshot(symbol, strategy, end_dt=None, file_html=None, fq=True, max_count=1000):
"""使用聚宽的数据对任意标的、任意时刻的状态进行策略快照
:param symbol: 交易标的
:param strategy: 择时交易策略
:param end_dt: 结束时间,精确到分钟
:param file_html: 结果文件
:param fq: 是否复权
:param max_count: 最大K线数量
:return: trader
"""... | 0b979008f3c950ed41aa85eff2031e6cb34b8685 | 6,700 |
def preprocess(batch):
""" Add zero-padding to a batch. """
tags = [example.tag for example in batch]
# add zero-padding to make all sequences equally long
seqs = [example.words for example in batch]
max_length = max(map(len, seqs))
seqs = [seq + [PAD] * (max_length - len(seq)) for seq in seqs... | 832b6453714e7b7eb23271b771bbc156a09d3784 | 6,701 |
def append_include_as(include_match):
"""Convert ``#include x`` to ``#include x as y``, where appropriate; also,
convert incorrect "as" statements. See INCLUDE_AS dict for mapping from
resource to its "as" target.
Parameters
----------
include_match : re._pattern_type
Match produced by ... | 0eaaa356efa33f0e64db6b3a843236fd15ebb66d | 6,702 |
def get_user_profiles(page=1, limit=10):
"""Retrieves a list of user profiles.
:param page: Page number
:type page: int
:param limit: Maximum number of results to show
:type limit: int
:returns: JSON string of list of user profiles; status code
:rtype: (str, int)
"""
# initialize q... | 7bcfe33925e49a90ac593fad53e4e169b107886e | 6,703 |
import sqlite3
def _repository():
"""Helper dependency injection"""
db = sqlite3.connect('covid_database.db', isolation_level=None)
return CovidTestDataRepository(db) | e30d30f3b4f9673df4863d261655aa6f38a527d7 | 6,704 |
def f(x):
"""Cubic function."""
return x**3 | 13832221de3490dbd92f4f1a26854baec7010023 | 6,705 |
from outliers import smirnov_grubbs as grubbs
def correct_anomalies(peaks, alpha=0.05, save_name=""):
"""
Outlier peak detection (Grubb's test) and removal.
Parameters
----------
peaks : array
vector of peak locations
alpha : real
significance level for Grubb's test
save_n... | cf33123e963b245007c8be4777cecd1224d4e3fa | 6,707 |
def svn_wc_walk_entries(*args):
"""
svn_wc_walk_entries(char path, svn_wc_adm_access_t adm_access, svn_wc_entry_callbacks_t walk_callbacks,
void walk_baton,
svn_boolean_t show_hidden, apr_pool_t pool) -> svn_error_t
"""
return apply(_wc.svn_wc_walk_entries, args) | 791e0f635aa56329f78a1ed0f171217518f9be05 | 6,708 |
def dlp_to_datacatalog_builder(
taskgroup: TaskGroup,
datastore: str,
project_id: str,
table_id: str,
dataset_id: str,
table_dlp_config: DlpTableConfig,
next_task: BaseOperator,
dag,
) -> TaskGroup:
"""
Method for returning a Task Group for scannign a table with DLP, and creating B... | 53950a99dddc4f2a61dca12908c3b2a17a3765c4 | 6,709 |
import textwrap
def dedent(ind, text):
"""
Dedent text to the specific indentation level.
:param ind: common indentation level for the resulting text (number of spaces to append to every line)
:param text: text that should be transformed.
:return: ``text`` with all common indentation removed, and... | 271b9fd270d78c4bc952af31d3d9be0ff6bdab73 | 6,711 |
def get_vendor(request):
"""
Returns the ``JSON`` serialized data of the requested vendor on ``GET`` request.
.. http:get:: /get_vendor/
Gets the JSON serialized data of the requested vendor.
**Example request**:
.. sourcecode:: http
GET /get... | e142854426ef406bdfe6e34d0629e80d49493c91 | 6,713 |
def ensure_bin_str(s):
"""assert type of s is basestring and convert s to byte string"""
assert isinstance(s, basestring), 's should be string'
if isinstance(s, unicode):
s = s.encode('utf-8')
return s | 3ce171f02a371073c5474596da9c963b0a77a415 | 6,714 |
def _word_accuracy(pred_data, ref_data):
"""compute word-level accuracy"""
pred_size = len(pred_data)
ref_size = len(ref_data)
if pred_size <= 0 or ref_size <= 0:
raise ValueError("size of predict or reference data is less than or equal to 0")
if pred_size != ref_size:
raise ValueErr... | c4abfcc439fca5d14b5edc8289ef9ee2d46807fe | 6,715 |
import requests
def api_retrieve_part(pt_id):
"""
Allows the client to call "retrieve" method on the server side to
retrieve the part from the ledger.
Args:
pt_id (str): The uuid of the part
Returns:
type: str
String representing JSON object which allows the clien... | 5043415dcdb95e59ec87271bf62d1f04f818af9b | 6,717 |
def smoP(dataMatIn, classLabels, C, toler, maxIter, kTup = ('lin',0)):
"""
完整的线性SMO算法
Parameters:
dataMatIn - 数据矩阵
classLabels - 数据标签
C - 松弛变量
toler - 容错率
maxIter - 最大迭代次数
kTup - 包含核函数信息的元组
Returns:
oS.b - SMO算法计算的b
oS.alphas - SMO算法计算的alphas
"""
oS = optStruct(np.mat(dataMatIn), np.mat(classLabel... | fb38ef33ab624a74f3da320c5e90a48aa307d588 | 6,718 |
def _get_output_data(output_list, heat, stack_id):
"""
获取output数据
"""
response = {
'code': 200,
'msg': 'ok',
'status': utils.INSTANTIATED,
'data': []
}
for item in output_list['outputs']:
output = heat.stacks.output_show(stack_id, item['output_key'])
... | aca183c1b158e6e7b9e414151e7f5d5505de1188 | 6,719 |
def _ensure_str(s):
"""convert bytestrings and numpy strings to python strings"""
return s.decode() if isinstance(s, bytes) else str(s) | 05f549166cc459371b380f62393bbc835aa7ff48 | 6,720 |
def get_polarimeter_index(pol_name):
"""Return the progressive number of the polarimeter within the board (0…7)
Args:
pol_name (str): Name of the polarimeter, like ``R0`` or ``W3``.
Returns:
An integer from 0 to 7.
"""
if pol_name[0] == "W":
return 7
else:
retu... | 0068931868e214896f6263e58fc09215352d502c | 6,721 |
def merge_sort(collection):
"""
Pure implementation of the fastest ordered collection with heterogeneous
: parameter collection : some mutable ordered collection with heterogeneous
comparable items inside
: return : a sollectiojn order by ascending
Examples :
>>> me... | b704792ef49629e7e9e04c22ffe03f08b3ef76fa | 6,722 |
def sma_centroids(dataframe, column, short_window, long_window, min_width=None, **kwargs):
"""Identify centermost point between two SMA interception points
Define regions as being bounded by two consecutive interceptions of SMAs
with different window widths, then choose the centermost data point within
... | 1157318d90ce514a3a85461851c158a0df9d2a3e | 6,723 |
def delMsg(msgNum):
"""Deletes a specified message from the inbox"""
global usrPrompt
try:
inboxMessages = json.loads(api.getAllInboxMessages())
# gets the message ID via the message index number
msgId = inboxMessages['inboxMessages'][int(msgNum)]['msgid']
msgAck = api.tras... | b3cc7a4568ca6eae3267cd5247abe88c5ccb8bec | 6,724 |
def capitalize_first(str):
"""Capitalizes only the first letter of the given string.
:param str: string to capitalize
:return: str with only the first letter capitalized
"""
if str == "":
return ""
return str[0].upper() + str[1:] | ed6dfdfd9709de1682c29ed152131b9da732441b | 6,725 |
def min_cost_edge(G, T):
"""Returns the edge with the lowest cost/weight.
Parameters
----------
G : NetworkX graph
T : Prim's Algorithm
Returns
-------
The edge with the lowest cost/weight.
"""
edge_list = possible_edges(G, T)
edge_list.sort(key = lambda e : cost(G... | 3720bb59cddf0b29beb9f9162941ddf7f86dd429 | 6,726 |
import io
import base64
def get_image_html_tag(fig, format="svg"):
"""
Returns an HTML tag with embedded image data in the given format.
:param fig: a matplotlib figure instance
:param format: output image format (passed to fig.savefig)
"""
stream = io.BytesIO()
# bbox_inches: expand the ... | f5c59a6f4f70fb6616cec4619d8cbf9ca2e28529 | 6,727 |
def reformat_language_tuple(langval):
"""Produce standardly-formatted language specification string using given language tuple.
:param langval: `tuple` in form ('<language>', '<language variant>'). Example: ('en', 'US')
:return: `string` formatted in form '<language>-<language-variant>'
"""
if lang... | 63c479d7dd273f31b9bdcc6c0ce81d4267a43714 | 6,728 |
def _create_ghostnet(variant, width=1.0, pretrained=False, **kwargs):
"""
Constructs a GhostNet model
"""
cfgs = [
# k, t, c, SE, s
# stage1
[[3, 16, 16, 0, 1]],
# stage2
[[3, 48, 24, 0, 2]],
[[3, 72, 24, 0, 1]],
# stage3
[[5, 72, 40, 0.25,... | 8b0bca5e4d711dce5150d8c3cdb187c9b1a23ec3 | 6,729 |
def re_suffix(string):
""" Remove any “os.extsep” prefixing a string, and ensure that
it ends with a “$” – to indicate a regular expression suffix.
"""
if not string:
return None
return rf"{string.casefold().lstrip(QUALIFIER).rstrip(DOLLA)}{DOLLA}" | fd1767f0d539e284f56c32f5ed4a8789a6638fca | 6,730 |
def _alternate_dataclass_repr(object) -> None:
"""
Overrides the default dataclass repr by not printing fields that are
set to None. i.e. Only prints fields which have values.
This is for ease of reading.
"""
populated_fields = {
field.name: getattr(object, f"{field.name}")
for f... | c9c07508a39c0732698c1ed6803ef00c4b2f65d6 | 6,731 |
def which_coords_in_bounds(coords, map_shape):
"""
Checks the coordinates given to see if they are in bounds
:param coords Union[array(2)[int], array(N,2)[int]]: [int, int] or [[int, int], ...], Nx2 ndarray
:param map_shape Tuple[int]: shape of the map to check bounds
:return Union[bool array(N)[boo... | 5606c24430e9967cade8bdeb789f10bed1248eb1 | 6,732 |
def get_activation_function(activation_function_name: str):
"""
Given the name of an activation function, retrieve the corresponding function and its derivative
:param cost_function_name: the name of the cost function
:return: the corresponding activation function and its derivative
"""
try:
... | f2a830c15cb93bd9fce1b66c2b5ca14530005cd5 | 6,733 |
def url_split(url, uses_hostname=True, split_filename=False):
"""Split the URL into its components.
uses_hostname defines whether the protocol uses a hostname or just a path (for
"file://relative/directory"-style URLs) or not. split_filename defines whether the
filename will be split off in an... | 5c76eb58c520043ab922c941806f24c60f9ee721 | 6,734 |
def memdiff_search(bytes1, bytes2):
"""
Use binary searching to find the offset of the first difference
between two strings.
:param bytes1: The original sequence of bytes
:param bytes2: A sequence of bytes to compare with bytes1
:type bytes1: str
:type bytes2: str
:rtype: int offset of... | fbcb221c77730c45be4c81a6ae7515e602468af5 | 6,735 |
def decomposeJonesMatrix(Jmat):
""" Decompose 2x2 Jones matrix to retardance and diattenuation vectors """
Jmat = Jmat / cp.sqrt(cp.linalg.det(Jmat))
q = cp.array([Jmat[0, 0] - Jmat[1, 1], Jmat[1, 0] + Jmat[0, 1], -1j * Jmat[1, 0] + 1j * Jmat[0, 1]]) / 2
tr = cp.trace(Jmat) / 2
c = cp.arccosh(tr)
... | 151320a0f77f2fb3a77d8e06b1e623c0fed6c673 | 6,736 |
def format_utc(time):
"""Format a time in UTC."""
return as_utc(time).strftime('%Y-%m-%d %H:%M:%S.%f') | 88624b8e166aa07172abd14c391945e33c77332f | 6,737 |
def _expand_sources(sources):
"""
Expands a user-provided specification of source files into a list of paths.
"""
if sources is None:
return []
if isinstance(sources, str):
sources = [x.strip() for x in sources.split(",")]
elif isinstance(sources, (float, int)):
sources =... | 6e16eaae5edb68a5be7e0af4be777fc76b70d22a | 6,740 |
from typing import Optional
def get_stream(stream_id: Optional[str] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetStreamResult:
"""
This data source provides details about a specific Stream resource in Oracle Cloud Infrastructure Streaming service.
Gets detailed infor... | fd7eb6675f5d232e90a94e18e4c68e6d538ca7e4 | 6,741 |
def fused_add_tanh_sigmoid_multiply(input_a, input_b, n_channels):
"""
Fusion method.
"""
n_channels_int = n_channels
in_act = input_a + input_b
t_act = ops.Tanh()(in_act[:, :n_channels_int, :])
s_act = ops.Sigmoid()(in_act[:, n_channels_int:, :])
acts = t_act * s_act
return acts | 9412a3b20960b0a280a06569846df744f14a9d63 | 6,743 |
import json
def _classes_dict(filename):
"""
Open JSON file and read the data for the Classes (and Origins).
filename - the file name as a string.
Runtime: O(n)
"""
class_dict = {} # {'robot': ['blitzcrank']}
class_bonus_dict = {}
dict = { 1: {}, 2: {}, 3: {}, 4 : {}, 6 : {}} # { 1 : {... | 44fa2acec6c7235995bfdabaab149b4cba2cb7cc | 6,744 |
def set_incident_seen(incident, user=None):
"""
Updates the incident to be seen
"""
is_org_member = incident.organization.has_access(user)
if is_org_member:
is_project_member = False
for incident_project in IncidentProject.objects.filter(incident=incident).select_related(
... | 8b970ec492bdb72b6e05c053f7a5b9bf919b15e7 | 6,745 |
def single_parity_check(
llr: np.array,
mask_steps: int = 0,
last_chunk_type: int = 0,
) -> np.array:
"""Compute beta value for Single parity node."""
all_sign = np.sign(np.prod(llr))
abs_alpha = np.fabs(llr)
first_min_idx, second_min_idx = np.argsort(abs_alpha)[:2]
result =... | 5cc9984bb86fdfd777b2a968fb887388a5422e4f | 6,746 |
def _deserialize_job_result(user_input: JSON) -> JobResult:
"""Deserialize a JobResult from JSON."""
job = _deserialize_job(user_input['job'])
plan = _deserialize_plan(user_input['plan'])
is_done = user_input['is_done']
outputs = dict() # type: Dict[str, Asset]
for name, asset in user_input['... | 883629fa2650fc043124c6ccf721ed38093daa19 | 6,747 |
def _brute_force_knn(X, centers, k, return_distance=True):
"""
:param X: array of shape=(n_samples, n_features)
:param centers: array of shape=(n_centers, n_features)
:param k: int, only looking for the nearest k points to each center.
:param return_distance: bool, if True the return the distance al... | b185a8d9e901a12a1385ed5ffc3183a5cc51c1b5 | 6,748 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.