content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def blit_array(surface, array):
"""
Generates image pixels from a JNumeric array.
Arguments include destination Surface and array of integer colors.
JNumeric required as specified in numeric module.
"""
if not _initialized:
_init()
if len(array.shape) == 2:
data = numeric.tra... | 850b6451ecc780fd163f574176a8c5683174046e | 22,100 |
def soerp_numeric(slc, sqc, scp, var_moments, func0, title=None, debug=False,
silent=False):
"""
This performs the same moment calculations, but expects that all input
derivatives and moments have been put in standardized form. It can also
describe the variance contributions and print out any outpu... | b38e824f341b8b179ada92b53bdfd3f16c665f07 | 22,101 |
def generate_IO_examples(program, N, L, V):
""" Given a programs, randomly generates N IO examples.
using the specified length L for the input arrays. """
input_types = program.ins
input_nargs = len(input_types)
# Generate N input-output pairs
IO = []
for _ in range(N):
input_va... | 4449974cf5a1bd04a89e5575fb48362da8fa1621 | 22,102 |
import os
def populate_runtime_info(query, impala, converted_args, timeout_secs=maxint):
"""Runs the given query by itself repeatedly until the minimum memory is determined
with and without spilling. Potentially all fields in the Query class (except
'sql') will be populated by this method. 'required_mem_mb_with... | 1d8044e648efd7401b9e798830a1f158059ae851 | 22,103 |
def secrecy_capacity(dist, rvs=None, crvs=None, rv_mode=None, niter=None, bound_u=None):
"""
The rate at which X and Y can agree upon a key with Z eavesdropping,
and no public communication.
Parameters
----------
dist : Distribution
The distribution of interest.
rvs : iterable of it... | c55655847f9d9cf586bd4e274f72359d0241c349 | 22,104 |
def encrypt_message(partner, message):
"""
Encrypt a message
:param parner: Name of partner
:param message: Message as string
:return: Message as numbers
"""
matrix = get_encryption_matrix(get_key(get_private_filename(partner)))
rank = np.linalg.matrix_rank(matrix)
num_blocks = ... | e8e96f99f511afb3b91a9c264f8452e45b14e165 | 22,105 |
def create_event(title, start, end, capacity, location, coach, private):
"""Create event and submit to database"""
event = Class(title=title, start=start, end=end, capacity=capacity, location=location, coach=coach, free=capacity, private=private)
db.session.add(event)
db.session.commit()
return even... | 4a1b6314eee362f6ae7f35685cb09fe969175c0b | 22,106 |
def regret_obs(m_list, inputs, true_ymin=0):
"""Immediate regret using past observations.
Parameters
----------
m_list : list
A list of GPy models generated by `OptimalDesign`.
inputs : instance of `Inputs`
The input space.
true_ymin : float, optional
The minimum val... | e9cc2567f9740deae7b681cc754d20a387fbc894 | 22,107 |
import numpy
def pmat2cam_center(P):
"""
See Hartley & Zisserman (2003) p. 163
"""
assert P.shape == (3, 4)
determinant = numpy.linalg.det
# camera center
X = determinant([P[:, 1], P[:, 2], P[:, 3]])
Y = -determinant([P[:, 0], P[:, 2], P[:, 3]])
Z = determinant([P[:, 0], P[:, 1],... | f959eab9feeeafd90c3a2178b77d81e509ef1282 | 22,108 |
def _http_req(mocker):
"""Fixture providing HTTP Request mock."""
return mocker.Mock(spec=Request) | 651866118fd25909e50469cb92f35a9aa3a6d873 | 22,109 |
def transform_data(df, steps_per_floor_):
"""Transform original dataset.
:param df: Input DataFrame.
:param steps_per_floor_: The number of steps per-floor at 43 Tanner
Street.
:return: Transformed DataFrame.
"""
df_transformed = (
df
.select(
col('id'),
... | 163bedd83315828001f4cca2abdc130a2a77a55a | 22,110 |
import logging
def get_client(bucket):
"""Get the Storage Client appropriate for the bucket.
Args:
bucket (str): Bucket including
Returns:
~Storage: Client for interacting with the cloud.
"""
try:
protocol, bucket_name = str(bucket).lower().split('://', 1)
except Valu... | 46a27b4a028daa927507f3e8b0d5aeb453fd302b | 22,111 |
def extract_text(xml_string):
"""Get text from the body of the given NLM XML string.
Parameters
----------
xml_string : str
String containing valid NLM XML.
Returns
-------
str
Extracted plaintext.
"""
paragraphs = extract_paragraphs(xml_string)
if paragraphs:
... | f3e80d960837d8663d9711bd9696644f00ba21e9 | 22,112 |
import os
def get_processing_info(data_path, actual_names, labels):
"""
Iterates over the downloaded data and checks which one is in our database
Returns:
files_to_process: List of file paths to videos
labs_to_process: list of same length with corresponding labels
"""
files_to_proc... | 0e2ed514159bd230d9315d1b668ce8a59d36b545 | 22,113 |
def search_organizations(search_term: str = None, limit: str = None):
"""
Looks up organizations by name & location.
:param search_term: e.g. "College of Nursing" or "Chicago, IL".
:param limit: The maximum number of matches you'd like returned - defaults to 10, maximum is 50.
:returns: String cont... | 5523f6278b4eff5618979ce942fb175b20042079 | 22,114 |
def call_math_operator(value1, value2, op, default):
"""Return the result of the math operation on the given values."""
if not value1:
value1 = default
if not value2:
value2 = default
if not pyd.is_number(value1):
try:
value1 = float(value1)
except Exception... | da1a163e4079cfd885d8ca163939111c9291767b | 22,115 |
def addGems(ID, nbGems):
"""
Permet d'ajouter un nombre de gems à quelqu'un. Il nous faut son ID et le nombre de gems.
Si vous souhaitez en retirer mettez un nombre négatif.
Si il n'y a pas assez d'argent sur le compte la fonction retourne un nombre
strictement inférieur à 0.
"""
old_value =... | 6f3778cec488138101a78a072591babb832d7f95 | 22,116 |
def BertzCT(mol, cutoff=100, dMat=None, forceDMat=1):
""" A topological index meant to quantify "complexity" of molecules.
Consists of a sum of two terms, one representing the complexity
of the bonding, the other representing the complexity of the
distribution of heteroatoms.
From S. H. Bertz, J... | 0ca8119db47121dc22e0554e114e51ad916af455 | 22,117 |
def BOPTools_AlgoTools_CorrectRange(*args):
"""
* Correct shrunk range <aSR> taking into account 3D-curve resolution and corresp. tolerances' values of <aE1>, <aE2>
:param aE1:
:type aE1: TopoDS_Edge &
:param aE2:
:type aE2: TopoDS_Edge &
:param aSR:
:type aSR: IntTools_Range &
:param... | 491b1930a017940137aa2a59c630f995f0fc8366 | 22,118 |
from typing import cast
def OldValue(lval, mem, exec_opts):
# type: (lvalue_t, Mem, optview.Exec) -> value_t
"""
Used by s+='x' and (( i += 1 ))
TODO: We need a stricter and less ambiguous version for Oil.
Problem:
- why does lvalue have Indexed and Keyed, while sh_lhs_expr only has
IndexedName?
... | e7205a56fbec502e1d9a0a48864142f0cd7a82e5 | 22,119 |
from typing import Tuple
def approx_min_k(operand: Array,
k: int,
reduction_dimension: int = -1,
recall_target: float = 0.95,
reduction_input_size_override: int = -1,
aggregate_to_topk: bool = True) -> Tuple[Array, Array]:
"""Retur... | e4716369b4371b27ccabaaa61d2157e513cf06ed | 22,120 |
def sitemap_host_xml():
"""Supplementary Sitemap XML for Host Pages"""
database_connection.reconnect()
hosts = ww_host.info.retrieve_all(database_connection)
sitemap = render_template("sitemaps/hosts.xml",
hosts=hosts)
return Response(sitemap, mimetype="text/xml") | 79b21d1465ef84c1cfaf192be0b2fa5bf07f1014 | 22,121 |
def WTC(df,N):
"""Within Topic Coherence Measure.
[Note]
It ignores a word which does not have trained word vector.
Parameters
----------
df : Word-Topic distribution K by V
where K is number of topics and V is number of words
N : Number of top N words ... | b5b50eef85f6e12c54c9ec16a2f7264aa057d344 | 22,122 |
def extract_static_override_features(
static_overrides):
"""Extract static feature override values.
Args:
static_overrides: A dataframe that contains the value for static overrides
to be passed to the GAM Encoders.
Returns:
A mapping from feature name to location and then to the override value... | 9425674eb2e0578ecbc926b249a6eb2f6afb37d0 | 22,123 |
def job_list_View(request):
"""
"""
job_list = Job.objects.filter()
paginator = Paginator(job_list, 10)
page_number = request.GET.get('page')
page_obj = paginator.get_page(page_number)
context = {
'page_obj': page_obj,
}
return render(request, 'jobapp/job-list.html', cont... | a2928ea255ff3cb044462fc4ebf7c530bd54b2fb | 22,124 |
import json
def edit_schedule(request):
"""Edit automatic updates schedule"""
if request.method == "POST":
schedule = models.UpdateSchedule.objects.get()
def fun(query):
return [int(x.strip()) for x in query.split(" ") if x.strip() != ""]
schedule.text = json.dumps({
... | c87ef4ff0088bf4d67a1078ffe11b4c723272a8a | 22,125 |
import math
def infection_formula(name_model, infectious_number, classroom_volume, classroom_ach):
""" Calculate infection rate of with/without a mask by selected model. """
if name_model == "wells_riley":
# Use wells riley model.
effect_mask = 1.0 / ((1.0 - config.EXHALATION_FILTRATION_EFFIC... | 99b14a88c4ed02716626d8bc037b3f54211caa2a | 22,126 |
def RetryWithBackoff(opts, fn, args=None, kwargs=None):
"""`fn` function must follow the interface suggested:
* it should return tuple <status, err> where
status - backoff status
err - error that happend in function to propogate it to caller."""
args = args or ()
kwargs = kwa... | bf040a93015f3a283ac858c8738dc6bd8c48b2af | 22,127 |
def noaa_api_formatter(raw, metrics=None, country_aggr=False):
"""Format the output of the NOAA API to the task-geo Data Model.
Arguments:
raw(pandas.DataFrame):Data to be formatted.
metrics(list[str]): Optional.List of metrics requested,valid metric values are:
TMIN: Minimum temper... | 155b9a0cee72f85d6f5329a5a68aca4aa1dfe1eb | 22,128 |
def crop_wav(wav, center, radius):
"""
Crop wav on [center - radius, center + radius + 1], and pad 0 for out of range indices.
:param wav: wav
:param center: crop center
:param radius: crop radius
:return: a slice whose length is radius*2 +1.
"""
left_border = center - radius
right_b... | 69a5a078f06b083694d5d5eb5328b63c70a6f17c | 22,129 |
def markdown(text: str) -> str:
"""Helper function to escape markdown symbols"""
return MD_RE.sub(r'\\\1', text) | 2cb5fb3f5cac2d5cc5b6d256c4a8357832f3e53e | 22,130 |
def import_sample(sample_name, db):
"""Import sample"""
cur = db.cursor()
cur.execute('select sample_id from sample where sample_name=?',
(sample_name, ))
res = cur.fetchone()
if res is None:
cur.execute('insert into sample (sample_name) values (?)',
(sam... | c477a4f036951cac88789b59f361cf9397a0e9ee | 22,131 |
import torch
def change_background_color_balck_digit(images, old_background, new_background, new_background2=None, p=1):
"""
:param images: BCHW
:return:
"""
if new_background2 is None:
assert old_background == [0]
if not torch.is_tensor(new_background):
new_backgr... | f17f627616c75f3673d6ed043f0f36751ccde2a1 | 22,132 |
def render_sprites(sprites, scales, offsets, backgrounds, name="render_sprites"):
""" Render a scene composed of sprites on top of a background.
An scene is composed by scaling the sprites by `scales` and offseting them by offsets
(using spatial transformers), and merging the sprites and background togethe... | c4210a3b1f123368c77d89fcf15634ead3d97c85 | 22,133 |
import ctypes
def load_shared_library(dll_path, lib_dir):
"""
Return the loaded shared library object from the dll_path and adding `lib_dir` to the path.
"""
# add lib path to the front of the PATH env var
update_path_environment(lib_dir)
if not exists(dll_path):
raise ImportError('Sh... | 983b6b42b25e5f7936117579b02babff30899d21 | 22,134 |
def preprocess_img(image):
"""Preprocess the image to adapt it to network requirements
Args:
Image we want to input the network (W,H,3) numpy array
Returns:
Image ready to input the network (1,W,H,3)
"""
# BGR to RGB
in_ = image[:, :, ::-1]
# image centralization
# They are the ... | c4a0136c03aa57a54db432e9abe8e35cbe43f0b6 | 22,135 |
def _parse_ec_record(e_rec):
"""
This parses an ENSDF electron capture + b+ record
Parameters
----------
e_rec : re.MatchObject
regular expression MatchObject
Returns
-------
en : float
b+ endpoint energy in keV
en_err : float
error in b+ endpoint energy
... | 00480d031a3e6b118d880ed5e2abb890e7e8b410 | 22,136 |
import datetime
def skpTime(time):
"""
Retorna un datetime con la hora en que la unidad genero la trama.
>>> time = '212753.00'
>>> datetime.time(int(time[0:2]), int(time[2:4]), int(time[4:6]), int(time[-2]))
datetime.time(21, 27, 53)
>>>
"""
return datetime.time(... | 8bfa7e4d7faa52152c0a63944502cd6b1975ebdf | 22,137 |
def calc_max_moisture_set_point(bpr, tsd, t):
"""
(76) in ISO 52016-1:2017
Gabriel Happle, Feb. 2018
:param bpr: Building Properties
:type bpr: BuildingPropertiesRow
:param tsd: Time series data of building
:type tsd: dict
:param t: time step / hour of the year
:type t: int
:re... | 3fe2ab28b8f0ba3e6ba2139ed168f08e1b0e969d | 22,138 |
def compress_pub_key(pub_key: bytes) -> bytes:
"""Convert uncompressed to compressed public key."""
if pub_key[-1] & 1:
return b"\x03" + pub_key[1:33]
return b"\x02" + pub_key[1:33] | 05824112c6e28c36171c956910810fc1d133c865 | 22,139 |
def is_tensor(blob):
"""Whether the given blob is a tensor object."""
return isinstance(blob, TensorBase) | 514e9fea7b6fc60078ea46c61d25462096fa47cc | 22,140 |
def transform_dlinput(
tlist=None, make_tensor=True, flip_prob=0.5,
augment_stain_sigma1=0.5, augment_stain_sigma2=0.5):
"""Transform input image data for a DL model.
Parameters
----------
tlist: None or list. If testing mode, pass as None.
flip_prob
augment_stain_sigma1
aug... | 9f7bacb5a27667667432d3775ae624f4fd57e2c6 | 22,141 |
def _(text):
"""Normalize white space."""
return ' '.join(text.strip().split()) | f99f02a2fe84d3b214164e881d7891d4bfa0571d | 22,142 |
import ipdb
def mean_IOU_primitive_segment(matching, predicted_labels, labels, pred_prim, gt_prim):
"""
Primitive type IOU, this is calculated over the segment level.
First the predicted segments are matched with ground truth segments,
then IOU is calculated over these segments.
:param matching
... | cf405144206e824a868f4eb777635237e8cc59b8 | 22,143 |
import os
def get_tmp_directory_path():
"""Get the path to the tmp dir.
Creates the tmp dir if it doesn't already exists in this file's dir.
:return: str -- abs path to the tmp dir
"""
tmp_directory = os.path.join(os.path.dirname(os.path.realpath(__file__)),
'tmp... | b480578e6ae7a1840e8bf4acce36a63253a33d80 | 22,144 |
def _infer_title(ntbk, strip_title_header=True):
"""Infer a title from notebook metadata.
First looks in metadata['title'] and if nothing is found,
looks for whether the first line of the first cell is an H1
header. Optionally it strips this header from the notebook content.
"""
# First try the... | e8152f0c160d2cb7af66b1a20f4d95d4ea16c703 | 22,145 |
import hashlib
def stable_hash(value):
"""Return a stable hash."""
return int(hashlib.md5(str(value).encode('utf-8')).hexdigest(), 16) | a5be51a971eb6c9a91489155216ef194f9d0d7ba | 22,146 |
def minimal_community(community_owner):
"""Minimal community data as dict coming from the external world."""
return {
"id": "comm_id",
"access": {
"visibility": "public",
},
"metadata": {
"title": "Title",
"type": "topic"
}
} | 18b99c30d4dff01b988e8ac311a6da92142e71ee | 22,147 |
from typing import Counter
def retrieve_descriptions(gene, descriptions, empties):
"""Given single gene name, grab possible descriptions from NCBI
and prompt user to select one"""
# Perform ESearch and grab list of IDs
query = gene + '[Gene Name]'
handle = Entrez.esearch(db='gene', term=query,
... | 524d4955a51eb0e3143c06d91eb7ae611579d9dd | 22,148 |
import time
def readCmd():
""" Parses out a single character contained in '<>'
i.e. '<1>' returns int(1)
returns the single character as an int, or
returns -1 if it fails"""
recvInProgress = False
timeout = time.time() + 10
while time.time() < timeout:
try:
rc = ser.re... | 3e7b1eef27ab41b7079c966bf696e95923ebe6eb | 22,149 |
def map_ground_truth(bounding_boxes, anchor_boxes, threshold=0.5):
"""
Assign a ground truth object to every anchor box as described in SSD paper
:param bounding_boxes:
:param anchor_boxes:
:param threshold:
:return:
"""
# overlaps shape: (bounding_boxes, anchor_boxes)
overlaps = ja... | 1609bac66f4132249e893996b07b1a8752b8ab48 | 22,150 |
import os
import time
def create_jumpbox(username, network, image_name='jumpBox-Ubuntu18.04.ova'):
"""Make a new jumpbox so a user can connect to their lab
:Returns: Dictionary
:param username: The user who wants to delete their jumpbox
:type username: String
:param network: The name of the net... | 6eddd8668d049e6403895b01e35006272a05a905 | 22,151 |
def MakeFrame(ea, lvsize, frregs, argsize):
"""
Make function frame
@param ea: any address belonging to the function
@param lvsize: size of function local variables
@param frregs: size of saved registers
@param argsize: size of function arguments
@return: ID of function frame or -1
... | f0affe28d506a65d2a43fa64f2b9a99dbaf62b25 | 22,152 |
import logging
import time
def mip_solver(f, strides, arch, part_ratios, global_buf_idx, A, Z, compute_factor=10, util_factor=-1,
traffic_factor=1):
"""CoSA mixed integer programming(MIP) formulation."""
logging.info(f"LAYER {f}")
num_vars = len(A[0])
num_mems = len(Z[0])
m = Mod... | 5367ac49f2b1724aa1c78ea07ff09a880456cdae | 22,153 |
def get_image_ids(idol_id):
"""Returns all image ids an idol has."""
c.execute("SELECT id FROM groupmembers.imagelinks WHERE memberid=%s", (idol_id,))
all_ids = {'ids': [current_id[0] for current_id in c.fetchall()]}
return all_ids | 036dfdc9d757b2a7c70b26653252bbb5e180a5f1 | 22,154 |
def sortarai(datablock, s, Zdiff, **kwargs):
"""
sorts data block in to first_Z, first_I, etc.
Parameters
_________
datablock : Pandas DataFrame with Thellier-Tellier type data
s : specimen name
Zdiff : if True, take difference in Z values instead of vector difference
NB: this... | 5127b293b63a0d67da9e0ec21ff3085beea5a836 | 22,155 |
import sys
def GetRemoteBuildPath(build_revision, target_platform='chromium',
target_arch='ia32', patch_sha=None):
"""Compute the url to download the build from."""
def GetGSRootFolderName(target_platform):
"""Gets Google Cloud Storage root folder names"""
if IsWindowsHost():
... | d2cfcd671c9dfd6a94857cea70d3bc4ed6ac0f96 | 22,156 |
import json
def _extract_then_dump(hex_string: str) -> str:
"""Extract compressed content json serialized list of paragraphs."""
return json.dumps(
universal_extract_paragraphs(
unpack(bytes.fromhex(hex_string))
)
) | 6be6f045ff86580e5d33239e8b8232f5c343723b | 22,157 |
import base64
import hmac
import hashlib
def sso_redirect_url(nonce, secret, email, external_id, username, name, avatar_url, is_admin , **kwargs):
"""
nonce: returned by sso_validate()
secret: the secret key you entered into Discourse sso secret
user_email: email address of the user who lo... | 7aefb1c67a23f0c1311ce4297760a13ea39769fe | 22,158 |
def normalized_cluster_entropy(cluster_labels, n_clusters=None):
""" Cluster entropy normalized by the log of the number of clusters.
Args:
cluster_labels (list/np.ndarray): Cluster labels
Returns:
float: Shannon entropy / log(n_clusters)
"""
if n_clusters is None:
n_clusters... | aaed21c7cd91e1b61eb8a8336978eded8673960e | 22,159 |
def ingest_data(data, schema=None, date_format=None, field_aliases=None):
"""
data: Array of Dictionary objects
schema: PyArrow schema object or list of column names
date_format: Pandas datetime format string (with schema only)
field_aliases: dict mapping Json field names to desired schema names
... | 94ac4c13a71275485a79404f20c702886b39fb1c | 22,160 |
def build_messages(missing_scene_paths, update_stac):
""" """
message_list = []
error_list = []
for path in missing_scene_paths:
landsat_product_id = str(path.strip("/").split("/")[-1])
if not landsat_product_id:
error_list.append(
f"It was not possible to bui... | 07865a38fad6e3f642d3e55b80fac734dbb7d94b | 22,161 |
def DecrementPatchNumber(version_num, num):
"""Helper function for `GetLatestVersionURI`.
DecrementPatchNumber('68.0.3440.70', 6) => '68.0.3440.64'
Args:
version_num(string): version number to be decremented
num(int): the amount that the patch number need to be reduced
Returns:
string: decremente... | e42585791063d7982675065be7480ae7b5ea637d | 22,162 |
def hi_means(steps, edges):
"""This applies kmeans in a hierarchical fashion.
:param edges:
:param steps:
:returns: a tuple of two arrays, ´´kmeans_history´´ containing a number of
arrays of varying lengths and ´´labels_history´´, an array of length equal
to edges.shape[0]
"""
sub_... | 60d242f1ed9a4009bac706053e56f0d450ca7a7a | 22,163 |
def tag_item(tag_name, link_flag=False):
"""
Returns Items tagged with tag_name
ie. tag-name: django will return items tagged django.
"""
print C3 % ("\n_TAGGED RESULTS_")
PAYLOAD["tag"] = tag_name
res = requests.post(
GET_URL, data=json.dumps(PAYLOAD), headers=HEADERS, verify=False)... | 038b6a81dec1ea7c6fb9c4d83eaa6425d950c2fd | 22,164 |
def movie_info(tmdb_id):
"""Renders salient movie data from external API."""
# Get movie info TMDB database.
print("Fetching movie info based on tmdb id...")
result = TmdbMovie.get_movie_info_by_id(tmdb_id)
# TMDB request failed.
if not result['success']:
print("Error!")
# Can'... | ee7188eddcc50d0114ae5b80bc753e803632d557 | 22,165 |
def diabetic(y, t, ui, dhat):
"""
Expanded Bergman Minimal model to include meals and insulin
Parameters for an insulin dependent type-I diabetic
States (6):
In non-diabetic patients, the body maintains the blood glucose
level at a range between about 3.6 and 5.8 mmol/L (64.8 and
104.4 mg/d... | 35949f9a3d6010e89346ebb7f2818230ca6148a0 | 22,166 |
def get_spacy_sentences(doc_text):
"""
Split given document into its sentences
:param doc_text: Text to tokenize
:return: list of spacy sentences
"""
doc = _get_spacy_nlp()(doc_text)
return list(doc.sents) | 30345e04add02fd74e8470ce667fee60ddc7140d | 22,167 |
def get_recommendations(commands_fields, app_pending_changes):
"""
:param commands_fields:
:param app_pending_changes:
:return: List of object describing command to run
>>> cmd_fields = [
... ['cmd1', ['f1', 'f2']],
... ['cmd2', ['prop']],
... ]
>>> app_fields = {
... ... | 03fa583a5d4ea526cfeaa671418488218e1b227f | 22,168 |
import collections
def file_based_convert_examples_to_features(examples,
label_list,
max_seq_length,
tokenizer,
output_file):
"""Convert a... | efb6a0d347ae3a99a5859cbd3e0c1216d09377e6 | 22,169 |
def hello():
"""Return a friendly HTTP greeting."""
return 'Hello World!!!' | ae3528d10f94c92c169f53d5c3897572c9032bc2 | 22,170 |
from typing import Union
from typing import List
from typing import Tuple
def _findStress(
syllables: Union[List[Syllable], List[List[str]]]
) -> Tuple[List[int], List[int]]:
"""Find the syllable and phone indicies for stress annotations"""
tmpSyllables = [_toSyllable(syllable) for syllable in syllables]
... | d4adc4b6156e4d823640a29815d75832c21f68ac | 22,171 |
from hydrus.data.helpers import get_path_from_type
import random
import string
def gen_dummy_object(class_title, doc):
"""
Create a dummy object based on the definitions in the API Doc.
:param class_title: Title of the class whose object is being created.
:param doc: ApiDoc.
:return: A dummy objec... | 88f096a483699b9126496564cfe755386012acce | 22,172 |
def gather_info(arguments) -> Info:
"""Gather info."""
if arguments.integration:
info = {"domain": arguments.integration}
elif arguments.develop:
print("Running in developer mode. Automatically filling in info.")
print()
info = {"domain": "develop"}
else:
info = _... | 4cc527373fe29b36526388716f2402101039cea2 | 22,173 |
import subprocess
def get_git_version():
"""
Get the version from git.
"""
return subprocess.check_output('git describe --tags'.split()).strip() | 9dd34bd2fc55df75b82f2ccae0005a3212d16623 | 22,174 |
from loopy.preprocess import preprocess_program, infer_unknown_types
def get_mem_access_map(program, numpy_types=True, count_redundant_work=False,
subgroup_size=None):
"""Count the number of memory accesses in a loopy kernel.
:arg knl: A :class:`loopy.LoopKernel` whose memory accesses ... | 8255cc6d62a333d2634283abee7e6fbe08e18cc8 | 22,175 |
def __is_geotagging_input(question_input, _):
"""Validates the specified geotagging input configuration.
A geotagging input configuration contains the following optional fields:
- location: a string that specifies the input's initial location.
Args:
question_input (dict): An input configuratio... | 8fc392f832cc6d5c38eb5ffd2e7e20ff50b4ffd3 | 22,176 |
def _be_num_input(num_type, than, func=_ee_num_input, text='', error_text="Enter number great or equal than ",
error_text_format_bool=True,
error_text_format="Enter number great or equal than {}", pause=True, pause_text_bool=True,
pause_text='Press Enter...', clear=... | 92f8d3c119b0c331c50c4213644003c62534deb9 | 22,177 |
def createParetoFig(_pareto_df,_bestPick):
"""
Initalize figure and axes objects using pyplot for pareto curve
Parameters
----------
_pareto_df : Pandas DataFrame
DataFrame from Yahoo_fin that contains all the relevant options data
_bestPick : Pandas Series
Option data for the b... | dc6d8e6566c8c12d9938bf57a22c569124b65895 | 22,178 |
def rem4(rings, si):
"""finds if the silicon atom is within a 4 membered ring"""
for i in range(len(rings)):
triangles = 0
distances = []
locations = []
for n in range(len(rings[i]) - 1):
for m in range(1, len(rings[i]) - n):
distances.append(distance(... | e38fb7e1349597fa79cd21d39ecb222f39de86b3 | 22,179 |
def ilogit(x):
"""Return the inverse logit"""
return exp(x) / (1.0 + exp(x)) | 064383b65c2e8b011d2a6cd6ce14bf7936dd3178 | 22,180 |
def get_out_of_bounds_func(limits, bounds_check_type="cube"):
"""returns func returning a boolean array, True for param rows that are out of bounds"""
if bounds_check_type == "cube":
def out_of_bounds(params):
""" "cube" bounds_check_type; checks each parameter independently"""
... | 56c82efd63afdb36fc4d60cda7912fd9a4edb1d0 | 22,181 |
from typing import Dict
from typing import Set
def inspectors_for_each_mode(lead_type="lead_inspector") -> Dict[str, Set[str]]:
"""
We want to be able to group lead inspectors by submode.
"""
if lead_type not in ["lead_inspector", "deputy_lead_inspector"]:
raise ValueError("Can only query for ... | b712e82a14ddc8153c0ce61ebd3e95faca5993ae | 22,182 |
from .link_shortcuts import add_shortcut_to_desktop, suffix
from .module_install import ModuleInstall
import os
def add_shortcut_to_desktop_for_module(name):
"""
Adds a shortcut on a module which includes a script.
@param name name of the module
@return shortcut was added ... | 9d621ea5bf8436cb06964e7670384a3c6c28c34c | 22,183 |
import tables
def is_hdf_file(f):
"""Checks if the given file object is recognized as a HDF file.
:type f: str | tables.File
:param f: The file object. Either a str object holding the file name or
a HDF file instance.
"""
if((isinstance(f, str) and (f[-4:] == '.hdf' or f[-3:] == '.h5')... | 55d89b0d1afdf2acf705d5266e2c44f6d3901c2e | 22,184 |
def dummy_receivers(request, dummy_streamers):
"""Provides `acquire.Receiver` objects for dummy devices.
Either constructs by giving source ID, or by mocking user input.
"""
receivers = {}
for idx, (_, _, source_id, _) in enumerate(dummy_streamers):
with mock.patch('builtins.input', side_ef... | 70d8e0f7c4f84f949bdc73a4fd240684d86baaed | 22,185 |
import six
import inspect
def get_package_formats():
"""Get the list of available package formats and parameters."""
# pylint: disable=fixme
# HACK: This obviously isn't great, and it is subject to change as
# the API changes, but it'll do for now as a interim method of
# introspection to get the ... | 5db4d576380b027768c22df91fcd4d23b94ae160 | 22,186 |
def construct_reverse_protocol(splitting="OVRVO"):
"""Run the steps in the reverse order, and for each step, use the time-reverse of that kernel."""
step_length = make_step_length_dict(splitting)
protocol = []
for step in splitting[::-1]:
transition_density = partial(reverse_kernel(step_mapping[... | 7526e1cab43eeb3ef58a1ac4a673bf9a9992e287 | 22,187 |
def tabinv(xarr, x):
"""
Find the effective index in xarr of each element in x.
The effective index for each element j in x is the value i such that
:math:`xarr[i] <= x[j] <= xarr[i+1]`, to which is added an interpolation fraction
based on the size of the intervals in xarr.
Parameter... | c020222355e4d7671e7117c30e3babf0fa1d1f46 | 22,188 |
import configparser
def getldapconfig() :
""" Renvoie la configuration ldap actuelle"""
cfg = configparser.ConfigParser()
cfg.read(srv_path)
try :
return (cfg.get('Ldap', 'ldap_address'),
cfg.get('Ldap', 'ldap_username'),
cfg.get('Ldap', 'ldap_password').replace("$perce... | 505c7d3728b986811a86841003cd763912c82a93 | 22,189 |
def rename_dict_key(_old_key, _new_key, _dict):
"""
renames a key in a dict without losing the order
"""
return { key if key != _old_key else _new_key: value for key, value in _dict.items()} | ddc497796e0e52677afdf09b7f4995cf3a534cbc | 22,190 |
def api_browse_use_case() -> use_cases.APIBrowseUseCase:
"""Get use case instance."""
return use_cases.APIBrowseUseCase(items_repository) | 653525c9338bf8f520014a530228512fae1ed03d | 22,191 |
import logging
def treeIntersectIds(node, idLookup, sampleSet, lookupFunc=None):
"""For each leaf in node, attempt to look up its label in idLookup; replace if found.
Prune nodes with no matching leaves. Store new leaf labels in sampleSet.
If lookupFunc is given, it is passed two arguments (label, idLook... | 86ddb852dd3f6c612c248fbf0a43dca738131660 | 22,192 |
def get_descriptive_verbs(tree, gender):
"""
Returns a list of verbs describing pronouns of the given gender in the given dependency tree.
:param tree: dependency tree for a document, output of **generate_dependency_tree**
:param gender: `Gender` to search for usages of
:return: List of verbs as st... | ec021c89cb59da2ff8abb0169ea2567cb2e3a13c | 22,193 |
def client():
"""Return a client instance"""
return Client('192.168.1.1') | 19cda306e37e7a34395b86010fb4331a238a6cbc | 22,194 |
import os
import sys
import re
from bs4 import BeautifulSoup
def load_html_file(file_dir):
""" Uses BeautifulSoup to load an html """
with open(file_dir, 'rb') as fp:
data = fp.read()
if os.name == 'nt' or sys.version_info[0] == 3:
data = data.decode(encoding='utf-8', errors='strict')
... | 999fba3d63ed3c0d62befe0b76baf0a0f3e0a7ca | 22,195 |
import termios, fcntl, sys, os
def read_single_keypress():
"""Waits for a single keypress on stdin.
This is a silly function to call if you need to do it a lot because it has
to store stdin's current setup, setup stdin for reading single keystrokes
then read the single keystroke then revert stdin bac... | 646c04bc5441557064714716087a9893c7fa66dc | 22,196 |
def set_table(table, fold_test, inner_number_folds, index_table, y_name):
""" Set the table containing the data information
Set the table by adding to each entry (patient) its start and end indexes in the concatenated data object.
In fact each patients i is composed by `n_i` tiles so that for example patie... | d46c0601b59f27a60ec99a5305113d94893ba748 | 22,197 |
def parse_args():
"""
引数パース
"""
argparser = ArgumentParser()
argparser.add_argument(
"-b",
"--bucket-name",
help="S3 bucket name",
)
argparser.add_argument(
"-d",
"--days",
type=int,
help="Number of days",
)
return argparser.par... | 36302c14466a2c1a1791217566c49687fc55b567 | 22,198 |
def predict(file):
"""
Returns values predicted
"""
x = load_img(file, target_size=(WIDTH, HEIGHT))
x = img_to_array(x)
x = np.expand_dims(x, axis=0)
array = NET.predict(x)
result = array[0]
answer = np.argmax(result)
return CLASSES[answer], result | 98ce2d770d7bffc47e6fe84521fd6992ab2a53fa | 22,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.