content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def definstance(name, ty, expr):
"""
Arguments:
- `name`: a string
- `ty`: a type of the form ClassName(t1,...,tn)
"""
root, _ = root_app(root_clause(ty))
if root.info.is_class:
class_name = root.name
c = defexpr(name, expr, type=ty, unfold=[class_name])
conf.cur... | 1b692a9ac49bc6a68568ee232e6e516f83b64adf | 20,309 |
from typing import List
def read_plaintext_inputs(path: str) -> List[str]:
"""Read input texts from a plain text file where each line corresponds to one input"""
with open(path, 'r', encoding='utf8') as fh:
inputs = fh.read().splitlines()
print(f"Done loading {len(inputs)} inputs from file '{path}... | 27b00f4dfcdf4d76e04f08b6e74c062f2f7374d0 | 20,311 |
def extract_tool_and_dsname_from_name(row):
"""
Extract Basecall (MB1.6K) into Basecall and MB1.6K, and 1600 three fields
:param instr:
:return:
"""
try:
toolname, dsname = row['name'].strip().split(' ')
dsname = dsname[1:-1]
except: # No tag process
toolname = row['... | f02b106da47544c522499af1ee8670870749fb20 | 20,312 |
def pyramid_pooling(inputs, layout='cna', filters=None, kernel_size=1, pool_op='mean', pyramid=(0, 1, 2, 3, 6),
flatten=False, name='psp', **kwargs):
""" Pyramid Pooling module. """
shape = inputs.get_shape().as_list()
data_format = kwargs.get('data_format', 'channels_last')
static_... | 1484a686791cd017a53d182994e19b333ffc00b3 | 20,313 |
def df(r, gamma):
"""
divergence-free function
"""
eta = soft_threshold(r, gamma)
return eta - np.mean(eta != 0) * r | bf4d0a5d8bcbb5fa80b66d1dd555f15a44117319 | 20,314 |
def clip_3d_liang_barsky(zmin, zmax, p0, p1):
"""Clips the three-dimensional line segment in the canonial view volume by
the algorithm of Liang and Barsky. Adapted from James D. Foley, ed.,
__Computer Graphics: Principles and Practice__ (Reading, Mass. [u.a.]:
Addison-Wesley, 1998), 274 as well as
h... | 2ffcb60a4b2b13344f2255f5d5d1816199c666a4 | 20,315 |
def RunLatencyTest(sending_vm, receiving_vm, use_internal_ip=True):
"""Run the psping latency test.
Uses a TCP request-response time to measure latency.
Args:
sending_vm: the vm to send the tcp request.
receiving_vm: the vm acting as the server.
use_internal_ip: whether or not to use the private IP ... | 5f235f0adefe988be564f8e6dce7edfd4f292be4 | 20,316 |
def get_descriptor_list(stackdriver):
"""Return a list of all the stackdriver custom metric descriptors."""
type_map = stackdriver.descriptor_manager.fetch_all_custom_descriptors(
stackdriver.project)
descriptor_list = type_map.values()
descriptor_list.sort(compare_descriptor_types)
return descriptor_li... | 9b4b16f3d3b0330a786db0310f889f8ac132cb32 | 20,317 |
def dankerize(string: str, upper_case_ratio=0.2) -> str:
"""
Transform a string to lower case, and randomly set some characters
to upper case and return the result.
string: the string to dankerize
upper_case_ratio: the upper_case/letter ratio
"""
ret = ""
for i in range(len(... | 55f186104166b0804cadae2df5fa19deaf36473b | 20,318 |
def distance_constraints_too_complex(wordConstraints):
"""
Decide if the constraints on the distances between pairs
of search terms are too complex, i. e. if there is no single word
that all pairs include. If the constraints are too complex
and the "distance requirements are strict" flag is set,
... | 43429fd64dbf5fa118e2cbf1e381686e1a8518c9 | 20,319 |
def greedy_search(model,
decoding_function,
initial_ids,
initial_memories,
int_dtype,
float_dtype,
max_prediction_length,
batch_size,
eos_id,
do_sample,
... | 3324a45ce13181ea55c8588e497864526272475d | 20,320 |
import time
def database_mostcited(response: Response,
request: Request=Query(None, title=opasConfig.TITLE_REQUEST, description=opasConfig.DESCRIPTION_REQUEST),
morethan: int=Query(15, title=opasConfig.TITLE_CITED_MORETHAN, description=opasConfig.DESCRIPTION_CITED_MORET... | b18d3a3674cb5a52b7d3ea05db985774d7d25a4c | 20,321 |
def format_event_leef(event):
"""Format an event as QRadar / LEEF"""
syslog_header = f'<13>1 {event["actionTime"]} {hostname}'
leef_header = f'LEEF:2.0|TrinityCyber|PTI|1|{event.pop("id")}|xa6|'
fields = dict()
fields["devTime"] = event.pop("actionTime")
fields[
"devTimeFormat"
] =... | ca463c9e86d6b7880e992aa11cd4b6ae7592dab4 | 20,322 |
def _file_path(ctx, val):
"""Return the path of the given file object.
Args:
ctx: The context.
val: The file object.
"""
return val.path | 7c930f2511a0950e29ffc327e85cf9b2b3077c02 | 20,323 |
def Mapping_Third(Writelines, ThirdClassDict):
"""
:param Writelines: 将要写入的apk的method
:param ThirdClassDict: 每一个APK对应的第三方的字典
:return: UpDateWritelines
"""
UpDateWriteLines = []
for l in Writelines:
if l.strip() in list(ThirdClassDict.keys()):
UpDateWriteLines.extend(Thir... | eb94db36d06104007cbbacf8884cf6d45fee46b5 | 20,324 |
def rotate_points_around_origin(points, origin, angle):
"""
Rotate a 2D array of points counterclockwise by a given angle around a given origin.
The angle should be given in degrees.
"""
angle = angle * np.pi / 180
ox, oy = origin.tolist()
new_points = np.copy(points)
new_points[:, 0] ... | 0e21c2a9d6c870202935f8dbd9e725d9586670c3 | 20,325 |
def get_names_to_aliases(inp) -> dict:
"""
Returns pair,
- out[0] = dictionary of names to sets of aliases
- out[1] = erros when calling names_to_links, i.e., when file-reading
@param inp: string vault directory or names_to_links dictionary
if string then get_names_to_links method is used
... | 9648099dc8422abceb5c095191e90f3dad14c4fb | 20,326 |
def length(vec):
"""
Length of a given vector. If vec is an scalar, its length is 1.
Parameters
----------
vec: scalar or arr
Input vector
Returns
-------
length: int
Length of vec. If vec is an scalar, its length is 1.
... | d8baea0b5f5e0bdc30b9e5a5d76b06cd876c87ba | 20,327 |
def build_eval_infeeds(params):
"""Create the TPU infeed ops."""
eval_size = get_eval_size(params)
num_eval_steps = eval_size // params.eval_batch_size
dev_assign = params.device_assignment
host_to_tpus = {}
for replica_id in range(params.num_replicas):
host_device = dev_assign.host_device(replica=rep... | e62586dd8fe6358eaed9a0a2eaf43fd607c0323b | 20,328 |
import json
def get_featured_parks(request):
""" Returns recommended parks as JSON
"""
featured_parks = Park.objects.filter(featured=True).prefetch_related('images')
response = {
'featured_parks': [{'id': n.pk, 'name': n.name, 'image': n.thumbnail} for n in featured_parks]
}
return Htt... | a3b45fa5b467434bf375a46f420538e5d5d78688 | 20,329 |
from typing import Sequence
from typing import Any
def make_data_output(structures: Sequence[Artefact[bytes]]) -> Artefact[list[Any]]:
"""Take xyz structure from xtb and parse them to a list of dicts."""
def to_dict(xyz: bytes) -> dict[str, Any]:
as_str = xyz.decode().strip()
energy = float(a... | ca9e7fd187ff98a9c9c5146e12f9bc8b0e1c0466 | 20,331 |
def total_angular_momentum(particles):
"""
Returns the total angular momentum of the particles set.
>>> from amuse.datamodel import Particles
>>> particles = Particles(2)
>>> particles.x = [-1.0, 1.0] | units.m
>>> particles.y = [0.0, 0.0] | units.m
>>> particles.z = [0.0, 0.0] | units.m
... | 8eca23b7b1a8fc8a7722543f9193f0e4a3397f24 | 20,332 |
def svn_repos_get_logs3(*args):
"""
svn_repos_get_logs3(svn_repos_t repos, apr_array_header_t paths, svn_revnum_t start,
svn_revnum_t end, int limit, svn_boolean_t discover_changed_paths,
svn_boolean_t strict_node_history,
svn_repos_authz_func_t authz_read_func,
svn_log_message... | 1dab074e8112e2be0d51709d5d3d93bfc11c8c7d | 20,333 |
def insertTimerOnOutput (signal, type):
"""
Plug the signal sout of the return entity instead of `signal` to
input signal to enable the timer.
- param signal an output signal.
- return an Timer entity.
"""
Timer = getTimerType (type)
timer = Timer ("timer_of_" + signal.name)
plug(sig... | c8914227e112916ac67faf532babb0119abc502f | 20,334 |
from typing import List
def anomaly_metrics(contended_task_id: TaskId, contending_task_ids: List[TaskId]):
"""Helper method to create metric based on anomaly.
uuid is used if provided.
"""
metrics = []
for task_id in contending_task_ids:
uuid = _create_uuid_from_tasks_ids(contending_task_i... | df67e16af8b0c018da347c47a430fbe137a8c353 | 20,335 |
import logging
import json
def alarm():
"""."""
if request.method == 'POST':
response = {'message': 'POST Accepted'}
logging.info('alarm POSTED!')
data = request.data
logging.info(data)
string = json.dumps(data)
producer.send('SIP-alarms', string.encode())
... | a4444c4bc3f761cfdeb98485c745b77e8227817e | 20,336 |
def train_net(solver_prototxt, roidb, output_dir,
pretrained_model=None, detection_pretrained_model =None, max_iters=40000):
"""Train a TD-CNN network."""
roidb = filter_roidb(roidb)
sw = SolverWrapper(solver_prototxt, roidb, output_dir, pretrained_model=pretrained_model, detection_pretrained... | af85a78e4a477ab55e949fa0d6f6d44400d1f62f | 20,337 |
def get_druminst_order(x):
"""helper function to determine order of drum instruments
relies on standard sequence defined in settings
"""
y = shared.get_inst_name(x + shared.octave_length + shared.note2drums)
return shared.standard_printseq.index(y) | 8cad6cd10487d51b6edd74444115d63b7e599641 | 20,338 |
def find_nearest_idx(array, value):
"""
Find index of value nearest to value in an array
:param np.ndarray array: Array of values in which to look
:param float value: Value for which the index of the closest value in
`array` is desired.
:rtype: int
:return: The index of the item in `arr... | 3eb48426bf01c625419bbf87893b7e877fd0538d | 20,339 |
def hard_tanh(x):
"""Hard tanh function
Arguments:
x: Input value
hard_tanh(x) = {-1, for x < -2,
tanh(x), for x > -2 and x < 2
1, for x > 2 }
returns value according to hard tanh function
"""
return tf.maximum(
tf... | 3c93f09aaeb57ee9bf4d3ccdb2ebe790333f8f67 | 20,340 |
async def get_publications(publication_id: str, embedded: bool = False):
"""
Given a Publication ID, get the Publication record from metadata store.
"""
publication = await get_publication(publication_id, embedded)
return publication | 8c4c81776abc1d8268192c23b1dee6c8c10bcfb0 | 20,341 |
def RandomNormal(inp):
"""
Random normally distributed weight initialization.
"""
return np.random.randn(inp) | d6922748ece8ec880eec6ba1b701424cd6fdd149 | 20,342 |
def get_transceiver_description(sfp_type, if_alias):
"""
:param sfp_type: SFP type of transceiver
:param if_alias: Port alias name
:return: Transceiver decsription
"""
return "{} for {}".format(sfp_type, if_alias) | ccb29d937495e37bc41e6f2cf35747d2acfe0d47 | 20,343 |
def find_contiguous_set(target_sum: int, values: list[int]) -> list[int]:
"""Returns set of at least 2 contiguous values that add to target sum."""
i = 0
set_ = []
sum_ = 0
while sum_ <= target_sum:
sum_ += values[i]
set_.append(values[i])
if sum_ == target_sum and len(set... | 64b6c1f99946856a33a79fed3d43395a5a9c1000 | 20,344 |
def nesoni_report_to_JSON(reportified):
"""
Convert a nesoni nway.any file that has been reportified to JSON
See: tables.rst for info on what is stored in RethinkDB
:param reportified: the reportified nway.any file (been through
nway_reportify()). This is essentially a list of ... | b78d9e9c124104a4e4c634e8fc2926804a06629d | 20,345 |
def DeferredLightInfoEnd(builder):
"""This method is deprecated. Please switch to End."""
return End(builder) | f2bad6ffea3170c53a13206ab43d8b7193ccb89d | 20,346 |
def move_character(character: dict, direction_index=None, available_directions=None) -> tuple:
"""
Change character's coordinates.
:param character: a dictionary
:param direction_index: a non-negative integer, optional
:param available_directions: a list of strings, optional
:precondition: char... | cc5cc3115437d0dc4e9b7ba7845565ee8147be30 | 20,348 |
def expandednodeid_to_str(exnode):
"""SOPC_ExpandedNodeId or SOPC_ExpandedNodeId* to its str representation in the OPC-UA XML syntax."""
a = ''
if exnode.ServerIndex:
a += 'srv={};'.format(exnode.ServerIndex)
nsu = string_to_str(ffi.addressof(exnode.NamespaceUri))
if nsu:
a += 'nsu={... | 062012a11128a42bbaeb8d7ff316a2a29a31928b | 20,349 |
def scrap_insta_description(inst) -> str:
"""
Scrap description from instagram account HTML.
"""
description = inst.body.div.section.main.div.header.section.find_all(
'div')[4].span.get_text()
return description | 898fa0d1cb44606374b131b8b471178a22ab74ed | 20,350 |
import time
def merge_by_sim(track_sim_list, track_data_dic, track_list, reid_th):
"""
Merge by sim.
Ref: https://stackoverflow.com/questions/30089675/clustering-cosine-similarity-matrix
"""
print('start clustering')
merge_start_time = time.time()
cost_matrix = get_cost_matrix(track_sim_l... | 68478cb1367dcd2ef8a2550c54ea57e265bbbdf5 | 20,351 |
def cycle(*args, **kargs):
"""
Returns the next cycle of the given list
Everytime ``cycle`` is called, the value returned will be the next item
in the list passed to it. This list is reset on every request, but can
also be reset by calling ``reset_cycle()``.
You may specify the list as... | 6a1606d5fc65eb690c4ccbad3c662dc671219502 | 20,353 |
def calc_rmsd(struct1, struct2):
"""
Basic rmsd calculator for molecules and molecular clusters.
"""
geo1 = struct1.get_geo_array()
ele1 = struct1.elements
geo2 = struct2.get_geo_array()
ele2 = struct2.elements
dist = cdist(geo1,geo2)
idx1,idx2 = linear_sum_assignmen... | cb368f6e4edaf223194f1e965a0f926f33e72330 | 20,354 |
def validate_flat_dimension(d):
"""Return strue if a 'key:value' dimension is valid."""
key, _, val = d.partition(':')
return validate_dimension_value(val) and validate_dimension_key(key) | ee663bbdc62dab3d247c09ee5950dc63dafcad15 | 20,355 |
def __get_from_imports(import_tuples):
""" Returns import names and fromlist
import_tuples are specified as
(name, fromlist, ispackage)
"""
from_imports = [(tup[0], tup[1]) for tup in import_tuples
if tup[1] is not None and len(tup[1]) > 0]
return from_imports | 28df8225ad9440386342c38657944cfe7ac3d3ca | 20,357 |
def change_dt_utc_to_local(dt):
"""
change UTC date time to local time zone Europe/Paris
"""
return convert_utctime_to_timezone(dt,'%Y%m%dT%H%M%SZ','Europe/Paris','%Y%m%dT%H%M%S') | 09b52fd15a4fd9512e05f0a2801927b7f8be385f | 20,358 |
import logging
import warnings
def sarimax_ACO_PDQ_search(endo_var, exog_var_matrix, PDQS, searchSpace, options_ACO, low_memory=False, verbose=False):
"""
Searchs SARIMAX PDQ parameters.
endo_var: is the principal variable.
exog_var_matrix: is the matrix of exogenous vari... | acae883a3aaeb501646f121753924fb321f471e5 | 20,359 |
def get_index(x, value, closest=True):
"""Get the index of an array that corresponds to a given value.
If closest is true, get the index of the value closest to the
value entered.
"""
if closest:
index = np.abs(np.array(x) - value).argsort()[0]
else:
index = list(x).index(value)
... | 19dc68407d576492f25235fc1efcc79895d8cb3f | 20,361 |
def process_spawn(window, args):
"""
Spawns a child process with its stdin/out/err wired to a PTY in `window`.
`args` should be a list where the first item is the executable and the
remaining will be passed to it as command line arguments.
Returns a process object.
"""
return (yield Trap.PR... | 979599c767f3e391541e8fd02a168cd29659bcea | 20,362 |
import json
import re
def insertTaskParams(taskParams, verbose=False, properErrorCode=False, parent_tid=None):
"""Insert task parameters
args:
taskParams: a dictionary of task parameters
verbose: True to see verbose messages
properErrorCode: True to get a detailed error co... | baa9f0c783361cec17cec9f6259e4f856aa0121d | 20,363 |
def read_domains(file_name):
"""
读取域名存储文件,获取要探测的域名,以及提取出主域名
注意:若是不符合规范的域名,则丢弃
"""
domains = []
main_domains = []
no_fetch_extract = tldextract.TLDExtract(suffix_list_urls=None)
file_path = './unverified_domain_data/'
with open(file_path+file_name,'r') as fp:
for d in fp.readl... | 856a7e7d93023bf59981d51a6210b988236a14a9 | 20,365 |
def determine_last_contact_incomplete(end_time_skyfield, events, times, antenna):
"""
gibt letzten Kontakt vervollständigt und Anzahl der an events in unvollständiger Folge zurück
:param end_time_skyfield: skyfield time
:param events: array of int
:param times: array of skyfield times
:param ant... | 8a234bed084fa829c7649de99b933a59c89cba5b | 20,366 |
def lam_est(data, J, B, Q, L = 3,
paras = [3, 20], n_trees = 200, include_reward = 0, fixed_state_comp = None, method = "QRF"):
"""
construct the pointwise cov lam (for both test stat and c.v.), by combine the two parts (estimated and observed)
Returns
-------
lam: (Q-1)-len list of fo... | 3a1637f2e522e414e7ddc5c470310c1f2c460ce0 | 20,367 |
def initialize_all(y0, t0, t1, n):
""" An initialization routine for the different ODE solving
methods in the lab. This initializes Y, T, and h. """
if isinstance(y0, np.ndarray):
Y = np.empty((n, y.size)).squeeze()
else:
Y = np.empty(n)
# print y0
# print Y
Y[0] = y0
T = np.li... | 552a92dd50aca926b1cb6c9e6aaafd1c1401b5c3 | 20,369 |
import random
def _sequence_event(values, length, verb):
"""Returns sequence (finite product) event.
Args:
values: List of values to sample from.
length: Length of the sequence to generate.
verb: Verb in infinitive form.
Returns:
Instance of `probability.FiniteProductEvent`, together with a te... | 1addd21c6c39451ac29f9bcf7551f070884e9328 | 20,370 |
def ndarrayToQImage(img):
""" convert numpy array image to QImage """
if img.dtype != 'uint8':
raise ValueError('Only support 8U data')
if img.dim == 3:
t = QtGui.QImage.Format_RGB888
elif img.dim == 2:
t = QtGui.QImage.Format_Grayscale8
else:
raise ValueError('Only ... | a08207266b03adff2dd66421572a0905f9525844 | 20,371 |
from datetime import datetime
import re
import base64
import uuid
def object_hook(dct, compile_re=False, ensure_tzinfo=True, encoding=None):
"""
Object hook used by hoplite_loads. This object hook can encode the
dictionary in the right text format. For example, json.loads by default
will decode '{'he... | bfe93f67813bda8e77e93a7ee33b6dc3bcbfe16a | 20,372 |
import requests
import pickle
def scrape_sp500_tickers():
"""Scrape the wikipedia page for the latest list of sp500 companies
Returns:
[pickle]: [list of sp500 companies]
"""
#set get file to look at wikipedia's list of sp500 companies
resp = requests.get('http://en.wikipedia.org/wiki/Lis... | 0c318e84f488c93254256394b1fe5d57d58c81a5 | 20,374 |
def get_top_k_recs(user_reps, item_reps, k):
"""
For each user compute the `n` topmost-relevant items
Args:
user_reps (dict): representations for all `m` unique users
item_reps (:obj:`np.array`): (n, d) `d` latent features for all `n` items
k (int): no. of most relevant items
R... | e209b8794fe3d8f8002dbbe48d858b335171c2f5 | 20,375 |
def some_function(t):
"""Another silly function."""
return t + " python" | 2bd8adc315e97409758f13b0f777ccd17eb4b820 | 20,377 |
def add_context_for_join_form(context, request):
""" Helper function used by view functions below """
# If the client has already joined a market
if 'trader_id' in request.session:
# If trader is in database
if Trader.objects.filter(id=request.session['trader_id']).exists():
tr... | aad1b592c6d28d9a69ec97a8be9d46f942cb3d7b | 20,379 |
def create_list(inner_type_info: CLTypeInfo) -> CLTypeInfoForList:
"""Returns CL type information for a list.
:param CLTypeInfo inner_type_info: Type information pertaining to each element within list.
"""
return CLTypeInfoForList(
typeof=CLType.LIST,
inner_type_info=inner_type_inf... | e74731984cc83172c60a79e1b1efe05d90a32342 | 20,380 |
def get_baseline(baseline_filename, plugin_filenames=None):
"""
:type baseline_filename: string
:param baseline_filename: name of the baseline file
:type plugin_filenames: tuple
:param plugin_filenames: list of plugins to import
:raises: IOError
:raises: ValueError
"""
if not basel... | f4318ee676e0c670f152feef0884a220eb1a38ac | 20,381 |
def del_ind_purged(*args):
"""
del_ind_purged(ea)
"""
return _ida_nalt.del_ind_purged(*args) | 80133af5acff0a9c284ec7894abd10bafa2671a1 | 20,382 |
import random
import hmac
def hash_password(password, salthex=None, reps=1000):
"""Compute secure (hash, salthex, reps) triplet for password.
The password string is required. The returned salthex and reps
must be saved and reused to hash any comparison password in
order for it to match the ... | cac468818560ed52b415157dde71d5416c34478c | 20,383 |
from typing import Dict
def create_scheduled_job_yaml_spec(
descriptor_contents: Dict, executor_config: ExecutorConfig, job_id: str, event: BenchmarkEvent
) -> str:
"""
Creates the YAML spec file corresponding to a descriptor passed as parameter
:param event: event that triggered this execution
:p... | 48e19b6637eafee72b0b3b04a1e31c8e6c163971 | 20,384 |
def ArgMin(iterable, key=None, default=None, retvalue=False):
"""
iterable >> ArgMin(key=None, default=None, retvalue=True)
Return index of first minimum element (and minimum) in input
(transformed or extracted by key function).
>>> [1, 2, 0, 2] >> ArgMin()
2
>>> ['12', '1', '123'] >> Arg... | 9c2515c3a37ab82e2b5df6b5d8dcf5ded6ad15ad | 20,386 |
import scipy
def localize_peaks_monopolar_triangulation(traces, local_peak, contact_locations, neighbours_mask, nbefore, nafter, max_distance_um):
"""
This method is from Julien Boussard see spikeinterface.toolki.postprocessing.unit_localization
"""
peak_locations = np.zeros(local_peak.size, dtype=dty... | c751ec223423007b170ce0020f6c21c72cff3cc2 | 20,387 |
def format_dict_with_indention(data):
"""Return a formatted string of key value pairs
:param data: a dict
:rtype: a string formatted to key='value'
"""
if data is None:
return None
return jsonutils.dumps(data, indent=4) | 085ac029aa73e5049eeec12e021997a5067966ce | 20,388 |
def _Rx(c, s):
"""Construct a rotation matrix around X-axis given cos and sin.
The `c` and `s` MUST satisfy c^2 + s^2 = 1 and have the same shape.
See https://en.wikipedia.org/wiki/Rotation_matrix#Basic_rotations.
"""
o = np.zeros_like(c)
i = np.ones_like(o)
return _tailstack2([[i, o, o],... | 01d436bee07458ede0484ed745ccf72568214240 | 20,390 |
def is_fraud(data):
"""
Identifies if the transaction was fraud
:param data: the data in the transaction
:return: true if the transaction was fraud, false otherwise
"""
return data[1] == 1 | 115e45a10f3429b9c33bc81fd94c24eff712f618 | 20,391 |
import scipy
def EvalBinomialPmf(k, n, p):
"""Evaluates the binomial pmf.
Returns the probabily of k successes in n trials with probability p.
"""
return scipy.stats.binom.pmf(k, n, p) | 0720359be48b514465eb3a10d3f271ac3c25dfb9 | 20,392 |
def reformat_icd_code(icd_code: str, is_diag: bool = True) -> str:
"""Put a period in the right place because the MIMIC-III data files exclude them.
Generally, procedure ICD codes have dots after the first two digits, while diagnosis
ICD codes have dots after the first three digits.
Adopted from: https... | 4992886b257dab5361f84dd0c7774f677466437f | 20,394 |
def parse_parent(self):
"""Parse enclosing arglist of self"""
gtor_left = tokens_leftwards(self.begin)
gtor_right = tokens_rightwards(self.end)
enc = Arglist()
enc.append_subarglist_right(self) # _left could have worked equally well
try:
parse_left(enc, gtor_left)
parse_right(... | aeae5b7d56614299d0d95d52a1cd7e8cecd036ff | 20,395 |
def dump_annotation(ribo_handle):
"""
Returns annotation of a ribo file in bed format
in string form.
Parameters
----------
ribo_handle : h5py.File
hdf5 handle for the ribo file
Returns
-------
A string that can be output directly as a bed file.
"""
boundaries ... | 54c98527d02ad5a136c0bc29bc794c3819fe5426 | 20,396 |
def calculate_ani(blast_results, fragment_length):
"""
Takes the input of the blast results, and calculates the ANI versus the reference genome
"""
sum_identity = float(0)
number_hits = 0 # Number of hits that passed the criteria
total_aligned_bases = 0 # Total of DNA bases that passed the cri... | 09b649dda337d2b812f5c5fd9ec75b34737e3f15 | 20,399 |
from typing import List
from typing import Dict
def process_line(line: str, conditional_chain: List[str],
fields: Dict[str, str]):
""" Processes a line in the template, i.e. returns the output html code
after evaluating all if statements and filling the fields. Since we
oftentimes are in ... | d84a679d1dc292f3f9cccaf7b6f6718c1ff7cbfc | 20,400 |
def get_groundstation_code(gsi):
"""
Translate a GSI code into an EODS domain code.
Domain codes are used in dataset_ids.
It will also translate common gsi aliases if needed.
:type gsi: str
:rtype: str
>>> get_groundstation_code('ASA')
'002'
>>> get_groundstation_code('HOA')
... | a9a04935cfceeb4ca4b90f7ba05ff5c7076ff917 | 20,401 |
def mixed_social_welfare(game, mix):
"""Returns the social welfare of a mixed strategy profile"""
return game.expected_payoffs(mix).dot(game.num_role_players) | 72c465211bdc79c9fcf2b1b9d8c7dd5abae5d8df | 20,403 |
import re
def isValid(text):
"""
"Play Blackjack"
"""
return bool(re.search(r'\bblackjack\b', text, re.IGNORECASE)) | c1960a9683bde9701b4e3900edd41e4d6e5444ac | 20,405 |
def init_app(app):
"""init the flask application
:param app:
:return:
"""
return app | 6e460eb1fdc19553c6c4139e60db06daec507a2d | 20,406 |
def bounds(geometry, **kwargs):
"""Computes the bounds (extent) of a geometry.
For each geometry these 4 numbers are returned: min x, min y, max x, max y.
Parameters
----------
geometry : Geometry or array_like
**kwargs
For other keyword-only arguments, see the
`NumPy ufunc doc... | bdf90b760fc7c62d66596159136961e7840077c4 | 20,407 |
def getRidgeEdge(distComponent, maxCoord, direction):
"""
最大値〜最大値-1の範囲で、指定された方向から見て最も遠い点と近い点を見つける。
緑領域からの距離が最大値近辺で、カメラから見て最も遠い点と近い点を見つけるための関数。
これにより、石の天面の中心と底面の中心を求める
"""
# 最大値
maxValue = distComponent[maxCoord]
# 最大値-1以上の点の座標群
ridge = np.array(np.where(distComponent >= maxValue - 1)... | b22b592ee9467f1205d49e5c83dfe978b5dc2f35 | 20,408 |
def map_vL(X, w):
"""
Maps a random sample drawn from vector Langevin with orientation u = [0,...,0,1] to
a sample that follows vector Langevin with orientation w.
"""
assert w.shape[0] == X.shape[0]
#assert np.linalg.norm(w) == 1.
#print('Orientation vector length : ' + str(np.linalg.norm(w)))
d = w.shape[0]
... | a7d06a295569bb08d800c46c302c5a38ef2c2f52 | 20,409 |
def get_constant_schedule_with_warmup(optimizer: Optimizer, num_warmup_steps: int, last_epoch: int = -1):
"""
Create a schedule with a constant learning rate preceded by a warmup period during which the learning rate
increases linearly between 0 and the initial lr set in the optimizer.
Args:
op... | 825c4e14f91992c39d5be37b814e5c3bd7177c50 | 20,410 |
def find_bigrams(textdict, threshold=0.1):
"""
find bigrams in the texts
Input:
- textdict: a dict with {docid: preprocessed_text}
- threshold: for bigrams scores
Returns:
- bigrams: a list of "word1 word2" bigrams
"""
docids = set(textdict.keys())
# to identify bigra... | 4f3d6e3b4b62e42a98ab8bc3f823853680ca9e6f | 20,412 |
def _rec_filter_to_info(line):
"""Move a DKFZBias filter to the INFO field, for a record.
"""
parts = line.rstrip().split("\t")
move_filters = {"bSeq": "strand", "bPcr": "damage"}
new_filters = []
bias_info = []
for f in parts[6].split(";"):
if f in move_filters:
bias_inf... | 496056126bdf390a6213dfad5c40c4a14ec35caa | 20,413 |
import ast
def ast_node_to_source(ast_node: ast.AST) -> str:
"""
Uses astor package to produce source code from ast
Also handles low-level ast functions, such as wrapping in a module if necessary,
and fixing line numbers for modified/extracted ast
Args:
ast_node:
Returns:
"""
... | bc4bb2a9f09907e2c9ab8a8f1629135695da6aa9 | 20,415 |
import typing
def _get_base(*, name: str, schemas: oa_types.Schemas) -> typing.Type:
"""
Retrieve the base class of a schema considering inheritance.
If x-inherits is True, retrieve the parent. If it is a string, verify that the
parent is valid. In either case, the model for that schema is used as th... | 47bcca20c82078cd3bd821a0d10e951b346a1e87 | 20,417 |
def classNumber(A):
""" Returns the number of transition classes in the matrix A """
cos = 0
if type(A[0][0]) == list:
cos = len(A)
else:
cos = 1
return cos | a71bce468f7429746bfe246d94f5dcebb85c41d4 | 20,418 |
def lz4_decompress_c(src, dlen, dst=None):
"""
Decompresses src, a bytearray of compressed data.
The dst argument can be an optional bytearray which will have the output appended.
If it's None, a new bytearray is created.
The output bytearray is returned.
"""
if dst is None:
dst = by... | 5b2b15f323c00a8cedec4b9caee0fea8dda89f76 | 20,419 |
def format_coordinates(obj, no_seconds=True, wgs_link=True):
"""Format WGS84 coordinates as HTML.
.. seealso:: https://en.wikipedia.org/wiki/ISO_6709#Order.2C_sign.2C_and_units
"""
def degminsec(dec, hemispheres):
_dec = abs(dec)
degrees = int(floor(_dec))
_dec = (_dec - int(flo... | 1fc6a151f73e8836ee935db3cf265438e597fec2 | 20,420 |
def delete_keys_on_selected():
"""
deletes set driven keys from selected controllers.
:return: <bool> True for success.
"""
s_ctrls = object_utils.get_selected_node(single=False)
if not s_ctrls:
raise IndexError("[DeleteKeysOnSelectedError] :: No controllers are selected.")
selected_... | 5d1b55bdcefcd8b4997432851e015e2a875eb80a | 20,422 |
def scan_continuation(curr, prompt_tag, look_for=None, escape=False):
"""
Segment a continuation based on a given continuation-prompt-tag.
The head of the continuation, up to and including the desired continuation
prompt is reversed (in place), and the tail is returned un-altered.
The hint value |l... | 1182394c26b6d9e745f469f5006b5269e5854db8 | 20,423 |
def solar_wcs_frame_mapping(wcs):
"""
This function registers the coordinates frames to their FITS-WCS coordinate
type values in the `astropy.wcs.utils.wcs_to_celestial_frame` registry.
"""
dateobs = wcs.wcs.dateobs if wcs.wcs.dateobs else None
# SunPy Map adds 'heliographic_observer' and 'rsu... | dd6a52e8356a242c5f2dfb4808e0a3d1ed57073f | 20,425 |
def toa_error_peak_detection(snr):
"""
Computes the error in time of arrival estimation for a peak detection
algorithm, based on input SNR.
Ported from MATLAB Code
Nicholas O'Donoughue
11 March 2021
:param snr: Signal-to-Noise Ratio [dB]
:return: expected time of arrival ... | 4ab2f653c81a29484d96aed58cb73ca4327dbde0 | 20,426 |
def statCellFraction(gridLimit, gridSpace, valueFile):
"""
Calculate the fractional value of each grid cell, based on the
values stored in valueFile.
:param dict gridLimit: Dictionary of bounds of the grid.
:param dict gridSpace: Resolution of the grid to calculate values.
:param str valueFile: ... | e26f011c10d94435b134e9f1b3adb2d1b1cd88ce | 20,428 |
def relative_url_functions(current_url, course, lesson):
"""Return relative URL generators based on current page.
"""
def lesson_url(lesson, *args, **kwargs):
if not isinstance(lesson, str):
lesson = lesson.slug
if course is not None:
absolute = url_for('course_page'... | b49009cfdb8e9095c9ca17fee39feb8689624bd4 | 20,430 |
def fix_CompanySize(r):
"""
Fix the CompanySize column
"""
if type(r.CompanySize) != str:
if r.Employment == "Independent contractor, freelancer, or self-employed":
r.CompanySize = "0 to 1 Employees"
elif r.Employment in [
"Not employed, but looking for work",
... | bd34bb3e72920fb7ef37279a743198387b1c4717 | 20,431 |
import yaml
from pathlib import Path
def write_thermo_yaml(phases=None, species=None, reactions=None,
lateral_interactions=None, units=None,
filename=None, T=300., P=1., newline='\n',
ads_act_method='get_H_act',
yaml_options={'def... | f8d12226a137d2cf3b9ddecb427dc51257498145 | 20,432 |
import random
def move_weighted(state: State, nnet: NNet) -> tuple:
"""
Returns are random move with weighted probabilities from the neural network.
:param state: State to evaluate
:param nnet: Neural network used for evaluation
:return: Move as ((origin_row, origin_column),(target_row,target_col... | 0d9ad3e6344c3c24e71530bd7bbe6dc5a0b9a254 | 20,433 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.