content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def colors():
"""Returns a list of colors."""
return ['red', 'blue', 'green', 'yellow', 'orange', 'purple', 'brown',
'black', 'pink'] | 4fa1eeb805e45e8471cc1d6ffa36a5c422017932 | 648,225 |
def member_summary_keys():
"""
MemberSummary definition
Optional keys: "givenName", "familyName"
"""
return [
"id",
"username",
"displayName",
"shortName",
"pronoun",
"avatar",
"memberStatus",
] | b458ec9167acf8507d52563c5bfc10385594468b | 648,227 |
def net_gains(principal,expected_returns,years,people=1):
"""Calculates the net gain after Irish Capital Gains Tax of a given principal for a given expected_returns over a given period of years"""
cgt_tax_exemption=1270*people #tax free threashold all gains after this are taxed at the cgt_ta_rate
cgt_tax_r... | 623b6c1126ad2486ba94c3b02f1a8ed335fed74b | 648,228 |
def calculate_daily_mean(ds, time_name='time'):
"""
Calculates the daily mean.
"""
return ds.resample(
'1d', dim=time_name, how='mean', keep_attrs=True) | 72ba4a65a179edaf3013fb9fcf8d15b8c450d0d9 | 648,229 |
def _format_font_size(size: float) -> str:
"""Strips away trailing .0 from 13.0.
Basically unused, since QFontDialog will only allow integer font sizes."""
return ("%f" % size).rstrip("0").rstrip(".") | a268888be1b66354dc193f9dcfd99fcb8f48d8bf | 648,230 |
import random
def create_id():
""" Generates a random hex id for managed entities """
return '%05x' % random.randrange(16**6) | 08a73bf6915708f0d61a70a1d44b761de7874ceb | 648,231 |
def is_unitless(ds, variable):
"""
Returns true if the variable is unitless
Note units of '1' are considered whole numbers or parts but still represent
physical units and not the absence of units.
:param netCDF4.Dataset ds: An open netCDF dataset
:param str variable: Name of the variable
"... | 8574327f657e67d2165f247a8892c38eab89784f | 648,232 |
def int_to_base(val, bdgts):
""" Convert an integer into a string with a given base.
Args:
val: Integer value to convert
bdgts: List of base digits
Returns:
String corresponding to the integer
"""
# Check zero
if val == 0:
return bdgts[0]
# Check negative n... | 56ac66dff33f01a9f3524458a268203f8a58cb1f | 648,233 |
def list_reverse2(list_in):
"""
:param list_in list:
:return list_out list :
Takes a list a returns a new list that is the reverse of the input
"""
list_out = []
length = len(list_in)
for part in range(length):
list_out.append(list_in[length - 1 - part])
return list_out | 1898b81685c1244e3828c308ca416fede2f7fcf0 | 648,234 |
def average(values):
"""Averages the values in an iterable.
values: iterable containing numbers
"""
return sum(values) / float(len(values)) | 50f9cc821d1423a79ce90f2a3f143119f110b1c8 | 648,235 |
from typing import Match
def replace_one_decorated_callable_start(m: Match) -> str:
"""Define the replacement function used in `correct_all_decorated_callable_starts`."""
start = int(m[5]) + int(m[6]) # number of decorators + line number of the first decorator
return f"{m[1]}/_type={m[2]}{m[3]}{start}:{m... | 819079d96e2aa60b745f16488dae916880dc0ba6 | 648,236 |
def _GetFailureTestRefs(test_summary):
"""Gets a list of test summaryRef id of all failure test.
Args:
test_summary: dict, a dict of test summary object.
Returns:
A list of failure test case's summaryRef id.
"""
failure_test_refs = []
if 'subtests' in test_summary:
for sub_test_summary in test_... | 47c8e7e5af7c2e5847983d1f492617e061eb1e19 | 648,237 |
import warnings
def check_consecutive_ranks_on_same_nodes(mpi):
"""
Check that consecutive MPI ranks are on the same nodes, and
return a corresponding boolean. Print a warning message if
it is not the case, this this can affect performance.
"""
# Skip this function if there is only one MPI ran... | fbfb7319c7da4bb19cb605eaebf0d1cc7270bb96 | 648,238 |
def printBondedAtoms(bond, shiftdummySerial):
"""Generate bond atoms line
Parameters
----------
bond : Bond Object
Bond Object
shiftdummySerial : int
Shift to remove structural dummy atoms and get index (should be 4)
Returns
-------
bondLine : str
Bond line data... | 0315b36368df927d6789b3306e8193a77227547f | 648,239 |
def get_file_object(directory, Params):
"""returns a file object for printing
"""
print('get_file_object - depracated routine')
print_num = Params.get_inc('PRINTS')
print_num_str = print_num.rjust(4,'0')
filer = directory + 'MOPS_EXTRACT_' + print_num_str + '.txt'
return filer | 2f4bce4ae03e7c3fad4ebc148554f3b7bc7a4b71 | 648,240 |
import shutil
def get_gaussian_version():
"""
Try and work out the gaussian version if it can not be found return none.
"""
if shutil.which("g16") is not None:
return "g16"
elif shutil.which("g09") is not None:
return "g09"
else:
return None | b4247c1f5a56e9890e9b293c061577f8aff4e41a | 648,241 |
import json
def to_json(context) -> str:
"""Convert the selected Selection Sets of the current rig to JSON.
Selected Sets are the active_selection_set determined by the UIList
plus any with the is_selected checkbox on."""
arm = context.object
active_idx = arm.active_selection_set
json_obj =... | 2bf65df6d1e158331a043f89c2083cc1c260267a | 648,242 |
def _tl_type_ ( leaf ) :
"""Get a type for TLeaf object
>>> tree = ...
>>> leaf = t.leaf ( 'QQQ' )
>>> print leaf.get_type ( )
"""
if not leaf : return 'NULL'
branch = leaf.GetBranch ()
typename = leaf.GetTypeName ()
name = branch.GetTitle()
p1 = na... | 05fd8e676c21bda7a8a976fa42189fffb56abb97 | 648,243 |
def my_name(self):
"""
Code chunk used in creating field classes: returns field name.
"""
# pylint: disable=protected-access
return self._fname | f35a7d373f154a1d4ac11c70cac6314789e563c7 | 648,245 |
def spaces(x, spa):
"""
spaces(x, spa)
Returns an array of the spacings from the original point given the distance
and the number of spaces.
"""
return list(map(lambda y: y * (x/spa), range(1, spa + 1))) | 00649fd53fa727ff4a5674972a6540ad740bbae2 | 648,246 |
import random
import string
def random_string(length=8):
"""Generate a random string of letters and numbers.
Args:
* *length* (int): Length of string, default is 8
Returns:
A string (not unicode)
"""
return "".join(
random.choice(string.ascii_letters + string.digits) for... | d2eec1fc58ead99e877fdfc84dca14788ffa794f | 648,247 |
def _get_docstring(name):
"""Return the docstring of an object with name"""
try:
obj = globals()[name]
except KeyError:
raise ValueError("Invalid object name")
return obj.__doc__ or "" | e053c4369d2c382612f7727f58b59363b3856ed1 | 648,248 |
import numpy
def _ffqi_op(forest_areas_array, smoothed_forest_areas, forest_areas_nodata):
"""Mask out ffqi only where there's an ffqi."""
result = numpy.empty_like(forest_areas_array, dtype=numpy.float32)
result[:] = forest_areas_nodata
# forest_areas_array and _nodata are integer types and not user-... | 9f976ed9e154f8b785e0bc5d50d4e2a64847a874 | 648,249 |
def __legacysignature(signature):
"""
For retrocompatibility reasons, we don't use a standard Signature.
Instead, we use the string generated by this method.
Basically, from a Signature we create a string and remove the default values.
"""
listsignature = str(signature)[1:-1].split(",")
for ... | 910677618a365eaf780bedb79eadb5f855327597 | 648,252 |
def definition():
"""UI view of dates"""
sql = """
SELECT d.set_cat_id, d.acad_year, d.dt, s.description + ' ' + c.description + ISNULL(' - ' + d.description,'') as description,
c.important
FROM conf_dt as d
INNER JOIN conf_dt_cat AS c on c.dt_cat_id = d.dt_cat_id
INNER JOIN f_set_cat AS s ON s.set_cat... | 731d0177206bbd1d93c4ad5ebe4ab199d33801fd | 648,253 |
import json
def pretty_print(js):
""" try to convert json to pretty-print format """
try:
return json.dumps(js, indent=4, separators=(",", ":"), sort_keys=True)
except Exception as e:
return "%s" % js | 58c9751975bb8e4cc4b1f4bbbf681b5ddd392f21 | 648,255 |
def traditional_constants_icr_equation(tdd):
""" Traditional ICR equation with constants from ACE consensus """
a = 450
return a / tdd | e4ad065665481978e52a6f82a986a51e2af1c659 | 648,256 |
def derive_fabs_awarding_sub_tier(row, office_list):
""" Derives the awarding sub tier agency code if it wasn't provided and can be derived from the office code.
Args:
row: the dataframe row to derive the awarding sub tier agency code for
office_list: A dictionary of sub tier codes ... | cc8f2db16ddab3f773da6f4c2c6a3c7f3f24102f | 648,257 |
import re
def escape_re_special_characters(s):
"""
given some string,
return a regex that matches that string literal
"""
for re_special_char in '/\-[]{}()*+?.,^$|#':
s = re.sub(f'\{re_special_char}', f'\{re_special_char}', s)
return s | f63fa197f4dd39d89261317c6ba6ddab02e7b8db | 648,258 |
def optimal_savings_square(mat_size, block_size):
"""optimal savings based on the block size of a square matrix."""
if mat_size % block_size != 0:
raise ValueError('block size must evenly divide mat_size.')
num_blocks = mat_size // block_size
return num_blocks * (num_blocks + 1) * block_size**2 / (2 * mat_s... | adf4614b96fdc038a65a10dff4750d6adc23dfc2 | 648,259 |
import logging
def get_all_trt(trt):
"""
All phenotype names
"""
all_trt = set()
for genome in trt.keys():
for trt_name in trt[genome].keys():
all_trt.add(trt_name)
logging.info(' No. of trait columns: {}'.format(len(all_trt)))
return sorted(all_trt) | a3222e07d3d2345420e4502e98b2c50628621b61 | 648,260 |
def cln_txt(str_inp:str)->str:
"""
remove special characters
"""
str_inp=str_inp.replace(u'\xa0',u' ')
str_inp=str_inp.replace(u'\n',u' ')
str_inp=str_inp.replace(u'\r',u' ')
txt=''.join([s for s in str_inp if not s in '!"#$%&\'()*+-;<=>?@[\\]^_`{|}~' ])
return txt.replace(' ','').stri... | 70b4ac10562bc246bde427f849a702fd653e7095 | 648,261 |
def score_logits(logits, tags, transitions, boundary_values):
"""Computes the likelihood score for the given sequence of tags, given
the provided logits (and the transition weights in the CRF model)"""
# Start with transitions from START and to END
total = boundary_values[tags[0]] + boundary_values[tags... | b0bed3cf05683e230063e00d1c2a2f3b44b5a761 | 648,263 |
import re
def get_matching_columns(dataframe, *args, **kwargs):
"""
Filter column whose names match the regular expressions defined in
``args``.
Args:
dataframe (pandas.DataFrame): Input DataFrame
\*args (List[str]): List of regular expressions matching column names
Keyword Args:
... | b5cbcb3c21c7004436865164ed6351fd8c1233a1 | 648,264 |
import requests
import sys
def api_delete_request(session, req):
"""Delete a single request label"""
headers = {'Accept':'application/json'}
url = "https://ega.ebi.ac.uk/ega/rest/access/v2/requests/delete/{}?session={}".format(req, session)
r = requests.get(url, headers = headers)
reply = r.json... | f2d31f78336d11f700cb0fd2895fd012b92fb995 | 648,265 |
def _clean_sample(sample, fields=None):
"""
Clean a sample resource from unnecessary fields
:param sample: the sample to clean
:type sample: dict
:return: Sample cleaned from unnecessary params
:rtype: dict
"""
if fields is None:
fields = ['_links', 'releaseDate', 'updateDate',... | 6e8987dbf7376f58ce75786ef3cec184a3598e8e | 648,266 |
def train_network(net, epochs, training_data, validation_data, batch_size, callbacks, verbose=1):
"""
train a network on data for a fixed number of epochs
parameters:
net: network to train
epochs: number of epochs
training_data: training data under the format of numpy arrays (inputs,... | d89704adc14bf2b609fa7bdb2300d59c4b2b5b1f | 648,267 |
import glob
import os
def get_newest_file_in_dir(path, exts):
""" Find the newest file in a directory, matching the extensions provided. """
dir_iter = []
for ext in exts:
dir_iter.extend(glob.iglob(os.path.join(path, ext)))
try:
return max(dir_iter, key=os.path.getctime)
except ... | 74160d4bc214d6ff137f0f985b8caa8de56f324c | 648,268 |
def get_feat_splits(all_feats, RAM_denom):
"""
Takes a list of features, splits it into a dictionary
{0:[feat1,feat2,feat3], 1:[feat4,feat5......
"""
assignments = []
num_feats = len(all_feats)
feats_per = num_feats//RAM_denom
if num_feats % RAM_denom != 0:
feats_per += 1
... | ec3f0be6ecad12bcc9402a2be2997f0edab188e5 | 648,269 |
def rgb(minimum, maximum, value):
"""Convert value within range to RGB."""
assert value <= maximum
assert value >= minimum
minimum, maximum = float(minimum), float(maximum)
r = 2 * (value - minimum) / (maximum - minimum)
b = int(max(0, 255 * (1 - r)))
r = int(max(0, 255 * (r - 1)))
g = 2... | 3c611cda74f12d87d3a603f1a88d2e6255d17495 | 648,270 |
import argparse
def create_parser():
"""Creates a parser for command-line arguments.
"""
parser = argparse.ArgumentParser()
# Model hyper-parameters
parser.add_argument('--image_size', type=int, default=32, help='The side length N to convert images to NxN.')
parser.add_argument('--g_conv_dim'... | 5d5f0ad3b7c1866ebb782ccf7928e59e94e910f8 | 648,271 |
def binomial(n, k):
"""
Return binomial coefficient ('n choose k').
This implementation does not use factorials.
"""
k = min(k, n - k)
if k < 0:
return 0
r = 1
for j in range(k):
r *= n - j
r //= j + 1
return r | 7786725d8b8aeb1511a69d7dd373ccfe21143beb | 648,272 |
def get_train_test(df, partition):
"""
Helper function to get train/test partitions from dataframe
df: set (train/test), partition (0-9)
"""
if str(partition) == "holdout":
return df[df.set == "train"], df[df.set == "test"]
return df[df.partition != int(partition)], df[df.partition == i... | a05fdcfba7fd73f14e8cfaaa761095e15f726c94 | 648,273 |
def count_colours(image):
"""Return the number of colours in the image - only works when the image
has been converted to a 'P' mode"""
return len(image.getcolors()) | 48d2d7c61f245e981e071098a6b2838ffd98ac71 | 648,274 |
import math
def distance(color1, color2):
"""(Cimpl.Color, Cimpl.Color) -> float
Return the Euclidean distance between two Color objects.
"""
r1, g1, b1 = color1
r2, g2, b2 = color2
return math.sqrt((r1 - r2) ** 2 + (g1 - g2) ** 2 + (b1 - b2) ** 2) | fbe8bfba1c800b633932c1d6b2e69ba9d44cade5 | 648,275 |
def getConvergents(coeffs: list) -> list:
"""Calculates convergents of the continued fraction
Details: https://en.wikipedia.org/wiki/Continued_fraction
Parameters:
coeffs: list
coefficients of continued fractions
Returns:
result: list
list of tuples (nomina... | 490b104cbfb03b770d4933cecca01029b7b78fea | 648,276 |
def print_struct_param(struct_param, transition_mode = "layertype-only", print_mode = "long"):
"""Print the struct_param in a concise way."""
if print_mode == "long":
struct_param_new = []
for layer_struct_param in struct_param:
num_neurons, layer_mode, layer_hyperparam = layer_struc... | 3fbe5fc8423122abfaa06b94b4379190b7189b81 | 648,277 |
def reverse_int(integer: int) -> int:
"""Reverse an integer."""
reversed_int = int(str(abs(integer))[::-1])
if integer < 0:
reversed_int *= -1
return reversed_int if -(2**31) < reversed_int < 2**31 - 1 else 0 | 5af0fd4da0fdf262b63fda0eeaba406a7bc534a0 | 648,278 |
def dekatrian_week(dek_day: int, dek_month: int) -> int:
"""Returns the Dekatrian week day from a Dekatrian date.
Here we can see the elegance of Dekatrian, since it's not necessary to
inform the year. Actually, barely it's necessary to inform the month,
as it's only needed to check if that is an Achron... | 14cbc62546fe4bf5ffc4234b8d892ae94f28256b | 648,279 |
def solution1(magazine, ransom): # O(N^2)
"""
Similar to src.strings.making_anagrams, detect if 2 strings can be equated by
only removing some words.
>>> solution1('give me one grand today night', 'give one grand one today')
False
>>> solution1('give me one g... | 362de142de6e37c137946db95965a54e34298fff | 648,280 |
from typing import List
def add_sos(token_ids: List[List[int]], sos_id: int) -> List[List[int]]:
"""Prepend sos_id to each utterance.
Args:
token_ids:
A list-of-list of token IDs. Each sublist contains
token IDs (e.g., word piece IDs) of an utterance.
sos_id:
The ID of the... | 779912dee80879b0f1def915264b2135b4661925 | 648,281 |
import torch
def concatenate_dict(*dicts):
"""Concatenates dictionaries as long as they have the same keys.
If one dictionary has one key that the others do not have,
the dictionaries lacking the key will have that key replaced by None.
Args:
*dicts: Description
*dicts (any num... | e54c723a0a00c3919e9298c3e01de3ba16458ac1 | 648,282 |
from typing import Dict
import pkg_resources
def get_pip_packages() -> Dict[str, str]:
"""
Returns a dictionary of pip packages names and their versions. Similar
to `$ pip freeze`
"""
return {
package.project_name: package.version
for package in pkg_resources.working_set
} | 1869cb0a0f5b2f5d62f0f540f23efc7ad8468df1 | 648,283 |
import math
def get_relative(x, y):
"""返回两个list数据的相关系数r"""
x_avg = sum(x) / len(x)
y_avg = sum(y) / len(y)
xy_pair = zip(x, y)
sum_xy, sum_x2, sum_y2 = 0, 0, 0
for x_, y_ in xy_pair:
sum_xy += (x_ - x_avg) * (y_ - y_avg)
sum_x2 += (x_ - x_avg) ** 2
sum_y2 += (y_ - y_avg... | 114b9b553c2debd6c3440ae55e24eb97ace97391 | 648,284 |
def dominate(s1, s2):
""" Returns true if S1 dominates S2. S1 dominates S2 if S1 is better
(it our case lower) in the two fitness functions """
score1 = s1.get_fitness_score()
score2 = s2.get_fitness_score()
return False if (score1[0] > score2[0] or score1[1] > score2[1] or
(sco... | ab3a7df8a55fe451ffa5ecda85935aeada70a829 | 648,285 |
from typing import Dict
import operator
def argmax(dict_: Dict):
"""
Get the argmax.
Parameters
----------
dict_ : dict
Returns
-------
argmax : tuple
Example
-------
>>> argmax({'a': 10, 'b': 70, 'c': 20})
'b'
"""
return max(dict_.items(), key=operator.itemg... | c88541f7da4cd61ef63d7ad11932ed69d83a1971 | 648,286 |
def field_cleaner(field: str) -> str:
"""Convert field string from an html response into a snake case variable.
Args:
field (str): A dirty field string.
Example:
|Input | Output |
|------------------|------------------------|
|Previous Close |... | 005438e5990e492249c93023d0de758acc6bdda0 | 648,287 |
import math
def multinomial(i_s):
"""Compute the multinomial (i_1 + ... + i_n)!/(i_1! ... i_n!)."""
itot = 0
denom = 1
for i in i_s:
itot += i
denom *= math.factorial(i)
return math.factorial(itot) / denom | 4f4a6e86ab3d55fd33498f83d5a00cd397605b23 | 648,288 |
from typing import Any
def build_where(**conditions: Any) -> str:
"""
Build WHERE statement with several `conditions`
If no `conditions` passed return `WHERE 1 = 1`
In case if a value has primitive type it will be an equal condition and
in case if it is an iterable it will be an include condition... | ec2d7c2aebe4798a7cb06b20f9d2c06259afdadd | 648,289 |
def build_user(first, last, **user_info):
#The double star tells python to make an empty dictionary
#so we can mix-and-match data types (e.g., string and int)
"""Build a dictionary containing user information"""
user_info['first'] = first
user_info['last'] = last
return user_info | c17141259260fd3d59154dbd90e749ce8fc4ad7f | 648,290 |
import re
def rAssetName(nodeNS):
"""
Return basename and id string, if nodeNS ends with digi
"""
return nodeNS.split('_')[0] + re.sub('.*?([0-9]*)$', r'\1', nodeNS)
#return nodeNS.split('_')[0] | fed06e1aa8cc8a419748f885f73840b1b79b017c | 648,291 |
import os
def phoSimInputFileName(obsHistID,
prefix='InstanceCatalogs/PhoSim_input',
suffix='.txt',
location='./'):
"""
function to return the absolute path to a filename for writing the phoSim
input corresponding to obsHistID.
P... | f0b8c1c564775fd624749837ea196a2b13e1e14b | 648,293 |
def pool(create_pool, server, loop):
"""Returns RedisPool instance."""
pool = loop.run_until_complete(
create_pool(server.tcp_address, loop=loop))
return pool | 2cf8cf38e07ff656cc9e5a43bfe18cfd56a73a6d | 648,294 |
def _is_hd(release_name):
""" Determine if a release is classified as high-definition
:param release_name: release name to parse
:type release_name: basestring
:return: high-def status
:rtype: bool
"""
if "720" in release_name or "1080" in release_name:
return True
return False | eac085e5de4a5edd63d1960cb1b3a8ef79b7fd58 | 648,295 |
import os
def _full_fn_to_record_fn(full_fn):
"""
Returns:
str : tree/c24d96eb_nohash_0.wav
"""
return os.path.join(os.path.basename(os.path.dirname(full_fn)), os.path.basename(full_fn)) | c87761f2a91cf2d2fb1d04b04fcf738d51bc7f01 | 648,296 |
def sum_client_agg(groupby_obj):
"""
Takes in the groupby obj from groupby
and aggregates it for all clients.
"""
# Count unique clients by month and drop/rename columns to reflect
# new aggredated DateFrame.
total_count_df = groupby_obj.count()
return total_count_df | 2bc242e0d9b985b57dd62d3d1e8faeddae640a7f | 648,297 |
def assign_orchestrator(
self,
orchestrator: str,
ssl_enabled: str = "false",
keepalive_count: int = 0,
port: int = 0,
) -> bool:
"""Assign an Orchestrator to the appliance
.. list-table::
:header-rows: 1
* - Swagger Section
- Method
- Endpoint
*... | c689ba7a635394a1b0807c1fa026bad29ea630e8 | 648,298 |
import json
def brute_force_login(socket_connection, file_name):
"""
:param socket_connection: connected socket object
:param file_name: string or path representing file name
:return: username
"""
credential = {"login": "", "password": ' '}
with open(file_name) as file_handler:
for... | 7af0bef7e703a40e73c96570f81748fc78fa4e60 | 648,300 |
import random
def random_password(choices, length):
""" Create Random strings
The random string is created out of the set of `string.ascii_letters` and `string.digits`.
Args:
length -- the length of the new random string
Returns:
A random string cosisting out of ascii letters and th... | 5d7065ebfd1ef1df5d91fabe0708c087540ecd2b | 648,301 |
import sys
import ssl
def ssl_context(protocol=None):
"""Workaround for old SSLContext() required protocol argument."""
if sys.version_info < (3, 5, 3):
return ssl.SSLContext(ssl.PROTOCOL_SSLv23)
return ssl.SSLContext() | 4601c189b89cf4c3e9ea56af413c8fed9bdf8b43 | 648,302 |
def clear_text(text: str):
""" Удаляет из строки лишние спец. символы, которые добавляет Ace-editor """
if isinstance(text, str):
return text.replace('\r', '').rstrip('\n')
else:
return text | c0566b292a3a49b5929a85cc20252ab583bd4192 | 648,303 |
def vep_csq_header():
"""Returns the CSQ description from the header of a VEP-annotated VCF file - Has the same fields as vep_csq"""
csq_header = """Allele|Consequence|IMPACT|SYMBOL|Gene|Feature_type|Feature|BIOTYPE|EXON|INTRON|HGVSc|HGVSp|cDNA_position|CDS_position|Protein_position|Amino_acids|Codons|Existing_... | f950681bdb2d3be64e9f9df13f3ceadd51f9f293 | 648,304 |
def _can_support_reuse_db(connection):
"""Return whether it makes any sense to
use REUSE_DB with the backend of a connection."""
# Perhaps this is a SQLite in-memory DB. Those are created implicitly when
# you try to connect to them, so our usual test doesn't work.
return not connection.creation._ge... | 98f71d7b1b2efb917cc8e94f117c20de080d078b | 648,305 |
import re
import os
def ListTests(path):
"""lists tests in directory "path" ending in _test.py."""
pattern = re.compile("^\w*_test.py$", re.IGNORECASE)
tests = []
for test in os.listdir(path):
if pattern.match(test):
tests.append(test)
tests.sort()
return tests | 7eb2a62205ef2cf60c6a2614a08707702fbacb17 | 648,306 |
def get_service(module, name):
"""Get details for brew service
:return: str formatted: `Name Status User Plist`
"""
rc, out, err = module.run_command(['brew', 'services', 'list'])
if rc != 0 or err:
module.fail_json(
msg='Error listing installed brew services [%s]: %s' % (name,... | 4a15695c42ba433edbad7d160ba07febb21c8fa8 | 648,307 |
def diff(old_list, new_list):
"""Compare the old and new lists of options."""
new_opts = []
new_defaults = []
deprecated_opts = []
for name, (group, option) in new_list.items():
# Find the new options
if name not in old_list.viewkeys():
new_opts.append(name)
# Fi... | 61dfe5b193a8b435f577452c9318a3669478cc79 | 648,308 |
def comb_sort(elements):
"""
Use the simple comb sort algorithm to sort the :param elements.
:param elements: a sequence in which the function __get_item__ and __len__ were implemented
:return: the sorted elements in increasing order
"""
length = len(elements)
if not length or length == 1:
... | 9ea46e11b79185defdcc806f85362830c10ab78d | 648,309 |
from typing import OrderedDict
def _set_table_column_names(names=None):
"""Define the table data columns to use in the html header.
Parameters
----------
names: collections.OrderedDict
The dictionary of string column header names and their types
Their types are the accepted google typ... | 15f5afc4f4efaf81e0380de90adaed83a6001d3d | 648,310 |
import random
import string
def generate(length: int, prefix: str = "", suffix: str = "") -> str:
"""Generate token"""
return (
prefix
+ "".join(random.choice(string.ascii_letters) for x in range(length))
+ suffix
) | 64a665f754c3416b376cbb85686675c58b8f60a0 | 648,311 |
def minmax_dc(a):
"""Find mix & max in a list by divide and conquer algorithm.
- Time complexity: O(n).
- Space complexity: O(1).
"""
if len(a) == 1:
return [a[0], a[0]]
elif len(a) == 2:
if a[0] < a[1]:
return [a[0], a[1]]
else:
return [a[1], a[0... | 1bf0e540ce1e9d4c01479c98d24876f0d1b32e40 | 648,312 |
def homepage():
"""List all available api routes."""
return (
f"Available Routes:<br/>"
f"<a href='http://127.0.0.1:5000/api/v1.0/precipitation'> /api/v1.0/precipitation</a><br/>"
f"<a href='http://127.0.0.1:5000/api/v1.0/stations'>/api/v1.0/stations</a><br/>"
f"<a href='http://1... | 55efc5f2429f89fb44afcf77f6b9962c08dde875 | 648,313 |
import base64
def decrypt(data, box):
"""
Decrypt data using private_key
@param data bytes : data to decrypt
@param private_key: nacl box to decrypt data
returns string of the original data
"""
_bytes = base64.b64decode(data)
return box.decrypt(_bytes).decode() | 878682251288fbd88c8b63e76dffb2d5b27554ae | 648,314 |
import socket
def get_local_hostname():
"""
Get the local ip address --linux/windows
:return:
"""
return socket.gethostname() | 8331419ef493bc637ea6af0a02739e54dde84948 | 648,315 |
import re
def clean_ne_records(record: str):
"""Base cleaning for ne records"""
record = record.replace("\t", " ").replace("|", " ").strip()
record = record.replace("\u200c", " ") # Nim-fasele
record = re.sub(" +", " ", record) # space cleaner
return record | 5c1a7c5854511d97c38c191e9ffbd7abe9ef520f | 648,316 |
import json
def json_validation(template):
"""
Json validator
:param template: json template
:type template: object
:return: bool
"""
try:
json.loads(template)
except ValueError:
return False
return True | 84cd9cf6ccdd9bf7b01031ac9f7f88ddea10b375 | 648,317 |
def get_ac_edge_index(ac_edges):
"""Get edge index"""
# Edge indices
edges_1 = ac_edges.apply(lambda x: (x['FROM_NODE'], x['TO_NODE']), axis=1).to_list()
edges_2 = ac_edges.apply(lambda x: (x['TO_NODE'], x['FROM_NODE']), axis=1).to_list()
# All combinations of from and to nodes
all_edges = edg... | eab1941cee41318c0eb1cce22c89c33173802296 | 648,318 |
def time():
"""start_time = datetime.now()
flight_time = datetime.strptime(flight, '%b %d %Y %I:%M%p')
hours_difference = abs(start_time - flight_time).total_seconds() / 3600.0"""
return int(1) | 0528877820c42764592faeea9bf013778d08874e | 648,319 |
import os
def package_dir():
"""Return the path containing this ell module """
return os.path.join(os.path.dirname(__file__)) | 830976b2abb8192a13849378f377e90d4bfe4dcb | 648,321 |
def simpleSubtractDictionaries(d1,d2):
"""
Subtract the elements of the second dictionary from the ones in the first dictionary. Assumes both share the same keys.
"""
assert set(d1.keys()) == set(d2.keys())
return dict([ (key, d1[key]-d2[key]) for key in d1]) | a102f1a19658f03316d743c8568ccc9bd188c2a4 | 648,322 |
def project(x, meta):
""" project 3D to 2D for polygon clipping
"""
proj_axis = max(range(3), key=lambda i: abs(meta['normal'][i]))
return tuple(c for i, c in enumerate(x) if i != proj_axis) | 4ed25fbac60c730e7a9fec5f4c3d0fd5046ca69d | 648,324 |
def get_data_tank_2():
"""Creates a set of data for use in the sample"""
values = []
values.append({"pressure": 345, "temperature": 89,
"time": "2017-01-11T22:20:23.430Z"})
values.append({"pressure": 356, "temperature": 0,
"time": "2017-01-11T22:21:23.430Z"})
v... | 760f4158021388768b0e8a21705a51f6779eff40 | 648,325 |
from datetime import datetime
def make_sim_exp_names(config, n_exp):
"""Helper to create simulator directory names using datetime and config"""
# Pull out some metadata
date = datetime.now().strftime('%Y%m%d_%H%M%S')
n_nonmot = config['exp_params']['n_non_motile']
n_mot = config['exp_params']['n_... | 56269cfad20775e8c83eb88a099bb3a9fe41ad5d | 648,326 |
def binary_to_decimal(binary):
"""binary değeri decimale çeviren fonksiyon"""
binary=str(binary)[::-1]
decimal,index = 0,0
for i in binary:
decimal+=pow(2,index)*int(i)
index+=1
return decimal | 8f36b236988217e6f3ac52f8cd0adc58a04ee3eb | 648,327 |
from typing import Any
def as_kafka_configuration_bool(value: Any) -> bool:
"""
Convert a value to a Python boolean, using the same conversions used by
the librdkafka configuration parser.
"""
# https://github.com/edenhill/librdkafka/blob/c8293af/src/rdkafka_conf.c#L1633-L1660
if isinstance(va... | 61f63b2f6dadc997290b454fc6d3cdcef81a5e9b | 648,328 |
def calc_charge_trans(m_potential, x_potential, iv, elec_affinity_non_metal, d_mx_avg):
"""
Calculate the estimated charge transfer energy (eV) of a structure
:param m_potential: Float, the metal site Madelung potential in V
:param x_potential: Float, the non_metal site Madelung potential in V
:par... | 563b677492ce13928262347e7ba8352d11aa44f7 | 648,329 |
import re
def _extract_failed_ps_instances(err_msg):
"""Return a set of potentially failing ps instances from error message."""
tasks = re.findall("/job:ps/replica:0/task:[0-9]+", err_msg)
return set(int(t.split(":")[-1]) for t in tasks) | b7cf036584dde71bfdb0bf0ead9017b94b7280e3 | 648,330 |
def init_vault(client, shares=1, threshold=1):
"""Initialise vault.
:param client: Client to use for initiliasation
:type client: CharmVaultClient
:param shares: Number of key shares to create
:type shares: int
:param threshold: Number of keys needed to unseal vault
:type threshold: int
... | 24f410289861da6545f244d7993daf88ef8b2055 | 648,331 |
def rw_at_form_temp(rw, rw_temperature, temperature_units, new_temperature):
"""
Converts formation water resistivity from a known temperature to formation temperature.
Parameters
----------
rw : float
Water Resistivity (ohmmm)
rw_temperature : float
Temperature Rw was measured ... | 844d0deaa81ec2ccda055384ccf5fd8d63ba2c56 | 648,332 |
def freq_to_time(self):
"""Performs the Fourier Transform and stores the resulting field in a VectorField of DataTime objects.
Parameters
----------
self : VectorField
a VectorField object
Returns
-------
a VectorField object
"""
# Dynamic import to avoid loop
module = _... | 0e0149da7aa3ff52e2ff43adb6213cddea1af531 | 648,333 |
def decimal2dm(decimal_degrees):
""" Converts a floating point number of degrees to the equivalent
number of degrees and minutes, which are returned as a 2-element list.
If 'decimal_degrees' is negative, only degrees (1st element of returned list)
will be negative, minutes (2nd element) will always be p... | 198f587b8467d5c8720e8d8544e31a042b76fa02 | 648,335 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.