content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def move_consonant_left(letters: list, positions: list) -> list:
"""Given a list of letters, and a list of consonant positions, move the consonant positions to
the left, merging strings as necessary.
>>> move_consonant_left(['a', 'b', '', '', 'bra'], [1])
['ab', '', '', '', 'bra']"""
for pos in p... | 3a1faae1c1ab9bec1fb077d8264cdd0474eba82a | 629,445 |
def SOD(fp):
"""Parse an SOD marker segment.
SOD - Start of data segment 0xFF 0x93
Last marker in a tile-part header. Bitstream data between a SOD and
the next SOT or EOC shall be a multiple of 8 bits.
"""
info = {}
return info | e36904d5904783df59615ea83339a854468fd065 | 629,446 |
import os
import pickle
def load_classifier(filepath):
"""
Takes an extractor and stores the classifier into filepath.
"""
if not os.path.exists(filepath):
raise ValueError("File does not exists")
with open(filepath, 'rb') as filehandler:
return pickle.load(filehandler) | bbffd9844fae59828249ff7e6f6a99b87ee5588a | 629,448 |
def index():
"""Briefly describes the REST API."""
return {'description': 'A simple lending library REST API that runs entirely on '
'serverless components.'} | 5d6d614c7958782fd654627aecf4d14262b2d7ed | 629,449 |
import argparse
def create_parser():
"""Create the argument parser for the main application.
Returns
-------
argparse.ArgumentParser
The application command-line parser.
"""
description = ['This is the UI for running the Dome Seeing Monitor.']
parser = argparse.ArgumentParser(des... | 9754b2701371966bfceb316af12053d079339164 | 629,450 |
import glob
from pathlib import Path
def get_mas_variables(path):
"""
Return a list of variables present in a given directory.
Parameters
----------
path :
Path to the folder containing the MAS data files.
Returns
-------
var_names : list
List of variable names presen... | ec0c218d850d93034ce2008f7f0d12a7267a04c5 | 629,451 |
import os
def osenv(env_name):
"""
Returns an empty string if the required environment
variable does not exist, else it's value.
"""
return os.environ.get(env_name, '') | c6f7fdc1c33a02273b8757fa38c82012dfba4121 | 629,452 |
def sort_tickets(fields, tickets) -> tuple:
"""
Get the valid and invalid tickets.
"""
valid_numbers = set()
for f in fields.values():
valid_numbers.update(f)
valids, invalids = [], []
for ticket in tickets:
invalid = []
for n in ticket:
if n in valid_num... | b13c2d72c62c10abcfe88e396681950011f19b95 | 629,453 |
def square_root(n):
"""
Compute and return the square root of n, where n is guaranteed to be a
non-negative integer.
"""
# this runs always n // 2 guaranteed, beacuse square root never
# be greater than half of that number n
for divisor in range(1, n+1):
qoutient = n // divisor
... | 42d5f32c6984a36598a264170bb7c196dab2749a | 629,454 |
def bundle(*addable):
""" Getting addable objects (such as Matching) and composing them to one.
When nothing is provided, this will raise a ValueError
"""
if len(addable) <= 0:
raise ValueError('Provide at least one Matching object')
return sum(addable[1:], addable[0]) | 37ded01839005e954c8ae7f8491a870b30b58e86 | 629,455 |
import torch
def repetition_penalty(logits, repetition_penalty, used_tokens):
""" Implement the repetition penalty, check paper
https://arxiv.org/pdf/1909.05858.pdf
"""
if used_tokens is not None and repetition_penalty != 1.0:
logits_update = torch.gather(logits, 1, used_tokens)
logit... | 81e88cc6cdaf9b50dd8a0c3e9e5370967f1872cc | 629,456 |
def strip_comments(line):
"""Remove comments."""
# Cull inline comments using ON/OFF nomenclature
pos = line.find(":")
while pos > -1:
pos2 = line[pos + 1 :].find(":")
if pos2 > -1:
# Add space to keep things seperated
line = line[:pos] + " " + line[pos + pos2 + 2... | 9ec81033632fb80f4f6075abf7bf789f5bb9178d | 629,457 |
import os
def infer_delimiter(filepath):
"""
From extension infer delimiter used in a separated values file.
:param str filepath: path to file about which to make inference
:return str | NoneType: extension if inference succeeded; else null
"""
ext = os.path.splitext(filepath)[1][1:].lower()
... | 267148c9b32442ff3e940e75c85967dbcd7e9f68 | 629,458 |
def find_fomoists(events_attendees, rsvp_statuses=['attending']):
"""
"events" is a list of lists of attendees:
[
[
{
"name": "Brittany Miller",
"rsvp_status": "attending",
"id": "1442173849420454"
},
...
]
...
]
... | 80a43ebc531456315157d14c932629c8e496c5d3 | 629,459 |
import re
def XmlString_to_Dictionary(xml_string):
"""XML string must be in the format <key>value</key>\n<key2>.. to work"""
pattern='<(?P<XML_tag>.+)>(?P<XML_text>.+)</.+>'
lines=xml_string.splitlines()
out_dictionary={}
for line in lines:
match=re.search(pattern,line)
if match:
... | 0ca783584f3de1ee56fb6ac6a3db826fbc7c4bf8 | 629,461 |
def _average_nadir_gain_dbi(pattern, angles):
"""Average gain on the nadir face of the satellite.
For simplicity, this function assumes some hard-coded values of
65-degrees off of boresight. That translates to 0->65 and (360-65)->360
"""
s = 0
n = 0
offset = 65
for i in range(len(patte... | 2144a01219bf67bc7bab84e0b392cad95c5aaf35 | 629,462 |
def get_id(record):
"""
Returns the Amazon DynamoDB key.
"""
return record['dynamodb']['Keys']['id']['S'] | 4211d847a382a8220bf842176266f7b7b9ece6fd | 629,463 |
def window_compensation():
""" Hann window compensation factor. """
return 2.0 | 783bad65b97737a4569d3ad96d79d4cd6b1d502f | 629,464 |
def join_string(phrase: str, join_s: str):
"""
Take the 'phrase' and intersperse it whit 'join_s' string
:param phrase: string to be interspersed
:param join_s: string
:return: interspersed string
"""
return join_s.join(phrase) | 380fa1b7ee9ea6cb4ee5b1e75b4dc32b0daecead | 629,465 |
def load_translations():
"""
load all translations
"""
translations = {}
langs = ['az', 'bs', 'ca', 'cy', 'eo', 'he', 'hr', 'hy', 'id', 'is', 'it', 'ja', 'kk', 'lv', 'mk', 'nb', 'nn', 'sl', 'uz']
for f_name in langs:
f_name = 'share/translations/%s.txt' % f_name
translation = {}... | f5bf09a8219efa2fb4ab4e99424e9cdecd1d88b7 | 629,467 |
import os
import importlib
def enumerate_plugins(dirpath, module_prefix, namespace, class_,
attributes={}, as_dict=False):
"""Import plugins of type `class` located at `dirpath` into the
`namespace` that starts with `module_prefix`. If `dirpath` represents a
filepath then it is conve... | d4c282ed179d82277f95e1c10ab9c0631cc653af | 629,468 |
from typing import Counter
def list_duplicates(iterable):
"""Return a set of duplicates in given iterator."""
return {key for key, count in Counter(iterable).items() if count > 1} | 5d11aa77f774ff4e700c2a5ffce9bb189d38bbea | 629,469 |
def MayaRender(frames, scene_file):
"""Render the given frames from the given scene.."""
return {'renderings': '/renderings/file.%04d.exr'} | 49c7732c0dc967d1cdab800100792ad52e98f0d9 | 629,470 |
def makeFullName(parScope, parName):
""" Create the fully-qualified name (inclues scope if used) """
# Skip scope (and leading dot) if no scope, even in cases where scope
# IS used for other pars in the same task.
if parScope:
return parScope+'.'+parName
else:
return parName | 0dda72bb1ed8a6f82eaa34362834d2329bae9630 | 629,471 |
def get_usernames(self):
""" Gets usernames table """
usernames = self.follows_db_c.execute("SELECT * FROM usernames")
if usernames:
return usernames
else:
return False | 9715221bd399e9e13331213005e1669ceb9523a3 | 629,472 |
def selectPivotIndex (ar, left, right, comparator):
"""Select pivot index for ar[left,right] inclusive using comparator."""
midIndex = (left + right)//2
lowIndex = left
if comparator(ar[lowIndex], ar[midIndex]) >= 0:
lowIndex = midIndex
midIndex = left
# when we get here, ar[lowInd... | 6d57c1931777fdd4335a674f8a8374c1243e1dc6 | 629,473 |
def check_data(data):
"""Helper function to test data structure decorator."""
return data | 5e2168d66f7db0586e898455fdbb5bea04ad6fb6 | 629,474 |
def curry(_curried_func, *args, **kwargs):
"""Reference: https://docs.djangoproject.com/en/2.2/_modules/django/utils/functional/
Deprecated in Django 3.0.
"""
def _curried(*moreargs, **morekwargs):
return _curried_func(*args, *moreargs, **{**kwargs, **morekwargs})
return _curried | 68fbcfe02fae6561eb9b32bcd125bb08aa5c95ba | 629,476 |
import re
def _definitionsOnly(s, execute=0):
"""
removes all text lines (only keeps definition of the form [name]:url)
"""
if not execute: return s
return "\n".join(re.findall("^\s*[[].*[\]]:.*$", s, re.MULTILINE)) | fc35b73334acc28492dea90e7518bd5c941707ee | 629,477 |
def metric_max_over_ground_truths(metric_fn, prediction, ground_truths):
"""
Calculate the maximum metric value when we have multiple ground truths.
i.e., for each question, we have multiple answers.
:param metric_fn: the function to calculate metric
:param prediction: our model predicted answer str... | 869d0cbc4c8f813c2ef5a789bf75ffa8bf987560 | 629,478 |
def is_known_footer(string):
"""Sometimes the excel has a footer for a command section and
we cannot very reliably differentiate it from a command value
(actually, it might be possible, but this appraoch is easier).
"""
if not string:
return False
lines = [
u'If Jacket Art is d... | ef00b21eed7df5dee83406810c342930d3ecd959 | 629,480 |
def copy_add_one(lst):
"""
Returns: copy of lst with 1 added to every element
Example: add_one([1,2,3,1]) returns [2,3,4,2]
Parameter lst: The list to copy
Precondition: lst is a list of all numbers
(either floats
or ints), or an empty list
"""
copy = [] # accumulator
for x in ls... | ea8d518c7dd22209372e27bdccae3f498970e2db | 629,481 |
def flatten_forward(x_input):
"""Perform the reshaping of the tensor of size `(K, L, M, N)`
to the tensor of size `(K, L*M*N)`
# Arguments
x_input: np.array of size `(K, L, M, N)`
# Output
output: np.array of size `(K, L*M*N)`
"""
K, L, M, N = x_input.shape
output = x_in... | 0767220baa652e5f4c6efbca7b3ffdb03f71902b | 629,482 |
def is_inside(center_point, corner_point):
"""
Find if center_point inside the bbox(corner_point) or not.
:param center_point: center point (x, y)
:param corner_point: corner point ((x1,y1),(x2,y2))
:return:
"""
x_flag = False
y_flag = False
if (center_point[0] >= corner_point[0][0])... | 1254990b9a775a56a09448f44965aeba7bc59a4d | 629,483 |
def contains_embedded_molfile(field_value):
"""Returns True if the RD file $DATUM field value contains an embedded
molfile, otherwise returns False."""
return field_value == '$MFMT' | ee800e23710d73f54ef4792f0b49e27caa98c5bc | 629,484 |
def flatten(d, sep='.', flat_type=dict):
"""Flatten a nested dict using a specific separator.
:param sep: When None, return dict with tuple keys (guaranties inversion of
flatten) else join the keys with sep
:param flat_type: Allow other mappings instead of flat_type to be
fl... | e9e1f6efc2fb677e1f5661797deb5398a469c5ec | 629,485 |
import torch
def hard_example_mining_cosemb(dist_mat, labels, cids):#, return_inds=False):
"""For each anchor, find hard positive and negative sample.
using cosine embedding formula
Args:
dist_mat: pytorch Variable, pair wise distance between samples, shape [N, N]
labels: pytorch LongTensor, w... | e5ef101fa3ae5df69cc093b4cf3ea587a01ff601 | 629,487 |
import torch
def reverse_letter_box(h, w, input_size, boxes, xywh=True):
"""
:param h: 输入网络的图片的原始高度
:param w: 输入网络的图片的原始宽度
:param input_size: 网络的固定输入图片大小
:param boxes: Tensor, shape: (..., 4(cx, cy, w, h))
:param xywh: Bool, True:boxes是(cx, cy, w, h)格式, False: boxes是(xmin, ymin, xmax, ymax)格式... | 2d7f37ef4328d2848bade47d7808455d46012863 | 629,488 |
import re
def FixRegexPatterns(obj):
"""
* Fix regular expression patterns before
outputting to appsettings json files.
Input:
* obj: String, List or Dictionary.
"""
if not isinstance(obj, (str, list, dict)):
raise Exception('obj must be a string, list or a dictionary.')
if isi... | b22e2230d00c4354659f64ec88d92f2b310fce0c | 629,489 |
def get_coord(vec,size,inter_dist):
"""
Converts a vector of two real values (a, b) to the coordinates of point (x, y).
(a,b) = [(x-x_c)/inter_dist, (y-y_c)/inter_dist], if a,b are in range from -1 to 1,
then (x,y) - some point inside the central square with side 2*inter_dist
"""
center = size[0... | 53d2cff40821aadceadd09010e522af9df1d3bfa | 629,490 |
def fill_runoff_array(
flux, istart, di, jstart, dj, depth_of_flux, runoff, run_depth,
area):
"""Fill the runoff array.
"""
number_cells = di * dj
total_area = number_cells * area[istart, jstart]
w = flux / total_area * 1000. # w is in kg/s not m/s
runoff[istart:istart + di, js... | 5fb1ec4c7bfbd641833d918a28ecbb4f230c8a88 | 629,493 |
import json
def save_json(data, path_target: str):
"""
Saves json data to file at given path.
:param data: Json to save.
:param path_target: Path where to store the json data. String.
"""
with open(path_target, 'w') as outfile:
json.dump(data, outfile)
print('Json saved to:', path_... | d8ce4bd067f20dcfaf0c99c7d3a869587b631ab2 | 629,494 |
from pathlib import Path
import string
def alphabet_file(tmpdir):
"""Fill a temporary file with the alphabet, one letter per line."""
filename = Path(tmpdir) / "data"
open(filename, "w").write("\n".join(string.ascii_lowercase))
return filename | 7591f0bf1a1b54e16a6fd5cb06846a7ff231bf2d | 629,495 |
def freq(rc_matrix):
"""
freq = read counts for this pair / total reads in this matrix
"""
total_reads = rc_matrix.values.sum()
# normalize the score by +1
rc_matrix += 1
freq = rc_matrix / total_reads
return freq | 44fbc84e468820f7be5144ca2f5e0a18a9017a1f | 629,496 |
import re
def definedinfile(filename, val):
""" Check if val is defined in the file """
for line in open(filename):
if re.search(val, line):
return True
return False | b5c8eaaf63813b2ae84eec96238976a480d591f0 | 629,498 |
import json
def parse_json_string(json_string):
"""Parse json string to object, if it fails then return none
:param json_string: json in string format
:type json_string: str
:return: object or none
:rtype: dict/None
"""
json_object = None
if not isinstance(json_string, str):
... | 71552552022cc82c425780fe8713e17d91ebc8b7 | 629,501 |
def edge_id_by_sender_and_receiver(connectivity, sid, rid):
"""Get edge id from the information about its sender and its receiver.
Parameters
----------
metadata: list
list of pgn.graph.Edge objects
sid: int
sender id
rid: int
receiver id
Returns
-------
""... | e6a5a42e57c482bff9370b9bdcf9ca6837357b72 | 629,502 |
import random
def read_uptime():
"""
Mocks read_updtime as this is a Linux-specific operaiton.
"""
return random.randint(0, 999999999) | 431f258f458fe32849e53236af4a31e6f02d07ed | 629,503 |
def chunk_into_passages(doc_offsets,
doc_stride,
passage_len_t,
doc_text):
""" Returns a list of dictionaries which each describe the start, end and id of a passage
that is formed when chunking a document using a sliding window approach. ""... | af76dd6f994c3eeb26175c0cf7fa05761b85749d | 629,505 |
def GetNewIssueStarrers(cnxn, services, issue_id, merge_into_iid):
"""Get starrers of current issue who have not starred the target issue."""
source_starrers = services.issue_star.LookupItemStarrers(cnxn, issue_id)
target_starrers = services.issue_star.LookupItemStarrers(
cnxn, merge_into_iid)
return set(... | 403fdf91bc8dd1df347217efa10467b8829bac54 | 629,506 |
def prior(position, gf):
"""A generic prior function."""
prior_prob = 0
for i, prior in enumerate(gf.priors):
prior_prob += prior.pdf(position[i])
return -prior_prob | 8bd0c52fd71c4f7467d0857dac2592e65190985e | 629,507 |
def computeF(V_max, rho_max, rho):
"""Computes flux F=V*rho
Parameters
----------
V_max : float
Maximum allowed velocity
rho : array of floats
Array with density of cars at every point x
rho_max: float
Maximum allowed car density
Returns
-------
... | a18869e3c13a7c6dca556a1b861bf655101327f7 | 629,508 |
def _avg(readings):
"""Python 2.7 does not have an average function"""
return sum(readings, 0.0) / len(readings) | d1c2a7e427a7fadf6468a39964ef6f094a4c7cf7 | 629,509 |
def get_atomic_number(molecule, atom_index):
"""Get the atomic number of an atom for a specified index.
Returns the atomic number of the atom present at index atom_index.
Parameters
----------
molecule : Molecule
The molecule to which the atom belongs.
atom_index : int
Index of... | 00b232fff40237203a77ae15f5c2e422304a581b | 629,510 |
def value_wrap(fn, *args):
"""
pure jank
"""
try:
return fn(*args)
except ValueError as e:
print(e)
return value_wrap(fn, *args) | 9ea3d7dd835577705e907253b20c78218bffa49e | 629,511 |
import os
def sample_id_from_dir(dir_path):
"""Return the sample id of a sample directory as defined by the cfsan snp pipeline.
This assumes the files for the sample are placed in a directory whose basename is the sample_id.
Parameters
----------
dir_path : str
Path to the directory.
... | 2a4162633cce3c312c1c55ee6a099ed9d9700a9e | 629,512 |
import math
def euclideanDistance(instance1, instance2, length):
"""
Calculate a euclidean distance between 2 tensors.
The lenght correspond to the lenght of the tensors after encoding a face it will always be 128.
:param instance1: encoding face tensor (shape 128)
:param instance1: enc... | 7c390e766c6d6516e0592f6914ca419620921492 | 629,513 |
def uri_sort_key(uri):
"""return a sort key for the given URI, based on whether it represents the primary work in the record"""
if uri.startswith('http://urn.fi/URN:NBN:fi:bib:me:'):
priority = int(uri[-2:]) # last two digits are 00 for the primary work, 01+ for other works mentioned
else:
p... | 2223ca084af9b81cb5ce24fdb6c671038973be85 | 629,514 |
import functools
def kfacmp_unsqueeze_if_missing_dim(mat_dim):
"""
Allows Kronecker-factored matrix-matrix routines to do matrix-vector products.
"""
def kfacmp_wrapper(kfacmp):
@functools.wraps(kfacmp)
def wrapped_kfacmp_support_kfacvp(mat):
is_vec = len(mat.shape) == mat... | 19c0898e2b80a7f753c32c748b12b9647ea037d7 | 629,515 |
def _from_stdin(prompt, default=None):
"""
Read from stdin, if default is not set to None, some input is expected.
Parameters
----------
prompt: str
The stdin prompt.
default:
Default value.
Returns
-------
value read
"""
while True:
return_val =... | 4aa6ebe6a346b0f712c0631d2c41906b300106d6 | 629,516 |
def get_ticket_detail(tickets):
"""
Iterate over ticket details from response.
:param tickets: ticket details from the response.
:return: List of ticket details which include required fields from resp.
"""
return [{
'TicketNumber': ticket.get('ticketNumber', ''),
'TicketStatus':... | 6c908863086b4f51d913fa6cee76c22ba9fb3a01 | 629,517 |
def getprop_PythonQt(prop):
"""getprop(property_or_getter)
Used on getters that have the same name as a corresponding
property. For PythonQt, this version will just return the
argument, which is assumed to be (the value of) a python property
through which PythonQt exposes Qt properties."""
ret... | c766c4db084e4403a4ec13935892080095e73c6f | 629,518 |
def _get_local_cache_repo_path(repo_ctx):
""" Return a default local path to clone the repository into else return the cache_directory attribute if supplied
(default location: $HOME/.git-cache/<repo-name>)
Args:
repo_ctx: Repository context of the calling rule
Returns:
... | fa01762f48dc97959ba3ccd696182167dcbacd22 | 629,519 |
def is_collection_key(value: str) -> bool:
"""<project id>/collections/s/<name>"""
if isinstance(value, str):
keys = value.split("/")
if len(keys) == 4 and str.isdigit(keys[0]) and keys[1] == "collections":
return True
return False | a7781e19e6afc30894643faab6e2ad8b1ce538d7 | 629,521 |
def _get_col_that_is_primary(common_cols, featuregroups):
"""
Helper method that returns the column among a shared column between featuregroups that is most often marked as
'primary' in the hive schema.
Args:
:common_cols: the list of columns shared between all featuregroups
:featuregro... | f9bdab097c73bc1a447e02d1929f5e9b4804c717 | 629,522 |
def merge(item_list):
""" 组装controller参数 """
url_list = []
for prefix, suffix_list in item_list.items():
for item in suffix_list:
url_list.append({
"url": prefix + item[0],
"view": item[1],
"endpoint": item[2]
})
return url... | eb04dcd86ce9f58120e44652ca14abf461b812fd | 629,523 |
def recent_date(**kwargs):
"""Select a recent date range for a location selector.
:keyword resolution: One keyword time resolution specifier, e.g. ``hours``
or ``days``.
:type resolution: int
>>> recent_date(months=6)
{'recent': {'months': 6}}
>>> recent_date(weeks=3)
{'recent': {'... | c61cd3f43def9253b076fd2761d190ae7b354d2f | 629,524 |
def navigate(obj, attr_path):
"""get the final attribute, will raise AttributeError when attr not exists
>>> navigate(dict(), '__class__.__name__')
'dict'
"""
attrs = attr_path.split('.')
target = obj
for attr in attrs:
target = getattr(target, attr)
return target | 5a57b273c4dc50dd0ff2d8472d003898b27170f2 | 629,525 |
def ordinal_suffix(n):
"""The ordinal suffix of integer *n* as a string."""
if n % 100 in [11, 12, 13]:
return 'th'
else:
return {1: 'st', 2: 'nd', 3: 'rd'}.get(n % 10, 'th') | eb96c4c4497831f9480c4e03b00b0786eb826526 | 629,526 |
def even_digits_large_data(t, *args):
""" The large data set has has values greater than 10 ** 5
For these, it is worth doing a computation to more quickly
discover our answer.
"""
def decide_down(i, digits):
last_pos = len(digits) - 1
if i + 2 > last_pos:
if i +... | a4dd257bf6e89f55491b4a91abb4b10a29b0b8c2 | 629,527 |
def makeTiles(db, args):
"""
Given a deepBlue object, return a list of regions that will be queried
"""
out = []
for (k, v) in db.chromsTuple:
start = 0
while start <= v:
end = start + args.binSize
if end > v:
end = v
out.append([k,... | 99d8af04945a7e224ab2d7335ff2f185a81507f2 | 629,528 |
def get_dims(slices):
"""Given a set of slices, gets number of pixels along x,y,z of reconstructed
volumetric image."""
ds = next(iter(slices)) #Takes an arbitrary element of slices
x_count = ds.Rows
y_count = ds.Columns
z_count = len(slices)
return (x_count,y_count,z_count) | b57742195aaa43249bc689e70f6dbd33b5cb5793 | 629,529 |
def index2label(ser):
"""Given series, return xtick label"""
return ' '.join(map(str, ser.values)) | a7d75f63c4f0192aa678edf556671cd0246481f2 | 629,530 |
from typing import List
def pessimistic_aggregation(alternative_assessment: List[int]) -> int:
"""
Aggregates the assessments of an alternative, using the minimum as aggregation function.
Args:
alternative_assessment: A list of integers, representing the assessments made of an alternative by a gr... | 29cf146e87e9d35fbb3e87ab82b0e0ea510e7234 | 629,531 |
import socket
def getPrimaryHostIpByUdp(sPeerIp = '255.255.255.255'):
"""
Worker for getPrimaryHostIp.
The method is opening a UDP socket targetting a random port on a
limited (local LAN) broadcast address. We then use getsockname() to
obtain our own IP address, which should then be the primary ... | 439c64a0929b31ab958fbeefe91f0e44eed31ff5 | 629,532 |
import math
def VD_553(FA, As, IBers, Phi_en, Ssym, a, lK, lers, dS, d3, Es, Ep):
"""
5.5.3 Alternating stress
"""
#
I_Bers = IBers - (math.pi / 64.) * d3**4
# (5.5/37)
sigma_SAb = ((1 + (1.0 / Phi_en - Ssym / a) * (lK / lers) * (Es / Ep)
* (math.pi * a * dS**3 / (8... | 413279f0ea63fd057c53aa7075ab09ce43486b57 | 629,533 |
import subprocess
def get_number_of_reads_fastq(filepath):
"""
Count the number of reads in a (gzipped) FASTQ file.
Assumes fours lines per read.
:type filepath: str
:rtype: int
"""
num = subprocess.check_output("zcat %s | echo $((`wc -l`/4))" % filepath,
... | c994d5eee5e2f8951df174c188ba789b737ba19b | 629,534 |
def osd_scenario4(osd, devices_dict, dmcrypt=False, batch=True):
"""
OSD scenario type7 generator
Args:
osd: osd node
devices_dict: dict of devices of the osd node supplied
dmcrypt: False by default
batch: True by default
Returns:
generated scenario, dmcrypt,batch... | 51c8eff187edcedd4a8118a61a25c342d8662a6a | 629,535 |
def purge(data):
"""
Removes all data entries with a blank game name.
:param data: the data read from titlekeys.json
:type data: list
:returns: the data devoid of entries having blank game names
:rtype: list
"""
return [d for d in data if d.get("name")] | 6d5e463161e0b631ebc705211c27676b80e06b73 | 629,536 |
import math
def complexLog(value, base = math.e):
"""Computes the log of a complex number."""
mag = (value*value.conjugate()).real**.5
tan_theta = value.imag/value.real
theta = math.atan(tan_theta)/math.log(base, math.e)
return complex(math.log(mag, base), theta) | 6af6e965b82e5755dd3a76da06ac30c584fa75f1 | 629,537 |
def team_sign(team: int) -> int:
"""Gives the sign for a calculation based on team.
Arguments:
team {int} -- 0 if Blue, 1 if Orange.
Returns:
int -- 1 if Blue, -1 if Orange
"""
return 1 if team == 0 else -1 | 41b5e9983212fc866fe596b9df9ef8ba6de1630d | 629,538 |
def _get_pt_to_obj(cvt_archive):
"""Creates a dict from centroid index to objective value in a CVTArchive."""
data = cvt_archive.as_pandas(include_solutions=False)
pt_to_obj = {}
for row in data.itertuples():
# row.index is the centroid index. The dataframe index is row.Index.
pt_to_obj[... | 1b975388f5d0d08735f3618ed2d8b6cd3da10f5e | 629,539 |
def count_co_occurrences(line):
"""
Create a dictionary with super hero ID and number of appearances
:param line: a line from the text file
:return: a dictionary
"""
elements = line.split()
return int(elements[0]), len(elements) - 1 | 0ad373e0616560e43fe855c892d525758b6a9bdc | 629,540 |
def has_cycle(head):
"""
Floyd’s Cycle-Finding Algorithm implementation
"""
if not head:
return False
tortoise = head
hare = head
while hare and hare.next:
tortoise = tortoise.next
hare = hare.next.next
if tortoise == hare:
return True
retu... | f952cce3ce1e92083d2e8ba41a825cf1fea878ab | 629,541 |
def getac(x):
"""Shortcut to return the second value of a data line. """
return x.split(":\\t")[1] | 55736014cea82563a969bcbfe986c15022fed570 | 629,542 |
from typing import OrderedDict
import random
def get_random_alert(key_count, rule_name, omit_rule_desc=False):
"""This loop generates key/value pairs with a key of length 6 and
value of length 148. when formatted, each line should consume
160 characters, account for newline and asterisk for bold.
... | 615f219b2484930351e8199cc9a8a188ff29edd7 | 629,543 |
def _lorenz_curve_integrator(lc_pts, method):
"""Calculates the area under a Lorenz curve.
Notes
-----
Could be utilized for integrating other simple, non-pathological
"functions" where width of the trapezoids is constant.
"""
x, y = lc_pts
# each point differs by 1/n
dx = 1 / x.s... | 010b0bc8b71bb28960fe72f73f47c9ac5aecd261 | 629,544 |
def apply(func, args, kwargs):
"""
a helper method that applies args and kwargs to given function and gets the result.
:param function func: function to be used.
:param tuple args: function positional arguments.
:param dict kwargs: function keyword arguments.
:returns: function result
"""
... | 37b2f1ee85c195398c608cc1ae6946e0940cfe77 | 629,545 |
def get_1D_overlap(eclusters, depth=1):
"""
Find blocks that are 1D overlapping,
returns cliques of block ids that are in conflict
"""
overlap_set = set()
active = set()
ends = []
for i, (chr, left, right) in enumerate(eclusters):
ends.append((chr, left, 0, i)) # 0/1 for left/... | 200f8349e50b84d1eb7cd17c2b39e37d7734cee0 | 629,546 |
def _get_translated_node(target_node, target_dom_to_doc_dom):
"""Convenience function to get node corresponding to 'target_node'
and to assign the tail text of 'target_node' to this node."""
dom_node = target_dom_to_doc_dom[target_node]
dom_node.tail = target_node.tail
return dom_node | 8b356c8acddbad1279b066ebc36a8799994558c3 | 629,547 |
def exp(x):
"""Return ``e**x``."""
return 1.0 | cd9e863f4bb0a5546092563533fdf9bf3ac929c4 | 629,548 |
import argparse
import sys
def parse_arguments():
"""
Parse the arguments given on the command line.
"""
parser = argparse.ArgumentParser(prog='LemonSpotter')
# general flags
parser.add_argument('-v', '--version',
action='version',
version='%(p... | 9079dd64dad39480ff85588a3ce90f2533ce4400 | 629,549 |
def centreGravite(atomsPositions, helice):
"""Calcule le centre de gravité de l'hélice à partir de getAtomsPositionsBetween
"""
# ATTENTION: les masses atomiques de O1- et N1+ ne sont peut être pas les bonnes
atomicMass = {'C': 12.0107, 'H': 1.00784, 'O': 15.999,
'O1-': 15.999, 'S': 16... | 2da3b543abab47a4fb49d9afd29ff08e0ab6237b | 629,550 |
def tree_child(tree, cname):
"""Locate a descendant subtree named cname using breadth-first search and
return it. If no such subtree exists, return None."""
for st in tree.iter_subtrees_topdown():
if (st.data == cname):
return st
return None | 43979bdc05a14cfa3f854cc798bdbfb6e59963e9 | 629,552 |
def explicit_transform(tarinfo):
""" Reject files with 'bar' anywhere in their path """
if 'bar' in tarinfo.name:
return False
else:
return tarinfo | e0d58c825ea3ea9ceb862789bc0799d5e5e964b3 | 629,553 |
import subprocess
def check_notary_status(uuid: str, username: str, password: str) -> int:
"""Get the notarization status of a given UUID.
Arguments:
uuid (str): The UUID of the app to check the status of.
username (str): The user that submitted the notarization request.
password (str... | 2b674f07eab269f2916a1790028d6154a1539b04 | 629,554 |
import os
def fixture_file():
"""
Helper to load fixture files by name.
"""
def load(name):
filepath = os.path.join(os.path.dirname(__file__), "fixtures", name)
with open(filepath, "rb") as f:
return f.read().decode("utf-8")
return load | 4d6ad1460ad925a04badd1c16894ae95a297de42 | 629,555 |
def shutdown_without_logon(on=0):
"""Habilitar Desligamento a Partir da Caixa de Dialogo de Logon
DESCRIPTION
Quando este ajuste esta habilitado, o botao de desligamento e mostrado
na caixa de dialogo de autenticacao quando o sistema inicia. Isto permite
que o sistema seja desligado se... | 6200bf71c2daeafd4b7ae3fc1ecf16c4e59dc7f2 | 629,556 |
def _Append(text):
"""Inserts a space to text if it is not empty and returns it."""
if not text:
return ''
if text[-1].isspace():
return text
return ' ' + text | a8e879cdda734387bf0f8dbbb7b80bf93ab01bcd | 629,557 |
import functools
import socket
import os
def requires_network(only_local_network=False):
"""
Simple decorator which is supposed to skip a test case in case there's no
network connection to the internet.
"""
def decorator(func):
@functools.wraps(func)
def wrapper(cls, *args, **kwar... | 8859a1f65fdec9b054248ef9bc58dc9831ad67b5 | 629,558 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.