content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def poly_union(poly_det, poly_gt):
"""Calculate the union area between two polygon.
Args:
poly_det (Polygon): A polygon predicted by detector.
poly_gt (Polygon): A gt polygon.
Returns:
union_area (float): The union area between two polygons.
"""
assert isinstance(poly_det, ... | fbd13a9b1ef4acee27fac7d04b00fc1cfc46ca08 | 3,651,275 |
def get_stoich(geom_i, geom_j):
""" get the overall combined stoichiometry
"""
form_i = automol.geom.formula(geom_i)
form_j = automol.geom.formula(geom_j)
form = automol.formula.join(form_i, form_j)
stoich = ''
for key, val in form.items():
stoich += key + str(val)
return stoic... | eaba89508d7c913a77ebf91097d620dc6fdff5a6 | 3,651,276 |
import requests
from bs4 import BeautifulSoup
def get_all_text(url):
"""Retrieves all text in paragraphs.
:param str url: The URL to scrap.
:rtype: str :return: Text in the URL.
"""
try:
response = requests.get(url)
# If the response was successful, no Exception will be raised
... | 364150aee7c1c093367d3d95bc5c0836dde978db | 3,651,277 |
from typing import List
def metadata_partitioner(rx_txt: str) -> List[str]:
"""Extract Relax program and metadata section.
Parameters
----------
rx_txt : str
The input relax text.
Returns
-------
output : List[str]
The result list of partitioned text, the first element
... | dd09aff9ea517813d43ff307fb9fc425b7338943 | 3,651,278 |
def make_aware(value, timezone):
"""
Makes a naive datetime.datetime in a given time zone aware.
"""
if hasattr(timezone, 'localize'):
# available for pytz time zones
return timezone.localize(value, is_dst=None)
else:
# may be wrong around DST changes
return value.rep... | b466b4fda2daf54b7aa5e8f00ad7b10397e61c7b | 3,651,279 |
def to_dict(funs):
"""Convert an object to a dict using a dictionary of functions.
to_dict(funs)(an_object) => a dictionary with keys calculated from functions on an_object
Note the dictionary is copied, not modified in-place.
If you want to modify a dictionary in-place, do adict.update(to_dict(funs)... | d22bbcb3c1913361c3906fd2e7f3d254dc67de28 | 3,651,280 |
import re
def parse_duration_string_ms(duration):
"""Parses a duration string of the form 1h2h3m4s5.6ms4.5us7.8ns into milliseconds."""
pattern = r'(?P<value>[0-9]+\.?[0-9]*?)(?P<units>\D+)'
matches = list(re.finditer(pattern, duration))
assert matches, 'Failed to parse duration string %s' % duration
times... | da2981590d70f32ee3514873602621a77b70cbe2 | 3,651,281 |
def fin(activity):
"""Return the end time of the activity. """
return activity.finish | ed5b1d1e0f29f403cfee357a264d05d5cc88093e | 3,651,282 |
def unfreeze_map(obj):
"""
Unfreezes all elements of mappables
"""
return {key: unfreeze(value) for key, value in obj.items()} | 2ba48f6cf89f44001b7940076c4763dc820d9aa1 | 3,651,283 |
from typing import Optional
from typing import Union
from datetime import datetime
def get_date(
value: Optional[Union[date, datetime, str]],
raise_error=False
) -> Optional[date]:
"""
Convert a given value to a date.
Args:
raise_error: flag to raise error if return is None or not
... | 501b2363aa2d40f16f6144995db8d840e62f750a | 3,651,284 |
def k_param(kguess, s):
"""
Finds the root of the maximum likelihood estimator
for k using Newton's method. Routines for using Newton's method
exist within the scipy package but they were not explored. This
function is sufficiently well behaved such that we should not
have problems solving for k... | 24df48746d53fd4573db10093065e7b49d5c7bfe | 3,651,286 |
def hex_to_bin(value: hex) -> bin:
"""
convert a hexadecimal to binary
0xf -> '0b1111'
"""
return bin(value) | b82c4fea08fc258a3b50be9a5e77b3d076a33459 | 3,651,287 |
def four_oneports_2_twoport(s11: Network, s12: Network, s21: Network, s22: Network, *args, **kwargs) -> Network:
"""
Builds a 2-port Network from list of four 1-ports
Parameters
----------
s11 : one-port :class:`Network`
s11
s12 : one-port :class:`Network`
s12
s21 : one-port... | 2f8b365b2ccb06c252337630f6e34b794a3a3eba | 3,651,288 |
def find_xml_command(rvt_version, xml_path):
"""
Finds name index src path and group of Commands in RevitPythonShell.xml configuration.
:param rvt_version: rvt version to find the appropriate RevitPythonShell.xml.
:param xml_path: path where RevitPythonShell.xml resides.
:return: Commands dictionary... | 1effc1b313d93e92b25deef1d62fc65c8f3e6975 | 3,651,289 |
import mimetypes
def put_data_to_s3(data, bucket, key, acl=None):
"""data is bytes not string"""
content_type = mimetypes.guess_type(key)[0]
if content_type is None:
content_type = 'binary/octet-stream'
put_object_args = {'Bucket': bucket, 'Key': key, 'Body': data,
'Cont... | 042fc8eea230559efdc60ca9f18db2e9d1766286 | 3,651,290 |
from pathlib import Path
def join_analysis_json_path(data_path: Path, analysis_id: str, sample_id: str) -> Path:
"""
Join the path to an analysis JSON file for the given sample-analysis ID combination.
Analysis JSON files are created when the analysis data is too large for a MongoDB document.
:param... | 5ae25e5c0df4801b23a34cdac09db709733844ca | 3,651,291 |
def user_profile(uname=None):
"""
Frontend gets user's profile by user name or modify user profile (to do).
Return user's complete profile and the recommendations for him (brief events).
:param uname: user's name, a string
:return: a json structured as {'user': [(0, 'who', 'password', 'email@student... | b43ab64b0d44e7d19342a90da261bf96489fed3a | 3,651,292 |
def circuit_status(self, handle: ResultHandle) -> CircuitStatus:
"""
Return a CircuitStatus reporting the status of the circuit execution
corresponding to the ResultHandle
"""
if handle in self._cache:
return CircuitStatus(StatusEnum.COMPLETED)
raise CircuitNotRunError(handle) | 7de17e03e3177f7b7c2de31650a0c341ab7e4fa6 | 3,651,293 |
def get_portfolio() -> pd.DataFrame:
"""
Get complete user portfolio
Returns:
pd.DataFrame: complete portfolio
"""
portfolio = get_simple_portfolio()
full_portfolio = pd.DataFrame()
for ticket in portfolio.index:
full_portfolio = full_portfolio.append(
_clea... | c04df5cf88e936cab9bd7f30a63ab3e695efd771 | 3,651,295 |
def findZeros( vec, tol = 0.00001 ):
"""Given a vector of a data, finds all the zeros
returns a Nx2 array of data
each row is a zero, first column is the time of the zero, second column indicates increasing
or decreasing (+1 or -1 respectively)"""
zeros = []
for i in range( vec.size - ... | 173f734c9b3abf876b48d194e691b517fd0ec816 | 3,651,296 |
from typing import List
def get_index(square_num: int) -> List[int]:
"""
Gets the indices of a square given the square number
:param square_num: An integer representing a square
:return: Returns a union with 2 indices
"""
for i in range(4):
for j in range(4):
if puzzle_st... | e9896ba58b76ea43069b408a445720f0b418488d | 3,651,297 |
def _ResolveName(item):
"""Apply custom name info if provided by metadata"""
# ----------------------------------------------------------------------
def IsValidName(value):
return bool(value)
# ----------------------------------------------------------------------
if Attributes.UNIVERSAL... | 0d303cb4577503b4e39f14da699cf77c9adf462f | 3,651,298 |
import re
def extract_errno(errstr):
"""
Given an error response from a proxyfs RPC, extracts the error number
from it, or None if the error isn't in the usual format.
"""
# A proxyfs error response looks like "errno: 18"
m = re.match(PFS_ERRNO_RE, errstr)
if m:
return int(m.group(... | adff11595d391a1bb4403c3c93a0bb4ab182254a | 3,651,299 |
def index():
""" Index page """
return render_template("index.html"); | af92fa468122a41ed33d55a591735d400cf68e0d | 3,651,300 |
def solve(in_array):
"""
Similar to 46442a0e, but where new quadrants are flips of the original array rather than rotations
:param in_array: input array
:return: expected output array
"""
array_edgelength = len(in_array[0]) # input array edge length
opp_end = array_edgelength*2-1 # used... | 0af23e82caf65bea64eeeae6da8400ef6ec03426 | 3,651,301 |
def trim_all(audio, rate, frame_duration, ambient_power=1e-4):
"""Trims ambient silence in the audio anywhere.
params:
audio: A numpy ndarray, which has 1 dimension and values within
-1.0 to 1.0 (inclusive)
rate: An integer, which is the rate at which samples are taken
fra... | 37d7ca77c9ab767c90fedf4008a7a28415c5ce3f | 3,651,302 |
def guess_initializer(var, graph=None):
"""Helper function to guess the initializer of a variable.
The function looks at the operations in the initializer name space for the
variable (e.g. my_scope/my_var_name/Initializer/*). The TF core initializers
have characteristic sets of operations that can be used to d... | 5a1e4a99037e51d87a8d75bc5f33e105f86a4153 | 3,651,303 |
def get_all(ptype=vendor):
""" returns a dict of all partners """
if ptype == vendor:
d = get_dict_from_json_file( VENDORS_JSON_FILE ) # will create file if not exist
if ptype == customer:
d = get_dict_from_json_file( CUSTOMERS_JSON_FILE )
return d | eb285d9462f85daec9c8b176edc6eaa90a09ff4c | 3,651,304 |
from catkin.find_in_workspaces import find_in_workspaces
def FindCatkinResource(package, relative_path):
"""
Find a Catkin resource in the share directory or
the package source directory. Raises IOError
if resource is not found.
@param relative_path Path relative to share or package source direct... | 17fe7bf3fb6b04f031d1bd8e0dd6558312dca92a | 3,651,306 |
from typing import Callable
import urllib3
from typing import Dict
from typing import Any
from typing import Optional
def send_udf_call(
api_func: Callable[..., urllib3.HTTPResponse],
api_kwargs: Dict[str, Any],
decoder: decoders.AbstractDecoder,
id_callback: Optional[IDCallback] = None,
*,
re... | d34323f1f276f14d0dc947835db490e78ca47691 | 3,651,307 |
import requests
import json
def migration_area_baidu(area="乌鲁木齐市", indicator="move_in", date="20200201"):
"""
百度地图慧眼-百度迁徙-XXX迁入地详情
百度地图慧眼-百度迁徙-XXX迁出地详情
以上展示 top100 结果,如不够 100 则展示全部
迁入来源地比例: 从 xx 地迁入到当前区域的人数与当前区域迁入总人口的比值
迁出目的地比例: 从当前区域迁出到 xx 的人口与从当前区域迁出总人口的比值
https://qianxi.baidu.com/?from=... | 4bb4afdde77c2b21222bde28a4f93e58cd8c6019 | 3,651,308 |
def ranges(locdata: LocData, loc_properties=None, special=None, epsilon=1):
"""
Provide data ranges for locdata.data property.
If LocData is empty None is returned.
If LocData carries a single value, the range will be (value, value + `epsilon`).
Parameters
----------
locdata : LocData
... | 28a23603dbb2abb52df4f7d2b35b6333050cfe43 | 3,651,309 |
def evaluate_available(item, type_name, predicate):
"""
Run the check_available predicate and cache the result.
If there is already a cached result, use that and don't
run the predicate command.
:param str item: name of the item to check the type for. i.e. 'server_types
:param str type_name: nam... | 872e81613c91141c81f6dafd27aee6e8642c1e59 | 3,651,311 |
def parse_args():
"""
Parses command line arguments
"""
parser = ArgumentParser(description="A multi-threaded gemini server")
parser.add_argument("-b", "--host", default=DEFAULT_HOST, help="Host to bind to")
parser.add_argument("-p", "--port", default=DEFAULT_PORT, help="Port to bind to")
pa... | 05dec02ce0f243f46896917c2f25108e6f592bb5 | 3,651,314 |
def get_mapping_rules():
""" Get mappings rules as defined in business_object.js
Special cases:
Aduit has direct mapping to Program with program_id
Request has a direct mapping to Audit with audit_id
Response has a direct mapping to Request with request_id
DocumentationResponse has a direct mapping... | 59b94070d3fe35eca8c356162caf9969c9ea47d0 | 3,651,315 |
async def get_pipeline(request: web.Request, organization, pipeline) -> web.Response:
"""get_pipeline
Retrieve pipeline details for an organization
:param organization: Name of the organization
:type organization: str
:param pipeline: Name of the pipeline
:type pipeline: str
"""
retur... | 0bbbe26111542173fda05fe8e3beccec99b6bfe8 | 3,651,318 |
def add_attachment(manager, issue, file):
"""
Replace jira's method 'add_attachment' while don't well fixed this issue
https://github.com/shazow/urllib3/issues/303
And we need to set filename limit equaled 252 chars.
:param manager: [jira.JIRA instance]
:param issue: [jira.JIRA.resources.Issue i... | 19d2fb57fbd116e27328c075a2899425243856b2 | 3,651,319 |
def _ols_iter(inv_design, sig, min_diffusivity):
""" Helper function used by ols_fit_dki - Applies OLS fit of the diffusion
kurtosis model to single voxel signals.
Parameters
----------
inv_design : array (g, 22)
Inverse of the design matrix holding the covariants used to solve for
... | da55a73fff02f2088b77d21a4b0a7a7308b0c855 | 3,651,320 |
from typing import Counter
def unarchive_collector(collector):
"""
This code is copied from `Collector.delete` method
"""
# sort instance collections
for model, instances in collector.data.items():
collector.data[model] = sorted(instances, key=attrgetter("pk"))
# if possible, bring t... | 3c0a05d31fafac34e0503bd5dd154c9201e7e94a | 3,651,321 |
from typing import List
from typing import Optional
from typing import Union
from typing import Dict
def remove_tag_from_issues(
issues: List[GitHubIssue],
tag: str,
scope: str = "all",
ignore_list: Optional[Union[List[int], List[Dict[str, int]]]] = None,
) -> List[GitHubIssue]:
"""remove_tag_from... | c8709f7e9a01f4c5320748ca181a3a813a9e754f | 3,651,322 |
from datetime import datetime
def days_remaining_context_processor(request):
"""Context processor. Adds days_remaining to context of every view."""
now = datetime.now()
return {'days_remaining' : (wedding_date - now).days} | 1aa9deb40b54627044926820921c4e5550f2050c | 3,651,323 |
from datetime import datetime
import time
def convert_time_range(trange, tz=None):
"""
Converts freeform time range into a tuple of localized
timestamps (start, end).
If `tz` is None, uses settings.TIME_ZONE for localizing
time range.
:param trange: - string representing time-range. The opti... | 64c24c3011418e93111ec856acdd4b6a94abd425 | 3,651,324 |
def process_waiting_time(kernel_data, node_id, phase_id, norm_vehs=False):
"""Processes batched waiting time computation"""
cycle_time = 60
def fn(x):
if (x / 13.89) < 0.1:
return 1.0
else:
return 0.0
wait_times = []
for t in kernel_data:
qt = defau... | 4489205a8d3ba58601875a7dee1b086fd7b639af | 3,651,325 |
def get_version():
""" Do this so we don't have to import lottery_ticket_pruner which requires keras which cannot be counted on
to be installed when this package gets installed.
"""
with open('lottery_ticket_pruner/__init__.py', 'r') as f:
for line in f.readlines():
if line.startswit... | 0ab355110918e1c92b056932ba1d03768826c4f2 | 3,651,326 |
import time
def train_model_regression(X, X_test, y, params, folds, model_type='lgb', eval_metric='mae', columns=None,
plot_feature_importance=False, model=None,
verbose=10000, early_stopping_rounds=200, n_estimators=50000):
"""
A function to train a varie... | 586e82a1efa42e41b0d0dfdddaf9d6d0afdd7bb4 | 3,651,327 |
def extract(d, keys):
"""
Extract a key from a dict.
:param d: The dict.
:param keys: A list of keys, in order of priority.
:return: The most important key with an value found.
"""
if not d:
return
for key in keys:
tmp = d.get(key)
if tmp:
return tmp | 9985e2f1079088251429fa26611fa6e15b920622 | 3,651,328 |
def edit_distance(y, y_hat):
"""Edit distance between two sequences.
Parameters
----------
y : str
The groundtruth.
y_hat : str
The recognition candidate.
the minimum number of symbol edits (i.e. insertions,
deletions or substitutions) required to change one
word into th... | 42e9ee4169848cd2fc491e6e99b67f96e59dd95b | 3,651,331 |
def sort_predictions(classes, predictions, bboxes):
""" Sorts predictions from most probable to least, generate extra metadata about them. """
results = []
for idx, pred in enumerate(predictions):
results.append({
"class_idx": np.argmax(pred),
"class": classes[np.argmax(pred)... | 1938bb3c1b301d15425a6574e66e136cdd43a867 | 3,651,332 |
def task_bootstrap_for_adming():
"""
"""
return {'actions': [(clushUtils.exec_script, [targetNode, "bootstrap_for_adming.py"],
{
'dependsFiles': [".passwords", f"{homeDir}/.ssh/id_rsa.pub"],
'user':"root",
... | 91180c0b8b9a497488d7b4d1515088f133f5626b | 3,651,333 |
from typing import List
from typing import Tuple
def reassign_clustered(
knn: List[Tuple[npt.NDArray, npt.NDArray]],
clusters: List[Tuple[str, int]],
min_sim_threshold: float = 0.6,
n_iter: int = 20,
epsilon: float = 0.05,
) -> List[Tuple[str, int]]:
"""Reassigns companies to new clusters base... | e90c61459cfeb8d906f155219cd4b758f4b8b5fe | 3,651,334 |
def boys(n,t):
"""Boys function for the calculation of coulombic integrals.
Parameters
----------
n : int
Order of boys function
t : float
Varible for boys function.
Raises
------
TypeError
If boys function order is not an integer.
ValueError
If bo... | 1232d53898abfd032e570ad7697379f8359a566f | 3,651,335 |
def get_diameter_by_sigma(sigma, proba):
""" Get diameter of nodule given sigma of normal distribution and probability of diameter coverage area.
Transforms sigma parameter of normal distribution corresponding to cancerous nodule
to its diameter using probability of diameter coverage area.
Parameters
... | 0cd32d685b21b71cbae06a0cfb48f226209eff44 | 3,651,336 |
import termcolor
def _colorize(val, color):
"""Colorize a string using termcolor or colorama.
If any of them are available.
"""
if termcolor is not None:
val = termcolor.colored(val, color)
elif colorama is not None:
val = "{}{}{}".format(TERMCOLOR2COLORAMA[color], val, colorama.S... | 77743f99fd845b1f8450c4bd93a52563e7c4c313 | 3,651,337 |
from pathlib import Path
def get_output_filename(output_folder: str, repository_type: str,
repository_name: str, filename: str) -> Path:
"""Returns the output filename for the file fetched from a repository."""
return (
Path(output_folder) / Path(repository_type.lower())
... | 23b806f98265b45b799dbcc177760d5ceb8248fb | 3,651,338 |
def wave_exist_2d_full_v2(b=.8):
"""
plot zeros of -nu1 + G(nu1,nu2) and -nu2 + G(nu2,nu1)
as a function of g
use accurate fourier series
"""
# get data
# nc1 bifurcation values
bif = np.loadtxt('twod_wave_exist_br1.dat')
#bif2 = np.loadtxt('twod_wave_exist_br2.dat')
bif... | a471a8b510ed786080e2e5f1b3c8159cc211ff19 | 3,651,340 |
def _parse_variables(vars_list):
"""Transform the list of vars stored in module definition in dictionnary"""
vars = {}
for var in vars_list:
key = var['name']
value = None
for var_type in ATTRIBUTE_TYPE:
if var_type in var:
value = var[var_type]
... | 59c88815abf08efe72dcca9efce4970bcd072b91 | 3,651,341 |
import logging
def get_vertical_axes(nc_file):
"""
Scan input netCDF file and return a list of vertical axis variables, requiring specific
axis names
"""
vertical_axes = []
for var_name, var in nc_file.variables.items():
if var_name in ('full_levels', 'half_levels'):
verti... | f26b89d9d9839759f3b1ed7a990d548f996e29d2 | 3,651,342 |
def b_2_d(x):
"""
Convert byte list to decimal
:param x: byte list
:return: decimal
"""
s = 0
for i in range(0, len(x)):
s += x[i]*2**i
return s | e865700ea30be535ad014908d6b6024186cc5ac6 | 3,651,344 |
def get(s, delimiter='', format="diacritical"):
"""Return pinyin of string, the string must be unicode
"""
return delimiter.join(_pinyin_generator(u(s), format=format)) | 7369e133f73e9517fc20f6b95809ba615172feae | 3,651,345 |
def top_dist(g1, g2, name='weight', topology_type=0):
"""
:param g1: graph 1
:param g2: graph 2
:param name: compared edge attribute
:param topology_type: topology distance normalization method
:return: topology distance
"""
max_v = max_edge(g1, name, max_edge(g2, name, 0)) # find max ... | 2abf2e74b3a715861389b75bfce8bc3c609a77c1 | 3,651,346 |
def refresh_track():
"""
For now the interface isn't refreshed
:return:
"""
try:
url = request.form["url"]
except KeyError:
return "nok"
with app.database_lock:
Track.refresh_by_url(app.config["DATABASE_PATH"], url)
return "ok" | 47cf865ec01093735050e7abb15d65ef97d2e1ba | 3,651,347 |
import pickle
def get_weights():
""" Loads uni-modal text and image CNN model weights.
Returns:
tuple: text and image weights.
"""
text_weight_file = open("models/unimodal_text_CNN_weights.pickle", "rb")
text_weights = pickle.load(text_weight_file)
text_weight_file.close()
image... | abff59a197130f5776fdb0cacc3f895ff5d7393e | 3,651,348 |
def get_data(start_runno, start_fileno, hall, fields): # pylint: disable=too-many-locals,too-many-branches
"""Pull the data requested, starting from first VALID run/file after/including
the specified one"""
val_dict = lambda: {'values': []}
ad_dict = lambda: {f'AD{det}': val_dict()
... | e740952bf5419956bb86f214b01e4a8deb8e6ebc | 3,651,349 |
def timelength_label_to_seconds(
timelength_label: spec.TimelengthLabel,
) -> spec.TimelengthSeconds:
"""convert TimelengthLabel to seconds"""
number = int(timelength_label[:-1])
letter = timelength_label[-1]
base_units = timelength_units.get_base_units()
base_seconds = base_units['1' + letter]
... | d0494fd2fabe07d0cae2dbc7c8c142b7b478533c | 3,651,350 |
from typing import List
def getUrlsAlias()->List[str]:
"""获取所有urls.py的别名"""
obj = getEnvXmlObj()
return obj.get_childnode_lists('alias/file[name=urls]') | be0f5a2b423a4fa9a58d9e60e2cc0d91f1d66949 | 3,651,351 |
def project_xarray(run: BlueskyRun, *args, projection=None, projection_name=None):
"""Produces an xarray Dataset by projecting the provided run.
EXPERIMENTAL: projection code is experimental and could change in the near future.
Projections come with multiple types: linked, and caclulated. Calculated field... | 8960b68090601c0a83da4ebb82c4b97f3751282f | 3,651,352 |
def collect_users():
"""Collect a list of all Santas from the user"""
list_of_santas = []
while 1:
item = input("Enter a name\n")
if not item:
break
list_of_santas.append(item)
return list_of_santas | d86ec360518fdb497b86b7f631fee0dc4464e2bb | 3,651,353 |
def check_role_exists(role_name, access_key, secret_key):
"""
Check wheter the given IAM role already exists in the AWS Account
Args:
role_name (str): Role name
access_key (str): AWS Access Key
secret_key (str): AWS Secret Key
Returns:
Boolean: True if env exists else F... | cd6f118424ca17f6e65e28abefed39e89bd66b95 | 3,651,354 |
def group_delay(group_key, flights):
"""
Group the arrival delay flights based on keys.
:param group_key: Group key to use for categorization.
:param flights: List of flights matching from an origin airport.
:return: Dictionary containing the list of flights grouped.
"""
dict_of_group_flight... | 0ae760f7da7762b97d6d7a5d5503b280ed39f855 | 3,651,355 |
def create_matrix(
score_same_brackets, score_other_brackets, score_reverse_brackets,
score_brackets_dots, score_two_dots, add_score_for_seq_match,
mode='simple'):
"""
Function that create matrix that can be used for further analysis,
please take note, that mode must be the same in c... | 7979a72b70ae2910051943c714676aec3d291dbc | 3,651,356 |
def view_inv(inventory_list):
"""list -> None
empty string that adds Rental attributes
"""
inventory_string = ''
for item in inventory_list:
inventory_string += ('\nRental: ' + str(item[0])+ '\nQuantity: '+ str(item[1])+
'\nDeposit: '+"$"+ str(item[2])+"\nPr... | 540b6bb2597ba5686a070749c2526ad09be25d5f | 3,651,357 |
def generate_smb_proto_payload(*protos):
"""Generate SMB Protocol. Pakcet protos in order.
"""
hexdata = []
for proto in protos:
hexdata.extend(proto)
return "".join(hexdata) | 848fdad11941a6d917bd7969fb7ffb77025cd13d | 3,651,358 |
def FeatureGrad_LogDet(grad_feature):
"""Part of the RegTerm inside the integral
It calculates the logarithm of the determinant of the matrix [N_y x N_y] given by the scalar product of the gradients along the N_x axis.
Args:
grad_feature (array_like): [N_samples, N_y, N_x], where N_x is the input s... | a32b472c6c69b441be52911f5a2f82011c5cab00 | 3,651,359 |
def get_every_second_indexes(ser: pd.Series,
even_index=True) -> pd.core.series.Series:
"""Return all rows where the index is either even or odd.
If even_index is True return every index where idx % 2 == 0
If even_index is False return every index where idx % 2 != 0
Assume d... | eb8c3b3a377c34e047d7daa525226cac18e21b7b | 3,651,360 |
def preprocess_input(text):
"""
정제된 텍스트를 토큰화합니다
:param text: 정제된 텍스트
:return: 문장과 단어로 토큰화하여 분석에 투입할 준비를 마친 텍스트
"""
sentences = nltk.sent_tokenize(text)
tokens = [nltk.word_tokenize(sentence) for sentence in sentences]
return tokens | 902c1aa5fc98ad5180ef7db670afbc972089a307 | 3,651,362 |
def create_count_dictionaries_for_letter_placements(all_words_list):
"""Returns a tuple of dictionaries where the index of the tuple is the counts for that index of each word
>>> create_count_dictionaries_for_letter_placements(all_words_list)
(dictPosition0, dictPosition1, dictPosition2, dictPosition3, dic... | 4d45ddda36c64ccfb357367521aa1983d738ab7b | 3,651,363 |
def parse_known(key, val) -> str:
"""
maps string from html to to function for parsing
Args:
key: string from html
val: associated value in html
Returns:
str
"""
key_to_func = {}
key_to_func["left"] = parse_number
key_to_func["top"] = parse_number
key_to_func... | 680a38496c368e7bd13f5578f4312914ac63c7f7 | 3,651,364 |
def getRecordsPagination(page, filterRecords=''):
""" get all the records created by users to list them in the backend welcome page """
newpage = int(page)-1
offset = str(0) if int(page) == 1 \
else str(( int(conf.pagination) *newpage))
queryRecordsPagination = """
PREFIX prov: <http://www.w3.org/ns/prov#>
PR... | 97221f9cfebe615744bc3ef488e8daf3ddc0dca4 | 3,651,365 |
import scipy.integrate
def integrate_intensity(data_sets, id, nθ, iN, NCO2, color1, color2):
"""Integrate intensity ove angle theta
Arguments:
data_sets {[type]} -- [description]
id {[type]} -- [description]
nθ {[type]} -- [description]
iN {[type]} -- [description]
... | 8336347f8fbe9c690800ae3efec185ba1a0e610d | 3,651,366 |
def new(request, pk=""):
""" New CodeStand Entry
When user presses 'Associate new project' there is a Project Container
associated, then you need reuse this information in the form
:param request: HttpResponse
:param pk: int - Indicates which project must be loaded
"""
if re... | 432949f5d7ae6869078c729d86bafabac0f17871 | 3,651,367 |
def sideral(
date, longitude=0.0, model="mean", eop_correction=True, terms=106
): # pragma: no cover
"""Sideral time as a rotation matrix
"""
theta = _sideral(date, longitude, model, eop_correction, terms)
return rot3(np.deg2rad(-theta)) | 01f3209db8996ad1e11ded48da26d286253c5f7d | 3,651,368 |
from splitgraph.core.output import conn_string_to_dict
from typing import Type
import click
def _make_mount_handler_command(
handler_name: str, handler: Type[ForeignDataWrapperDataSource]
) -> Command:
"""Turn the mount handler function into a Click subcommand
with help text and kwarg/connection string pa... | 0e8aa0cf3973c265e0df2b1815afd65042fa5d14 | 3,651,369 |
def test_load_settings_onto_instrument(tmp_test_data_dir):
"""
Test that we can successfully load the settings of a dummy instrument
"""
# Always set datadir before instruments
set_datadir(tmp_test_data_dir)
def get_func():
return 20
tuid = "20210319-094728-327-69b211"
instr =... | 96f3d96b7a83989c390bcc629f39df618c553056 | 3,651,370 |
import html
def dashboard_3_update_graphs(n_intervals):
"""Update all the graphs."""
figures = load_data_make_graphs()
main_page_layout = html.Div(children=[
html.Div(className='row', children=[
make_sub_plot(figures, LAYOUT_COLUMNS[0]),
make_sub_plot(figures, LAYOUT_COLUM... | b0b67dd06540ffff3c09d2c0ce87d0e5edb44bdf | 3,651,371 |
import numpy as np
from mvpa2.datasets import Dataset
import copy
def fx(sl, dataset, roi_ids, results):
"""this requires the searchlight conditional attribute 'roi_feature_ids'
to be enabled"""
resmap = None
probmap = None
for resblock in results:
for res in resblock:
if res... | 6b5e968882d0fe2e27c9302bc2b821509cfaafa1 | 3,651,372 |
import pathlib
import stat
def check_file(file_name):
"""
test if file: exists and is writable or can be created
Args:
file_name (str): the file name
Returns:
(pathlib.Path): the path or None if problems
"""
if not file_name:
return None
path = path... | 5b8ff64795aa66d3be71444e158357c9b7a1b2c0 | 3,651,373 |
async def push(request):
"""Push handler. Authenticate, then return generator."""
if request.method != "POST":
return 405, {}, "Invalid request"
fingerprint = authenticate(request)
if not fingerprint:
return 403, {}, "Access denied"
# Get given file
payload = await request.get_... | aeedd0c0c336b756898a98460e15a24b3411c5c2 | 3,651,374 |
from urllib.request import urlretrieve
from urllib import urlretrieve
def getfile(url, outdir=None):
"""Function to fetch files using urllib
Works with ftp
"""
fn = os.path.split(url)[-1]
if outdir is not None:
fn = os.path.join(outdir, fn)
if not os.path.exists(fn):
#Find ap... | 9cf70384fd81f702c29316e51fed9ca80802f022 | 3,651,375 |
def isroutine(object):
"""Return true if the object is any kind of function or method."""
return (isbuiltin(object)
or isfunction(object)
or ismethod(object)
or ismethoddescriptor(object)) | 386893f99c8cdd00c5523ef7ce052784e6ae9ca8 | 3,651,376 |
import json
def account_upload_avatar():
"""Admin Account Upload Avatar Action.
*for Ajax only.
Methods:
POST
Args:
files: [name: 'userfile']
Returns:
status: {success: true/false}
"""
if request.method == 'POST':
re_helper = ReHelper()
data = re... | c17f93eb7e5e750508aa34aedeaffb5b9410f15e | 3,651,377 |
def get_front_end_url_expression(model_name, pk_expression, url_suffix=''):
"""
Gets an SQL expression that returns a front-end URL for an object.
:param model_name: key in settings.DATAHUB_FRONTEND_URL_PREFIXES
:param pk_expression: expression that resolves to the pk for the model
:param ur... | c763f1d891f35c36823bb2fb7791a3d145f57164 | 3,651,378 |
def mock_config_entry() -> MockConfigEntry:
"""Return the default mocked config entry."""
return MockConfigEntry(
title="KNX",
domain=KNX_DOMAIN,
data={
CONF_KNX_INDIVIDUAL_ADDRESS: XKNX.DEFAULT_ADDRESS,
ConnectionSchema.CONF_KNX_MCAST_GRP: DEFAULT_MCAST_GRP,
... | e8585d7c0f793e0636f29bb91d5533fc22a14a4b | 3,651,379 |
def load_escores(name_dataset, classifier, folds):
"""Excluir xxxxxxx Return escore in fold. """
escores=[]
escores.append(load_dict_file("escores/"+name_dataset +"_"+classifier +"_escore_grid_train"+str(folds)))
return escores
for index in range(folds):
escores.append(load_dict_file("escore... | 6afa5b7db023bec903dbab26203edc5d7c162280 | 3,651,380 |
def get_devices():
""" will also get devices ready
:return: a list of avaiable devices names, e.g., emulator-5556
"""
ret = []
p = sub.Popen(settings.ADB + ' devices', stdout=sub.PIPE, stderr=sub.PIPE, shell=True)
output, errors = p.communicate()
print output
segs = output.split("\n")
for seg in segs:
device... | b3b3a377483f694ecac7f57f6f76a40727be4eee | 3,651,381 |
import logging
import tqdm
import multiprocessing
def _proc_event_full(st, **kwargs):
"""
processings including
:param st:
:param kwargs:
:return:
"""
# instrument response removal, spectral whitening, temporal normalization
# autocorrelation and filter, then output results.
def i... | cd069f684fba1a8d037aa8d08245859098b25c1f | 3,651,382 |
import types
def optional_is_none(context, builder, sig, args):
"""Check if an Optional value is invalid
"""
[lty, rty] = sig.args
[lval, rval] = args
# Make sure None is on the right
if lty == types.none:
lty, rty = rty, lty
lval, rval = rval, lval
opt_type = lty
opt... | a00b6725b43e8d09e8261b228f58319a27b191f9 | 3,651,383 |
import logging
def get_volume_disk_capacity(pod_name, namespace, volume_name):
"""
Find the container in the specified pod that has a volume named
`volume_name` and run df -h or du -sb in that container to determine
the available space in the volume.
"""
api = get_api("v1", "Pod")
res = ap... | 29d20c5dfb481be9a58dec85a23e20b9abd9cc5f | 3,651,384 |
import re
def is_valid_battlefy_id(battlefy_id: str) -> bool:
"""
Verify a str is a Battlefy Id (20 <= length < 30) and is alphanumeric.
:param battlefy_id:
:return: Validity true/false
"""
return 20 <= len(battlefy_id) < 30 and re.match("^[A-Fa-f0-9]*$", battlefy_id) | ba3f79f4897425b87962f04506fdff1da684c122 | 3,651,385 |
def echo(word:str, n:int, toupper:bool=False) -> str:
"""
Repeat a given word some number of times.
:param word: word to repeat
:type word: str
:param n: number of repeats
:type n: int
:param toupper: return in all caps?
:type toupper: bool
:return: result
:return type: str
... | 62a68c1ff577781a84a58f124beec8d31b0b456c | 3,651,386 |
def verify_package_info(package_info):
"""Check if package_info points to a valid package dir (i.e. contains
at least an osg/ dir or an upstream/ dir).
"""
url = package_info['canon_url']
rev = package_info['revision']
command = ["svn", "ls", url, "-r", rev]
out, err = utils.sbacktick(comma... | 6a38e50c2ab121260cbaaa9c188f2470784e65fb | 3,651,387 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.