content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def max_production_rule(mod, prj, tmp):
"""
**Constraint Name**: Fuel_Prod_Max_Production_Constraint
**Enforced Over**: FUEL_PROD_OPR_TMPS
Fuel production can't exceed available production capacity.
"""
return (
mod.Produce_Fuel_FuelUnitPerHour[prj, tmp]
<= mod.Fuel_Production_C... | 54c976f6f3186d41d62519702908cd300e4bab29 | 664,896 |
import argparse
def get_predict_args():
"""
Retrieves and parses the 3 command line arguments provided by the user when
they run the program from a terminal window. This function uses Python's
argparse module to created and defined these 3 command line arguments. If
the user fails to provide som... | 4b8b7d6e575188d6087de9a55d59099088565526 | 664,897 |
def legacy_id_to_url_fn(id: str) -> str:
"""Generate an arxiv.org/archive URL given a paper ID."""
return 'https://arxiv.org/archive/' + id | 05859591e6af147c2df5e958e1e2b3a4473e9376 | 664,898 |
import json
def utf8safe_encoder(obj):
"""
This fixes riak unicode issues when strings in blob are already UTF-8.
"""
return json.dumps(obj) | 8e387d2b9fe24c5e797f97594966a495d7c328d1 | 664,899 |
def coord_num(phi):
"""
Calculates coordination number value as a function of porosity using the
relationship:
n = 20.0 - 34.0*phi + 14.0*phi**2.0
The above expression was copied from Avseth's QSI book, equation 2.7 on
page 55.
Usage:
n = coord_num(phi)
Inputs:
phi = ... | 45a6fb8bf351fadc3fe981c6f6e624080812acd6 | 664,900 |
def feature_engineering(df):
"""Add statistics to raw data to analyze changes across time"""
# day-to-day change
df['result_count_absolute_change'] = df.groupby('keyword').results_count.diff().reset_index(drop=True) # day-to-day absolute change
df['result_count_relative_change'] = (df.result_count_ab... | 10198d93c27f3d45ee046c751d89188768dfc108 | 664,901 |
def get_branch(version: str) -> str:
""" Get the branch of an update """
return 'stable' if version.startswith('V') else 'weekly' | 36231a8f6aa64e7134d9eacc408a5de02124b799 | 664,903 |
def get_const_ratio_ints(ints, length):
"""f(n) = a(b^n)"""
first = ints[0]
ratio = int(ints[1] / ints[0])
return [first * (ratio ** n) for n in range(length)] | 1637819169c9f62f56fa0701d8407be0f54fc691 | 664,904 |
def _CreateGooPkgRepo(messages, repo_id):
"""Create a goo repo in guest policy.
Args:
messages: os config guest policy api messages.
repo_id: 'google-cloud-ops-agent-windows-[all|1]'.
Returns:
zoo repos in guest policy.
"""
return messages.PackageRepository(
goo=messages.GooRepository(
... | 2f67432924414c8485be9c7d1f99db4e8533e7f8 | 664,905 |
def confirm_proceed(prompt='Shall I proceed? (y/n)'):
"""
Prompts user for confirmation. Expects 'y' or 'n'.
"""
confirm = ''
while confirm not in ('y', 'Y', 'n', 'N'):
confirm = input(prompt)
if confirm in ('n', 'N'):
return False
return True | a71d78f5670eca9a13997b603e6c6805001e9167 | 664,906 |
def set_inheritance(name, top_classes, schemas):
"""Set inheritance for object with a certain name."""
# this is the list of special keys that we copy in manually
copied_keys = set(['type', 'properties', 'required'])
# remove the class itself
print(f'\nProcessing {name}')
top_classes = top_class... | e14c5cad4fe8dbfcf57d3b8a39c97ba2659fef01 | 664,907 |
def reversepath(path):
"""
This function reverses a path.
"""
return path[::-1] | 16a9b33eaf6bb4f602952c094a2e1d272ae82857 | 664,908 |
import math
def computeCoordinates(point1 : tuple, point2 : tuple) -> tuple:
"""
Compute intersection points between circles.
No/One point intersection not counted into
"""
x0, y0, r0 = point1
x1, y1, r1 = point2
d = math.sqrt((x1-x0)**2+(y1-y0)**2)
a = (r0**2-r1**2+d**2)/(2*d)
h = math.sqrt(abs(r0**2-a**2)... | 151c633be0f7fe7e419decf9f5b6481316ffbdd2 | 664,909 |
import json
def json_minimal(data):
"""Get JSON data in minimal form."""
return json.dumps(data, separators=(",", ":")) | e4b76f5decb0060f86071fed1a6fecf55012daff | 664,910 |
import collections
def get_table_data(cursor, table_name, single_row=False, replace_none=False):
"""
Extract all the data of the table
Args:
cursor: the DB cursor
table_name: the name of the database
single_row: if True, returns a single row
replace_none: if True, replace ... | f8b15f82998bc4516346d54caeed40cc5f4fea1b | 664,911 |
import os
def create_dir_callback(ctx, params, value: str):
"""
Create and return directory if it doesn't exist.
:param ctx: The click context
:param params: The click params
:param value: The value to create the directory from
:returns: The directory path
"""
os.makedirs(value, exist... | 3bebed2d11864e006e0f492aa474a7790a69ed6c | 664,912 |
def galois_multiply(a, b):
"""Galois Field multiplicaiton for AES"""
p = 0
while b:
if b & 1:
p ^= a
a <<= 1
if a & 0x100:
a ^= 0x1b
b >>= 1
return p & 0xff | f9df9ff55f58747c0c2669e3813666841f0ce8ee | 664,914 |
import os
import requests
def sign_in():
"""
Signs into breezy using account credentials
:param:
:return:
"""
user_mail = os.environ["BREEZY_USER"]
password = os.environ["BREEZY_PASS"]
my_session = requests.session()
sign_in_url = "https://app.breezy.hr/signin"
data = {
... | cfc4b42f821fe7b0b5a0ec7ca2b87dd1ebaaa18c | 664,915 |
import numpy
def make_test_ellipse(center=[1, 1], width=1, height=.6, phi=3.14 / 5):
"""Generate Elliptical data with noise
Args
----
center (list:float): (<x_location>, <y_location>)
width (float): semimajor axis. Horizontal dimension of the ellipse (**)
height (float): semiminor axis. Verti... | 4466bff1e4ed866bb98d0507e1119ab26bfcb9ab | 664,916 |
import base64
def serialise_job_command(command):
"""Serialise job command."""
return base64.b64encode(command.encode()).decode("utf-8") | 422edea7b319111099fd85af4b084ed5658ce353 | 664,917 |
import math
def calc_node_distance(graph, node_1, node_2):
"""
Calculates distance between two nodes of graph,
Requires node attribute 'position' as shapely Point, e.g. Point(10, 15.2)
Parameters
-----------
graph : nx.graph
Graph object of networkx
node_1 : int
Node id of... | a0a0def854fe2cef4e1fa59567b05a98874d8637 | 664,918 |
def compareThresh(value,threshold,mode,inclusive, *, default=False):
"""Returns a boolean only if value satisfies the threshold test. In case of failure of any sort, returns the default value (which defaults to 'False').
Accepted mode values are '<', '>', '<=' and '>='."""
#normalizing input
i... | ea3b4fc683c7940996d42c27962217a1ebec7efe | 664,919 |
import subprocess
def ex_subprocess(cmd):
"""subprocess wrapper function
Arguments:
- cmd (list(str)): the command to feed the subprocess
Return:
(out, compl_proc, error_proc) (3-uple):
- out (int) : 1 suprocess fail, 0 subprocess succeed
- compl_proc (subproc... | f1870ad119102d4bca991a729adc5232e02492e8 | 664,920 |
def get_L_BB_w_d(L_HP_d, L_dashdash_d, L_dashdash_w_d):
"""
Args:
L_HP_d: param L_dashdash_d:
L_dashdash_w_d:
L_dashdash_d:
Returns:
"""
return L_dashdash_w_d - L_HP_d * (L_dashdash_w_d / L_dashdash_d) | dd9459ec09ac9c42f3e9c64bd0eddd32f12e8428 | 664,921 |
from typing import Union
import argparse
def bool_none(value: str) -> Union[bool, None]:
""" String True, False or None and return types bool or None."""
error_msg = f"{value} is an invalid bool or none"
if value == "True":
return True
elif value == "False":
return False
elif value... | 6b33e1cac1d686f1d70132ab32a33e9de8093f23 | 664,922 |
def filter_rule(_):
"""
No rule is needed
"""
return True | 59502d20357ba108f900605b30df012ea9e0462d | 664,923 |
def calc_total_event(events_dict: dict) -> int:
"""各照射回数の合計を求める
Args:
events_dict (dict):
Returns:
int: cnt
"""
cnt = 0
for key in events_dict.keys():
n = int(events_dict[key])
cnt = cnt + n
return cnt | 62f7fb699238e208bdaf1b2dcf3527932e97a4ad | 664,925 |
def _compute_bands_from_cuts(cuts, sequence_length, linear=True):
"""Compute the size of the obtained bands from the position of cuts.
Returns a list of band sizes.
Parameters
----------
cuts
Location of the different cuts on the plasmid.
sequence_length
Length of the DNA molecule... | 39fbf3b4d5bdfb188cb18aee69c454d59818da68 | 664,926 |
import glob
def sorted_glob(pathname):#, cmp=None, key=None, reverse=None):
"""Returns a sorted list of file names matching glob pattern `pathname'.
Added here to accomodate older python that do not have sorted() function."""
rslt = glob.glob(pathname)
rslt.sort() #cmp=cmp, key=key, reverse=reverse)
return ... | 658cc141b54838cbffd07f6b34bd2bfcca50b704 | 664,927 |
def partition(array, left_index, right_index):
"""
分区函数
:param array: 一个数组
:param left_index: 数组的左边界,起始通常是 0
:param right_index: 数组的右边界,起始通常是数组长度 - 1
:return: 返回基准元素的位置
"""
pivot = array[left_index]
while left_index < right_index:
while left_index < right_index and pivot <= a... | 50948b079836455ea0bef15f8d694a1978fd6ded | 664,928 |
def _units_coef_clac():
"""
Calculates the unit coefficients
Parameters
----------
Returns
-------
: dictionary
"density" in (double) g cm^-3
"pressure" in (double) dyns cm^-3
"r" in (double) km
"j" in (double) m^2 kg
"""
# mas of sun in kg
cons... | b4b7c8d5c7797d30d4b6047de2db63b7337f790c | 664,929 |
def _get_valid_indices(shape, ix0, ix1, iy0, iy1):
"""Give array shape and desired indices, return indices that are
correctly bounded by the shape."""
ymax, xmax = shape
if ix0 < 0:
ix0 = 0
if ix1 > xmax:
ix1 = xmax
if iy0 < 0:
iy0 = 0
if iy1 > ymax:
iy1 = ym... | 576038f9b724688a654536e149d3731d90f4f33f | 664,931 |
def get_var(environ, keys, default=None):
"""Try each of the keys in turn before falling back on the default."""
for key in keys:
if environ.has_key(key):
return environ.get(key)
return default | 6fff84d57c8713e09d134e1dea827c4bcff9b4b7 | 664,932 |
def sometrue(*args, **kwargs):
"""
Check whether some values are true.
Refer to `any` for full documentation.
See Also
--------
any : equivalent function; see for details.
"""
return any(*args, **kwargs) | a457d7c0d67f4993703f3689022fcd07cdf930df | 664,933 |
def concept_folders():
"""
Returns the folders containing concepts.
"""
return ['comorbidity', 'demographics', 'measurement', 'medication', 'organfailure', 'treatment', 'score', 'sepsis', 'firstday'] | e53f61553b8f94e501827023f1403db0d8e21ad6 | 664,934 |
def _label_str(block):
"""Returns a string by which the given block may be named, even if `None`."""
if block is None:
return 'exit'
else:
return block.label_str | 17c4a3ede998dc1d62860777132f22763bb07b5d | 664,935 |
def react_polymer(polymer_string):
"""
Iterate through polymer_string, replacing all instances where two
adjacent characters are case-insensitive equal but not equal (i.e. A and a)
with the empty string
"""
# convert to a list since strings are immutable
polymer_list = [i for i in polymer_st... | 6ed62ba4c70c3848764619b9cb3ef06057e512d0 | 664,936 |
import codecs
def to_json(python_object):
"""For py3 compat"""
if isinstance(python_object, bytes):
return {'__class__': 'bytes',
'__value__': codecs.encode(python_object, 'base64').decode()}
raise TypeError(repr(python_object) + ' is not JSON serializable') | 955a2d1c37083dc481594259333ef6bd472c5a67 | 664,937 |
def deepgetattr(obj, attr, default = None):
"""
Get a named attribute from an object; multi_getattr(x, 'a.b.c.d') is
equivalent to x.a.b.c.d. When a default argument is given, it is
returned when any attribute in the chain doesn't exist; without
it, an exception is raised when a missing attribute is... | fb3363d362f198e1ad4037f18b8c514be5742c49 | 664,938 |
def snps_to_genes(snps):
"""Convert a snps dict to a genes dict."""
genes = {}
for chrom in snps.values():
for snp in chrom.values():
if snp.gene.name not in genes:
genes[snp.gene.name] = snp.gene
return genes | 0fdddbffd468fa96546c8ce4289ffa770ec962eb | 664,939 |
def expected_cuts(cut_coords):
"""Expected cut with test_demo_mosaic_slicer."""
if cut_coords == (1, 1, 1):
return {'x': [-40.0], 'y': [-30.0], 'z': [-30.0]}
if cut_coords == 5:
return {'x': [-40.0, -20.0, 0.0, 20.0, 40.0],
'y': [-30.0, -15.0, 0.0, 15.0, 30.0],
... | c0d9f8824e217ff38807f05dfb97c7e2cc4201f0 | 664,940 |
def graphql_mutation(
field_name, field_type, arguments={}, context_args=[],
description=None, is_deprecated=False, deprecation_reason=None):
"""Annotate a function as corresponding to a GraphQL mutation.
Decorator that annotates a function as corresponding to a GraphQL
mutation; i.e. a fie... | 9606cc1360e896c43033d857294f7a78c5499471 | 664,941 |
def _wrap_update_fn(opt_name, opt_update):
"""Wraps the optimizer update function to have the same function signiture.
Args:
opt_name: the optimizer name.
opt_update: the optimizer update function.
Returns:
A wrapped optimizer update function.
"""
def update_fn(grads, optimizer_state, params, bat... | 85db549a213dab714c60b6bb7b0abd409862c349 | 664,942 |
def KWW_modulus(x, logomega0, b, height):
"""1-d KWW: KWW(x, logomega0, b, height)"""
return height / ((1 - b) + (b / (1 + b)) * (b * (10**logomega0 / x) + (x / 10**logomega0)**b)) | f8a21b20ca992fe9ce28ed5d4b915f3489b99c7c | 664,943 |
import shutil
def check_disk_space(available_disk_space_percent_threshold):
""" Checks if disk space is above given threshold.
Args:
available_disk_space_percent_threshold(int): The disk space threshold
you want the root drive to be above.
Returns:
(Bool): Returns true if disk sp... | 1cddea39081ec4374025591ffccd3651d66bbd67 | 664,944 |
def _flatten(lst, cls):
"""
Helper function -- return a copy of list, with all elements of
type ``cls`` spliced in rather than appended in.
"""
result = []
for elt in lst:
if isinstance(elt, cls):
result.extend(elt)
else:
result.append(elt)
return resu... | c3a7b2fc3ad6c543dc1dde7e4c17631631d11405 | 664,945 |
def humanize_timedelta(td):
"""Pretty-print a timedelta in a human readable format."""
secs = int(td.total_seconds())
hours, secs = divmod(secs, 60 * 60)
mins, secs = divmod(secs, 60)
if hours:
return '%dh %dm' % (hours, mins)
if mins:
return '%dm' % mins
return '%ds' % secs | fce51215776b39f0745dbc81b9bc1072e05cf443 | 664,946 |
def sublist_name_from_connection_id(conn_name, subconn_name):
"""
Removes prefixed parent_connection_id from connection_id
as introduced by sesam 2019.09
:param conn_name: list connection name aka parent_connection_id
:param subconn_name: subconnection name aka connection_id
"""
return conn_... | 2aeb31b1857e67623ef5a0dacc01ad964c678f25 | 664,947 |
def is_game_row_valid(game, lookup):
"""Returns whether all columns can be found in the game entry.
Parameters:
game: the entry for the game
lookup: a lookup for fields to indexes in columns
Returns:
true if valid row otherwise False
"""
for index in lookup.values():
... | a1a177788ddf827c236b4e71c7f8ee1a10fc9b65 | 664,948 |
def format_syntax_error(e: SyntaxError) -> str:
""" Formats a SyntaxError. """
if e.text is None:
return "```py\n{0.__class__.__name__}: {0}\n```".format(e)
# display a nice arrow
return "```py\n{0.text}{1:>{0.offset}}\n{2}: {0}```".format(
e, "^", type(e).__name__) | 2ef5713ef65338c4f6b0a878a3632da85816bb20 | 664,949 |
def load_jumping_distribution_from_hdf5_group(group):
"""
Loads a `distpy.jumping.JumpingDistribution.JumpingDistribution` from the
given hdf5 group.
Parameters
----------
group : h5py.Group
the hdf5 file group from which to load the
`distpy.jumping.JumpingDistribution.Jumpi... | 4583c66da617a4db01da856077d2c977aca250ec | 664,950 |
from typing import List
from typing import Dict
def diff_to_new_interesting_lines(unified_diff_lines: List[str]) -> Dict[int, str]:
"""
Extracts a set of 'interesting' lines out of a GNU unified diff format.
Format:
gnu.org/software/diffutils/manual/html_node/Detailed-Unified.html
@@ from-li... | 67e213b5b9f704287b25fa4cd226267b50869aa2 | 664,951 |
def inconsistent_typical_range_stations(stations):
"""Return list of stations with inconsistent data."""
inconsistent_stations = []
for x in stations:
if not x.typical_range_consistent():
inconsistent_stations.append(x.name)
return inconsistent_stations | 4edbba2512a623243769819c5bfd8b721590e3e8 | 664,952 |
import argparse
def controll_argument():
""" command line arguments """
# args
parser = argparse.ArgumentParser()
parser.add_argument("log_path")
parser.add_argument("out_path")
args = parser.parse_args()
log_path = args.log_path
out_path = args.out_path
return log_path, out_path | 02f88f0c593950c0a72eb37d50c995d288385fd6 | 664,953 |
def load_key():
"""
Load the previously generated key
"""
return open("secret.key", "rb").read() | 47bcb2d8802674b5c2854c21dc27975c0a3f2ca3 | 664,954 |
import random
def first_cards(closed_deck):
"""returns 7 random cards for a player"""
cards=random.sample(closed_deck,7)
#Checks the cards given dont exceed 50pt
score=0
for i in range(7):
score+=cards[i][2]
while score>50:
cards=random.sample(closed_deck,7)
score=0
... | e521a2088cab8387bf16caa23fec1b91622c9de4 | 664,955 |
import shutil
def terminalWidth():
"""!
Return the current number of columns of the terminal.
\note This does not give the proper size if `sys.stdout` is
redirected to a file.
"""
return shutil.get_terminal_size().columns | ec57c0af3f07b8e40002a6e80b786100d54f1f3f | 664,956 |
import enum
def get_definitions(swagger_spec):
""" Converts definition dict into an enum to eliminate magic strings. """
if not hasattr(swagger_spec, "_definitions_enum"):
def_dict = swagger_spec.spec_dict.get("definitions")
swagger_spec._definitions_enum = enum.Enum("Definitions", def_dict)
... | e516c12abf00c2962b054c3927167927a36139b6 | 664,957 |
import argparse
def required_length(nmin,nmax, sort: bool = False):
"""Fonction donnant le nombre d'arguments min et max
:param nmin: nombre min d'arguments
:type: int
:param nmax: nombre max d'arguments
:type: int
:param sort:
:type: bool
"""
class RequiredLength(argparse.Actio... | 434f35fab9e0cbd8d7b75bad63ccba02158b045b | 664,958 |
def position_is_bomb(bombs, position):
"""Check if a given position is a bomb.
We don't check the board because that is an unreliable source. An agent
may be obscuring the bomb on the board.
"""
for bomb in bombs:
if position == bomb.position:
return True
return False | 7f0692d8cd650eb5bb735fca33717d0e5c6d0b01 | 664,959 |
import pkg_resources
def ribbon():
"""Entry point for getting the pyxll ribbon file.
Returns a list of (filename, data) tuples.
"""
ribbon = pkg_resources.resource_string(__name__, "resources/ribbon.xml")
return [
(None, ribbon)
] | 032f3333071731d66fd920a34f3f892d5d165847 | 664,960 |
def find_xpath(xpath, tree, namespaces={}, **kwargs):
"""
Find elements within an XML tree whose attributes match certain
values.
:param xpath: an xpath query string.
:param tree: `xml.etree.ElementTree` object.
:param namespaces: a dictionary of namespace prefixes.
:param kwargs: specifies... | 2fe1bbc305a2dc651865b171efdcf5ea33d6089b | 664,961 |
import re
def get_hm(in_file):
"""
从输入文件中获取 hm
:param in_file:
:return:
"""
if not isinstance(in_file, str):
return
m = re.match(r".*_(\d{4})_", in_file)
if m is None:
return
else:
return m.groups()[0] | 2fa3eee49d982928e67d3f73015fd43f0904e669 | 664,962 |
import math
def _CalcNumberOfLODs(size):
"""
For illustration only. Use len(_CalcLodSize(...)) instead.
This method suffers from numerical accuracy issues.
"""
assert False
return math.ceil(math.log(max(size))/math.log(2)) + 1 if size and max(size) >= 1 else 0 | 6731be8ecb789a2ec805ad7fe894b3433cd83658 | 664,963 |
import inspect
def getPublicTypeMembers(type_, onlyValues=False):
"""
Useful for getting members from types (e.g. in enums)
>>> [_ for _ in getPublicTypeMembers(OS, True)]
['Linux', 'Windows']
"""
retVal = []
for name, value in inspect.getmembers(type_):
if not name.startswith("... | 859dcce8245e6eac372fc8db5e4559366600b309 | 664,964 |
def imt(token, i=None, m=None, t=None):
"""Helper function to simplify comparisons Instance, Match and TokenType
:param token:
:param i: Class or Tuple/List of Classes
:param m: Tuple of TokenType & Value. Can be list of Tuple for multiple
:param t: TokenType or Tuple/List of TokenTypes
:return:... | bd510fda8679479a3569db78d7f20dbe55cbcd34 | 664,965 |
def rolling_average(current_avg: float, new_value: float, total_count: int) -> float:
"""Recalculate a running (or moving) average
Needs the current average, a new value to include, and the total samples
"""
new_average = float(current_avg)
new_average -= new_average / total_count
new_average +... | 212792c49d4ab83a3edb3547820028e1fbb8dad5 | 664,966 |
from typing import List
from typing import Dict
def _process(proc_data: List[Dict]) -> List[Dict]:
"""
Final processing to conform to the schema.
Parameters:
proc_data: (List of Dictionaries) raw structured data to process
Returns:
List of Dictionaries. Structured to conform to t... | ce8a7e10ab12ba58b41c4e8286b054ea4f81dad0 | 664,967 |
def regex_escape(raw):
"""Escape lua regex."""
escaped = raw
escaped = escaped.replace("%", "%%")
escaped = escaped.replace("^", "%^")
escaped = escaped.replace("$", "%$")
escaped = escaped.replace("(", "%(")
escaped = escaped.replace(")", "%)")
escaped = escaped.replace("[", "%[")
e... | 70e602d5882c69312fe73de9c6c116164a613cfc | 664,968 |
def remove_specific_key(dictionary, key):
"""
Remove a specific named key from a dictionary.
Args:
dictionary: The dictionary to have a key removed
key: The key to be removed
Returns:
dictionary: The dictionary with the key removed
"""
if key in dictionary:
del ... | fca4bc62e300ced8d472219374594235bc549f2b | 664,969 |
def is_bad_common(radar):
"""common rejection conditions for all radars"""
no_dualpol = 'PHIDP' not in radar.fields
not_ppi = radar.sweep_mode['data'][0] != 'azimuth_surveillance'
elevation = radar.get_elevation(0).mean()
high_elev = elevation > 1.5
low_elev = elevation < 0.05
return no_dual... | f49d0facbb18a80022ab846b66089a8298409fa1 | 664,970 |
def series(ui, repo, **opts):
"""print the entire series file
Returns 0 on success."""
repo.mq.qseries(
repo, missing=opts.get('missing'), summary=opts.get('summary')
)
return 0 | 4ffc520a0158d5c255d24ae82ed5092635d78559 | 664,971 |
def pulse_sink_port(sink, name_or_desc):
"""
Returns the PulseSinkInfo that matches the string, either against the name or the description.
:param sink: the PulseSinkObject to get the port from
:type sink: pulsectl.PulseSinkObject
:param name_or_desc: the name or description string to look for, use... | 819c97da9b5f27d65a59ad8d1b85335bc11de8d4 | 664,972 |
def compss_open(job, *args, **kwargs): # pylint: disable=unused-argument
"""
Dummy open function required when copying from out of the COMPSs system
"""
return job | 7373482d0e4e3dcf458a6eaa9aca647d00c25609 | 664,973 |
import torch
def less_three_percentage(y_true, y_pred, interval):
""" less three accuracy for one batch """
batch_size = y_pred.shape[0]
height = y_pred.shape[1]
width = y_pred.shape[2]
interval = interval.reshape(batch_size)
mask_true = torch.ne(y_true, 0.0).float()
denom = torch.sum(mask... | bf94ccd430cd351de3de5a41cf1cff541cad62af | 664,974 |
import pandas
def unsplit(x,f):
"""
same as R's unsplit function
Read of the values specified in f from x to a vector
Inputs:
x: dictionary of value->[items]
f: vector specifying values to be read off to the vector
"""
y = pandas.DataFrame({"y":[None]*len(f)})
f = pandas.Serie... | c006fb80dba1db18cd25c35ef0ee0e1f212bade0 | 664,975 |
def _group_list(items, lens):
"""
Unflat the list of items by lens
:param items: list of items
:param lens: list of integers
:return: list of list of items grouped by lengths
"""
res = []
cur_ofs = 0
for g_len in lens:
res.append(items[cur_ofs:cur_ofs+g_len])
cur_ofs ... | 1057ee2493fe6a439377f33b0c4f5401f3d7cefa | 664,976 |
import json
def dump_bytes(*args, **kwargs):
"""Converts an object to JSON and returns the bytes."""
return json.dumps(*args, **kwargs).encode("ascii") | 95fbaf372723a3e462ab572e3311da79c596221c | 664,977 |
import copy
def _GenerateInferredAshFlags(device_config):
"""Generate runtime-packed ash flags into a single device config.
Chrome flags are packed into /ui:serialized-ash-flags in the
resultant runtime-only configuration, as a string of null-terminated
strings.
Args:
device_config: transformed config... | 0501a4a985910c8412584d9b64d620e6ae12febd | 664,978 |
from typing import Sequence
def _should_ignore_markdown_cell(
source: Sequence[str],
skip_celltags: Sequence[str],
tags: Sequence[str],
) -> bool:
"""
Return True if the current cell should be ignored from processing.
Parameters
----------
source
Source from the notebook cell
... | a3de5307c3252df0388d2bc7d5f8060759b6f76f | 664,979 |
def leapyr(year: int):
""""
This function defines if the year is
a Leap year (366 days)
or a Normal year (365 days).
Then it will to the variable n the value of 366 or 365, accordingly.
Returns a Tuple:
- number of days tha year,
- and a Boolean :
... | 80f867dc8eb4c53e24f5de80cb0c15b7c69b1458 | 664,980 |
def station_locations(df, id_index):
"""
Creates a dictionary with station IDs as keys and locations as values.
Parameters
----------
df : pandas DataFrame
Bikeshare trip data.
id_index : dict
Maps station ID (arbitrary integer) to the range from 0 to number of stations
Ret... | 482c1f1a1c4c42768b9a06e5ed608c6d95da4144 | 664,981 |
def camel_to_snake(s: str) -> str:
"""Converts "CamelCase" to "snake_case"."""
return "".join(f"_{c}" if c.isupper() else c for c in s).strip("_").lower() | d6697877e5a00ce2bb1149dd6cf0da2b0230c9cd | 664,982 |
import re
def tag_is_spacegroup(text):
"""Check if a HTML tag looks like a spacegroup name.
This does a very crude test to see whether the supplied
string looks like a spacegroup name (rather than a random
HTML tag)."""
spacegroup = re.compile(r"<?[PABCIFHRpabcifhr] *[1-9][1-9]? *[1-9]?[1-9]? *[1-9]?[1-9]... | 05f38893179982c3092d5c7527190be64630a113 | 664,983 |
import math
import torch
def phi_2d(seq, n):
"""
computes bi-linear interpolation coefficients of a single 2D point
:param seq: Tensor of shape (traj_len, batch, 2); the sequence of positions (should be normalized in [0,1] interval)
:param n: number of nodes (in the case of a square grid, its dimensio... | 3ea100fe2ff2e11d9682e96c57c3104aa12871ec | 664,984 |
import binascii
def npbytearray2hexstring(npbytearray, prefix="0x"):
"""Convert a NumPy array of uint8 dtype into a hex string.
Example:
npbytearray2hexstring(array([15, 1], dtype=uint8)) = "0x0f01"
"""
return prefix + binascii.hexlify(bytearray(npbytearray)).decode("utf-8") | 0d2dd571b25261774d7aad5156dbdb2bf9ec6357 | 664,985 |
def update_halley(yvals, y0):
"""Calculate the variable increment using Halley's method.
Calculate the amount to increment the variable by in one iteration of
Halley's method. The goal is to find the value of x for which y(x) = y0.
`yvals` contains the values [y(x0), y'(x0), y''(x0), ...] of the functi... | c2021d0c21bd8a345da6808756c207a27afefeff | 664,986 |
def calculate_angle(hour, minute):
"""
Assuming 12 hours is 360 degree which is
(720 minutes) or 0.5 degree per minute
and 60 minutes = 360* which 6 degree per minutes.
"""
if hour == 12 and minute == 60:
hour, minute = 0, 0
angle_of_hour_hand = (60 * hour + minute) / 2
angle_of_... | 09a5b09cc7787258237b5f676c3e60fc769e34ca | 664,987 |
def getAllSupportedCommands():
"""(Script only)
Retrieves all available integration commands and scripts
:return: Object of all available integrations and scripts
:rtype: ``dict``
"""
return {} | 76231f68234f6e51fbc3b04567bc43c390272672 | 664,988 |
def cosine_dis(XXT):
"""
[Added 22/10/2018]
Performs XXT*-1 + 1 quickly on the lower triangular part.
"""
n = len(XXT)
for i in range(n):
for j in range(i):
XXT[i, j] *= -1
XXT[i, j] += 1
return XXT | b7505e6b79ed093b244317b3801f37b8219e2bf0 | 664,990 |
import torch
def spatial_gradient(x: torch.Tensor, dim: int) -> torch.Tensor:
"""
Calculate gradients on single dimension of a tensor using central finite difference.
It moves the tensor along the dimension to calculate the approximate gradient
dx[i] = (x[i+1] - x[i-1]) / 2.
Adapted from:
... | b60b2aa2b251dc0aa2ebc57eae25c17b436ba46d | 664,991 |
def convert_by_vocab(vocab, items, unk_info):
"""Converts a sequence of [tokens|ids] using the vocab."""
output = []
for item in items:
if item in vocab:
output.append(vocab[item])
else:
output.append(unk_info)
return output | bf7b8cfab2e55a0c980efe055057194badf8ab09 | 664,992 |
def _fill_fields(fields, values):
"""Fill all possible *fields* with key/[value] pairs from *values*.
:return: subset of *values* that raised ValueError on fill (e.g. a select
could not be filled in because JavaScript has not yet set its values.)
"""
unfilled = []
for name, field_values in v... | f3189ebff4bf086ae28a00fdbbdecaeda2243ce4 | 664,993 |
def initialized(machine):
"""
Check to see if the given machine is initialized.
:param machine: Machine to check to see if default attributes are set
:return: `True` if the machine has its attributes set, `False` otherwise
"""
return all(hasattr(machine, attr) for attr in ('state', 'transition'... | a625827f7c53102a98521042a050e682df69b13e | 664,995 |
import unicodedata
def doc_content(filename: str) -> str:
"""Return the content of file."""
with open(filename, mode="r", encoding="utf-8") as f:
try:
return unicodedata.normalize("NFC", f.read())
except UnicodeDecodeError as e:
raise ValueError("The input file must be... | 8c8548983219623577804077c35a11978859df5b | 664,997 |
def indices_to_coordinates(i, dx=1, offset=0):
"""dx = (X.max() - X.min()) / (N - 1) + offset
X is an array of x's
N is the length X
"""
return i * dx + offset | 2b5598a5fd9a744a51836353b4bf84272a69fc77 | 664,998 |
from numpy import exp
def htc(water,
geometry,
T_w):
"""
Subcooled boiling:
The correlation of Thom originally developed for
Pressurized Water Reactors was adapted to the
one-side heating conditions by CEA by introducing
a modification of the exponent in... | f772a455edfa76e6402975710188c79c947f98c2 | 664,999 |
def _read_nlines(filename, nlines):
"""
Read at most nlines lines from file filename.
If nlines is < 0, the entire file is read.
"""
if nlines < 0:
with open(filename) as fh:
return fh.readlines()
lines = []
with open(filename) as fh:
for lineno, line in enumerat... | d3e12f85f6be40c4f2f1644540d9d362a6c78672 | 665,000 |
def human_time(seconds):
"""Returns a human-friendly representation of the number of seconds."""
assert seconds >= 0
hours = seconds / (60 * 60)
minutes = (seconds / 60) % 60
seconds = seconds % 60
return '%02d:%02d:%02d' % (hours, minutes, seconds) | ee339ab652a3a715a15514b2d40a75eb46f05e1f | 665,001 |
from pathlib import Path
def datadir():
""" """
return Path(__file__).parent.joinpath("data") | 3e46571f02669cd7c76232657d63cffbf4af096e | 665,002 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.