content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def get_motif_proteins(meme_db_file):
""" Hash motif_id's to protein names using the MEME DB file """
motif_protein = {}
for line in open(meme_db_file):
a = line.split()
if len(a) > 0 and a[0] == 'MOTIF':
if a[2][0] == '(':
motif_protein[a[1]] = a[2][1:a[2].find(')')]
else:
mot... | 88e42b84314593a965e7dd681ded612914e35629 | 3,650,449 |
def pixellate_bboxes(im, bboxes, cell_size=(5,6), expand_per=0.0):
"""Pixellates ROI using Nearest Neighbor inerpolation
:param im: (numpy.ndarray) image BGR
:param bbox: (BBox)
:param cell_size: (int, int) pixellated cell size
:returns (numpy.ndarray) BGR image
"""
if not bboxes:
return im
elif not... | 8c028714467c350dfd799671b0b18739705393ba | 3,650,451 |
def StepToGeom_MakeHyperbola2d_Convert(*args):
"""
:param SC:
:type SC: Handle_StepGeom_Hyperbola &
:param CC:
:type CC: Handle_Geom2d_Hyperbola &
:rtype: bool
"""
return _StepToGeom.StepToGeom_MakeHyperbola2d_Convert(*args) | 6896b27c10526b3a7f1d5840a63209a6f30d163e | 3,650,453 |
def create_dict(local=None, field=None, **kwargs):
"""
以字典的形式从局部变量locals()中获取指定的变量
:param local: dict
:param field: str[] 指定需要从local中读取的变量名称
:param kwargs: 需要将变量指定额外名称时使用
:return: dict
"""
if field is None or local is None:
return {}
result = {k: v for k, v in local.items() ... | 19aceef7f648cc72f29fceba811085cde9d6d587 | 3,650,454 |
def sum_list_for_datalist(list):
"""
DB에 저장할 때, 기준일로부터 과거 데이터가 존재하지 않을 경우에는
0을 return 한다.
:param list:
:return: float or int
"""
mysum = 0
for i in range(0, len(list)):
if list[i] == 0:
return 0
mysum = mysum + list[i]
return mysum | bae8966f64c642176d92d31c27df691e0f255d6a | 3,650,455 |
def elu(x, alpha=1.):
"""Exponential linear unit.
Arguments:
x {tensor} -- Input float tensor to perform activation.
alpha {float} -- A scalar, slope of negative section.
Returns:
tensor -- Output of exponential linear activation
"""
return x * (x > 0) + alpha * (tf... | c40c7aa4a0553dc6b0b6c6dd9f583a701f022e70 | 3,650,456 |
def coalesce(*args):
"""
Compute the first non-null value(s) from the passed arguments in
left-to-right order. This is also known as "combine_first" in pandas.
Parameters
----------
*args : variable-length value list
Examples
--------
>>> import ibis
>>> expr1 = None
>>> ex... | 0fb1af5db75c7ad65f470e348d76d0f289ba5ff2 | 3,650,457 |
import json
def get_analysis(poem, operations, rhyme_analysis=False, alternative_output=False):
"""
View for /analysis that perform an analysis of poem running the different
operations on it.
:param poem: A UTF-8 encoded byte string with the text of the poem
:param operations: List of strings with... | 1f40376a4ecbbe6453caa909406f595707cc44be | 3,650,458 |
def get_detail_root():
"""
Get the detail storage path in the git project
"""
return get_root() / '.detail' | aa2c30ed839d32e084a11c52f17af621ecfb9011 | 3,650,459 |
def solve(strs, m, n):
"""
2D 0-1 knapsack
"""
def count(s):
m, n = 0, 0
for c in s:
if c == "0":
m += 1
elif c == "1":
n += 1
return m, n
dp = []
for _ in range(m + 1):
dp.append([0] * (n + 1))
for s ... | 3fb2b16fc9059227c0edce1199269988d18cb908 | 3,650,460 |
def bk_category_chosen_category():
"""Returns chosen category for creating bk_category object."""
return "Bread" | cbf1c933e5c2b69214e828afaab5babdba61dca8 | 3,650,461 |
import math
def apply_weights(
events,
total_num=1214165.85244438, # for chips_1200
nuel_frac=0.00003202064566, # for chips_1200
anuel_frac=0.00000208200747, # for chips_1200
numu_frac=0.00276174709613, # for chips_1200
anumu_frac=0.00006042213136, # for chips_1200
cosmic_frac=0.99714... | 81f35a51b3d28577204087511f9c405ff56afaaa | 3,650,462 |
def _pipe_line_with_colons(colwidths, colaligns):
"""Return a horizontal line with optional colons to indicate column's
alignment (as in `pipe` output format)."""
segments = [_pipe_segment_with_colons(a, w) for a, w in zip(colaligns, colwidths)]
return "|" + "|".join(segments) + "|" | 76dd17c761e7adb06fe57c5210645a4fe3872374 | 3,650,463 |
from datetime import datetime
def convert_to_dates(start, end):
"""
CTD - Convert two strings to datetimes in format 'xx:xx'
param start: String - First string to convert
param end: String - Second string to convert
return: datetime - Two datetimes
"""
start = datetime.strptime(start, "%H:... | 53ffb9924d31385aac2eafc66fe7a6159e5a310d | 3,650,464 |
def flipud(m):
"""
Flips the entries in each column in the up/down direction.
Rows are preserved, but appear in a different order than before.
Args:
m (Tensor): Input array.
Returns:
Tensor.
Raises:
TypeError: If the input is not a tensor.
Supported Platforms:
... | 06770689d23ca365fb57a6b9d1e74654b30ddaf2 | 3,650,465 |
def get_book_url(tool_name, category):
"""Get the link to the help documentation of the tool.
Args:
tool_name (str): The name of the tool.
category (str): The category of the tool.
Returns:
str: The URL to help documentation.
"""
prefix = "https://jblindsay.github.io/wbt_bo... | daf6c8e0832295914a03b002b548a82e2949612a | 3,650,466 |
import hashlib
def game_hash(s):
"""Generate hash-based identifier for a game account based on the
text of the game.
"""
def int_to_base(n):
alphabet = "BCDFGHJKLMNPQRSTVWXYZ"
base = len(alphabet)
if n < base:
return alphabet[n]
return int_to_base(n // base)... | c218a2607390916117921fe0f68fc23fedd51fc3 | 3,650,467 |
import math
def thumbnail_url(bbox, layers, qgis_project, style=None, internal=True):
"""Internal function to generate the URL for the thumbnail.
:param bbox: The bounding box to use in the format [left,bottom,right,top].
:type bbox: list
:param layers: Name of the layer to use.
:type layers: ba... | aa405eae72eacd7fd7b842bf569cc1ba3bc19315 | 3,650,468 |
def evaluate_prediction_power(df, num_days=1):
""""
Applies a shift to the model for the number of days given, default to 1, and feed the data to
a linear regression model. Evaluate the results using score and print it.
"""
scores = {}
print "Num days: {}".format(range(num_days))
for... | d4e91c8eb656fea8fce16cc16eb1588415c80849 | 3,650,469 |
def get_select_file_dialog_dir():
""""
Return the directory that should be displayed by default
in file dialogs.
"""
directory = CONF.get('main', 'select_file_dialog_dir', get_home_dir())
directory = directory if osp.exists(directory) else get_home_dir()
return directory | 9ae485caf5c5162e0b0e4082cee3e99925861717 | 3,650,470 |
def join_collections(sql_query: sql.SQLQuery) -> QueryExpression:
"""Join together multiple collections to return their documents in the response.
Params:
-------
sql_query: SQLQuery object with information about the query params.
Returns:
--------
An FQL query expression for joined and fi... | 62ad0cbad609e8218b4ac9d78f893fbcfc90618e | 3,650,473 |
def querylist(query, encoding='utf-8', errors='replace'):
"""Split the query component into individual `name=value` pairs and
return a list of `(name, value)` tuples.
"""
if query:
qsl = [query]
else:
return []
if isinstance(query, bytes):
QUERYSEP = (b';', b'&')
... | 25f726aa76c3b34a9aebc5e111b28162d0b91e3f | 3,650,474 |
def rotate_space_123(angles):
"""Returns the direction cosine matrix relating a reference frame B
rotated relative to reference frame A through the x, y, then z axes of
reference frame A (spaced fixed rotations).
Parameters
----------
angles : numpy.array or list or tuple, shape(3,)
Thr... | f62ac16e63591c4852681479ab9d39227bad3dfc | 3,650,475 |
def get_tac_resource(url):
"""
Get the requested resource or update resource using Tacoma account
:returns: http response with content in xml
"""
response = None
response = TrumbaTac.getURL(url, {"Accept": "application/xml"})
_log_xml_resp("Tacoma", url, response)
return response | 4d3fce0c7c65a880bf565c79285bcda081d4ef5a | 3,650,477 |
def cosweightlat(darray, lat1, lat2):
"""Calculate the weighted average for an [:,lat] array over the region
lat1 to lat2
"""
# flip latitudes if they are decreasing
if (darray.lat[0] > darray.lat[darray.lat.size -1]):
print("flipping latitudes")
darray = darray.sortby('lat')
r... | 87a8722d4d0b7004007fbce966a5ce99a6e51983 | 3,650,478 |
def _GetSoftMaxResponse(goal_embedding, scene_spatial):
"""Max response of an embeddings across a spatial feature map.
The goal_embedding is multiplied across the spatial dimensions of the
scene_spatial to generate a heatmap. Then the spatial softmax-pooled value of
this heatmap is returned. If the goal_embedd... | 547e61b403d99f2c0a4b5a0f78c03f7051a10d5c | 3,650,479 |
def summarize_star(star):
"""return one line summary of star"""
if star.find('name').text[-2] == ' ':
name = star.find('name').text[-1]
else:
name = ' '
mass = format_star_mass_str(star)
radius = format_star_radius_str(star)
temp = format_body_temp_str(star)
metallicity = for... | f9860d742a646637e4b725e39151ed8f5e8adf0f | 3,650,480 |
def to_unicode(text, encoding='utf8', errors='strict'):
"""Convert a string (bytestring in `encoding` or unicode), to unicode."""
if isinstance(text, unicode):
return text
return unicode(text, encoding, errors=errors) | 1acb85930349832259e9309fed3669fbd1114cad | 3,650,481 |
def parse_pipfile():
"""Reads package requirements from Pipfile."""
cfg = ConfigParser()
cfg.read("Pipfile")
dev_packages = [p.strip('"') for p in cfg["dev-packages"]]
relevant_packages = [
p.strip('"') for p in cfg["packages"] if "nested-dataclasses" not in p
]
return relevant_packa... | 72f559193b77989afc3aa200b6806ef051280673 | 3,650,482 |
from typing import Mapping
def print_dist(d, height=12, pch="o", show_number=False,
title=None):
""" Printing a figure of given distribution
Parameters
----------
d: dict, list
a dictionary or a list, contains pairs of: "key" -> "count_value"
height: int
number of maximum lines f... | d6636edbca5b16de8984c36bf9533ae963e21e0e | 3,650,483 |
def count_primes(num):
"""
Write a function that returns the number
of prime numbers that exist up to and including a given number
:param num: int
:return: int
"""
count = 0
lower = int(input())
upper = int(input())
for num in range(lower, upper + 1):
if num > 1:
... | 7a544265f3a7eca9118b0647bc8926c655cdb8ec | 3,650,485 |
def run_experiment(config):
"""
Run the experiment.
Args:
config: The configuration dictionary.
Returns:
The experiment result.
"""
return None | b12a8a5cbdb03d60ca618826f20c9a731a39fd2a | 3,650,486 |
def read_notification(notification_id):
"""Marks a notification as read."""
notification = Notification.query.get_or_404(notification_id)
if notification.recipient_email != current_user.email:
abort(401)
notification.is_read = True
db.session.add(notification)
db.session.commit()
ret... | b2d4066be7b202d680415831fa6d3aa60e2896dc | 3,650,487 |
def grayscale_blur(image):
"""
Convert image to gray and blur it.
"""
image_gray = cv.cvtColor(image, cv.COLOR_BGR2GRAY)
image_gray = cv.blur(image_gray, (3, 3))
return image_gray | 4e8bf0479c653a3ed073481ad71e2530527ec4a3 | 3,650,488 |
import hmac
def calculate_stream_hmac(stream, hmac_key):
"""Calculate a stream's HMAC code with the given key."""
stream.seek(0)
hash_hmac = hmac.new(bytearray(hmac_key, "utf-8"), digestmod=HASH_FUNCTION)
while True:
buf = stream.read(4096)
if not buf:
break
hash_hm... | 35da77cc708b4dc8a256fbfcc012da8c68868c8c | 3,650,489 |
import re
def convert_tac(ThreeAddressCode):
"""Reads three adress code generated from parser and converts to TAC for codegen;
generates the three_addr_code along with leaders;
populates generate symbol table as per three_addr_code"""
for i in range(ThreeAddressCode.length()):
three_addr_inst... | 4a9408cfbd6b6f79a618b7eb89aa55e6aab25689 | 3,650,491 |
def is_english_score(bigrams, word):
"""Calculate the score of a word."""
prob = 1
for w1, w2 in zip("!" + word, word + "!"):
bigram = f"{w1}{w2}"
if bigram in bigrams:
prob *= bigrams[bigram] # / float(bigrams['total'] + 1)
else:
print("%s not found" % bigra... | 834e28a32806d0599f5df97d978bc6b9c1a51da7 | 3,650,492 |
def cat(fname, fallback=_DEFAULT, binary=True):
"""Return file content.
fallback: the value returned in case the file does not exist or
cannot be read
binary: whether to open the file in binary or text mode.
"""
try:
with open_binary(fname) if binary else open_text(fname) as f:... | b3f645d79607f1ed986fe76aa20689d0860ef9ca | 3,650,493 |
import codecs
def createStringObject(string):
"""
Given a string (either a ``str`` or ``unicode``), create a
:class:`ByteStringObject<ByteStringObject>` or a
:class:`TextStringObject<TextStringObject>` to represent the string.
"""
if isinstance(string, string_type):
return TextStringOb... | 07c0ca42faa2b68dc347e1edad7f70a07930d891 | 3,650,495 |
import win32com.client
def _get_windows_network_adapters():
"""Get the list of windows network adapters."""
wbem_locator = win32com.client.Dispatch('WbemScripting.SWbemLocator')
wbem_service = wbem_locator.ConnectServer('.', 'root\cimv2')
wbem_network_adapters = wbem_service.InstancesOf('Win32_Network... | 796c25089411633d11b28fdd9c23d900db7005f0 | 3,650,496 |
def project(dim, states):
"""Qiskit wrapper of projection operator.
"""
ket, bra = states
if ket in range(dim) and bra in range(dim):
return st.basis(dim, ket) * st.basis(dim, bra).dag()
else:
raise Exception('States are specified on the outside of Hilbert space %s' % states) | 351a190ec183264af58de15944efb3af255c5b03 | 3,650,497 |
def check_service_status(ssh_conn_obj, service_name, status="running", device='server'):
"""
Author: Chaitanya Vella (chaitanya-vella.kumar@broadcom.com)
Function to check the service status
:param ssh_conn_obj:
:param service_name:
:param status:
:return:
"""
st.log("##### Checking ... | d8f2a9be7a784ad874d218601fdc043babdafe6e | 3,650,498 |
def _persist_block(block_node, block_map):
"""produce persistent binary data for a single block
Children block are assumed to be already persisted and present in
block_map.
"""
data = tuple(_to_value(v, block_map) for v in block_node)
return S_BLOCK.pack(*data) | 2fb97099135fe931d1d387ed616b152ed7c28b34 | 3,650,499 |
import logging
def get_sagemaker_feature_group(feature_group_name: str):
"""Used to check if there is an existing feature group with a given feature_group_name."""
try:
return sagemaker_client().describe_feature_group(FeatureGroupName=feature_group_name)
except botocore.exceptions.ClientError as e... | 1e94e894b1686a6833df51f1006f3f845a9e63b4 | 3,650,501 |
def check_system(command, message, exit=0, user=None, stdin=None, shell=False, timeout=None, timeout_signal='TERM'):
"""Runs the command and checks its exit status code.
Handles all of the common steps associated with running a system command:
runs the command, checks its exit status code against the expec... | 31d83941d5198d0786a6a67a4b1bcd320c26218a | 3,650,502 |
import json
def getJson(file, filters={}):
"""Given a specific JSON file (string) and a set of filters (dictionary
key-values pairs), will return a JSON-formatted tree of the matching data
entries from that file (starting as a null-key list of objects).
"""
with open(file, 'r') as f:
j = json.loads(f.rea... | 7b6832eae476eef48584690d993c2dee301bb565 | 3,650,504 |
def underline_node_formatter(nodetext, optionstext, caller=None):
"""
Draws a node with underlines '_____' around it.
"""
nodetext_width_max = max(m_len(line) for line in nodetext.split("\n"))
options_width_max = max(m_len(line) for line in optionstext.split("\n"))
total_width = max(options_widt... | 598e3aaf875b2539b93ec03d8665cc8011872015 | 3,650,505 |
def layers(vgg_layer3_out, vgg_layer4_out, vgg_layer7_out, num_classes):
"""
Create the layers for a fully convolutional network. Build skip-layers using the vgg layers.
:param vgg_layer3_out: TF Tensor for VGG Layer 3 output
:param vgg_layer4_out: TF Tensor for VGG Layer 4 output
:param vgg_layer7... | cf907d29555fbb7e9a11a1b2f6981637a977bf48 | 3,650,507 |
def determine_issues(project):
"""
Get the list of issues of a project.
:rtype: list
"""
issues = project["Issue"]
if not isinstance(issues, list):
return [issues]
return issues | 7b8b670e4ad5a7ae49f3541c87026dd603406c9f | 3,650,508 |
def get_media_after_date(mountpoint: str, date:str):
"""
Date format in EXIF yyyy:mm:dd, look for EXIF:CreateDate
"""
metadata = get_media_list(mountpoint)
filtered_meta = list()
for m in metadata:
if 'File:FileModifyDate' in m:
if is_after(m['File:FileModifyDate'].split(' ')... | 950c937540bd44cd1f577f1ee763262dad51d353 | 3,650,510 |
import random
def run_normal_game():
"""Run a complex game, like the real thing."""
stage = create_stage()
contestant_first_pick = random.randrange(3)
montys_pick_algorithm(stage, contestant_first_pick)
contestant_second_pick = contestants_second_pick_algorithm(stage, contestant_first_pick)
... | 04f3e8805b3b7d7d9e9f631eee635c4b9af75fdf | 3,650,511 |
def reformat_wolfram_entries(titles, entries):
"""Reformat Wolfram entries."""
output_list = []
for title, entry in zip(titles, entries):
try:
if ' |' in entry:
entry = '\n\t{0}'.format(entry.replace(' |', ':')
.replace('\n', '\n\t... | ba236671187ba4ab80fb013b3ee40c6ae58cc1c8 | 3,650,512 |
import six
def GetAndValidateRowId(row_dict):
"""Returns the integer ID for a new Row.
This method is also responsible for validating the input fields related
to making the new row ID.
Args:
row_dict: A dictionary obtained from the input JSON.
Returns:
An integer row ID.
Raises:
BadRequest... | be9f096ddb8bba036d1fa06cdd3565296a949762 | 3,650,514 |
def generate_test_cases(ukernel, channel_tile, pixel_tile, isa):
"""Generates all tests cases for a BILINEAR micro-kernel.
Args:
ukernel: C name of the micro-kernel function.
channel_tile: Number of channels processed per one iteration of the inner
loop of the micro-kernel.
pixel_tile... | 4fe3243c3f8d2ab3ce7861b46aa96ee79ef1014a | 3,650,515 |
def get_file_range(ase, offsets, timeout=None):
# type: (blobxfer.models.azure.StorageEntity,
# blobxfer.models.download.Offsets, int) -> bytes
"""Retrieve file range
:param blobxfer.models.azure.StorageEntity ase: Azure StorageEntity
:param blobxfer.models.download.Offsets offsets: download ... | be4f2f06c64ee457152fe582128b36db1a1baae4 | 3,650,516 |
def parse_cli_args():
"""Return parsed command-line arguments."""
parser = ArgumentParser(description='parse and summarize a GLSL file')
parser.add_argument('path')
shader_type_names = [member.name for member in ShaderType]
parser.add_argument('shader_type', nargs='?',
choice... | a044e20ea91e05c09cccc118641dac68ce748142 | 3,650,517 |
def genus_species_name(genus, species):
"""Return name, genus with species if present.
Copes with species being None (or empty string).
"""
# This is a simple function, centralising it for consistency
assert genus and genus == genus.strip(), repr(genus)
if species:
assert species == spe... | 1fed57c5c87dfd9362262a69429830c7103b7fca | 3,650,518 |
def _native_set_to_python_list(typ, payload, c):
"""
Create a Python list from a native set's items.
"""
nitems = payload.used
listobj = c.pyapi.list_new(nitems)
ok = cgutils.is_not_null(c.builder, listobj)
with c.builder.if_then(ok, likely=True):
index = cgutils.alloca_once_value(c.... | 808a10d85cc19c0b1c31b3e01afc9bbb402e1e90 | 3,650,519 |
def var_to_str(var):
"""Returns a string representation of the variable of a Jax expression."""
if isinstance(var, jax.core.Literal):
return str(var)
elif isinstance(var, jax.core.UnitVar):
return "*"
elif not isinstance(var, jax.core.Var):
raise ValueError(f"Idk what to do with this {type(var)}?")
... | 820645057359f8704cbd28d2545b9bb3c6e2f4d3 | 3,650,521 |
def lal_binary_neutron_star(
frequency_array, mass_1, mass_2, luminosity_distance, a_1, tilt_1,
phi_12, a_2, tilt_2, phi_jl, theta_jn, phase, lambda_1, lambda_2,
**kwargs):
""" A Binary Neutron Star waveform model using lalsimulation
Parameters
----------
frequency_array: array_... | 4641e65e9f422bb9be9a90f2f849ab58f1cdea51 | 3,650,522 |
def handledisc(tree):
"""Binarize discontinuous substitution sites.
>>> print(handledisc(Tree('(S (X 0 2 4))')))
(S (X 0 (X|<> 2 (X|<> 4))))
>>> print(handledisc(Tree('(S (X 0 2))')))
(S (X 0 (X|<> 2)))
"""
for a in tree.postorder(lambda n: len(n) > 1 and isinstance(n[0], int)):
binarize(a, rightmostunary=Tru... | 1e164d0174a4b31462369a10e56f9d69d936d18b | 3,650,523 |
def check_bounds(shape: Shape, point: Coord) -> bool:
"""Return ``True`` if ``point`` is valid index in ``shape``.
Args:
shape: Shape of two-dimensional array.
point: Two-dimensional coordinate.
Return:
True if ``point`` is within ``shape`` else ``False``.
"""
return (0 <... | 88ab89fddf3f85fc38f3404ed90f384f50337905 | 3,650,524 |
def logout(home=None):
"""
Logs out current session and redirects to home
:param str home: URL to redirect to after logout success
"""
flask_login.logout_user()
return redirect(request.args.get('redirect',
home or url_for('public.home'))) | bded682e6807532aa6382ea0855ee4d335da550f | 3,650,525 |
def N(u,i,p,knots):
"""
u: point for which a spline should be evaluated
i: spline knot
p: spline order
knots: all knots
Evaluates the spline basis of order p defined by knots
at knot i and point u.
"""
if p == 0:
if knots[int(i)] < u and u <=knots[int(i+1)]:
retu... | 0cd0756d558ee99b0ed32350860bc27f023fa88b | 3,650,526 |
def check_merge(s, idn) -> bool:
"""
Check whether a set of nodes is valid to merge
"""
found = False
in_size = None
out_size = None
stride = None
act = None
nds = [idn[i] for i in state2iset(s)]
if len(nds) == 1:
return True
for nd in nds:
if not isinstance(n... | d0edfee6150d7814c926fb59d413b61a989c9808 | 3,650,528 |
def typeMap(name, package=None):
""" typeMap(name: str) -> Module
Convert from C/C++ types into VisTrails Module type
"""
if package is None:
package = identifier
if isinstance(name, tuple):
return [typeMap(x, package) for x in name]
if name in typeMapDict:
return ty... | 6f8ed31cfe1eb88201d0131d43c0fb0da2295405 | 3,650,529 |
def _rm_from_diclist(diclist, key_to_check, value_to_check):
"""Function that removes an entry form a list of dictionaries if a key of
an entry matches a given value. If no value of the key_to_check matches the
value_to_check for all of the entries in the diclist, the same diclist will
be returned that ... | 89806ec5029923709bd44d794d75a84f440c5aa7 | 3,650,530 |
import scipy
def odr_linear(x, y, intercept=None, beta0=None):
"""
Performs orthogonal linear regression on x, y data.
Parameters
----------
x: array_like
x-data, 1D array. Must be the same lengths as `y`.
y: array_like
y-data, 1D array. Must be the same lengths as `x`.
... | 51fc464cb60e5b05645907d5ed3ec40d1b9cdb54 | 3,650,531 |
def get_centroid_world_coordinates(geo_trans, raster_x_size, raster_y_size, x_pixel_size, y_pixel_size):
"""Return the raster centroid in world coordinates
:param geo_trans: geo transformation
:type geo_trans: tuple with six values
:param raster_x_size: number of columns
:type raster_x_size: int
... | e0dd1d57cb020a85d9784f2c9bf22b4b8035ffae | 3,650,532 |
import json
def save_change_item(request):
"""
保存改变项
算法:在rquest_list中查找对应的uuid,找到后将数据更新其中
:param request:
:return:
"""
if request.method != 'POST':
return HttpResponse("数据异常.")
str_data = request.POST.get('jsons')
logger.info("change_item: " + str_data)
jsons = json.lo... | 434bd1e77690cd60dd163a39fd1cb90dd0cb4952 | 3,650,533 |
import pytdx.hq
import pytdx.util.best_ip
def get_lastest_stocklist():
"""
使用pytdx从网络获取最新券商列表
:return:DF格式,股票清单
"""
print(f"优选通达信行情服务器 也可直接更改为优选好的 {{'ip': '123.125.108.24', 'port': 7709}}")
# ipinfo = pytdx.util.best_ip.select_best_ip()
api = pytdx.hq.TdxHq_API()
# with api.connect(ipi... | 2953cbd800ad2e2b6bc6122ec225f34d165773ea | 3,650,534 |
def getStopWords(stopWordFileName):
"""Reads stop-words text file which is assumed to have one word per line.
Returns stopWordDict.
"""
stopWordDict = {}
stopWordFile = open(stopWordFileName, 'r')
for line in stopWordFile:
word = line.strip().lower()
stopWordDict[word] = None... | 8bb85683f257c35de9d04e4993b42cd758a802e6 | 3,650,538 |
def metade(valor):
"""
-> Realiza o calculo de metade salárial
:param valor: Valor do dinheiro
:param view: Visualizar ou não retorno formatado
:return: Retorna a metade do valor
"""
if not view:
return moeda(valor / 2)
else:
return valor / 2
return valor / 2 | fb1bbb605b8a0f1b8623ca70940377bd3c6a440a | 3,650,539 |
def monopole(uvecs: [float, np.ndarray], order: int=3) -> [float, np.ndarray]:
"""
Solution for I(r) = 1.
Also handles nonzero-w case.
Parameters
----------
uvecs: float or ndarray of float
The cartesian baselines in units of wavelengths. If a float, assumed to be the magnitude of
... | 6828b4014fc7970a4d85b6d04b6d3e16249d3dae | 3,650,540 |
def get_question(
numbers: OneOrManyOf(NUMBERS_AVAILABLE),
cases: OneOrManyOf(CASES_AVAILABLE),
num: hug.types.in_range(1, MAX_NUM + 1) = 10):
"""When queried for one or multiple numbers and cases, this endpoint returns a random question."""
questions = []
bag = NounCaseQuestionBag(
no... | b32d76f6ee7519935292743f6d7d8b8ad7357d3a | 3,650,541 |
from textwrap import dedent
def _print_attrs(attr, html=False):
"""
Given a Attr class will print out each registered attribute.
Parameters
----------
attr : `sunpy.net.attr.Attr`
The attr class/type to print for.
html : bool
Will return a html table instead.
Returns
... | 5044764b8799eed66d3e11fe9423922d79fd9981 | 3,650,542 |
import struct
def create_wave_header(samplerate=44100, channels=2, bitspersample=16, duration=3600):
"""Generate a wave header from given params."""
# pylint: disable=no-member
file = BytesIO()
numsamples = samplerate * duration
# Generate format chunk
format_chunk_spec = b"<4sLHHLLHH"
fo... | b0b53b33733e5456e321cd7c276ad95754140f8a | 3,650,543 |
import unicodedata
import re
def xslugify(value):
"""
Converts to ASCII. Converts spaces to hyphens. Removes characters that
aren't alphanumerics, underscores, slash, or hyphens. Converts to
lowercase. Also strips leading and trailing whitespace.
(I.e., does the same as slugify, but also converts... | 7a8a3f00011a46465ccafdcaf1ac797577511b2b | 3,650,544 |
def firstcond(list1, list2):
"""this is a fixture for testing conditions when
the list is a four node list """
ll = LinkedList()
ll.insert(1, 5)
ll.insert(3, 9)
ll.insert(2, 4)
return ll | 6e50038285e84e986304de5d2b28bef0db32b63d | 3,650,545 |
def random_portfolio(n, k, mu=0., sd=0.01, corr=None, dt=1., nan_pct=0.):
""" Generate asset prices assuming multivariate geometric Brownian motion.
:param n: Number of time steps.
:param k: Number of assets.
:param mu: Drift parameter. Can be scalar or vector. Default is 0.
:param sd: Volatility o... | 86801609a44619565188cd58b1d519c2e326086b | 3,650,548 |
def superpose_images(obj, metadata, skip_overlaps=False,
num_frames_for_bkgd=100, every=1,
color_objs=False, disp_R=False, b=1.7, d=2,
false_color=False, cmap='jet', remove_positive_noise=True):
"""
Superposes images of an object onto one frame.
... | 10767c9d10e5d32af51a31f1f8eb85d8989bb5d4 | 3,650,550 |
def gen_s_linear(computed_data, param ):
"""Generate sensitivity matrix for wavelength dependent sensitivity modeled as line"""
mat=np.zeros((computed_data.shape[0],computed_data.shape[0]))
#print(mat.shape)
for i in range(computed_data.shape[0]):
for j in range(computed_data.shape[0]):
... | c18c31e65804d65ac7419a2037f889a0f9de2f96 | 3,650,551 |
import numpy
def upsample2(x):
"""
Up-sample a 2D array by a factor of 2 by interpolation.
Result is scaled by a factor of 4.
"""
n = [x.shape[0] * 2 - 1, x.shape[1] * 2 - 1] + list(x.shape[2:])
y = numpy.empty(n, x.dtype)
y[0::2, 0::2] = 4 * x
y[0::2, 1::2] = 2 * (x[:, :-1] + x[:, 1:]... | 4eb23d668154ac12755c0e65eeff485ac5e5dd23 | 3,650,552 |
import six
def mark_safe(s):
"""
Explicitly mark a string as safe for (HTML) output purposes. The returned
object can be used everywhere a string or unicode object is appropriate.
Can be called multiple times on a single string.
"""
if isinstance(s, SafeData):
return s
if isinstan... | dab8c0dfb78fd22fb35b5abc3680f74de8a1089a | 3,650,553 |
def index():
""" Root URL response """
return jsonify(name='Payment Demo REST API Service', version='1.0'), status.HTTP_200_OK | 2d370a9fdf1878f60af6de264d99193d06ff96d2 | 3,650,555 |
def unvoigt(A):
"""
Converts from 6x1 to 3x3
:param A: 6x1 Voigt vector (strain or stress)
:return: 3x3 symmetric tensor (strain or stress)
"""
a=np.zeros(shape=(3,3))
a[0,0]=A[0]
a[0,1]=A[5]
a[0,2]=A[4]
a[1,0]=A[5]
a[1,1]=A[1]
a[1,2]=A[3]
a[2,0]=A[4]
a[2,1]=A[3]
a[2,2]=A[2]
return (a) | 72b28fceedb5ae2d34c768d5c29b5924310ff2b3 | 3,650,556 |
def _calculate_rmsd(P, Q):
"""Calculates the root-mean-square distance between the points of P and Q.
The distance is taken as the minimum over all possible matchings. It is
zero if P and Q are identical and non-zero if not.
"""
distance_matrix = cdist(P, Q, metric='sqeuclidean')
matching = lin... | 22261e75edf3edf378fa30daa5c33abc68ff93cd | 3,650,558 |
def initialize_parameters():
"""
Initializes weight parameters to build a neural network with tensorflow. The shapes are:
W1 : [4, 4, 3, 8]
W2 : [2, 2, 8, 16]
Note that we will hard code the shape values in the function to make the grading simpler.
Normall... | 43481172a70ea88bcf5cfbc95792365c5af2ea52 | 3,650,559 |
import time
import random
import string
import hashlib
def generate_dynamic_secret(salt: str) -> str:
"""Creates a new overseas dynamic secret
:param salt: A ds salt
"""
t = int(time.time())
r = "".join(random.choices(string.ascii_letters, k=6))
h = hashlib.md5(f"salt={salt}&t={t}&r={r}".enco... | 2a9bdf00daea91f13f34724d1c744c17e9b4d6cf | 3,650,560 |
def is_sim_f(ts_kname):
""" Returns True if the TSDist is actually a similarity and not a distance
"""
return ts_kname in ('linear_allpairs',
'linear_crosscor',
'cross_correlation',
'hsdotprod_autocor_truncated',
... | 11c18983d8d411714ba3147d4734ad77c40ceedf | 3,650,562 |
import pika
from typing import Union
def initialise_pika_connection(
host: Text,
username: Text,
password: Text,
port: Union[Text, int] = 5672,
connection_attempts: int = 20,
retry_delay_in_seconds: float = 5,
) -> "BlockingConnection":
"""Create a Pika `BlockingConnection`.
Args:
... | 7364547a4836aea0b277098bed75b8c5ec874522 | 3,650,563 |
def units(arg_name, unit):
"""Decorator to define units for an input.
Associates a unit of measurement with an input.
Parameters
----------
arg_name : str
Name of the input to attach a unit to.
unit : str
Unit of measurement descriptor to use (e.g. "mm").
Example
-----... | 45bd1695cada5612e2ce9e39632ed1357556535f | 3,650,564 |
from typing import Callable
async def to_thread_task(func: Callable, *args, **kwargs) -> Task:
"""Assign task to thread"""
coro = to_thread(func, *args, **kwargs)
return create_task(coro) | ad666a91588a670be7babf84294f338f0148b8e1 | 3,650,565 |
from typing import Dict
from typing import Any
from typing import Optional
from typing import Union
from pathlib import Path
def combo2fname(
combo: Dict[str, Any],
folder: Optional[Union[str, Path]] = None,
ext: Optional[str] = ".pickle",
sig_figs: int = 8,
) -> str:
"""Converts a dict into a hum... | 9951171647167e39753546645f8e1f185d9fa55a | 3,650,567 |
def cls_from_str(name_str):
"""
Gets class of unit type from a string
Helper function for end-users entering the name of a unit type
and retrieving the class that contains stats for that unit type.
Args:
name_str: str
Returns:
UnitStats
"""
name_str = name_str.l... | 4dc26f8586065319a25f8965a5267308bd8dbfea | 3,650,568 |
def convert_to_github_url_with_token(url, token):
"""
Convert a Github URL to a git+https url that identifies via an Oauth token. This allows for installation of
private packages.
:param url: The url to convert into a Github access token oauth url.
:param token: The Github access token to use for th... | 9b9c5e17cb389eb938af1221518a6838e65712bc | 3,650,569 |
from datetime import datetime
import numpy
def get_numbers_of_papers(metrics):
"""
Convert the metrics into a format that is easier to work with. Year-ordered
numpy arrays.
"""
publications = metrics['histograms']['publications']
year, total, year_refereed, refereed = [], [], [], []
y = l... | ce8b079ea416ff01b4974ea7ae7aa82080321cbb | 3,650,570 |
import json
from typing import Dict
def test_base_provider_get_transform_json_exception(mock_name, mock_value):
"""
Test BaseProvider.get() with a json transform that raises an exception
"""
mock_data = json.dumps({mock_name: mock_value}) + "{"
class TestProvider(BaseProvider):
def _get(... | abb81b142a34f264466b808867bc3a7cc4460fcf | 3,650,571 |
def load_check_definitions(lang):
"""
Retrieve Trust Advisor check definitions
"""
retval = {}
resp = TA_C.describe_trusted_advisor_checks(language=lang)
if resp:
try:
checks = resp['checks']
retval = {a['id']:a for a in checks}
except ValueError:
... | 43bca091506d33270a7e0fa3ec6ca84e4c342bf6 | 3,650,572 |
def filter_phrase(comments, phrase):
"""Returns list of comments and replies filtered by substring."""
results = []
for comment in comments:
if phrase.lower() in comment.message.lower():
results.append(comment)
for reply in comment.replies:
if phrase.lower() in reply.... | 0865163f117550e36b2c21608739649b7b99f825 | 3,650,573 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.