content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
from pathlib import Path
import ast
def get_messages(src):
"""gets the directly connected nodes of a peer"""
messages_path = str(Path(__file__).parent.parent.parent) + \
"/.data/messages/"
try:
with open("{0}/{1}".format(messages_path, src), "r") as messages_file:
... | 35f8b81c2f5fac916b284fe87af1cc03bbb67006 | 675,109 |
def selectNGramModel(models, sentence):
"""
Requires: models is a list of NGramModel objects sorted by descending
priority: tri-, then bi-, then unigrams.
starting from the beginning of the models list, returns the
first possible model that can be used for the current sentence
based on... | 540dee7762e1b8b2a11ac631a26bc127d28264e6 | 675,110 |
def isHexadecimalPalindrome(num):
"""assumes num is an integer
returns True if num in hexadecimal form is a palindrome, else False"""
return str(hex(num))[2::] == str(hex(num))[:1:-1] | a74462fab2dcc3c46c1ee17997d1cfee2f6dafdb | 675,111 |
def search_non_residue(p):
"""Find a non residue of p between 2 and p
Args:
p: a prime number
Returns:
a integer that is not a quadratic residue of p
or -1 if no such number exists
"""
for z in range(2, p):
if pow(z, (p - 1) // 2, p) == p - 1:
... | d74762a11f7557089f58be6b41840aa60074c00d | 675,112 |
def unique_list(obj, key=None):
"""
Remove same element from list
:param obj: list
:param key: key function
:return: list
"""
checked = []
seen = set()
for e in obj:
_e = key(e) if key else e
if _e not in seen:
checked.append(e)
seen.add(_e)
... | 5391a34c91c38da461402eb9a5c7ade68bb9972e | 675,113 |
import os
def seq_to_pathsep(x):
"""Converts a sequence to an os.pathsep separated string."""
return os.pathsep.join(x) | b306a46d154c7d367dd6f125249bd4f8b18e8b28 | 675,114 |
def get_function_input(function):
"""
Return a with the single input that is documented using
api.decoratos.input
"""
parameters = []
if hasattr(function, 'doc_input'):
(description, return_type, required) = function.doc_input
parameters.append({
'name': 'body',
... | 4f733818dc02752e8ed98d5b6c20466c048c9524 | 675,115 |
import json
def _zk_data_to_dict(data):
"""json load data retreived with zk_client.get()"""
if not isinstance(data, str):
data = data.decode('utf-8')
return json.loads(data) | 0a40238b67ea8a3a51d63b1569148f87ed678f98 | 675,116 |
import six
def _generate_faux_mime_message(parser, response, content):
"""Convert response, content -> (multipart) email.message.
Helper for _unpack_batch_response.
"""
# We coerce to bytes to get consistent concat across
# Py2 and Py3. Percent formatting is insufficient since
# it includes t... | 972dac3d4d8f6bb73a09c1faca6a9282cfb5dc0c | 675,117 |
import subprocess
def flake8(path, *args):
"""Run flake8."""
proc = subprocess.run(
['flake8', '--select', 'A,E,F,W,C',
'--ignore', 'E201,E202,E203,E221,E222,E241,F821', '.'] + list(args),
stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=str(path))
stderr = proc.stderr.decode()... | efe1e21937307f6b669bb0bae4685731a81a1d8e | 675,118 |
def same_orientation(lineA, lineB):
"""Return whether two paired end reads are of the same orientation."""
# SAM flags
reverse = 16
mate_reverse = 32
flagA = int(lineA.split()[11])
flagB = int(lineB.split()[11])
return ((flagA & reverse) == (flagB & reverse) and
(flagA & mate_... | edc352006163794acd5c41629305f7f8df2320a8 | 675,119 |
def latest_lines(lines, last):
"""Return lines after last and not empty
>>> latest_lines(['a', 'b', '', 'c', '', 'd'], 1)
6, ['c', 'd']
"""
last_lnum = len(lines)
latest = [l for n, l in enumerate(lines, 1) if n > last and l.strip()]
return last_lnum, latest | b0890ae4cb11face42efd01937165f14a7f2ba79 | 675,120 |
def statement(line):
"""Converts if statements"""
if "if " in line and not 'elif' in line:
lsplit = line.split('if ', maxsplit=1)
ls = lsplit[0] + 'if '
rs = lsplit[1]
# Replace the ':' at the end of the statement
rs = lsplit[1].replace(':','{')
rs = '(' + rs
... | f5afb9ce806b422b6c30d56cce98176d03a09f6b | 675,121 |
def gradient_t(prev_image, image):
"""Find gradient along time: time derivative using two images
Arguments:
prev_image {tensor} -- image at timestamp 1
image {tensor} -- image at timestamp 2
Returns:
tensor -- time derivative of image
"""
return prev_image-image | 509848cdc51bfd5783febca3722d7474c5b510b6 | 675,122 |
def _indentation(line):
"""Returns the length of the line's leading whitespace, treating tab stops
as being spaced 8 characters apart."""
line = line.expandtabs()
return len(line) - len(line.lstrip()) | 4f43618f642ad9b50a80901a31fadfd44a7dfce2 | 675,123 |
def task_key(task):
"""返回给定 task 的排序键"""
function, args = task
return function.__name__, args | 5dd286e5f0ae33ce032e12b6acc002357e153dc9 | 675,124 |
def sum_fuel_across_sectors(fuels):
"""Sum fuel across sectors of an enduse if multiple sectors.
Otherwise return unchanged `fuels`
Arguments
---------
fuels : dict or np.array
Fuels of an enduse either for sectors or already aggregated
Returns
-------
sum_array : np.array
... | 6a9dea9be2899bd9884106333c550e1ccf619883 | 675,125 |
import itertools
def element_ancestry(element):
"""Iterates element plus element.parents."""
return itertools.chain((element,), element.parents) | 523fb5b4749ba33e2ddee9bad23c480ffcf5f66b | 675,126 |
def dasherize(word: str) -> str:
"""Replace underscores with dashes in the string.
Example::
>>> dasherize("foo_bar")
"foo-bar"
Args:
word (str): input word
Returns:
input word with underscores replaced by dashes
"""
return word.replace("_", "-") | 4a255f0d68106fd8a169e5a2a3ad63b86ba069cf | 675,127 |
def log2floor(n):
"""
Returns the exact value of floor(log2(n)).
No floating point calculations are used.
Requires positive integer type.
"""
assert n > 0
return n.bit_length() - 1 | d29fb7e60bfc233aa6dbad7ffb8a1fe194460645 | 675,128 |
def _recipe_type(raw_configuration):
"""
Given a raw repository configuration, returns its recipe type.
:param raw_configuration: configuration as returned by the SCRIPT_NAME_GET
groovy script.
:type raw_configuration: dict
:return: Group, Proxy or Hosted
"""
return raw_configuratio... | fda2bf9ff0043400c99f52b683adffd80adb7943 | 675,129 |
def standardize(X):
""" Standardize data set by mean and standard deviation """
mu = X.mean(axis=0, keepdims=True)
s = X.std(axis=0, keepdims=True)
return (X-mu)/s | 1857d60191415c91bacec8d066d0d70bede1129a | 675,131 |
def detection_center(detection):
"""Computes the center x, y coordinates of the object"""
#print(detection)
bbox = detection['bbox']
center_x = (bbox[0] + bbox[2]) / 2.0 - 0.5
center_y = (bbox[1] + bbox[3]) / 2.0 - 0.5
return (center_x, center_y) | c3a3465abea09ff9952fccbdec55563c26989d39 | 675,132 |
def delay(a=0.2, b=0.8):
"""Random delay between `a=0.2` and `b=0.8`"""
return 0.3 | d5959ba4f19c946e5d4ac704e20d5c84ab839773 | 675,133 |
import requests
def get_countries_names() -> list:
"""
Function for getting list of all countries names procived by public
COVID-19 api on site "https://api.covid19api.com"
Returns
-------
List with all countries names.
Example
-------
>>> countries_names = get_countries_names()
... | ce15682922799a8ece5590ce51184a92d628788f | 675,134 |
def duplicate(image):
"""Copy a channel. Alias for :py:meth:`PIL.Image.Image.copy`.
:rtype: :py:class:`~PIL.Image.Image`
"""
return image.copy() | b4fb666851e4c17891d371646b321d6c6a76a775 | 675,135 |
def overlaps(pattern_a, pattern_b):
"""Returns a boolean indicating if two patterns are overlapped.
Args:
pattern_a: SimilarPattern or TimeSpan.
pattern_b: SimilarPattern or TimeSpan.
Returns:
boolean indicating if the patterns are overlapped.
"""
start_a = pattern_a.start_time
start_b = patter... | ab0e00ef8503107b72f1e819eca91f5ce5c87d3c | 675,136 |
def pre_post_columns(tools):
"""
Returns all the column headers, and headers of columns containing
normalized citation counts belonging to when before and after a
tool was added to the repository.
"""
column_headers = tools.columns.values.tolist()
pre = []
post = []
for header in c... | cd89021e3dbff1ab879e8edf0cd9bd30b6845ec6 | 675,137 |
def distance_residues(r1, r2):
"""Return the distance between two residues."""
center_1 = r1.get_mass_center()
center_2 = r2.get_mass_center()
return (sum(map(lambda t: (t[0] - t[1])**2, zip(center_1, center_2))))**0.5 | d927d6ab0575f1c11cf24b7d2ddfe498f1532afd | 675,139 |
def max_weighted_independent_set_in_path_graph(weights):
""" Computes the independent set with maximum total weight for a path graph.
A path graph has all vertices are connected in a single path, without cycles.
An independent set of vertices is a subset of the graph vertices such that
no two vertices ... | 3be9d7dd54b939260f37ff2c97c18f18df0644b5 | 675,141 |
import argparse
def build_parser():
"""Set up argument parser and returns"""
parser = argparse.ArgumentParser(
description='Checks for new requests to multiple teams')
parser.add_argument('teams', metavar='id', type=str, nargs='*',
help='A list of teams to monitor for chang... | 675540edf6e4506cde6bf8ba240ebc53eddf209b | 675,142 |
def select_with_processing(selector, cluster_sim):
"""A selection wrapper that uses the given operator to select from
the union of the population and the currently processing individuals.
"""
def select(population):
return selector(population + cluster_sim.processing)
return select | 76cf35e02dfe391ff3e2b6f552a36b87d2ce5cf9 | 675,143 |
def get_si(simpos):
"""
Get SI corresponding to the given SIM position.
"""
if ((simpos >= 82109) and (simpos <= 104839)):
si = 'ACIS-I'
elif ((simpos >= 70736) and (simpos <= 82108)):
si = 'ACIS-S'
elif ((simpos >= -86147) and (simpos <= -20000)):
si = ' HRC-I'
elif ... | fadf3d641c30cec35e73b100cd78a55d5808cbd0 | 675,144 |
import json
def get_parameters(template):
"""
Builds a dict of parameters from a workflow manifest.
Parameters
----------
template : dict
Returns
-------
dict
Parameters.
"""
parameters = {}
prefix = "PARAMETER_"
for var in template["container"]["env"]:
... | 2f31f2729a9127606df5f7847827dac746addcce | 675,145 |
import argparse
def get_parser():
"""return arg parser"""
p = argparse.ArgumentParser(description="""Make a subreads.bam/xml containing all reads of a fasta file""")
p.add_argument("in_fasta", help="Input FASTA file")
p.add_argument("in_bam_fofn", help="Input BAM fofn")
p.add_argument("out_prefix"... | 3d32707686f6a4865d90578abfc0031c3dd487c3 | 675,146 |
def create_index_of_A_matrix(db):
"""
Create a dictionary with row/column indices of the A matrix as key and a tuple (activity name, reference product,
unit, location) as value.
:return: a dictionary to map indices to activities
:rtype: dict
"""
return {
(
db[i]["name"],
... | 2abb7f67f358127f659588599a9f02f691614422 | 675,147 |
def current_green_or_left(before, after, current=None):
"""
Checks if green and left green lights works well.
:param before: has to be None, "yellow" or "blink"
:param after: has to be None or "blink"
:param current: Set as default None, so it won't trigger tests as the colour is only relevant for p... | 5b265e81839b208cf3200aab483d628a8fb86a20 | 675,148 |
def get_conversion_plus_io(backend_model, tier):
"""
from a carrier_tier, return the primary tier (of `in`, `out`) and
corresponding decision variable (`carrier_con` and `carrier_prod`, respectively)
"""
if "out" in tier:
return "out", backend_model.carrier_prod
elif "in" in tier:
... | 92df1577c9ce711c10ebb511bb187f43b04db74a | 675,149 |
import io
def decode_int8(fh: io.BytesIO) -> int:
"""
Read a single byte as an unsigned integer.
This data type isn't given a special name like "ITF-8" or "int32" in the spec, and is only used twice in the
file descriptor as a special case, and as a convenience to construct other data types, like ITF... | b20de27afb0af997449f7e178bba0d91322e234c | 675,150 |
def __test_data_five():
"""Test data"""
return [
(4, 5, 95),
(1, 4, 52135),
(3, 4, 12136),
(3, 5, 62099),
(4, 5, 50458),
] | 0368c39f6944bb6dead618db5f3d675144c6b591 | 675,151 |
def notas(*n, sit=False):
"""
--> recebe as notas e grava em um dicionario
:param n: notas
:param sit: Opcional de mostrar ou não a situação
:return: retrona um dicionario
"""
lista = [*n]
dic = {'total': len(lista), 'maior': max(lista), 'menor': min(lista), 'média': sum(lista) / len(lis... | 6ff4b2f146459cace61df91cc8e8a16560628c40 | 675,152 |
import struct
import fcntl
import termios
def get_terminal_size():
"""
Get terminal width and height
Return (width, height) tuple
"""
h, w, hp, wp = struct.unpack('HHHH',
fcntl.ioctl(0, termios.TIOCGWINSZ,
struct.pack('HHHH', 0, 0, 0, 0)))
return w, h | 7535b3b2915649e85465742c875d6fba0bac38d1 | 675,153 |
def full_qualified(pkg, symbols):
"""
パッケージ名と、文字列表記されたシンボルのリスト(このEus_pkgクラスと対応するEuslispのパッケージ以外のシンボルが含まれていても良い)を受け取る。
対応するパッケージ内のシンボルのみを取り出し、それぞれパッケージ接頭語(大文字)をつけ、リストにして返す。
>>> full_qualified("TEST", ['var1', 'OTHER-PACK::var2', 'LISP::var3'])
['TEST::var1', 'LISP::var3']
Args:
pkg (str... | 0599e6efa4ddd12a3a11a976e3de731623fe550c | 675,154 |
import pickle
def LoadModel(filname):
"""
Load a model using pickle
Parameters
----------
filname : str
model file name.
Returns
-------
model : dict
Output of BuildModel methode, a dict with:
-"model" an sklearn trained random forest classifier.
... | ccf500e02c912a7fc9db15924524ce21ca1e651f | 675,155 |
import ctypes
def _malloc_char_array(n):
"""
Return a pointer to allocated UTF8 (C char) array of length `n'.
"""
t = ctypes.c_char * n
return t() | a67c6101e243392388fcba723dd37e4fe00cc0a1 | 675,156 |
def _validate_list_int(s, accept_none=False):
"""
A validation method to convert input s to int or list and raise error if it is not convertable
"""
if s is None and accept_none:
return None
try:
return int(s)
except (ValueError, TypeError):
try:
return list(s)
except ValueError:
raise ValueError('C... | 02b4bd06331905cb2ada06b8cc86c9916617b21f | 675,157 |
def configure_camera_url(camera_address: str,
camera_username: str = 'admin',
camera_password: str = 'iamironman',
camera_port: int = 554,
camera_stream_address: str = 'H.264',
camera_protocol: s... | ef06089e84b00c070e4fe89b0bfc34afd21e3f40 | 675,158 |
def filer_elements(elements, element_filter):
"""Filter elements.
Ex.: If filtered on elements [' '], ['a', ' ', 'c']
becomes ['a', 'c']
"""
return [element for element in elements if element not in element_filter] | 205c9bae6bb28f96d67bc6a02c5bd1ed5ed6c534 | 675,159 |
from pathlib import Path
def data_folder():
"""Fixture shortcut to the test/data folder."""
return Path(__file__).parent.joinpath("data") | 1c8321ec154f6db4880769145d5bb5d05569199a | 675,160 |
def any_true_p (seq, pred) :
"""Returns first element of `seq` for which `pred` returns True,
otherwise returns False.
"""
for e in seq :
if pred (e) :
return e
else :
return False | 24c374cfbbef49be7a76ba471b61e4122f0619e3 | 675,161 |
def _resize(im, width, height):
"""
Resizes the image to fit within the specified height and width; aspect ratio
is preserved. Images always preserve animation and might even result in a
better-optimized animated gif.
"""
# resize only if we need to; return None if we don't
if im.size.width ... | 3729e1a75b1187846818489ded4a7a2b47fb67f5 | 675,162 |
def as_path(path):
"""
path の中の空白を除く
"""
path = path.replace(', ', ',') # ','の後ろの' 'を除去する
return path | 22626f099dd1a6d1a9ada3bc019e493312167283 | 675,163 |
def worker_mock(mocker):
""" Prevent the queue consumption, so that the queues could be checked. """
return mocker.patch('kopf.reactor.queueing.worker') | 07800b3aa366e48a11ad13db262e594ea4996c03 | 675,164 |
def SCPRunCmd(env, cmd, *args):
"""Returns a function to run."""
del args
return cmd.Run(env, force_connect=True) | 873f473a35f90d81d9f250d8e927d9c8f7a980fc | 675,165 |
import numpy
def multi_label_combination(output_idx, output_target, output_data, shift, output_rate, mode="mean"):
"""
:param output_idx:
:param output_target:
:param output_data:
:param shift:
:param output_rate:
:param mode:
:return:
"""
win_shift = int(shift * output_rate)
... | 01f8e5ec7dad784b3314c48f7d5dcfbe53cc32b6 | 675,166 |
def toPyModel(model_ptr):
"""
toPyModel(model_ptr) -> model
Convert a ctypes POINTER(model) to a Python model
"""
if bool(model_ptr) == False:
raise ValueError("Null pointer")
m = model_ptr.contents
m.__createfrom__ = 'C'
return m | d302ca64968a85e05d02cfc40953f26682284bac | 675,167 |
import socket
import struct
import errno
def waitForIPC(ipcPort, timeout, request):
"""Timeout is in seconds."""
#time.sleep(2)
# assume 127.0.0.1 for now
address = "127.0.0.1"
port = int(ipcPort)
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
# overall timeout in microseconds
... | 5e5b42e9d7856dd1854cbf5343d7ca4f6452605f | 675,168 |
def valid(x, y, n, m):
"""Check if the coordinates are in bounds.
:param x:
:param y:
:param n:
:param m:
:return:
"""
return 0 <= x < n and 0 <= y < m | 407ed497ea97f8a133cdffe0756d322853841ed3 | 675,169 |
def poulet():
"""Fonction appellée pour le chemin /lapin.
Returns:
str: un message de la plus grande importance
"""
return "Hello Lapin !" | 59e14348ea9e95a26e2603448e9309847f1afeb9 | 675,171 |
def _is_control_defined(node, point_id):
""" Checks if control should be created on specified point id
Args:
name (str): Name of a control
point_id (int): Skeleton point number
Returns:
(bool)
"""
node_pt = node.geometry().iterPoints()[point_id]
... | 77aced682fbe6c3f414c9781cee2d49e9ef54a14 | 675,172 |
from pathlib import Path
def rezume_mini():
"""Returns the path to the rezume-mini.yml fixture file."""
return Path("./tests/fixtures/rezume-mini.yml") | a521c765b64770e8c95760521662fdff73bffd81 | 675,173 |
import re
import json
def parse_json(filename):
""" remove //-- and /* -- */ style comments from JSON """
comment_re = re.compile('(^)?[^\S\n]*/(?:\*(.*?)\*/[^\S\n]*|/[^\n]*)($)?', re.DOTALL | re.MULTILINE)
with open(filename) as f:
content = f.read()
match = comment_re.search(content)
... | e14f5e278e85ea7d25b361f052b9fd2bed8748dd | 675,174 |
def some_ood():
"""
values
w w
5 6 5 6
+----+----+ +----+----+
1| 15 | 16 | 1| 51 | 61 |
+----+----+ +----+----+
x 2| | 26 | x 2| | 62 |
+----+----+ +----+----+
3| 35 | 36 | 3| 53 | 63 |
... | 7148edd345be449402461f7b4e98b0cabe1dec3b | 675,175 |
def debris_frommelt_func(b, a, k):
""" estimate debris thickness from melt (b is melt, a and k are coefficients) """
return 1 / k * (1 / b - 1 / a) | 32b69eddd76ee71484fd613a3d3980ce15de3b21 | 675,176 |
def levelFromHtmid(htmid):
"""
Find the level of a trixel from its htmid. The level
indicates how refined the triangular mesh is.
There are 8*4**(d-1) triangles in a mesh of level=d
(equation 2.5 of
Szalay A. et al. (2007)
"Indexing the Sphere with the Hierarchical Triangular Mesh"
ar... | 86a2ca1c7176b06c38ff1acd028349690fb34aee | 675,177 |
def return_color(index):
"""
this returns the color from the list colors
:param index:
:return:
"""
colors = ['tab:blue', 'tab:orange', 'tab:green', 'tab:red', 'tab:purple', 'tab:brown', 'tab:pink', 'tab:gray',
'tab:olive', 'tab:cyan']
num = len(colors)
return colors[index ... | a730182580dc42c6a21dd8f25a7601fbc971d9d9 | 675,178 |
def inherits_init(cls):
"""Returns `True` if the class inherits its `__init__` method.
partof: #SPC-notify-inst.inherits
"""
classname = cls.__name__
suffix = f"{classname}.__init__"
return not cls.__init__.__qualname__.endswith(suffix) | d4c39567cd9f087a48091b46a12d3d30313e98b3 | 675,179 |
import pprint
def fargs(*args, **kwargs):
"""
Format `*args` and `**kwargs` into one string resembling the original call.
>>> fargs(1, [2], x=3.0, y='four')
"1, [2], x=3.0, y='four'"
.. note:: The items of `**kwargs` are sorted by their key.
"""
items = []
for arg in args:
i... | 034ebee17ada81afee7973e53d913385a0e5f799 | 675,180 |
def clean(text):
"""
Return an updated and cleaned Text object from a `text` Text object
normalizing some pucntuations around some name and acronyms.
"""
if not text:
return text
text = text.replace('A. M.', 'A.M.')
return text | 8c17af6533e3cbf053ceaa4b0f9ada5a02d09e3f | 675,181 |
def decode_message(string, shifts):
"""Decode the message, shifting only letters in the string."""
result = ""
# Because not all characters are shifted, keep track here of the current
# shift index.
current_shift = 0
for char in string:
current_char = char
reference = None
... | 36e6a67727e30c1309f162af086de6d1ba317c38 | 675,182 |
from typing import Tuple
from pathlib import Path
def operating_system() -> Tuple[str, str]:
"""Return what operating system we are running.
Returns:
A tuple with two strings, the first with the operating system and the
second is the version. Examples: ``('ubuntu', '20.04')``,
``('cen... | f16081081f3616e2bc1d0592d49487dcb07b9ef0 | 675,183 |
import os
import subprocess
def deserialize_single_upk_file(upk_utils_dir, upk_file_filename, output_dir):
"""
:param upk_utils_dir:
:param xcom_unpacked_upk_dir:
:param output_dir:
:return:
"""
call_result = None
original_current_dir = os.getcwd()
try:
os.chdir(output_dir... | 10af12136887192065906ce352188f4da83038f3 | 675,184 |
import os
def get_out_bash_path(outdir):
"""Takes an output directory that search results are written to, and
returns a path for a file to write query file list to.
"""
return os.path.join(outdir, '0_run_searches.sh') | 1b83c2203733e1d9d3b1163ceb73d6cf8541fe97 | 675,185 |
def get_max_key(d):
"""Return the key from the dict with the max value."""
return max(d, key=d.get) | 966f5b1be593a9266d0e3239c37d5ef83cec17fc | 675,186 |
def generate_sample(id, name, controlled_metadata, user_metadata, source_meta):
"""
Create a sample record
"""
sample = {
'node_tree': [{
"id": id,
"type": "BioReplicate",
"meta_controlled": controlled_metadata,
"meta_user": user_metadata,
... | 5657d367642f8a3dd5b0b6a921c1fe8d9dc30672 | 675,187 |
import os
def is_file_writeable(path):
"""
Returns true if the file specified is write- or createable
"""
if os.path.isfile(path):
return os.access(path, os.W_OK)
else:
return os.access(os.path.dirname(path), os.W_OK) | cdaa3c38bc55d520d4cd46f90a01d1bdeb92a86b | 675,188 |
def readline_comment(file, symbol='#'):
"""Reads line from a file object, but ignores everything after the
comment symbol (by default '#')"""
line = file.readline()
if not line:
return ''
result = line.partition(symbol)[0]
return result if result else readline_comment(file) | bd964dfb2c9bc877e9c8ed3c9f280131468a7a10 | 675,189 |
def MixinRepository(wrapped, instance, args, kwargs):
"""
Signals that a repository is a mixin repository (a repository that
contains items that help in the development process but doesn't contain
primitives used by other dependent repositories). Mixin repositories
must be activated on top of other ... | be90552dd58c3917a2f3ebef7e677d27729d33a7 | 675,190 |
def fibonacci(n : int) -> int:
"""Returns the fibbonacci function at a specific point\n
** Uses the built in functool's module lru_cache decorator
"""
if n in (0,1):
return 1
return fibonacci(n-1) + fibonacci(n-2) | 7ed79349e34da6f9e112da215056a687179bb3ee | 675,191 |
import torch
def init_weights(model, weights_path, caffe=False, classifier=False):
"""Initialize weights"""
print('Pretrained %s weights path: %s' % ('classifier' if classifier else 'feature model',
weights_path))
weights = torch.load(weights_path)
if not ... | b67d138b4cd7040601422e3e196dad798ca46f5d | 675,192 |
import re
def collect_subroutine_calls(lines,ifbranch_lines):
"""
Collect a dictionary of all subroutine call instances. In the source code
on entry the "subroutine call" is given in the form of a function call, e.g.
t5 = nwxc_c_Mpbe(rhoa,0.0d+0,gammaaa,0.0d+0,0.0d+0)
we need to know the "nwxc_c_Mpbe(r... | 1c11cd4ae028323f6439dbb86693c3999ddc93cb | 675,193 |
def micro(S, C, T):
"""
Computes micro-average over @elems
"""
S, C, T = sum(S.values()), sum(C.values()), sum(T.values())
P = C/S if S > 0. else 0.
R = C/T if T > 0. else 0.
F1 = 2 * P * R /(P + R) if C > 0. else 0.
return P, R, F1 | f6d613c77af7dcd4fc59a97027b3daf71b4155af | 675,194 |
import xxhash
def get_hash(fname: str) -> str:
"""
Get xxHash3 of a file
Args:
fname (str): Path to file
Returns:
str: xxHash3 of file
"""
xxh = xxhash.xxh3_64()
with open(fname, "rb") as f:
for chunk in iter(lambda: f.read(4096), b""):
xxh.update(chun... | 677be15e6082d84aa3cb0408fe231ebe27faefa6 | 675,195 |
def avgprecision(results):
"""
:param results: List of True/False values
"""
total_points = 0.0
correct = 0.0
for i, p in enumerate(results):
position = i + 1
if p:
correct += 1
points = correct / position
total_points += points
return tot... | 5f93d8e689d24147e4cafb86db484d1f8c32b41e | 675,196 |
def get_free_memory():
"""
Try to figure out how much memory is free on a Unix system.
Returns free memory in mB.
"""
data = open("/proc/meminfo", 'rt').readlines()
free = 0
for line in data:
if line.startswith("MemFree") or line.startswith("Buffers") or line.startswith("Cached"):
... | c02db53d5c77e5f26036ffa2b0d6dc5cd79a734e | 675,197 |
def get_id_of_likers(post_link, bot) -> list:
"""It collects a set of likers id."""
id_link = bot.get_media_id_from_link(post_link)
id_of_likers = [int(id_of_liker) for id_of_liker in
bot.get_media_likers(str(id_link))]
return id_of_likers | 143c4314972c0c0d665c4a5fc8a26a1d9fc4662f | 675,199 |
def cull(data, index, min=None, max=None):
"""Sieve an emcee clouds by excluding walkers with search variable 'index'
smaller than 'min' or larger than 'max'."""
ret = data
if min is not None:
ret = ret[ret[:, index] > min, :]
if max is not None:
ret = ret[ret[:, index] < max, :]
... | ebb10ea622d9107e745089fcb3f6279faeb8c907 | 675,200 |
import yaml
from typing import OrderedDict
def yaml_ordered_load(stream, Loader=yaml.Loader, object_pairs_hook=OrderedDict):
"""Function to load YAML file using an OrderedDict
See: https://stackoverflow.com/questions/5121931/in-python-how-can-you-load-yaml-mappings-as-ordereddicts
"""
class OrderedL... | 29f2d8ddb22b6cf6ff8f0127a1e34fb58caf977d | 675,201 |
def split_dataset_sizes(stream_list, split_sizes):
"""Splits with different sizes
Args:
stream_list (list): list of stream path
split_sizes (list): batch size per worker
"""
out = []
start = 0
total = sum(split_sizes)
for split_size in split_sizes[:-1]:
num = int(spl... | cdfd37f15c852881f9c38c860d8856e1d2a7de9c | 675,204 |
def marc21_online_resources(self, key, value):
"""Get series.
series.name: [490$a repetitive]
series.number: [490$v repetitive]
"""
return {'uri': value.get('u')} | adaab85b75da6f1ce04fe5ca34d709ee3287ba5f | 675,205 |
def all_nums(table):
"""
Returns True if table contains only numbers (False
otherwise)
Example: all_nums([[1,2],[3,4]]) is True
all_nums([[1,2],[3,'a']]) is False
Parameter table: The candidate table to modify
Preconditions: table is a rectangular 2d List
"""
result = True... | 8a0f1358d3ec729b04f4171aa171cf141acc702d | 675,206 |
from typing import List
import sys
def read_stdin(auto_strip=True) -> List[str]:
"""Read STDIN into a list of :class:`.str`'s and then returns that list."""
lines = []
for ln in sys.stdin:
lines.append(ln.strip() if auto_strip else ln)
return lines | 25284256eb104969b454173dccd6d445daaf9f30 | 675,207 |
def _itemNames(comb):
""" Item names from result of knapsack01
Args:
comb tuple of tuples result of knapsack01
Returns:
tuple sorted item ids
"""
return tuple(sorted(item for item,_,_ in comb)) | fa865f2b612e63debd4a1392b7a318ccf0b69f31 | 675,208 |
def split_def_command(command):
"""Split command in parts: variable name, specific command, definition.
Return None if command is invalid.
"""
# procedo per casi
# il che significa che dopo un '@' non posso usare un ':'
# perché verrebbe intercettato per primo!
valid_commands = [":", ... | 0bb00aae0c66f7b183bb49e0a87bf6a111891135 | 675,209 |
def get_ingredients(drink_dict):
""" Create a list of ingredients and measures
Form data is passed as a dictionary. The functions iterates through
the key/value pairs and appends the ingredients and measures to its
own list called ingredients.
Args:
drink_dict : The dictionary containing t... | 5ec86b71ab8bf0d9b1d6291d7d14cbfbeff2d867 | 675,210 |
def linear (x, parameters):
"""Sigmoid function
POI = a + (b * x )
Parameters
----------
x: float or array of floats
variable
parameters: dict
dictionary containing 'linear_a', and 'linear_b'
Returns
-------
float or array of floats:
function re... | 3e2f42cdb5fa1b722c7f3fd15294e4488b99649d | 675,211 |
def rax_clb_node_to_dict(obj):
"""Function to convert a CLB Node object to a dict"""
if not obj:
return {}
node = obj.to_dict()
node['id'] = obj.id
node['weight'] = obj.weight
return node | 14526744ef608f06534011d1dcdd5db62ac8b702 | 675,212 |
import argparse
def parse_arguments(args):
""" Parse the arguments from the user"""
parser=argparse.ArgumentParser(description="Create a tile of images.")
parser.add_argument('--input',help="Comma delimited list of input image files", required=True)
parser.add_argument('--output',help="Output fil... | 88b606c4455419a556c411d7fb5367c933fdf8a4 | 675,213 |
def estimate_statematrix_from_output(output, prev):
"""Given output from the neural net, construct a statematrix"""
matrix = []
for i in range(0, 156, 2):
pair = [int(output[i] > 0), int(output[i+1] > 0)]
if pair[0] == 1:
if prev[i] > 0:
matrix.append([1, 0])
... | d2d5900c90316b41611829255a9136c2106f0e2e | 675,214 |
from typing import List
import random
def unique_floats_sum_to_one(num: int) -> List[float]:
"""return a list of unique floats summing up to 1"""
random_ints = random.sample(range(1, 100), k=num)
total = sum(random_ints)
return [(n / total) for n in random_ints] | e84e5e081571aa2a385019b522fb05d2775964d6 | 675,215 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.