content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import params
def __convert_sysctl_dict_to_text():
"""
Convert sysctl configuration dict to text with each property value pair separated on new line
"""
sysctl_file_content = "### HAWQ System Parameters ###########\n"
for key, value in params.hawq_sysctl.iteritems():
if not __valid_input(value):
r... | ccea96f72c0730ee072b7fc174f02d6f302282d6 | 3,636,220 |
from typing import Union
from typing import List
from typing import Dict
from typing import Any
from typing import Optional
from typing import cast
import requests
def vizualScript(
inputds: str,
script: Union[List[Dict[str, Any]], Dict[str, Any]],
script_needs_compile: bool = False,
properties: Optional[D... | 93ded6562e49110134ecbf1fade7c5c2b7a57582 | 3,636,221 |
def _to_sparse_input_and_drop_ignore_values(input_tensor, ignore_value=None):
"""Converts a `Tensor` to a `SparseTensor`, dropping ignore_value cells.
If `input_tensor` is already a `SparseTensor`, just return it.
Args:
input_tensor: A string or integer `Tensor`.
ignore_value: Entries in `dense_tensor` ... | bfbde83654a817ab12a85d4fa321eba6d731174d | 3,636,222 |
from datetime import datetime
import logging
def parse_date(date_str):
"""
>>> parse_date("22 April 2011 at 20:34")
datetime.datetime(2011, 4, 22, 20, 34)
>>> parse_date("9 July 2011")
datetime.datetime(2011, 7, 9, 0, 0)
>>> parse_date("September 2003")
datetime.datetime(2003, 9, 1, 0, 0)
... | cc56ce8517d9efd1de5f41a2ca645a54530635db | 3,636,223 |
def pkcs7_unpad_strict(data, block_size=16):
"""Same as `pkcs7_unpad`, but throw exception on incorrect padding.
Mostly used to showcase the padding oracle attack.
"""
pad = data[-1]
if ord(pad) < 1 or ord(pad) > block_size:
raise Exception('Invalid padding length')
for i in range(2, or... | 0cb7c2d66c30de8bac54ca714dfa05a29d4f0cbd | 3,636,225 |
def cut(d1: dict, d2: dict) -> dict:
"""Removes the keys/values in `d1` to `d2` if they do
not already exist (non-mutating action)
Examples:
.. highlight:: python
.. code-block:: python
from map_ops.operations import cut
d1 = {"foo": 1, "bar": 1}
d2 = ... | 4985d9cb6ff804149a4fddd85bd2c01dd72b9f0d | 3,636,226 |
def chiresponse(A,x):
"""
Deprecated, just use normal "response" function above!
The response function used in the chi squared fitting portion of the simulation.
Meant to imitate the actual response of a scintillator.
Inputs 2 vectors, and responds with a cos^x dependence.
Parame... | 95a07a63e63277a091100fa8519b329c6b2f90de | 3,636,227 |
def _remove_trailing_string(content, trailing):
"""
Strip trailing component `trailing` from `content` if it exists.
Used when generating names from view classes.
"""
if content.endswith(trailing) and content != trailing:
return content[:-len(trailing)]
return content | 775bafba5ea518e03499c9351b74ac472c265c9a | 3,636,228 |
def find_loop_size( public_key, subject=7 ):
"""
To transform a subject number, start with the value 1.
Then, a number of times called the loop size, perform the following steps:
- Set the value to itself multiplied by the subject number.
- Set the value to the remainder after dividing... | 831f5f3e9867b06640493226fa35a89251f5aad5 | 3,636,230 |
def lambda_local_ep(ngl, ind_passive, passive_el, disp_vector, dyna_stif, coord, connect, E, v, rho):
""" Calculates the lambda parameter of the local elastic potential energy function.
Args:
ngl (:obj:`int`): Degrees of freedom.
ind_passive (:obj:`numpy.array`): Index of passive elements.
... | 63925ebbd28710f1d9d3e3c64d8f364de1f76e36 | 3,636,231 |
from re import T
def from_spanning_matroid(matroid: tuple[set[T], list[set[T]]]) -> list[set[T]]:
"""Construct flats from a matroid defined by spanning sets.
Args:
matroid (tuple[set[T], list[set[T]]]): A matroid defined by spanning sets.
Returns:
list[set[T]]: The flats of a given matro... | 9b2ff51cec3be92b8442e9bc807f14a8ee4412dc | 3,636,232 |
def get_value_for_attribute(attribute):
"""For a given key return the value.
Args:
attribute (str): Some metadata key.
Returns:
str: The value of the requested key, if key isn't present then None.
"""
path = '/computeMetadata/v1/instance/attributes/%s' % attribute
try:
... | 2b61f018988db90165f06e975a6478ba3f606652 | 3,636,236 |
def list_selected_groups(remote):
"""Returns a list of unique facegroup IDs for the current face selection (requires an active selection)"""
cmd1 = mmapi.StoredCommands()
key1 = cmd1.AppendSelectCommand_ListSelectedFaceGroups()
remote.runCommand(cmd1)
groups1 = mmapi.vectori()
cmd1.GetSelectComm... | 2ec5346c6e34c8fc35670a3061d65a92ec518c47 | 3,636,237 |
def make_user_variable(
id_name, cluster_name, w_name, d_name, y_tree_name, y_name, x_name_ord,
x_name_unord, x_name_always_in_ord, z_name_list,
x_name_always_in_unord, z_name_split_ord, z_name_split_unord,
z_name_mgate, z_name_amgate, x_name_remain_ord, x_name_remain_unord,
x_balance_name_ord, ... | d7f9f85a75df28e1db7f3dee71d625bbe99c6106 | 3,636,238 |
import re
def get_skip_report_step_by_index(skip_report_list):
"""Parse the missed step from skip a report.
Based on the index within the skip report file (each line a report), the
missed step for this entry gets extracted. In case no step could be found,
the whole entry could not been parsed or no r... | 7aa46050702aba07902ceec586175fce2226e1e3 | 3,636,239 |
from typing import List
def constraint_notes_are(sequence: FiniteSequence, beat_offset: int, pitches: List[int]) -> bool:
"""Tells us if the context note on the given beat_offset
has the same pitches as the given list of pitches
"""
if beat_offset > sequence.duration:
return True
offset_ev... | 26a0182f708f310af0fa022e7ca6e3e34951fe3c | 3,636,241 |
from re import T
def clip(tensor: T.Tensor, a_min: T.Scalar=None,
a_max: T.Scalar=None) -> T.Tensor:
"""
Return a tensor with its values clipped between a_min and a_max.
Args:
tensor: A tensor.
a_min (optional): The desired lower bound on the elements of the tensor.
a_max... | d80d27711f5b257b9b132a313018c74d365d1159 | 3,636,243 |
def remove_objects_from_args(args, # type: Iterable[Any]
kwargs, # type: Dict[str, Any]
pvalue_class # type: Union[Type[T], Tuple[Type[T], ...]]
):
# type: (...) -> Tuple[List[Any], Dict[str, Any], List[T]]
"""For internal use ... | e68d59e00f18357f83817bc49248a0297a869624 | 3,636,244 |
import re
def reminder_validator(input_str):
"""
Allows a string that matches utils.REMINDER_REGEX.
Raises ValidationError otherwise.
"""
match = re.match(REMINDER_REGEX, input_str)
if match or input_str == '.':
return input_str
else:
raise ValidationError('Expected format:... | 3dc1895a19170ec8143ed6b62020d0e4b87f174b | 3,636,245 |
def evaluate_nll(confidences, true_labels, log_input=True, eps=1e-8, reduction="mean"):
"""
Args:
confidences (Array): An array with shape [N, K,].
true_labels (Array): An array with shape [N,].
log_input (bool): Specifies whether confidences are already given as log values.
eps ... | f2694b495f3856269fcdf5c934b3ffabe45a0491 | 3,636,246 |
import re
def parse(features: str) -> AirPlayFlags:
"""Parse an AirPlay feature string and return what is supported.
A feature string have one of the following formats:
- 0x12345678
- 0x12345678,0xabcdef12 => 0xabcdef1212345678
"""
match = re.match(r"^0x([0-9A-Fa-f]{1,8})(?:,0x([0-9A-Fa-f... | ae4e69cb3c03f5c1252067c491a8e05875d642de | 3,636,247 |
def _prefix_with_swift_module(path, resource_info):
"""Prepends a path with the resource info's Swift module, if set.
Args:
path: The path to prepend.
resource_info: The resource info struct.
Returns: The path with the Swift module name prepended if it was set, or just
the path itself if ... | f2a12f59a3c30c09fa20d65b806779ad47f49b90 | 3,636,248 |
from datetime import datetime
def str2datetime(dt, format=None):
"""
convert a string into a datetime object, it can be:
- 2013-05-24 18:49:46
- 2013-05-24 18:49:46.568
@param dt string
@param format format for the conversion, the most complete one is
... | b304eb4b0bdaf87efda333475f879fb64a8f690d | 3,636,249 |
from ..utils import sampling
def get_zoomin(self, scale=1.0):
"""
Returns a spherical region encompassing maximally refined cells.
Moved from Amr class.
What should it do??
Parameters
----------
scale : float
The radius of the returned sphere is scaled by 'scale'.
"""
im... | 52a4ead516a1b11a0e6fc6c1791488e62bbbe222 | 3,636,251 |
def parse_repeating_time_interval_to_days(date_str):
"""Parsea un string con un intervalo de tiempo con repetición especificado
por la norma ISO 8601 en una cantidad de días que representa ese intervalo.
Devuelve 0 en caso de que el intervalo sea inválido.
"""
intervals = {'Y': 365, 'M': 30, 'W': 7... | c417c0fc971ae0c94f651634ef5fb27f1accff24 | 3,636,252 |
def get_pk_and_validate(model):
"""
:param model:
:return:
"""
hits = []
for field in get_model_fields(model):
extra_attrs = field.field_info.extra
if extra_attrs.get('primary_key'):
hits.append(field)
hit_count = len(hits)
if hit_count != 1:
raise ER... | 3da628de19d9280f3fcacd232bc7de084596bc09 | 3,636,253 |
def lat_to_y(lat):
"""Convert latitude to Web-Mercator
Args:
lat: a latutude value
Returns:
float: a Web-Mercator y coordinate
"""
r = 6_378_137 # radius of the Earth at the equator
return log(tan((90 + lat) * pi / 360)) * r | 142770214f9503653ed8d2c38be39e69730dc4c6 | 3,636,254 |
def generate_lasso_mask(image, selectedData):
"""
Generates a polygon mask using the given lasso coordinates
:param selectedData: The raw coordinates selected from the data
:return: The polygon mask generated from the given coordinate
"""
height = image.size[1]
y_coords = selectedData["lass... | 10831928275f5799814576e71a8faf3af019b35d | 3,636,256 |
from math import pi
def guitar(C):
"""Triangular wave (pulled guitar string)."""
L = 0.75
x0 = 0.8*L
a = 0.005
freq = 440
wavelength = 2*L
c = freq*wavelength
w = 2*pi*freq
num_periods = 1
T = 2*pi/w*num_periods
# Choose dt the same as the stability limit for Nx=50
dt =... | 0bd0ae7f5a720f330f27b1d16cbdadaea76535fd | 3,636,257 |
def start_threads_dict():
"""
获取指定URL起始THREADS字典
:return: dict-->配置中指定URL起始THREADS字典
"""
temp_dict = dict()
enable_flag = const.CONF.get('Auto_Test.assign_start_threads', 'ENABLE')
if enable_flag and isinstance(enable_flag, str):
if enable_flag.lower() == 'true':
temp_dic... | 45829c774b0b0a539fc9bede8989940dcae7a863 | 3,636,258 |
from typing import Optional
def exists_in_s3(s3_path: str) -> Optional[bool]:
"""Check whether a fully specified s3 path exists.
Args:
s3_path: Full path on s3 in format "s3://<bucket_name>/<obj_path>".
Returns:
Boolean of whether the file exists on s3 (None if there was an error.)
"... | 2f72fcf0f5f56d45e7cc9a63d0b572ef8eb652af | 3,636,259 |
from ethpm.uri import check_if_chain_matches_chain_uri
from typing import List
def validate_single_matching_uri(all_blockchain_uris: List[str], w3: Web3) -> str:
"""
Return a single block URI after validating that it is the *only* URI in
all_blockchain_uris that matches the w3 instance.
"""
match... | efc814456b74f2783de2c1fc214cba11b7b6a9ad | 3,636,260 |
import time
def ListAndWaitForObjects(service, counting_start_time,
expected_set_of_objects, object_prefix):
"""List objects and wait for consistency.
Args:
service: the ObjectStorageServiceBase object to use.
counting_start_time: The start time used to count for the inconsisten... | d2a3c2704cca699c588c4382b16643c23d578553 | 3,636,261 |
from typing import List
def load_mbb_player_boxscore(seasons: List[int]) -> pd.DataFrame:
"""Load men's college basketball player boxscore data
Example:
`mbb_df = sportsdataverse.mbb.load_mbb_player_boxscore(seasons=range(2002,2022))`
Args:
seasons (list): Used to define different season... | 1967c629045b1c7a0bc11e27a37e70ca8c12d8b7 | 3,636,262 |
from datetime import datetime
def countdown(code, input):
""" .countdown <month> <day> <year> - displays a countdown to a given date. """
error = '{red}Please use correct format: %scountdown <month> <day> <year>' % code.prefix
text = input.group(2).strip()
if ' ' in text:
text = text.split()
... | e06aa49396c3348f9641889d2dc58ef19f65a821 | 3,636,263 |
def split_rdd(rdd):
"""
Separate a rdd into two weighted rdds train(70%) and test(30%)
:param rdd
"""
SPLIT_WEIGHT = 0.7
(rdd_train, rdd_test) = rdd.randomSplit([SPLIT_WEIGHT, 1 - SPLIT_WEIGHT])
return rdd_train, rdd_test | 082439fb41108da171610dc3d03ab1f8f9f021c5 | 3,636,264 |
def QuickSort(A, l, r):
"""
Arguments:
A -- total number list
l -- left index of input list
r -- right index of input list
Returns:
ASorted -- sorted list
cpNum -- Number of comparisons
"""
# Number of comparisons
cpNum = r - l
# Base case
if cpNum == 0:
return [A[l]], 0
elif cpNum < 0:
return [], ... | 26092d222d93d8b931ab6f2d5c539ac5c9e00b2f | 3,636,265 |
from typing import Counter
def checksum(input):
""" Checksum by counting items that have duplicates and/or triplicates and multiplying"""
checksum_twos = 0
checksum_threes = 0
for id in input:
c = [v for k,v in Counter(id).items()]
if 2 in c:
checksum_twos += 1
if ... | 8ba72e795b5868a852ce0c9c234ca35088057538 | 3,636,267 |
def Rescale(UnscaledMatrix, Scales):
"""Forces a matrix of raw (user-supplied) information
(for example, # of House Seats, or DJIA) to conform to
svd-appropriate range.
Practically, this is done by subtracting min and dividing by
scaled-range (which itself is max-min).
"""
# Calulate multi... | 9201078f3395aa11e75529f01f8e6486409c1347 | 3,636,268 |
def winrate_of(node: sgf.Node) -> float:
"""
The winrate of the node/position is defined as winrate of the most visited child.
"""
max_visits = 0
winrate = 0
variations = ([] if node.next == None else [node.next]) + node.variations
for child in variations:
if "B" in child.properties ... | d7893fdd0295f6b43fec258351c201ae8d789f1a | 3,636,269 |
def extract_kernel_version(kernel_img_path):
"""
Extracts the kernel version out of the given image path.
The extraction logic is designed to closely mimick the logic Zipl configuration to BLS
conversion script works, so that it is possible to identify the possible issues with kernel
images.
:... | 2f75b220ff3e68b8c2ae2a046b7c604a786b05b8 | 3,636,270 |
def about(request):
""" About view """
try:
about = About.objects.get().description
except:
about = "No information here yet."
return render(request, 'about_page.html', {'about': about}) | 60ea35c1c50f54c4c54ea207f48cd7805f27571a | 3,636,271 |
def concat_strings(string_list):
"""
Concatenate all the strings in possibly-nested string_list.
@param list[str]|str string_list: a list of strings
@rtype: str
>>> list_ = (["The", "cow", "goes", "moo", "!"])
>>> concat_strings(list_)
'The cow goes moo !'
>>> list_ = (["This", "senten... | bbeb884e2cd4c689ce6e61c147558c993acc5f09 | 3,636,272 |
def produce_grid(tuple_of_limits, grid_spacing):
"""Produce a 2D grid for the simulation system.
The grid is based on the tuple of Cartesian Coordinate limits calculated in
an earlier step.
Parameters
----------
tuple_of_limits : tuple
``x_min, x_max, y_min, y_max``
grid_spacing : ... | 9ce30e74e4740cdbde520eb71156c6ce4799304e | 3,636,273 |
def intensity_histogram_measures(regionmask, intensity):
"""Computes Intensity Distribution features
This functions computes features that describe the distribution characteristic of the instensity.
Args:
regionmask=binary image
intensity= intensity image
"""
feat= Intensity_His... | f1bcb7a3517555d68193c9e526d0016eee81d4b5 | 3,636,274 |
def match(input_character, final_answer):
"""
:param input_character: str, allow users to input a string that will be verified whether
there are any matches with the final answer.
:param final_answer: str, the final answer.
:return: str, return the matching result that could consist of '-' and lette... | 4323cd2eefa00126baad11576cdc9a29fe94ec0b | 3,636,275 |
def render_error(request, status=500, title=_('Oops!'),
err_msg=_('An error occured')):
"""Render any error page with a given error code, title and text body
Title and description are passed through as-is to allow html. Make
sure no user input is contained therein for security reasons. The... | 26c5bc2a6699a1065bc492d8ca8c83d4146dae58 | 3,636,277 |
def affaire_spatial(request):
"""
Get modification affaire by affaire_fille
"""
# Check connected
if not check_connected(request):
raise exc.HTTPForbidden()
results = request.dbsession.query(VAffaire).filter(
VAffaire.date_cloture == None
).filter(
VAffaire.date_envo... | 1f1743765f0c044a1070b5ee3cc7a2328233c24a | 3,636,278 |
def get_cosets(big_galois: GaloisGroup, small_galois: GaloisGroup) -> SetOfCosets:
"""
Given a big group `big_galois` and a subgroup `small_galois`, return the cosets
of small_galois \\ big_galois.
Args:
big_galois: A `GaloisGroup` whose cosets to examine
small_galois: The acting subgro... | b312a490727f860f8e1423cf0ab7e877e8df6ba4 | 3,636,279 |
import calendar
def get_month_day_range(date):
"""
For a date 'date' returns the start and end date for the month of 'date'.
Month with 31 days:
>>> date = datetime.date(2011, 7, 27)
>>> get_month_day_range(date)
(datetime.date(2011, 7, 1), datetime.date(2011, 7, 31))
Month with 28 days:... | 610ff43b0e637afba780119c76181c6ff033a299 | 3,636,281 |
def measure_of_risk_callback(app):
"""
Attaches the callback function for the component
rendered in the measure_of_risk function
Args:
app = the dash app
Returns:
None
"""
component_id = 'measure-risk'
@app.callback(
Output(component_id + 'out', 'children'),
... | 6beabaae619a94db258d41e1f9062de4018fbf68 | 3,636,282 |
from typing import Union
from typing import Optional
from typing import Tuple
from typing import cast
from typing import List
def dot(
a: Union[float, ArrayLike],
b: Union[float, ArrayLike],
*,
dims: Optional[Tuple[int, int]] = None
) -> Union[float, Array]:
"""
Get dot product of simple numbe... | 298f9ea31386eff1dee33aec4fa47a29fd5a6f20 | 3,636,283 |
def read_float64(field: str) -> np.float64:
"""Read a float64."""
return np.float64(field) if field != "" else np.nan | f26da82fa22e79a370facad2d787ce3aee70723a | 3,636,284 |
def write_hypergraph(hgr, colored = False):
"""
Return a string specifying the given hypergraph in DOT Language.
@type hgr: hypergraph
@param hgr: Hypergraph.
@type colored: boolean
@param colored: Whether hyperedges should be colored.
@rtype: string
@return: String specify... | 2e25eecd84ea0d8724c6f4618478e1cd7a7676d6 | 3,636,285 |
def sort_gtf(gtf_path, out_path):
"""Sorts a GTF file based on its chromosome, start position, line number.
:param gtf_path: path to GTF file
:type gtf_path: str
:return: path to sorted GTF file, set of chromosomes in GTF file
:rtype: tuple
"""
logger.info('Sorting {}'.format(gtf_path))
... | 5cb1289b81a0c05a138cac5d2ae6213f46d47110 | 3,636,286 |
def leia_dinheiro(msg):
"""
-> Recebe um valor digitado pelo usuário e verifica se é um
valor númerico válido
:param msg: Mensagem a ser mostrada ao usuário
:return: Retorno o valor digitado pelo usuário caso seja válido
"""
while True:
num = input(msg).strip().replace(',', '.') # S... | aa8e21243009af1fde6d6c5e9cb611acff36369e | 3,636,287 |
from typing import OrderedDict
def format_analyse(parsed_tokens, to_1d_flag=False):
"""
入力
parsed_tokens # list(list(str)) : 変数毎の変数名/インデックスがtokenizedなトークンリスト
出力
res,dic # FormatNode,OrderedDict<str:VariableInformation> : フォーマット情報のノードと変数の情報を保持した辞書を同時に... | 76d42cc83f26c31273ae6aadd42479861c49ff69 | 3,636,288 |
def KAMA(df: pd.DataFrame, window: int = 10, pow1: int = 2, pow2: int = 30) -> pd.DataFrame:
"""
Kaufman's Adaptive Moving Average (KAMA) is an indicator that
indicates both the volatility and trend of the market.
"""
df_with_signal = df.copy()
df_with_signal["signal"] = kama(df["close"], window... | 79f23b1c840a4bc0860d9bc84fceceedb1c1b6b3 | 3,636,289 |
def cast_to_str(obj):
"""Return a string representation of a Seq or SeqRecord.
Args:
obj (str, Seq, SeqRecord): Biopython Seq or SeqRecord
Returns:
str: String representation of the sequence
"""
if isinstance(obj, str):
return obj
if isinstance(obj, Seq):
retu... | cd4100c6ef41b9ff33346349f6c70ac30e9ccd20 | 3,636,290 |
def _octet_bits(o):
"""
Get the bits of an octet.
:param o: The octets.
:return: The bits as a list in LSB-to-MSB order.
:rtype: list
"""
if not isinstance(o, int):
raise TypeError("o should be an int")
if not (0 <= o <= 255):
raise ValueError("o should be between 0 and ... | f472a2ab65702e59439b7693260abf040d4e7742 | 3,636,291 |
import networkx
def to_graph(l):
"""
Credit: Jochen Ritzel
https://stackoverflow.com/questions/4842613/merge-lists-that-share-common-elements
"""
G = networkx.Graph()
for part in l:
# each sublist is a bunch of nodes
G.add_nodes_from(part)
# it also implies a number of ... | da50880d4b056ffcf538b305dc418cdb11d2f41f | 3,636,293 |
def convert_mcmc_labels(param_keys, unit_labels=False):
"""Returns sequence of formatted MCMC parameter labels
"""
keys = list(param_keys)
for i, key in enumerate(keys):
if 'qb' in key:
label_str = r'$Q_\mathrm{b,' + f'{key[-1]}' + '}$'
elif 'mdot' in key:
label_... | d4059cd0b43f7968d0a59e7f760d9a226c4e6af1 | 3,636,294 |
def superuser_exempt(filter_authorization_verification):
"""Decorator to exempt any superuser from filtering, authorization, or verification functions."""
def superuser_exempt_fun(request, arg):
if request.user.is_superuser:
if isinstance(arg, QuerySet):
return arg
... | 1fa3752971be8ba291fd454c0704673b6687af9d | 3,636,295 |
from mindquantum import Circuit
def u1(lambd, q):
"""Openqasm u1 gate."""
return Circuit().rz(lambd, q) | 723035f9e3822e1a7ae385fba5bee51f457936a8 | 3,636,298 |
def get_simple_object(key='slug', model=None, self=None):
"""
get_simple_object() => Retrieve object instance.
params => key, model, self
return => object (instane)
"""
try:
if key == 'id':
id = self.kwargs['id']
instance = model.objects.get(id=id)
else:
... | 218a742e8652b3edebd6be9676e10c7b5dd709ab | 3,636,299 |
def create_app():
"""Create and configure an instance of the Flask application."""
app = Flask(__name__)
# vvvvv use sqlite database vvvvv
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///db.sqlite3'
# vvvvv have DB initialize the app
DB.init_app(app)
@app.route('/')
def root():
... | 92663b60bd9faf1d850f69a550b17102b92ffcb9 | 3,636,300 |
from mpi4py import MPI
def MPITest(commsize):
"""
A decorator that repeatedly calls the wrapped function,
with communicators of varying sizes.
This converts the test to a generator test; therefore the
underlyig test shall not be a generator test.
Parameters
----------
commsize: scala... | 3bb33e5d3d6919916ba865d79a5e0a16cdbb1b99 | 3,636,301 |
def getClassicalPitchNames(pitches):
"""
takes a list of pitches and returns a list of classical pitch class names
"""
return getPitchNames([normalizePitch(x,12) for x in pitches],getClassicalPitchNameCandidates) | 737dccb3abe83c2bbb2c983cfa3fb80a4fbc5052 | 3,636,302 |
import pymel.core.uitypes
def toPyUIList(res):
# type: (str) -> List[pymel.core.uitypes.PyUI]
"""
returns a list of PyUI objects
Parameters
----------
res : str
Returns
-------
List[pymel.core.uitypes.PyUI]
"""
if res is None:
return []
return [pymel.core.uity... | 6f3d35a1a7c10bc461561edcdb4b52404de3e5a7 | 3,636,303 |
def best_B(Ag):
""" Given an antigenic determinant Ag this function returns the binding
value of the best possible binder. """
top = 0
for i in range(len(Ag)):
etop = np.min(cf.TD20[int(Ag[i]) - 1])
top += etop
return top | b02afd943de6a4c8b2f9f1b4d897e5f03074c000 | 3,636,304 |
def forward_gradients_v2(ys, xs, grad_xs=None, gate_gradients=False):
"""Forward-mode pushforward analogous to the pullback defined by tf.gradients.
With tf.gradients, grad_ys is the vector being pulled back, and here d_xs is
the vector being pushed forward."""
if type(ys) == list:
v = [tf.ones_... | 02fea7fc2367e69d2c6b085ea1a1379b7a442674 | 3,636,305 |
import resource
def __limit_less(lim1, lim2):
"""Helper function for comparing two rlimit values, handling "unlimited" correctly.
Params:
lim1 (integer): first rlimit
lim2 (integer): second rlimit
Returns:
true if lim1 <= lim2
"""
if lim2 == resource.RLIM_INFINITY:
... | 8c8faebd4cc1eecfbd8e0a73b16b2bee0a433572 | 3,636,306 |
from typing import List
def getswarmlocations() -> List[str]:
"""
checks if the provided location is a location where a swarm can happen.
:param location: the provided location
:return: boolean if location is in the list of locations where swarms can happen,
"""
swarmlocationlist = open("comma... | 3a7db13c8a0176a4cc9a9dda38b23041639917a9 | 3,636,307 |
from typing import Any
from typing import Optional
def Request(
default: Any = Undefined,
*,
default_factory: Optional[NoArgAnyCallable] = None,
alias: Optional[str] = None,
) -> Any:
"""
Used to provide extra information about a field.
:param default: since this is replacing the field’s ... | 83ad97bc7a276e0d9d715031f263cf8d66fdaf78 | 3,636,308 |
def val_err_str(val: float, err: float) -> str:
"""
Get a float representation of a value/error pair and create a string representation
12.345 +/- 1.23 --> 12.3(12)
12.345 +/- 0.012 -> 12.345(12
12345 +/- 654 ---> 12340(650)
:param val: float representing the value
:param err: float represe... | 5b759ff8e6996704edb7f6b68f6cb7e307593c9e | 3,636,311 |
import re
def find_map(address):
"""
Look up a specified address in the /proc/PID/maps for a process.
Returns: A string representing the map in question, or None if no match.
"""
maps = fetch_maps()
for m in re.finditer(begin_pattern, maps):
begin = int(m.group("begin"), 16)
e... | c9a07d982b92ef1e165fa8e1bcc9ea3873f2f912 | 3,636,313 |
import regex
def _format_css_declarations(content: list, indent_level: int) -> str:
"""
Helper function for CSS formatting that formats a list of CSS properties, like `margin: 1em;`.
INPUTS
content: A list of component values generated by the tinycss2 library
OUTPUTS
A string of formatted CSS
"""
output = ... | 56205e557858349f17a8d7a549d472c3f549c2cc | 3,636,314 |
def rosen_hess(x):
"""
The Hessian matrix of the Rosenbrock function.
Parameters
----------
x : array_like
1-D array of points at which the Hessian matrix is to be computed.
Returns
-------
rosen_hess : ndarray
The Hessian matrix of the Rosenbrock function at `x`.
... | 449c869e821c0e97e4126bd5955df5bd39d93f95 | 3,636,315 |
def flow_corr():
"""
Symmetric cumulants SC(m, n) at the MAP point compared to experiment.
"""
fig, axes = plt.subplots(
figsize=figsize(0.5, 1.2), sharex=True,
nrows=2, gridspec_kw=dict(height_ratios=[4, 5])
)
observables = ['sc', 'sc_normed']
ylims = [(-2.5e-6, 2.5e-6), (... | c2d887e3a646ad5e3f1f7570f8a7ee19bf25d1b1 | 3,636,316 |
def dodecagon(samples=128, radius=1):
"""Create a dodecagon mask.
Parameters
----------
samples : `int`, optional
number of samples in the square output array
radius : `float`, optional
radius of the shape in the square output array. radius=1 will fill the
x
Returns
... | a45a8eaa723c9c0da93fa6477a07d1a13d6524e0 | 3,636,317 |
def port_name(name, nr=0):
"""Map node output number to name."""
return name + ":" + str(nr) | a82e0b9940fa6b7f11f1a11fbd8a1b9b1a57c07b | 3,636,318 |
def AC3(csp, queue=None, removals=None, arc_heuristic=csp.dom_j_up):
"""[Figure 6.3]"""
if queue is None:
queue = {(Xi, Xk) for Xi in csp.variables for Xk in csp.neighbors[Xi]}
csp.support_pruning()
queue = arc_heuristic(csp, queue)
checks = 0
while queue:
(Xi, Xj) = queue.pop()
... | 507e942633da0ac1487db0c75375ac0e6d37a069 | 3,636,320 |
from typing import Optional
from typing import List
from typing import Union
import pandas
def load(
name: str,
ids: Optional[List[Union[str, int]]] = None,
limit: Optional[int] = None,
) -> pandas.DataFrame:
"""Load dataset data to a pandas DataFrame.
Args:
name:
The dataset ... | 40499ccc3942d4c59c8588257c9f40a2d622109d | 3,636,321 |
def _stringify(values):
"""internal method: used to convert values to a string suitable for an xml attribute"""
if type(values) == list or type(values) == tuple:
return " ".join([str(x) for x in values])
elif type(values) == type(True):
return "1" if values else "0"
else:
return ... | a8f3c290ef949a254ca5dca9744ff3f4c602c4d2 | 3,636,322 |
def xml_safe(s):
"""Returns the XML-safe version of a given string.
"""
new_string = s.replace("&", "&").replace("<", "<")
new_string = new_string.replace("\r", "").replace("\n", "<br/>")
return new_string | 166bf2b78441b4f22bf3a89f8be56efb756fe72f | 3,636,323 |
import re
def range_values(ent):
"""Extract values from the range and cached label."""
data = {}
range_ = [e for e in ent.ents if e._.cached_label.split('.')[0] == 'range'][0]
values = re.findall(FLOAT_RE, range_.text)
if not all([re.search(INT_TOKEN_RE, v) for v in values]):
raise Rejec... | 4fe1388727ef432a6b9587a2c179dafc6f60d42a | 3,636,324 |
def get_weights(connections):
"""Returns the weights of the connections
:param connections:
:return: Numpy array of weights
"""
return np.array(nest.GetStatus(connections, keys="weight")) | 50371989cf32b37bc7a25837db2c866e579ac0b6 | 3,636,326 |
def w2v_matrix_vocab_generator(w2v_pickle):
"""
Creates the w2v dict mapping word to index and a numpy matrix of (num words, size of embedding), words will
be mapped to their index, such that row ith will be the embedding of the word mapped to the i index.
:param w2v_pickle: Dataframe containing token ... | 3228d73facc7756cfcf32fb10d9d54f0b40c84d7 | 3,636,327 |
def concat(
dfs, axis=0, join="outer", uniform=False, filter_warning=True, ignore_index=False
):
"""Concatenate, handling some edge cases:
- Unions categoricals between partitions
- Ignores empty partitions
Parameters
----------
dfs : list of DataFrame, Series, or Index
axis : int or s... | 7f89a93410c3171e967682df954d259651cc5b91 | 3,636,328 |
def resize(dataset: xr.Dataset, invalid_value: float = 0) -> xr.Dataset:
"""
Pixels whose aggregation window exceeds the reference image are truncated in the output products.
This function returns the output products with the size of the input images : add rows and columns that have been
truncated. Thes... | 75729c99cf77ffeb79153bb4ff17ea69dac12f7b | 3,636,329 |
import requests
def score(graphs, schema, url, port):
"""
graphs is expected to be a list of dictionaries, where each entry in the
list represents a graph with
* key idx -> index value
* key nodes -> list of ints representing vertices of the graph
* key edges -> list of list of ints represen... | 090846132114dfadfc950f3fff384e26c439acce | 3,636,330 |
from typing import List
from typing import Dict
def group_by_author(commits: List[dict]) -> Dict[str, List[dict]]:
"""Group GitHub commit objects by their author."""
grouped: Dict[str, List[dict]] = {}
for commit in commits:
name = commit["author"]["login"]
if name not in grouped:
... | 239c523317dc8876017d4b61bc2ad8887444085e | 3,636,331 |
import re
def convert(name):
"""
CamelCase to under_score
:param name:
:return:
"""
s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', name)
return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower() | c92db5a27d4086f8c46cbcb17005e3fc0534b2cb | 3,636,332 |
def plot(graph, particles=None, polyline=None, particles_alpha=None, label_start_end=True,
bgcolor='white', node_color='grey', node_size=0, edge_color='lightgrey', edge_linewidth=3, **kwargs):
"""
Plots particle approximation of trajectory
:param graph: NetworkX MultiDiGraph
UTM projection
... | 3f57d69bd69c9164715db9fde5020c7da8aa42df | 3,636,333 |
def non_empty_string(value):
"""Must be a non-empty non-blank string"""
return bool(value) and bool(value.strip()) | 707d6c39a52b1ec0e317d156e74fef78170739d9 | 3,636,334 |
def metadataAbstractElementRequiredChildElementTest6():
"""
Optional child elements, child elements required.
>>> doctestMetadataAbstractElementFunction(
... testMetadataAbstractElementKnownChildElements,
... metadataAbstractElementRequiredChildElementTest6(),
... requiredChildEleme... | dd114d393269b9731aba8bbc6681f1a1b29643e0 | 3,636,335 |
def index():
"""
List containers
"""
containers = g.api.get_containers()
clonable_containers = []
for container in containers:
if container['state'] == 'STOPPED':
clonable_containers.append(container['name'])
context = {
'containers': containers,
'clonable... | 5e5178eba9824a9a4c83b5e179cf1fd6b3b8ed30 | 3,636,336 |
import torch
def spatial_discounting_mask():
"""
Input:
config: Config should have configuration including HEIGHT, WIDTH,
DISCOUNTED_MASK.
Output:
tf.Tensor: spatial discounting mask
Description:
Generate spatial discounting mask constant.
Spatial discounting ma... | 1ac2ffaf0b3ef70b9efe0965ef9ecd8bb16fe7ce | 3,636,337 |
def pca_results(scaled, pca):
"""
Plot the explained variance of the DataSet as a barchart,
and return a DataFrame with the explained variance for each
feature, for each dimension of the PCA.
-----------------------------------------------------------
# Parameters:
# scaled (pd.DataFrame): The DataFrame in wh... | 48c5e2c740238c0005740de9171ad509e146fbed | 3,636,339 |
import pwd
def get_uid_from_user(user):
"""Return UID from user name
Looks up UID matching the supplied user name;
returns None if no matching name can be found.
NB returned UID will be an integer.
"""
try:
return pwd.getpwnam(str(user)).pw_uid
except KeyError:
return No... | dd4f6f839f985b923199b438216c567e1e84327d | 3,636,340 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.