content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import math
def calc_val_resize_value(input_image_size=(224, 224),
resize_inv_factor=0.875):
"""
Calculate image resize value for validation subset.
Parameters:
----------
input_image_size : tuple of 2 int
Main script arguments.
resize_inv_factor : float
... | 5a8bcb77d849e62ef5ecfad74f5a3470ab4cfe59 | 3,648,341 |
import requests
def fetch_http(url, location):
"""
Return a `Response` object built from fetching the content at a HTTP/HTTPS based `url` URL string
saving the content in a file at `location`
"""
r = requests.get(url)
with open(location, 'wb') as f:
f.write(r.content)
content_t... | b1229bec9c09528f5fb9dcdd14ee2cc6678410c4 | 3,648,342 |
def mat_normalize(mx):
"""Normalize sparse matrix"""
rowsum = np.array(mx.sum(1))
r_inv = np.power(rowsum, -0.5).flatten()
r_inv[np.isinf(r_inv)] = 0.
r_mat_inv = sp.diags(r_inv)
mx = r_mat_inv.dot(mx).dot(r_mat_inv)
return mx | 9caeaf660e7a11b7db558248deb3097e9cca2f57 | 3,648,343 |
def user_syntax_error(e, source_code):
"""Returns a representation of the syntax error for human consumption.
This is only meant for small user-provided strings. For input files,
prefer the regular Python format.
Args:
e: The SyntaxError object.
source_code: The source code.
Returns:
A multi-li... | 79272de37844b043656a98d796913769e89ebb17 | 3,648,345 |
import re
def check_comment(comment, changed):
""" Check the commit comment and return True if the comment is
acceptable and False if it is not."""
sections = re.match(COMMIT_PATTERN, comment)
if sections is None:
print(f"The comment \"{comment}\" is not in the recognised format.")
else:
... | 6ad96bb465e2079895ad87d35b4bc7a000312eaf | 3,648,346 |
def GetBankTaskSummary(bank_task):
""" Summarizes the bank task
params: bank_task = value of the object of type bank_task_t
returns: String with summary of the type.
"""
format_str = "{0: <#020x} {1: <16d} {2: <#020x} {3: <16d} {4: <16d} {5: <16d} {6: <16d} {7: <16d}"
out_string = forma... | afbc3b4e8707428dc951d5d199441923e477ac0c | 3,648,347 |
def angle(o1,o2):
"""
Find the angles between two DICOM orientation vectors
"""
o1 = np.array(o1)
o2 = np.array(o2)
o1a = o1[0:3]
o1b = o1[3:6]
o2a = o2[0:3]
o2b = o2[3:6]
norm_a = np.linalg.norm(o1a) * np.linalg.norm(o2a)
norm_b = np.linalg.norm(o1b) * np.linalg.norm... | db6211f4067339b7740eb52cc3f101f6ef69f08c | 3,648,348 |
def get_project_id_v3(user_section='user'):
"""Returns a project ID."""
r = authenticate_v3_config(user_section, scoped=True)
return r.json()["token"]["project"]["id"] | 7cbb004609e3623d6a5d4bbf45766ea753027f5c | 3,648,349 |
def get_platform_arches(pkgs_info, pkg_name):
"""."""
package_info = get_package_info(pkgs_info, pkg_name)
platforms_info = package_info.get('platforms', {})
platform_arches = platforms_info.get('arches', [])
return platform_arches | d6da2a95592f1ecf1e89935dfecef84fe2ee9313 | 3,648,350 |
from typing import Optional
def unformat_number(new_str: str, old_str: Optional[str], type_: str) -> str:
"""Undoes some of the locale formatting to ensure float(x) works."""
ret_ = new_str
if old_str is not None:
if type_ in ("int", "uint"):
new_str = new_str.replace(",", "")
... | 419698cf46c1f6d3620dbb8c6178f0ba387ef360 | 3,648,352 |
def is_triplet(tiles):
"""
Checks if the tiles form a triplet.
"""
return len(tiles) == 3 and are_all_equal(tiles) | a0223a0fde80c147de7e255db0a5563424d1a427 | 3,648,354 |
def cli(ctx, comment, metadata=""):
"""Add a canned comment
Output:
A dictionnary containing canned comment description
"""
return ctx.gi.cannedcomments.add_comment(comment, metadata=metadata) | bacfab650aac1a1785a61756a7cbf84aab7df77a | 3,648,355 |
def get_latest_slot_for_resources(latest, task, schedule_set):
"""
Finds the latest opportunity that a task may be executed
:param latest: type int
A maximum bound on the latest point where a task may be executed
:param task: type DAGSubTask
The task to obtain the latest starting slot fo... | 455f852152877c856d49882facabdd6faabad175 | 3,648,356 |
import requests
def _get_text(url: str):
"""
Get the text from a message url
Args:
url: rest call URL
Returns:
response: Request response
"""
response = requests.get(url["messageUrl"].split("?")[0])
return response | fe711167748ca6b0201da7501f3b38cc8af8651d | 3,648,357 |
def divideFacet(aFacet):
"""Will always return four facets, given one, rectangle or triangle."""
# Important: For all facets, first vertex built is always the most south-then-west, going counter-clockwise thereafter.
if len(aFacet) == 5:
# This is a triangle facet.
orient = aFacet[4] #... | 2e5891cb0ab7d23746ca18201be0f7360acc76b4 | 3,648,358 |
def compute_g(n):
"""g_k from DLMF 5.11.3/5.11.5"""
a = compute_a(2*n)
g = []
for k in range(n):
g.append(mp.sqrt(2)*mp.rf(0.5, k)*a[2*k])
return g | 86aeb38e4ecec67f539586b0a96aa95b396d0639 | 3,648,359 |
def get_colden(theta_xy, theta_xz, theta_yz, n_sample_factor=1.0,
directory=None, file_name='save.npy', quick=False,
gridrate=0.5, shift=[0, 0, 0], draw=False, save=False, verbose=False):
"""
Rotate gas into arbitrary direction
"""
if gridrate < 2**(-7):
boxsize... | bb19845492adfde70c85f3a8faf64784130ab7b9 | 3,648,362 |
def PyException_GetCause(space, w_exc):
"""Return the cause (another exception instance set by raise ... from ...)
associated with the exception as a new reference, as accessible from Python
through __cause__. If there is no cause associated, this returns
NULL."""
w_cause = space.getattr(w_exc, spa... | dce5c1df12af7074ce25387e493ccac1aaac27ec | 3,648,363 |
def row_interval(rows: int) -> Expression:
"""
Creates an interval of rows.
Example:
::
>>> tab.window(Over
>>> .partition_by(col('a'))
>>> .order_by(col('proctime'))
>>> .preceding(row_interval(4))
>>> .following(CURRENT_ROW)
... | eaa998eb3498eeed8034d43efb89eaa3cbaa5b2b | 3,648,365 |
from typing import Any
def build_post_async_retry_failed_request(*, json: Any = None, content: Any = None, **kwargs: Any) -> HttpRequest:
"""Long running post request, service returns a 202 to the initial request, with an entity that
contains ProvisioningState=’Creating’. Poll the endpoint indicated in the Az... | 867cf51bec949367ce2722ca16d35462947623f3 | 3,648,366 |
def splitclass(classofdevice):
"""
Splits the given class of device to return a 3-item tuple with the
major service class, major device class and minor device class values.
These values indicate the device's major services and the type of the
device (e.g. mobile phone, laptop, etc.). If you google ... | 37c19ab17293b4fd0c46cff24c30e349459f7bd0 | 3,648,367 |
def change_to_local_price(us_fee):
"""Get us dollar change price from redis and apply it on us_fee.
"""
dollar_change = RedisClient.get('dollar_change')
if not dollar_change:
raise ValueError(ERRORS['CHANGE_PRICE'])
Rial_fee = float(us_fee) * int(dollar_change)
return int(Rial_fee) | bdd89a461e84a6acb6f49f2fb0159a9fa7404b17 | 3,648,368 |
def get_positive(data_frame, column_name):
"""
Query given data frame for positive values, including zero
:param data_frame: Pandas data frame to query
:param column_name: column name to filter values by
:return: DataFrame view
"""
return data_frame.query(f'{column_name} >= 0') | 2aec7f611a1b181132f55f2f3ca73bf5025f2474 | 3,648,369 |
def axes(*args, **kwargs):
"""
Add an axes to the figure.
The axes is added at position *rect* specified by:
- ``axes()`` by itself creates a default full ``subplot(111)`` window axis.
- ``axes(rect, axisbg='w')`` where *rect* = [left, bottom, width,
height] in normalized (0, 1) units. *ax... | 1277afb8b3a6513129632216d8c3a6c2b5718449 | 3,648,370 |
def scrape_options_into_new_groups(source_groups, assignments):
"""Puts options from the :py:class:`OptionParser` and
:py:class:`OptionGroup` objects in `source_groups` into the keys of
`assignments` according to the values of `assignments`. An example:
:type source_groups: list of :py:class:`OptionPar... | 4524a975b604a146814c9c913d3727e0bd296368 | 3,648,371 |
def resnext56_32x2d_cifar10(classes=10, **kwargs):
"""
ResNeXt-56 (32x2d) model for CIFAR-10 from 'Aggregated Residual Transformations for Deep Neural Networks,'
http://arxiv.org/abs/1611.05431.
Parameters:
----------
classes : int, default 10
Number of classification classes.
pretr... | 110b9b4443d4761b7f89a3d01b28d2c4ec8eba00 | 3,648,372 |
def is_internet_file(url):
"""Return if url starts with http://, https://, or ftp://.
Args:
url (str): URL of the link
"""
return (
url.startswith("http://")
or url.startswith("https://")
or url.startswith("ftp://")
) | 00f9d90d580da3fe8f6cbc3604be61153b17a154 | 3,648,374 |
from .observable.zip import zip_
from typing import Any
from typing import Tuple
def zip(*args: Observable[Any]) -> Observable[Tuple[Any, ...]]:
"""Merges the specified observable sequences into one observable
sequence by creating a :class:`tuple` whenever all of the
observable sequences have produced an ... | c33915df586bb2c337d7fee275d4df30364cd704 | 3,648,375 |
def GetFilter(image_ref, holder):
"""Get the filter of occurrences request for container analysis API."""
filters = [
# Display only packages
'kind = "PACKAGE_MANAGER"',
# Display only compute metadata
'has_prefix(resource_url,"https://www.googleapis.com/compute/")',
]
client = holder.cl... | 276104cab3c9348151437548ecd69801f20e5363 | 3,648,376 |
def predict_image_paths(image_paths, model_path, target_size=(128, 128)):
"""Use a trained classifier to predict the class probabilities of a list of images
Returns most likely class and its probability
:param image_paths: list of path(s) to the image(s)
:param model_path: path to the pre-trained model... | 8071a178751ce25edbf664f1a69d1dd43b3e6290 | 3,648,377 |
def in_bounding_box(point):
"""Determine whether a point is in our downtown bounding box"""
lng, lat = point
in_lng_bounds = DOWNTOWN_BOUNDING_BOX[0] <= lng <= DOWNTOWN_BOUNDING_BOX[2]
in_lat_bounds = DOWNTOWN_BOUNDING_BOX[1] <= lat <= DOWNTOWN_BOUNDING_BOX[3]
return in_lng_bounds and in_lat_bounds | c4756c10bc45b81850f0e998be7bf420e355aa4d | 3,648,378 |
def __DataContainerERT_addFourPointData(self, *args, **kwargs):
"""Add a new data point to the end of the dataContainer.
Add a new 4 point measurement to the end of the dataContainer and increase
the data size by one. The index of the new data point is returned.
Parameters
----------
... | 11d42774e3e422aaa9a8fe664e5e4641b51248d4 | 3,648,379 |
def refresh_remote_vpsa(session, rvpsa_id, return_type=None, **kwargs):
"""
Refreshes information about a remote VPSA - such as discovering new pools
and updating how much free space remote pools have.
:type session: zadarapy.session.Session
:param session: A valid zadarapy.session.Session object. ... | 6acc4a049397862c72a21deb8e38f65af5c424a7 | 3,648,382 |
def zeros(shape, int32=False):
"""Return a blob of all zeros of the given shape with the correct float or
int data type.
"""
return np.zeros(shape, dtype=np.int32 if int32 else np.float32) | 68bb2960a3a364f01b8fcc39495e44562936c98f | 3,648,383 |
def _connect():
"""Connect to a XMPP server and return the connection.
Returns
-------
xmpp.Client
A xmpp client authenticated to a XMPP server.
"""
jid = xmpp.protocol.JID(settings.XMPP_PRIVATE_ADMIN_JID)
client = xmpp.Client(server=jid.getDomain(), port=settings.XMPP_PRIVATE_SERV... | 1d407d80c22a371205c85e9223164cfa01063781 | 3,648,384 |
def index():
"""Return the main page."""
return send_from_directory("static", "index.html") | 2dbbf0d103e78bcd503f8254aac7f8a1a45f9176 | 3,648,385 |
from typing import List
def get_groups(records_data: dict, default_group: str) -> List:
"""
Returns the specified groups in the
SQS Message
"""
groups = records_data["Groups"]
try:
if len(groups) > 0:
return groups
else:
return [default_group]
except... | 29ffe05da86816750b59bab03041d8bf43ca8961 | 3,648,386 |
def build_stats(history, eval_output, time_callback):
"""Normalizes and returns dictionary of stats.
Args:
history: Results of the training step. Supports both categorical_accuracy
and sparse_categorical_accuracy.
eval_output: Output of the eval step. Assumes first value is eval_loss and
second... | 3419bcc0b2441fd2ea67ddec0b50574017b71a75 | 3,648,387 |
def truncate_single_leafs(nd):
"""
>>> truncate_single_leafs(node(name='a', subs=[node(name='a', subs=None, layer='a')], layer=None))
node(name='a', subs=None, layer='a')
"""
if nd.layer:
return nd
if nd.subs and len(nd.subs) == 1:
if nd.subs[0].layer:
return node(nd.... | 46e837dbd84df3c2cad5c5597d56f3ba716146f8 | 3,648,388 |
def postprocess_output(output, example, postprocessor):
"""Applies postprocessing function on a translation output."""
# Send all parts to the postprocessing.
if postprocessor is None:
text = output.output[0]
score = None
align = None
else:
tgt_tokens = output.output
... | 57c30c1cf9178ae28ef97c8662ed2fe6559f5dd6 | 3,648,389 |
def get_aqua_timestamp(iyear,ichunk,branch_flag):
"""
outputs a timestamp string for model runs with a
predifined year-month-day timestamp split into
5 x 73 day chunks for a given year
"""
if branch_flag == 0:
if ichunk == 0:
timestamp = format(iyear,"04") + '-01-01-00000'
... | 7566da7f22ee31e7e17a86a908bb510c176d32ea | 3,648,390 |
def aggregate_native(gradients, f, m=None, **kwargs):
""" Multi-Krum rule.
Args:
gradients Non-empty list of gradients to aggregate
f Number of Byzantine gradients to tolerate
m Optional number of averaged gradients for Multi-Krum
... Ignored keyword-arguments
Returns:
Ag... | 6a0b6309c9296587f581d8d941896643e096a3d5 | 3,648,391 |
import types
def isNormalTmpVar(vName: types.VarNameT) -> bool:
"""Is it a normal tmp var"""
if NORMAL_TMPVAR_REGEX.fullmatch(vName):
return True
return False | 4ca52c849f913d15ede4c3ed4d4888d68ca5cd8b | 3,648,392 |
import time
def count_time(start):
"""
:param start:
:return: return the time in seconds
"""
end = time.time()
return end-start | 1945f6e6972b47d7bbdb6941ee7d80b8a6eedd9a | 3,648,394 |
def split_by_state(xs, ys, states):
"""
Splits the results get_frame_per_second into a list of continuos line segments,
divided by state. This is to plot multiple line segments with different color for
each segment.
"""
res = []
last_state = None
for x, y, s in zip(xs, ys, states):
... | 0a872617bd935f7c52ee0d10e759674969a19c4e | 3,648,395 |
def final_spectrum(t, age, LT, B, EMAX, R, V, dens, dist, Tfir, Ufir, Tnir, Unir, binss, tmin, ebreak, alpha1, alpha2):
"""
GAMERA computation of the particle spectrum (for the extraction of the
photon sed at the end of the evolution of the PWN)
http://libgamera.github.io/GAMERA/docs/time_de... | 00ce850d759739ffcb69a5af5c62325b39bd5446 | 3,648,396 |
def modal():
"""Contributions input controller for modal view.
request.vars.book_id: id of book, optional
request.vars.creator_id: id of creator, optional
if request.vars.book_id is provided, a contribution to a book is presumed.
if request.vars.creator_id is provided, a contribution to a creator ... | 13222d8e4d611fe0005f3df3db05f10c6c9fb057 | 3,648,397 |
def returns(data):
"""Returns for any number of days"""
try:
trading_days = len(data)
logger.info(
"Calculating Returns for {} trading days".format(trading_days))
df = pd.DataFrame()
df['daily_returns'] = data.pct_change(1)
mean_daily_returns = df['daily_retur... | c533433e23cb2f246cdb3f3d8f445afc9d0ea0bc | 3,648,398 |
def do_rot13_on_input(input_string, ordered_radix=ordered_rot13_radix):
""" Perform a rot13 encryption on the provided message.
"""
encrypted_message = str()
for char in input_string:
# Two possibilities: in radix, or NOT in radix.
if char in ordered_radix:
# must find inde... | ccf37364860a661498290245a408d7cc4edbf896 | 3,648,399 |
def pwr_y(x, a, b, e):
"""
Calculate the Power Law relation with a deviation term.
Parameters
----------
x : numeric
Input to Power Law relation.
a : numeric
Constant.
b : numeric
Exponent.
e : numeric
Deviation term.
Returns
-------
nume... | e736d9bb2e4305ef0dc0a360143a611b805f7612 | 3,648,400 |
def file_update_projects(file_id):
""" Page that allows users to interact with a single TMC file """
this_file = TMCFile.query.filter_by(uid=file_id).first()
project_form = AssignProjectsToFile()
if project_form.validate_on_submit():
data = dict((key, request.form.getlist(key) if len(... | 172d0caccb3e7ba39282cb6860fb80fca0a050bb | 3,648,401 |
def find_optimal_cut(edge, edge1, left, right):
"""Computes the index corresponding to the optimal cut such that applying
the function compute_blocks() to the sub-blocks defined by the cut reduces
the cost function comparing to the case when the function compute_blocks() is
applied to the whole matrix. ... | 63120c904a71b6dc40d75df6db19a5bdb619f9e2 | 3,648,402 |
def seq_to_networkx(header, seq, constr=None):
"""Convert sequence tuples to networkx graphs."""
graph = nx.Graph()
graph.graph['id'] = header.split()[0]
graph.graph['header'] = header
for id, character in enumerate(seq):
graph.add_node(id, label=character, position=id)
if id > 0:
... | 7c44b3aa0fb30637eda9bc7e960db1e3d65e7907 | 3,648,403 |
def add_vertex_edge_for_load_support(network, sup_dic, load_dic, bars_len, key_removed_dic):
"""
Post-Processing Function:
Adds vertices and edges in accordance with supports and loads
returns the cured network
"""
if not key_removed_dic:
load_sup_dic=merge_two_dicts(sup_dic, load_dic)
... | ce52cfac5e3bb58b31cfc1b2e243c435c5926d0f | 3,648,404 |
def mimicry(span):
"""Enrich the match."""
data = {'mimicry': span.lower_}
sexes = set()
for token in span:
if token.ent_type_ in {'female', 'male'}:
if token.lower_ in sexes:
return {}
sexes.add(token.lower_)
return data | 724d09156e97961049cb29d9f3c1f02ab5af48b0 | 3,648,405 |
def LeftBinarySearch(nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
low = 0
high = len(nums)
while low < high:
mid = (low + high) // 2
if nums[mid] < target:
low = mid + 1
else:
high = mid
assert l... | d08f72e1563ee91e9ca6c9cf95db4c794312aa59 | 3,648,406 |
async def security_rule_get(
hub, ctx, security_rule, security_group, resource_group, **kwargs
):
"""
.. versionadded:: 1.0.0
Get a security rule within a specified network security group.
:param name: The name of the security rule to query.
:param security_group: The network security group c... | 34fb0cc8c2399f3749970b1061e2d5d209b11750 | 3,648,408 |
def create_centroid_pos(Direction, Spacing, Size, position):
# dim0, dim1,dim2, label):
"""
:param Direction,Spacing, Size: from sitk raw.GetDirection(),GetSpacing(),GetSize()
:param position:[24,3]
:return:
"""
direction = np.round(list(Direction))
direc0 = direction[0:7:3]
direc1... | 67f252a237f294bdf738bf0b5e9a89aad51201d7 | 3,648,409 |
from sklearn.model_selection import GroupKFold
def group_split_data_cv(df, cv=5, split=0):
"""
Args:
cv: number of cv folds
split: index of the cv fold to return
Note that GroupKFold is not random
"""
splitter = GroupKFold(n_splits=cv)
split_generator = splitter.split(df, group... | 4d2fb6c62bdd313aa9b16d52b637adbfd1adc654 | 3,648,410 |
def encode(valeur,base):
""" int*int -->String
hyp valeur >=0
hypothèse : base maxi = 16
"""
chaine=""
if valeur>255 or valeur<0 :
return ""
for n in range (1,9) :
calcul = valeur % base
if (calcul)>9:
if calcul==10:
bit='A'
if... | c5fe7d129ab19d1f77ac9d5160f5d714a796c0a0 | 3,648,411 |
def main(request):
"""
Main admin page.
Displayes a paginated list of files configured source directory (sorted by
most recently modified) to be previewed, published, or prepared for
preview/publish.
"""
# get sorted archive list for this user
try:
archives = request.user.archiv... | 9f10a3546dbbd209b8d91e812c4190c3498b1c03 | 3,648,412 |
def parse_char(char, invert=False):
"""Return symbols depending on the binary input
Keyword arguments:
char -- binary integer streamed into the function
invert -- boolean to invert returned symbols
"""
if invert == False:
if char == 0:
return '.'
elif char == 1... | 38c0d1c150a1c8e8f7d2f3d1bde08ec3e5ceb65b | 3,648,413 |
def get_transformer_dim(transformer_name='affine'):
""" Returns the size of parametrization for a given transformer """
lookup = {'affine': 6,
'affinediffeo': 6,
'homografy': 9,
'CPAB': load_basis()['d'],
'TPS': 32
}
assert (transformer_na... | 8e61b2e135c2f5933955082b4d951ff2f88283b7 | 3,648,415 |
def ListVfses(client_urns):
"""Lists all known paths for a list of clients.
Args:
client_urns: A list of `ClientURN` instances.
Returns:
A list of `RDFURN` instances corresponding to VFS paths of given clients.
"""
vfs = set()
cur = set()
for client_urn in client_urns:
cur.update([
... | 20bf77875d099106e5190d02c0c62d38eb1a6590 | 3,648,416 |
def delete_product(productId):
"""Deletes product"""
response = product2.delete_product(productId)
return response | 394848c8b9c8803140744b8a1a1eb6995cd04bf7 | 3,648,417 |
def compute_face_normals(points, trilist):
"""
Compute per-face normals of the vertices given a list of
faces.
Parameters
----------
points : (N, 3) float32/float64 ndarray
The list of points to compute normals for.
trilist : (M, 3) int16/int32/int64 ndarray
The list of face... | 4bbe9f7311f6125fd73b028c984e09ee4f124791 | 3,648,418 |
def get_deletion_confirmation(poll):
"""Get the confirmation keyboard for poll deletion."""
delete_payload = f"{CallbackType.delete.value}:{poll.id}:0"
delete_all_payload = f"{CallbackType.delete_poll_with_messages.value}:{poll.id}:0"
locale = poll.user.locale
buttons = [
[
Inlin... | 6d741aa13d3d5234c53115b8b74c353fdce9e87e | 3,648,419 |
def ngram_tokenizer(lines, ngram_len=DEFAULT_NGRAM_LEN, template=False):
"""
Return an iterable of ngram Tokens of ngram length `ngram_len` computed from
the `lines` iterable of UNICODE strings. Treat the `lines` strings as
templated if `template` is True.
"""
if not lines:
return
n... | fb7f079ddee8bac10b2ae9efd306a482042b8a0f | 3,648,420 |
def list_datasets(service, project_id):
"""Lists BigQuery datasets.
Args:
service: BigQuery service object that is authenticated. Example: service = build('bigquery','v2', http=http)
project_id: string, Name of Google project
Returns:
List containing dataset names
"""
data... | 2712e6a99427ce3b141e7948bba36e8e724f82bc | 3,648,421 |
def tors(universe, seg, i):
"""Calculation of nucleic backbone dihedral angles.
The dihedral angles are alpha, beta, gamma, delta, epsilon, zeta, chi.
The dihedral is computed based on position of atoms for resid `i`.
Parameters
----------
universe : Universe
:class:`~MDAnalysis.core... | 1efcac83c7ec6689e33830daf011bead5199e5dd | 3,648,422 |
def get_metric(metric,midi_notes,Fe,nfft,nz=1e4,eps=10,**kwargs):
"""
returns the optimal transport loss matrix from a list of midi notes (interger indexes)
"""
nbnotes=len(midi_notes)
res=np.zeros((nfft/2,nbnotes))
f=np.fft.fftfreq(nfft,1.0/Fe)[:nfft/2]
f_note=[2.0**((n-60)*1./12)*440 for n... | f21717f239431fac2e37e6b59abfdcb6b964aa0c | 3,648,423 |
def octave(track, note, dur):
"""Generate the couple of blanche"""
track.append(Message('note_on', note=note, velocity=100, time=0))
track.append(Message('note_on', note=note + 12, velocity=100, time=0))
track.append(Message('note_off', note=note, velocity=64, time=dur))
track.append(Message('note_o... | c94391677849b1aef58df1a08ade0bae3fe691f5 | 3,648,424 |
def solveTrajectoryPickle(dir_path, file_name, only_plot=False, solver='original', **kwargs):
""" Rerun the trajectory solver on the given trajectory pickle file. """
# Load the pickles trajectory
traj_p = loadPickle(dir_path, file_name)
# Run the PyLIG trajectory solver
if solver == 'original':
... | a5b5dca042906e86eb153c8889466bff983af243 | 3,648,425 |
def load_data(path):
"""
读取.mat的原始eeg数据
:param path:
:return:
"""
data=scio.loadmat(path)
labels = data['categoryLabels'].transpose(1, 0)
X = data['X_3D'].transpose(2, 1, 0)
return X,labels | 69d540529b93705b3fb3a34a607da469825185f5 | 3,648,426 |
def distance_along_glacier(nx, map_dx):
"""Calculates the distance along the glacier in km.
Parameters
----------
nx : int
number of grid points
map_dx : int
grid point spacing
Returns
-------
ndarray
distance along the glacier in km.
"""
return np.linsp... | 58acc7f48b0f901b1c3e800ea6e98046805f855a | 3,648,427 |
def make_postdict_to_fetch_token(token_endpoint: str, grant_type: str,
code: str, client_id: str,
client_secret: str,
redirect_uri: str) -> dict:
"""POST dictionary is the API of the requests library"""
return {'u... | f366fc140c70d094ff99b28a369ac96b4c2a8b49 | 3,648,428 |
def _haxe_std_lib(ctx):
"""
_haxe_std_lib implementation.
Args:
ctx: Bazel context.
"""
toolchain = ctx.toolchains["@rules_haxe//:toolchain_type"]
build_source_file = ctx.actions.declare_file("StdBuild.hx")
toolchain.create_std_build(
ctx,
ctx.attr.target,
... | 7a29757f7fa9fdcd1942b73221633a0eb7afc2f8 | 3,648,429 |
def spread_match_network(expr_df_in, node_names_in):
"""
Matches S (spreadsheet of gene expressions) and N (network)
The function returns expr_df_out which is formed by reshuffling columns of
expr_df_in. Also, node_names_out is formed by reshuffling node_names_in. The
intersection of node_names_out ... | c0b78263a341d3b7682922eb9a948c21ab2e7e45 | 3,648,431 |
import io
def top_level(url, data):
"""Read top level names from compressed file."""
sb = io.BytesIO(data)
txt = None
with Archive(url, sb) as archive:
file = None
for name in archive.names:
if name.lower().endswith('top_level.txt'):
file = name
... | 0fe92b1d038248f5f759d19b1e27ad013b3592c2 | 3,648,432 |
import requests
def get_timeseries_data(request):
"""
AJAX Controller for getting time series data.
"""
return_obj = {}
# -------------------- #
# VERIFIES REQUEST #
# -------------------- #
if not (request.is_ajax() and request.method == "POST"):
return_obj["error"] = "... | d8bb691f99d4a993d2b8e7c7e52f079566f45a63 | 3,648,433 |
from typing import List
from typing import Tuple
import bisect
def line_col(lbreaks: List[int], pos: int) -> Tuple[int, int]:
"""
Returns the position within a text as (line, column)-tuple based
on a list of all line breaks, including -1 and EOF.
"""
if not lbreaks and pos >= 0:
return 0, ... | 6b99e3b19ed1a490e4a9cc284f99e875085f819a | 3,648,434 |
def sample_from_script(script_path, num_lines, chars_per_line):
"""Sample num_lines from a script.
Parameters
----------
script_path : str
Path to the script
num_lines : int
Number of lines to sample.
chars_per_line : int
Numer of consecutive characters... | 52e04582ec297ac512b2d2586524c7c4cb46b1d0 | 3,648,436 |
def is_valid_uuid(x):
"""Determine whether this is a valid hex-encoded uuid."""
if not x or len(x) != 36:
return False
return (parse_uuid(x) != None) | 707618844ddb4375c855e12ca2f75966a91d7c5b | 3,648,437 |
def wait_for_needle_list(
loops: int,
needle_list: list[tuple[str, tuple[int, int, int, int]]],
sleep_range: tuple[int, int],
):
"""
Works like vision.wait_for_needle(), except multiple needles can be
searched for simultaneously.
Args:
loops: The number of tries to look for each nee... | 4f09801f54d2f29aea18eb868c7ef44ab0532627 | 3,648,438 |
import random
def get_word():
"""Returns random word."""
words = ['Charlie', 'Woodstock', 'Snoopy', 'Lucy', 'Linus',
'Schroeder', 'Patty', 'Sally', 'Marcie']
return random.choice(words).upper() | c4437edc3a1e91cd90c342eda40cfd779364d9c1 | 3,648,439 |
from datetime import datetime
def parsed_json_to_dict(parsed):
"""
Convert parsed dict into dict with python built-in type
param:
parsed parsed dict by json decoder
"""
new_bangumi = {}
new_bangumi['name'] = parsed['name']
new_bangumi['start_date'] = datetime.strptime(
pa... | e3bb8306e19a16c9e82d5f6e96c9b4a3707c0446 | 3,648,441 |
import pandas
def plot_shift_type_by_frequency(tidy_schedule: pandas.DataFrame) -> tuple:
"""
Plots a bar graph of shift type frequencies.
:param tidy_schedule: A pandas data frame containing a schedule,
as loaded by load_tidy_schedule().
:type tidy_schedule: pandas.DataFrame
:return: A tuple... | 81fb649cd8439932bbbbf27d9690c5ab9f96e410 | 3,648,443 |
def load_image(path, size=None):
"""
Load the image from the given file-path and resize it to the given size if not None.
Eg: size = (width, height)
"""
img = Image.open(path)
if (size != None) and (size != ''):
img = img.resize(size=size, resample=Image.LANCZOS)
img = np.array(img... | e770ea3447ce8a7d236c4712859707b8e3cd8248 | 3,648,444 |
import secrets
import ipaddress
def call_wifi(label):
"""Wifi connect function
Parameters
----------
label : str
Output label
Returns
-------
None
"""
try:
# Setup wifi and connection
print(wifi.radio.connect(secrets['ssid'], secrets['password']))
... | a1514ff756b5217b8f79b4f9af882a234b1ad17d | 3,648,445 |
def load_normalized_face_landmarks():
"""
Loads the locations of each of the 68 landmarks
:return:
"""
normalized_face_landmarks = np.float32([
(0.0792396913815, 0.339223741112), (0.0829219487236, 0.456955367943),
(0.0967927109165, 0.575648016728), (0.122141515615, 0.691921601066),
... | 2dbd191371345c4382efa3573b54e281607da37c | 3,648,446 |
from datetime import datetime
from shutil import copyfile
def backup_file(file):
"""Create timestamp'd backup of a file
Args:
file (str): filepath
Returns:
backupfile(str)
"""
current_time = datetime.now()
time_stamp = current_time.strftime("%b-%d-%y-%H.%M.%S")
backupf... | 1c1b33028aab01b4e41ed3ef944202ecc53415df | 3,648,448 |
def svn_client_mergeinfo_log_eligible(*args):
"""
svn_client_mergeinfo_log_eligible(char path_or_url, svn_opt_revision_t peg_revision,
char merge_source_path_or_url, svn_opt_revision_t src_peg_revision,
svn_log_entry_receiver_t receiver,
svn_boolean_t discover_changed_paths,
ap... | 9f372556d56e0fdc88afc5b3fd35218fb46f3768 | 3,648,449 |
def share_nodes_sockets():
"""
Create a shared node layout where the simulation and analysis ranks share
compute nodes. Furthermore, they share sockets of the node.
"""
shared_sockets = SummitNode()
for i in range(10):
shared_sockets.cpu[i] = "simulation:{}".format(i)
shared_soc... | d34bfb1b97e4e3b06dee54a89c084dd404c3c6ca | 3,648,450 |
def _rle_decode(data):
"""
Decodes run-length-encoded `data`.
"""
if not data:
return data
new = b''
last = b''
for cur in data:
if last == b'\0':
new += last * cur
last = b''
else:
new += last
last = bytes([cur])
... | 8463ff6a20b3a39df7b67013d47fe81ed6d53477 | 3,648,452 |
def find_shift_between_two_models(model_1,model_2,shift_range=5,number_of_evaluations=10,rotation_angles=[0.,0.,0.],
cropping_model=0,initial_guess=[0.,0.,0.], method='brute_force',full_output=False):
"""
Find the correct shift alignment in 3D by using a different optimization... | 39dea881a5a00174b178d22910b5cee6d7ce48cd | 3,648,453 |
from typing import Optional
import requests
def get_url(
url: str,
stream: bool = False,
session: Optional[requests.Session] = None
) -> requests.Response:
"""Call requests.get() on a url and return the requests.Response."""
if not session:
session = retry_session()
resp = session.get(... | c056446cbb1966f79b472de2f140b9962246fd75 | 3,648,454 |
from typing import Optional
def uploadFromPath(localFilePath: str,
resource,
bucketName: str,
fileID: str,
headerArgs: Optional[dict] = None,
partSize: int = 50 << 20):
"""
Uploads a file to s3, using multipart uplo... | ee8ca7e177ab8538fd668a42111f86503b57edc1 | 3,648,455 |
def scale_log2lin(value):
"""
Scale value from log10 to linear scale: 10**(value/10)
Parameters
----------
value : float or array-like
Value or array to be scaled
Returns
-------
float or array-like
Scaled value
"""
return 10**(value/10) | 04f15a8b5a86a6e94dd6a0f657d7311d38da5dc0 | 3,648,456 |
from typing import Union
import torch
from typing import Optional
from typing import List
def train(
train_length:Union[int, TrainLength], model:nn.Module, dls:DataLoaders, loss_func:LossFunction,
opt:torch.optim.Optimizer, sched=None, metric:Optional[Metric]=None,
device=None, clip_grad:ClipGradOptions... | ad6e4796df66a38df2140060a2150f77b8d7c525 | 3,648,457 |
def _error_to_level(error):
"""Convert a boolean error field to 'Error' or 'Info' """
if error:
return 'Error'
else:
return 'Info' | b43e029a4bb14b10de4056758acecebc85546a95 | 3,648,458 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.