content
stringlengths 39
14.9k
| sha1
stringlengths 40
40
| id
int64 0
710k
|
---|---|---|
def dict_subtract(d1, d2):
"""Subtract one dictionary from another.
Args:
d1 (dict): First dictionary.
d2 (dict): Second dictionary.
Returns:
dict: `d1 - d2`.
"""
if set(d1.keys()) != set(d2.keys()):
raise ValueError("Dictionaries have different keys.")
return {k: d1[k] - d2[k] for k in d1.keys()} | a8098f66ce1ca85803c90d9cfc058ae96b3f8123 | 28,369 |
import re
def clean_name(name: str) -> str:
"""
Bring the name into a standard format by replacing multiple spaces and characters
specific for German language
"""
result = re.sub(r"\s+", " ", name)
return (
result.replace("ß", "ss")
.lower()
.replace("ä", "ae")
.replace("ü", "ue")
.replace("ö", "oe")
) | 8cb8ba45fcec1dcc0e04ccfcd4263ae3e82e9fb5 | 28,370 |
import json
def json_from_file(file_path):
"""
Read a file and convert it into a json object
:param file_path: path of file
:return: A json object
"""
file = open(file_path, "r")
return json.loads(file.read()) | 3342c083e64254a271b31b1c7a6747ac448f4078 | 28,381 |
import torch
def batch_audio(audios, max_frames=2048):
"""Merge audio captions. Truncate to max_frames. Pad with 0s."""
mfcc_lengths = [len(cap[:max_frames, :]) for cap in audios]
mfcc = torch.zeros(len(audios), max(mfcc_lengths), audios[0].size(1))
for i, cap in enumerate(audios):
end = mfcc_lengths[i]
mfcc[i, :end] = cap[:end]
return mfcc.permute(0, 2, 1), torch.tensor(mfcc_lengths) | 79ea2a9e8459dda945f00e4f9a4edb22a445da93 | 28,382 |
def get(node, name):
"""
Given a KML Document Object Model (DOM) node, return a list of its sub-nodes that have the given tag name.
"""
return node.getElementsByTagName(name) | 84c48b9e1ec1e71ee615357a10586950f995c991 | 28,384 |
def int_to_bitstring(x: int) -> str:
""" Function to convert an integer to AT LEAST a 32-bit binary string.
For integer less than 32 bits, it will pad the integer with extra bits of 0s until it is of size 32bit.
If the integer is greater than 32-bits, then return the binary representation with the minimum number of bits to
represent the integer.
Parameters
----------
x: int
Integer to convert to bitstring
Returns
-------
str
Bitstring of AT LEAST size 32-bits.
Notes
-----
Here are some example cases.
.. highlight:: python
.. code-block:: python
>>> int1 = 2
>>> int_to_bitstring(int1)
00000000000000000000000000000010
>>> int2 = 9999999999999
>>> int_to_bitstring(int2)
10010001100001001110011100101001111111111111
In the first example, the binary representation of 2 is simply 10. Hence, the function pads the bitstring with
30 0s on the left to return a 32-bit bitstring. In the second example, 9999999999999 in binary consist of > 32-bits,
hence the function returns the full binary representation.
"""
return '{:032b}'.format(x) | 34c022eedf5d73d68cac56f296bd53cc62b2be24 | 28,394 |
def get_best_hits(matches, evalue_cutoff):
"""
get the best hit: one with smallest evalue and highest score.
if at least two hits have same evalue and score, report them all
"""
best_hits = []
evalue_sorted = sorted(matches, key=lambda x: x[2])
best_evalue = evalue_sorted[0][2]
if best_evalue <= evalue_cutoff:
scores = []
for el in evalue_sorted:
if best_evalue == el[2]:
scores.append(el)
score_sorted = sorted(scores, key=lambda x: x[3], reverse=True)
best_score = score_sorted[0][3]
for el in score_sorted:
if best_score == el[3]:
best_hits.append(el)
return best_hits | 9bf21eecc896d29fb888ec772fc7dbab8a6913cc | 28,396 |
import re
def find_coords_string(file_path):
"""
Parse a file path using a regular expresion to find a substring
that looks like a set of coordinates,
and return that.
"""
match = re.search(
"([-]?[\d]{1,3}\.[\d]{1,3}[_,][-]?[\d]{1,3}\.[\d]{1,3})", file_path
)
if not match:
return None
coords_string = match.groups()[0]
return coords_string | 2d6fd569122222d3600aea5500bd515dea8b8596 | 28,397 |
import requests
def load_inspect_api(url):
""" Load inspect API and return Json response """
r = requests.get(url)
if r.status_code != 200:
raise RuntimeError(
'Failed to read inspect API. Error %d.' % (r.status_code))
return r.json() | 6a3a722a6a5e9752fd3f9ef5806cca3209392bbe | 28,398 |
def can_edit_address(user, address):
"""Determine whether the user can edit the given address.
This method assumes that an address can be edited by:
- users with proper permission (staff)
- customers who "own" the given address.
"""
has_perm = user.has_perm("account.manage_users")
belongs_to_user = address in user.addresses.all()
return has_perm or belongs_to_user | 724be0e3023a4776604f869b506a35f216c3461e | 28,399 |
def parse_input(inp, options):
"""Parses user-provided input
Check if the given input can be seen as an index of the options list.
Parameters
----------
inp : str
User input
options : list
List of option strings
Returns
----------
parsed_choice
The index corresponding to the input if index is valid for the options list
else None
"""
try:
parsed_choice = int(inp)
if parsed_choice >= 0 and parsed_choice < len(options):
return parsed_choice
except:
return None | fcb63ce473d08363373af3488b87b49a19c782e0 | 28,401 |
def filename_segment(value):
"""Check that the string is valid for use as part of a filename."""
for character in value:
if not character.isalnum() and character not in '-_. ':
raise ValueError(f"invalid value: '{value}'")
return value | 44f9e0b26501accf7facb0c766938865648a5121 | 28,404 |
def _early_stop(args, eval_history):
"""
Determines early stopping conditions. If the evaluation loss has
not improved after `args.early_stop` epoch(s), then training
is ended prematurely.
Args:
args: `argparse` object.
eval_history: List of booleans that indicate whether an epoch resulted
in a model checkpoint, or in other words, if the evaluation loss
was lower than previous losses.
Returns:
Boolean indicating whether training should stop.
"""
return (
len(eval_history) > args.early_stop
and not any(eval_history[-args.early_stop:])
) | 5e8d698703750a2f4be2564b4905c5e7d42815ed | 28,409 |
def _line_to_array(agile_line):
"""convert the weird AGILEPack weights output to an array of floats"""
entries = agile_line.split(',')[1:]
return [float(x) for x in entries] | 0693a75ecce5dc105aedf9fa44d16e1e6959befa | 28,412 |
def is_dialog_complete(handler_input):
"""
Checks whether the dialog is complete according to the dialog model
:param handler_input: (HandlerInput)
:return: (boolean)
"""
if not hasattr(handler_input.get_request(), "dialogState"):
return False
return handler_input.get_request().dialogState == "COMPLETE" | c9137b497bf472e88f05f8395166db5b18fe5f51 | 28,429 |
def log_call(call_next, *args, **kwargs):
"""Decorator to log the call signature"""
arg_items = [str(a) for a in args] + [
f"{k}={v}" for k,v in kwargs.items()
]
arg_string = ",".join(arg_items)
print(f"Calling {call_next}({arg_string})")
return call_next(*args, **kwargs) | 4c6becf8731944b2c2e80c51a16fe62034d81102 | 28,435 |
def tags_to_text(tags):
"""Return a text of sorted tags"""
str_tags = [str(t) for t in tags]
sorted_tags = sorted(str_tags)
return '\n'.join(sorted_tags) | a4bf2111517e3b8f616e84490bd37e9f197c698a | 28,436 |
def protocol_stage_settings(settings):
""""Load settings for each milling stage, overwriting default values.
Parameters
----------
settings : Dictionary of user input argument settings.
Returns
-------
protocol_stages
List containing a dictionary of settings for each protocol stage.
"""
protocol_stages = []
for stage_settings in settings["lamella"]["protocol_stages"]:
tmp_settings = settings["lamella"].copy()
tmp_settings.update(stage_settings)
protocol_stages.append(tmp_settings)
return protocol_stages | fd2b65ffcf71ea674e32eb80a69faec27ff9b66d | 28,441 |
def evaluate(env, policy, num_episodes = 10):
"""Evaluates the policy.
Args:
env: Environment to evaluate the policy on.
policy: Policy to evaluate.
num_episodes: A number of episodes to average the policy on.
Returns:
Averaged reward and a total number of steps.
"""
total_timesteps = 0
total_returns = 0.0
for _ in range(num_episodes):
episode_return = 0
timestep = env.reset()
while not timestep.is_last():
action = policy.act(timestep.observation)
timestep = env.step(action)
total_returns += timestep.reward[0]
episode_return += timestep.reward[0]
total_timesteps += 1
return total_returns / num_episodes, total_timesteps / num_episodes | 8ebac5d9862662b45395c8cbdacace2cb4058b47 | 28,444 |
import shlex
def _join(split_command: list[str]) -> str:
"""Concatenate the tokens of the list split_command and return a string."""
return " ".join(shlex.quote(arg) for arg in split_command) | 127cd1a7366c843c328b1e29632811e964de0542 | 28,445 |
from pathlib import Path
def check_file_exists(sub_dir: Path, file: Path):
"""Check if the supplied `file` arg exists.
Args:
sub_dir (Path): the fully qualified subdirectory
file (Path): the file to check
Returns:
Path: if valid, the file
Raises:
Exception: if save file doesn't exist or is in the wrong place
"""
if file.resolve().parent != sub_dir:
file = sub_dir / file
if not file.exists():
raise Exception(f'{file} isn\'t in {sub_dir}')
if file.exists():
return file
else:
save_file = sub_dir / file
if not save_file.exists():
raise Exception(
f"""{save_file} doesn't exist.
Please check the filename and/or location.
"""
)
return save_file | e421dc28adb49291fc4740c5163604e772d6aa2e | 28,447 |
def uploaded_file_extension(filename: str) -> str:
"""
Returns the extension from a file name
:param filename: Name of the file with its extension
:type filename: str
:return: The extension of the file
:rtype: str
"""
extension = filename.rsplit('.', 1)[1].lower()
return "%s%s" % (".", extension) | 03d62a28997d535427fded44d0df1ffc8a646f6f | 28,449 |
def load_fragment(soup, fragment, cache):
"""
Load and cache a BNC fragment, given the id `fragment`.
"""
if fragment in cache:
return cache[fragment]
fragment_xml = soup.find('text', {'xml:id': fragment})
cache[fragment] = fragment_xml
return fragment_xml | 56333e7736d501f0cef66f1b956cefd1d8c3071b | 28,453 |
def may_change_leading_case(text):
"""
Checks whether the string `text` can
change the letter case of its leading letter.
"""
for c in text:
if c.isalpha():
return True
if c.isspace():
continue
return False
return False | ba3b30c4e5a65104671f25970a65b93e6d4d7dcf | 28,454 |
def sinum_frmt(x):
"""
Generate SIunitx style formatted number output for plotting tables to TeX.
This function can be used as a formatter for printing DataFrames to Latex
tabes when using the Latex package SIunitx.
Parameters
----------
x : int, float
Value to format.
Returns
-------
str
Formatted value.
"""
if isinstance(x, (int, float)):
if x < 1e3:
return r'\num{' + '{0:.3G}'.format(x) + '}'
elif x >= 1e3:
return r'\num{' + '{0:.0f}'.format(x) + '}'
else: # x is nan
return '-'
else:
return x | 3ed5311d242b99c946e1ea1d514187a5823b2be0 | 28,457 |
def vprint(verbose: bool):
"""
Utility function for optional printing.
Parameters
----------
verbose: bool
If True, returns print function, else False
Returns
-------
callable
"""
return print if verbose else lambda *a, **k: None | 5295914f2fc9b8aaa146b74c8b5ff3ec7b501cab | 28,458 |
import json
def get_top_python_packages(top_n=100):
"""
Generate list of most downloaded python packages
Args:
top_n: the number of most downloaded packages to return
Returns:
(list) Names of most downloaded packages
"""
# JSON file containing top 4000 packages
# found here: https://hugovk.github.io/top-pypi-packages/
top_python_pkgs = "top_python_pkg_downloads.json"
with open(top_python_pkgs, "r") as j:
contents = json.loads(j.read())
# store names of top packges
top_pkgs = []
cnt = 0
for pkg in contents["rows"]:
# only append TOP_N number of packages
if cnt == top_n:
break
top_pkgs.append(pkg["project"])
cnt += 1
return top_pkgs | d19136a5ee21fe65c33ef4a5336f46863bf2c6b0 | 28,459 |
def get_arrhythmia_type(fields):
"""Returns type of arrhythmia based on fields of the sample
Arguments
---------
fields: fields of sample read from wfdb.rdsamp
Returns
-------
Type of arrhythmia
'a': asystole
'b': bradycardia
't': tachycardia
'f': ventricular fibrillation
'v': ventricular tachycardia
"""
arrhythmias = {
'Asystole': 'a',
'Bradycardia': 'b',
'Tachycardia': 't',
'Ventricular_Tachycardia': 'v',
'Ventricular_Flutter_Fib': 'f'
}
arrhythmia_type = fields['comments'][0]
return arrhythmias[arrhythmia_type] | 4772acc3612492a4f41acac0619435774f11cdff | 28,463 |
def chain_3(d3f_dg3, dg_dx, d2f_dg2, d2g_dx2, df_dg, d3g_dx3):
"""
Generic chaining function for third derivative
.. math::
\\frac{d^{3}(f . g)}{dx^{3}} = \\frac{d^{3}f}{dg^{3}}(\\frac{dg}{dx})^{3} + 3\\frac{d^{2}f}{dg^{2}}\\frac{dg}{dx}\\frac{d^{2}g}{dx^{2}} + \\frac{df}{dg}\\frac{d^{3}g}{dx^{3}}
"""
return d3f_dg3*(dg_dx**3) + 3*d2f_dg2*dg_dx*d2g_dx2 + df_dg*d3g_dx3 | 90c7563821a30fe0ff0b7e2431122d4754d52210 | 28,464 |
import warnings
def ditto(request):
"""
Deprecated.
"""
warnings.warn("The ditto context_processor is no longer used.", DeprecationWarning)
return {} | 7250488bf5d94aa14dec7ba64974642542149e59 | 28,469 |
def createProperMovieDictionary(raw_dict):
"""
Takes the dictionary provided by the request (full of strings)
and formats it where some variables need to have other types (e.g int, float)
also escapes all the single quotes characters in strings
:param raw_dict: the raw dictionary with the movie information provided by the api
:return proper_dict: a dictionary with the proper types to input in the database
containing id, title, year, length, rating and the cast
(a dictionary of actors in movies)
"""
try:
year = int(raw_dict['year'])
except ValueError:
year = 0
try:
rating = float(raw_dict['rating'])
except ValueError:
rating = 0.0
proper_dict = {
'id': raw_dict['id'],
'title': raw_dict['title'].replace(u'\xa0', u'').replace("'", "''"),
'year': year,
'length': raw_dict['length'],
'rating': rating,
'cast': raw_dict['cast']
}
for actor in proper_dict['cast']:
actor['actor'] = actor['actor'].replace("'", "''")
actor['character'] = actor['character'].replace("'", "''")
return proper_dict | ac30cbff86bfd9659c9363d31acacbd3c76b6f0f | 28,472 |
def get_phred_query(sample_id, gt_ll, genotype, prefix=" and ", invert=False):
"""Default is to test < where a low value phred-scale is high
confidence for that genotype
>>> get_phred_query(2, 22, "het")
' and gt_phred_ll_het[1] < 22'
>>> get_phred_query(2, 22, "het", prefix="")
'gt_phred_ll_het[1] < 22'
>>> get_phred_query(2, 22, "het", prefix="", invert=True)
'gt_phred_ll_het[1] > 22'
"""
assert genotype in ("het", "homref", "homalt")
if not gt_ll: return ""
# they passed in the subject:
if hasattr(sample_id, "sample_id"):
sample_id = sample_id.sample_id
sign = ["<", ">"][int(invert)]
s = "gt_phred_ll_{genotype}[{sample_id}] {sign} {gt_ll}"\
.format(sample_id=sample_id-1, genotype=genotype,
gt_ll=gt_ll, sign=sign)
return prefix + s | 3b913725bafec554c105173fb4ff720324aa8ae7 | 28,475 |
def _command_to_string(cmd):
"""Convert a list with command raw bytes to string."""
return ' '.join(cmd) | e8c39aa287f64099358e420b63b507f6f3f68c7a | 28,477 |
def get_racecar_camera_topics(racecar_name):
""" The camera topics where the racecar publishes the frames
Arguments:
racecar_name (str): The name of the racecar
"""
return [
"/{}/main_camera/zed/rgb/image_rect_color".format(racecar_name),
"/sub_camera/zed/rgb/image_rect_color"
] | 7d535d2e6f9e9d056dec8604dc856901b30b2c20 | 28,478 |
from pathlib import Path
def find_modules(x):
"""Get all python files given a path
Args:
x (string): file path
Returns:
(list): recursive list of python files including sub-directories
"""
return Path(x).rglob('*.py') | 1b8b84087c3de476c8e2b96b8f09001755ebabac | 28,488 |
def medium_file(file_path):
"""Open a medium file (headerless tsv, 2 columns (str, float))
Return a generator of (str, float) tuples
This function is used by argparse for type validation."""
def row_generator(file_path):
with open(file_path, "r") as fh:
for line in fh:
reaction_id, lower_bound, upper_bound = line.rstrip().split("\t")
yield (reaction_id, float(lower_bound), float(upper_bound))
return row_generator(file_path) | eba4c372a1c07feab28634d65dcbd148f9dfa995 | 28,489 |
def score(board):
"""
This function takes a nested list of numbers representing a Reversi
board and returns the score of player 1 and 2 out of that board.
:param board: nested list of integers that represent a Reversi board
:returns: a tuple (s1, s2) representing the points of player 1 and 2
:pre-condition: board must be a nested list of numbers (should be 8 * 8)
:raises: TypeError, if pre-condition is not true
"""
s1, s2 = 0, 0
for row in board:
s1 += row.count(1)
s2 += row.count(2)
return s1, s2 | e8545cd43924849aae39c355eecf23607311593d | 28,491 |
def rules_cidrs_and_security_groups(rules):
"""
Return a dict with keys "cidrs" and "sgids"
from a list of security group rules.
:param rules: list of security group rules
:type rules: list
:return: Dict with keys "cidrs" and "sgids"
:rtype: dict
"""
cidrs = set(
ip_range["CidrIp"]
for rule in rules
for ip_range in rule["IpRanges"]
)
sgids = set(
group_pair["GroupId"]
for rule in rules
for group_pair in rule["UserIdGroupPairs"]
)
return {"cidrs": cidrs, "sgids": sgids} | 7da621f59543ae929856c78c69d101b234c4540c | 28,493 |
def dimer_true(dataframe, col_num, dimer_list):
"""
Boolean masks to let us know which primers from original df
form dimers. If so they are dropped.
Args:
dataframe (pd.DataFrame): the primer dataframe
col_num (int): the column number to check for primer match
dimer_list (list): the list containing primer dimer info
Returns:
out_series (pd.Series): boolean masked series, True if primer is dimer, else False
"""
out_series = dataframe.iloc[:, col_num].isin([seq[1] or seq[2] for seq in dimer_list])
return out_series | 138bcbaf01ed93bfb195e89900b37ab682bd6dea | 28,496 |
def child_dir_name(parent, child):
"""return the child directory name truncated under the parent"""
if parent == '' or child == '': return child
plen = len(parent)
clen = len(child)
if child[0:plen] != parent: return child # not a proper child
# return everything after separator
if clen < plen + 2: return '.' # trivial as child
else: return child[plen+1:] # remove parent portion | 85b003ee346580dda2647a64b31a93f7ada25d25 | 28,497 |
from typing import Dict
from typing import Any
from typing import Union
def get_cluster_mode(
cycle_config: Dict[str, Any],
) -> Union[None, str]:
"""
Decode the cluster mode from the cycle configuration. Currently only a
`slurm`, `local`, or None mode are available.
Parameters
----------
cycle_config : Dict[str, Any]
The cluster mode is searched within this cycle configuration.
Returns
-------
mode : str or None
The specified cluster mode. If the mode is None, then no mode was found.
"""
try:
if cycle_config['CLUSTER']['slurm']:
mode = 'slurm'
else:
mode = 'local'
except KeyError:
mode = None
return mode | 6ac157e812dfbe3627d1f3bf363b774f083801f8 | 28,499 |
def _select_last_iteration_only(jobs):
"""
Looks through a list of jobs and removes duplicates (only keeps last iteration of a particular job)
"""
jobs_by_name = {}
for job in jobs:
if job.name in jobs_by_name:
jobs_by_name[job.name].append(job)
else:
jobs_by_name[job.name] = [job]
selected_jobs = []
for name, named_jobs in jobs_by_name.items():
named_jobs = sorted(named_jobs, key=lambda j: j.id, reverse=True)
selected_jobs.append(named_jobs[0])
return selected_jobs | cd00f51ec3be8349538daf7470552b735eda2902 | 28,501 |
def extract_hashtags(hashtags_string):
"""
Split the string of hashtags into a list of hashtags
:param hashtags_string: hashtags as a single string
:return: list of hashtags
"""
hashtags = hashtags_string.split()
return hashtags | 9ead711230f55b8a2ba3ab29a3c3c09ffb86184c | 28,507 |
def sampleFunction2(x2: int, y2: float) -> float:
"""
Multiply int and float sample.
:param x2: x value
:type x2: int
:param y2: y value
:type y2: float
:return: result
:return type: float
"""
return x2 * y2 | 554707befa81313f7ca084afbb39b5a75f44040e | 28,509 |
def midi2freq(midi_number):
"""
Given a MIDI pitch number, returns its frequency in Hz.
Source from lazy_midi.
"""
midi_a4 = 69 # MIDI Pitch number
freq_a4 = 440. # Hz
return freq_a4 * 2 ** ((midi_number - midi_a4) * (1. / 12.)) | 995453032f5280e5b8a28a2265ef2c4de8f83b8e | 28,510 |
import json
def format_str(str_value, is_json):
"""
Returns a formatted string with break lines; if is_json True, pretty format the output
:param str_value: plain text or json value
:param is_json: Boolean
:return: str
"""
str_value = json.dumps(str_value, indent=4, sort_keys=True) if is_json else str_value
return '\n {} \n'.format(str_value) | 3840a355b44404a0c0022f0297453023a2eb698a | 28,513 |
def default_empty(default):
"""Check an input against its falsy value or return a default."""
def get_value(test_value):
if test_value:
return test_value
else:
return default
return get_value | b3ff34d8fb5d46a62ad11a439dad7d03fb4425f2 | 28,515 |
def _find_error_code(e):
"""Gets the approriate error code for an exception e, see
http://tldp.org/LDP/abs/html/exitcodes.html for exit codes.
"""
if isinstance(e, PermissionError):
code = 126
elif isinstance(e, FileNotFoundError):
code = 127
else:
code = 1
return code | a9e14ec1cf01f0eba65b231aa7a40afaf4712535 | 28,516 |
def make_behaving(ary, dtype=None):
""" Make sure that `ary` is a "behaving" bohrium array of type `dtype`.
Requirements for a behaving array:
* Is a bohrium array
* Points to the first element in the underlying base array (no offset)
* Has the same total length as its base
Parameters
----------
ary : BhArray
The array to make behaving
dtype : boolean, optional
The return array is converted to `dtype` if not None
Returns
-------
A behaving BhArray that might be a copy of `ary`
Note
----
Use this function to make sure that operands given to `execute()` is "behaving" that is
the kernel can access the arrays without worrying about offset and stride.
"""
if ary.isbehaving():
ret = ary
else:
ret = ary.flatten(always_copy=True)
if dtype is not None:
ret = ret.astype(dtype)
return ret | e74c3c276ef2f5eb0ddb3d9b7870af0035cdaab4 | 28,521 |
from pathlib import Path
def file_exists(filename):
""" Returns true if file exists
:param filename: The file name to check
:type filename: str
:returns: True if file exists
:rtype: bool
"""
file_handle = Path(filename)
if file_handle.is_file():
return True
else:
return False | 5800f9b15aa869993e8bc0decea0ea1bf4a449e6 | 28,523 |
def center_y(display_height: int) -> int:
"""
Find the vertical center position of given screen/space/display
Parameters:
display_width (int) : The character height of the screen/space/display
Returns:
(int): Vertical character number
"""
return display_height // 2 | b59a325ef4fb84d306f22c7c5717b1d9a155ed45 | 28,527 |
def parse_syntax(line):
"""
>>> parse_syntax('syntax: glob')
'glob'
>>> parse_syntax('syntax: regexp')
'regexp'
>>> parse_syntax('syntax: none')
Traceback (most recent call last):
...
Exception: Unknown syntax "none"
"""
line = line.replace(':', ' ')
_, syntax = line.split()
if syntax in ['glob', 'regexp']:
return syntax
else:
raise Exception('Unknown syntax "%s"' % syntax) | 8f619b216ede8cc9bdd8198f6433add997c87768 | 28,528 |
def boundCreator(mus, sigmas, c=3):
"""
Creates interval around the mean
Parameters
----------
mus : array of shape [Num flights, time-steps, num of features]
the mean temporal values to be used.
sigmas : array of shape [Num flights, time-steps, num of features]
the temporal standard deviation values to be used.
c : TYPE, optional
DESCRIPTION. The default is 3.
Returns
-------
upper : array
upper bound.
lower : array
lower bound.
"""
upper = mus + c*sigmas
lower = mus - c*sigmas
return upper,lower | 5ec6af891a0c39fd6f51e961de13a0db946a20cc | 28,531 |
def coerce_to_bool(x: str) -> bool:
"""Convert string to bool value."""
if x.lower() in ('true', 'yes', 'on', '1', 'false', 'no', 'off', '0'):
return x.lower() in ('true', 'yes', 'on', '1')
raise ValueError() | d8da41c00ad94e75fd20f3c4a4aaaf8fb04cbb08 | 28,532 |
def get_ua_platform(user_agent):
"""Get platform (mobile, tablet, pc)."""
if user_agent.is_mobile:
return "mobile"
elif user_agent.is_tablet:
return "tablet"
elif user_agent.is_pc:
return "pc"
else:
return "unknown" | be735fa118fd09a25f3120dda8bdb1c45943b859 | 28,538 |
def create_deterministic_delayer(delay):
"""
Create a deterministic delayer that always returns the same delay value
Args:
delay (float): Delay value to return
Returns:
function: delayer
"""
assert delay >= 0, "Inputted delay must be non-negative!"
return lambda: delay | 8d25603dc273b631eef2e270753dbb6ae4c7d959 | 28,545 |
def check_bounds(position, size):
"""
Checks whether a coordinate is within the indices of a grid.
Parameters
----------
position: list
the coordinate to check for within the grid
size: int
the size of the grid to compare the coordinate values to
Return
----------
boolean:
True if the coordinate is within the grid, false if otherwise
"""
for elem in position:
if elem < 0 or elem >= size:
return False
return True | f93721e2b852df8e2e52d0e8fb7157f60bda7536 | 28,548 |
def field_validator(value, validators: set) -> bool:
"""
Execute a set of validator functions (the _is_x) against a value.
Return True if any of the validators are True.
"""
return any([True for validator in validators if validator(value)]) | d8331dac68e85b1725280af9df6b71f8f0c46465 | 28,549 |
def line_filter(regexp, lines):
"""
Filter each line of input by a regular expression.
If the regular expression is not matched, then the line is not output.
"""
output = []
for line in lines:
match = regexp.match(line)
if match:
output.append(line)
return output | 8b3ed6abde04a0278fa98d618117bb5ee686baf8 | 28,556 |
def get_nonblocking(queue):
""" Get without blocking from multiprocessing queue"""
try:
resp = queue.get(block=False)
except Exception as e:
resp = None
return resp | 8cb190f8652a8ea54b6f469cac4204b1706b4d6e | 28,558 |
def move(password, position_x, position_y):
"""Move letter from position_x to position_y.
Letter should be removed from password and inserted at position_y.
"""
to_move = password.pop(position_x)
password.insert(position_y, to_move)
return password | a63124adeb25aeec1e31469d808725f5654b3928 | 28,561 |
def predict_raw(model, periods):
"""Returns the raw output of a Prophet model.
Paramaters
----------
model : dict
A trained Prophet model created with init_fit.
periods : int
The number of periods to forecast.
cap : float
An upper limit for the case of logistic growth.
Returns
-------
prophet_output : DataFrame
The output of m.predict() method of the Prophet class.
"""
future = model['m'].make_future_dataframe(periods=periods)
future['cap'] = model['cap']
prophet_output = model['m'].predict(future)
return prophet_output | 709fbf4757b968d7b6cc882ccea1c6be222d418c | 28,564 |
def compss_wait_on(obj):
"""
Dummy compss_wait_on
:param obj: The object to wait on.
:return: The same object defined as parameter
"""
return obj | cb433878c460a507d98c1c3a8880626f804b201f | 28,565 |
def get_dict_dot(d: dict, key: str, default=None):
""" Gets an entry from a dictionary using dot notation key, eg: this.that.something """
try:
if isinstance(d, dict) and key:
split = key.split(".")
value = d.get(split[0], None)
if value is not None:
if len(split) == 1:
return value
return get_dict_dot(value, key[len(split[0]) + 1 :], default)
except KeyError:
pass
return default | 2e179f81ee7d05554150fad2fd8363d44c4b3a88 | 28,568 |
def edge_list_get_tail_index(edge_list, tail_index):
"""
Takes a list of edges and returns an edge if the tail_index matches the
given index, or None otherwise.
"""
for edge in edge_list :
if edge.tail_index == tail_index :
return edge
return None | 1d7f55afec3fb9da269d1c45dd111ce05cb10bd5 | 28,575 |
import math
def _fraction2str(num, decimals=2):
"""
Helper method to pretty print percentages.
Args:
num: A number in the range [0,1].
"""
if isinstance(num, str):
return num
mult = math.pow(10, decimals)
if num < 0.5/mult:
return "0"
ret = str(int(num*mult+.5)/float(mult))
if len(ret) < decimals+2:
ret += "0"
if ret[0] == "0":
return ret[1:]
return ret | 5b2483fb5c2fe3ec4c543c4d6e1186491bb348dc | 28,576 |
def all_lines_at_idx(mm, idx_list):
""" return a list of lines given a list of memory locations
follow up on all_lines_with_tag
e.g. all_lines_at_idx(mm, all_lines_with_tag(mm, 'Atom') )
reads '''
Atom 0 0 0 0
Atom 1 1 1 1
Atom 2 2 2 2
'''
Args:
mm (mmap.mmap): memory map to file
idx_list (list): a list of memory locations (int)
Return:
list: a list of strings, each being the line at idx
"""
lines = []
for idx in idx_list:
mm.seek(idx)
# row back to beginning of line
ibegin = mm.rfind('\n')
if ibegin == -1:
ibegin = 0
mm.seek(ibegin)
mm.readline()
# read desired line
line = mm.readline()
lines.append(line)
return lines | 2ca06a01773bdf1ab0f94cf5a60405c5f85ca772 | 28,577 |
def _get_attrs_items(obj):
"""Returns a list of (name, value) pairs from an attrs instance.
The list will be sorted by name.
Args:
obj: an object.
Returns:
A list of (attr_name, attr_value) pairs.
"""
return [(attr.name, getattr(obj, attr.name))
for attr in obj.__class__.__attrs_attrs__] | 6e1ac65ea2b9a136581dfdddf8e789fc8fa9da90 | 28,580 |
def safe_col_name(args_pair):
"""Ensure that the column name is safe for SQL (unique value, no spaces, no trailing punctuation).
Typically called with `df.columns = [*map(safe_col_name, enumerate(df.columns.to_list()))]`
Args:
args_pair: tuple of arguments from map function in `(idx, col)`
Returns:
string: safely formatted string for SQLite
"""
idx, col = args_pair
col = col.strip().replace(' ', '_').replace('.', '_').replace(',', '_')
return str(idx) if col == '' else col | 51256b15ee2fcc55cbc77dbdc2aa03408a6f1e26 | 28,585 |
def format_sec_fixed(sec):
"""Format seconds in a fixed format."""
return '%d:%02d:%02d' % (int(sec / 3600), int(sec % 3600 / 60), int(round(sec % 60))) | d6fb346e3a83b451e65277a6301f49b0f91e5efb | 28,591 |
def temp_column_name(*dataframes):
"""Gets a temp column name that isn't included in columns of any dataframes
Parameters
----------
dataframes : list of Pandas.DataFrame
The DataFrames to create a temporary column name for
Returns
-------
str
String column name that looks like '_temp_x' for some integer x
"""
i = 0
while True:
temp_column = "_temp_{}".format(i)
unique = True
for dataframe in dataframes:
if temp_column in dataframe.columns:
i += 1
unique = False
if unique:
return temp_column | 307d6d1778ac550c1a0ba468e2fd81206d9c0cb9 | 28,597 |
def get_func_and_script_url_from_initiator(initiator):
"""Remove line number and column number from the initiator."""
if initiator:
return initiator.rsplit(":", 2)[0].split(" line")[0]
else:
return "" | 9029050bdc567e02dceca9a3967f289fc21324ab | 28,600 |
def format_array(arr, precision=4):
""" Create a string representation of a numpy array with less precision
than the default.
Parameters
----------
arr : array
Array to be converted to a string
precision : int
Number of significant digit to display each value.
Returns
-------
str
Nice string representation of the array.
"""
if arr is None:
return ""
formatting_str = "{0:." + str(precision) + "g}"
str_values = [formatting_str.format(float(val)) for val in arr]
content = ", ".join(str_values)
return "[" + content + "]" | fb97da91c88a769aa95454666f734a6bc68ef4f5 | 28,601 |
def black_percentage(rgb):
"""
rgb: rgb tuple of a pixel
returns: pixel percentage of black
"""
if isinstance(rgb, int):
return 100 - rgb
return 100 - (int((((rgb[0] + rgb[1] + rgb[2])/3)*100)/255)) | 916f2c61e0af68509ba6fa45fe187c5144ba5337 | 28,608 |
def _align(value, alignment):
"""Find the smallest multiple of `alignment` that is at least as large as `value`."""
return ((value - 1) // alignment + 1) * alignment | 9bbe11caf6221b73778caf9f2583ed3829d22942 | 28,609 |
def to_full_year(two_digit_year, threshold=80):
"""Converts a year given by two digits to a full
year number.
Input params:
threshold: up to which ending the year should be thought
of as 1900s.
"""
ending = int(two_digit_year)
return (1900+ending) if ending > threshold else (2000+ending) | 346654e1106795fa3d64d0d05ede16074c8a181e | 28,615 |
def identityfunc(arg):
"""Single argument identity function.
>>> identityfunc('arg')
'arg'
"""
return arg | 6987908c3229623fcd5201978aa33f2362caa54d | 28,619 |
def is_mixed_case(string: str) -> bool:
"""Check whether a string contains uppercase and lowercase characters."""
return not string.islower() and not string.isupper() | 230a452a2690fda4a90f59e8aaede8f8233c78a7 | 28,621 |
def get_timestamp(integer):
"""
Parses integer timestamp from csv into correctly formatted string for xml
:param integer: input integer formatted hhmm
:return: output string formatted to hh:mm:ss
"""
string = str(integer)
if len(string) == 1:
return '00:0{}:00'.format(string)
elif len(string) == 2:
return '00:{}:00'.format(string)
else:
minutes = string[-2:]
hours = string[:-2]
if len(hours) == 1:
hours = '0' + hours
return '{}:{}:00'.format(hours, minutes) | 81b4fa1e9237ee37abfe067b76b2e8656b409473 | 28,623 |
from bs4 import BeautifulSoup
import re
def _parse_table(html, id, include_headers=True):
"""
Parse HTML table with given ID.
Keyword arguments:
html -- the HTML to parse
id -- the ID of the table to parse
include_headers -- whether to include the headers in the output (default True)
Returns: a list of rows
"""
# Parse out data table
soup = BeautifulSoup(html, "html.parser")
table_list = soup.find_all(id=id) # output is list-type
# We expect the first table to be there with our data
assert len(table_list) > 0
table = table_list[0]
output_rows = []
column_tags = ["td"]
if include_headers:
column_tags.append("th")
# Loop through the table and grab the data
for table_row in table.find_all("tr"):
columns = table_row.find_all(column_tags)
output_row = []
for column in columns:
# Collapse newlines
partial = re.sub(r"\n", " ", column.text)
# Standardize whitespace
clean_text = re.sub(r"\s+", " ", partial).strip()
output_row.append(clean_text)
# Skip any empty rows
if len(output_row) == 0 or output_row == [""]:
continue
output_rows.append(output_row)
return output_rows | e4317f657645f9de4a9055b1b4dc23ca7b75c56c | 28,635 |
def using_append_to_construct_a_list(n):
""" Constructs [1, 2, 3, ... n] by using the append list method. """
new = []
for k in range(1, n + 1):
new.append(k)
return new | 529946ad34ec3c4b86a2decabffc052fd74e7cbe | 28,636 |
def is_single_bool(val):
"""Check whether a variable is a ``bool``.
Parameters
----------
val
The variable to check.
Returns
-------
bool
``True`` if the variable is a ``bool``. Otherwise ``False``.
"""
# pylint: disable=unidiomatic-typecheck
return type(val) == type(True) | 24a18577e08d43c36bdb89a196eb1406608528a5 | 28,637 |
import configparser
def config_parser(config_file):
"""
Configuration file parsing.
Returns dictionary with configuration parameters:
'one_auth_file' - Opennebula sessions credential file path,
'key_file' - AES key file path,
'workers_quantity' - ZMQ workers quantity,
'server_ip' - IP address for ZMQ routing server binding,
'server_port' - Port number for ZMQ routing server binding,
'pidfile' - PID file path,
'vm_user' - VM user name,
'password_size' - Size password for VM users,
'password_complexity' - Complexity password for VM users(bool),
'loggerconf_file' - Logger configuration file path.
"""
config = configparser.ConfigParser()
config.read(config_file)
cinfig_dict = {'one_auth_file': config.get('auth_file','one_auth_file'),
'key_file': config.get('auth_file','key_file'),
'workers_quantity': int(config.get('zmq_workers_quantity','workers_quantity')),
'server_ip': config.get('ip_address_port','server_ip'),
'server_port': config.get('ip_address_port','server_port'),
'pidfile': config.get('pid_file','pidfile'),
'vm_user': config.get('vm_user_name','vm_user'),
'password_size': int(config.get('password_vm_users','password_size')),
'password_complexity': config.getboolean('password_vm_users','password_complexity'),
'loggerconf_file': config.get('logger_config_file','loggerconf_file')
}
return cinfig_dict | 8847d8344caeed24b6673dc34712430b8892d18b | 28,641 |
def always_true(*args, **kwargs):
"""Always returns True, no matter the arguments."""
return True | 94d8e3845fecf0ea2d991bbd09a03c5fd14c4ca8 | 28,642 |
def average_error(state_edges_predicted, state_edges_actual):
"""
Given predicted state edges and actual state edges, returns
the average error of the prediction.
"""
total=0
for key in state_edges_predicted.keys():
#print(key)
total+=abs(state_edges_predicted[key]-state_edges_actual[key])
#print(state_edges_predicted[state])
return total/len(state_edges_predicted) #Returns weighted average error | 40d132682e49b556e8cc0fc71015947202b9cf08 | 28,643 |
import re
def remove_bracketed_text(s):
"""
Removes text in brackets from string :s: .
"""
s = re.sub(r'\([^\()]+?\)', '', s)
s = re.sub(r'\[[^\[]]+?\]', '', s)
s = re.sub(r'\[[^\[]]+?\]', '', s)
return s.strip() | 13290df1b16eae86dca8f9cc00be93660b25b741 | 28,644 |
def expand_dims_as(x, y):
"""Expand the shape of ``x`` with extra singular dimensions.
The result is broadcastable to the shape of ``y``.
Args:
x (Tensor): source tensor
y (Tensor): target tensor. Only its shape will be used.
Returns:
``x`` with extra singular dimensions.
"""
assert len(x.shape) <= len(y.shape)
assert x.shape == y.shape[:len(x.shape)]
k = len(y.shape) - len(x.shape)
if k == 0:
return x
else:
return x.reshape(*x.shape, *([1] * k)) | b914d4cc47916dc98ff535ff964b80d943f88d87 | 28,649 |
import re
def get_branches(aliases):
"""Get unique branch names from an alias dictionary."""
ignore = ['pow', 'log10', 'sqrt', 'max']
branches = []
for k, v in aliases.items():
tokens = re.sub('[\(\)\+\*\/\,\=\<\>\&\!\-\|]', ' ', v).split()
for t in tokens:
if bool(re.search(r'^\d', t)) or len(t) <= 3:
continue
if bool(re.search(r'[a-zA-Z]', t)) and t not in ignore:
branches += [t]
return list(set(branches)) | 25cd6ed33275229d1124b6dfbec503840104dd26 | 28,650 |
def get_waze_navigation_link(xy_tuple):
"""
Create a navigation link from a tuple containing an x and y tuple for Waze.
:param xy_tuple: Tuple of (x,y) coordinates.
:return: String url opening directly in waze for navigation.
"""
return 'waze://?ll={lat},{lon}&navigate=yes'.format(lat=xy_tuple[1], lon=xy_tuple[0]) | cd6e08453b84856e55922ee9ba7b042bc55d5901 | 28,667 |
import yaml
def load_yaml(yml_path):
"""Load parameter from yaml configuration file.
Args:
yml_path (string): Path to yaml configuration file
Returns:
A dictionary with parameters for cluster.
"""
with open(yml_path, 'r') as stream:
data_loaded = yaml.safe_load(stream)
return data_loaded | b123f1084c28dc6624d56036bac8d20278d5acea | 28,669 |
def format_list(str_list):
""" convert a list of strings to a string with square brackets "[\"something\", \"something\"]"
which is suitable for subprocess.run
"""
list_repr = ['\"{}\"'.format(item).replace("\"", "\\\"") for item in str_list]
joint_str = ",".join(list_repr)
return joint_str | e4e9ff96445413d7cfc4251ecbc1dca9a64339bb | 28,670 |
def format_percentile(q):
"""Format percentile as a string."""
if 0 <= q <= 1.0:
q = 100.0 * q
return '{:3.1f}%'.format(q) | 7451f8bb53b47a72e20c4cb94402922d497dff43 | 28,671 |
def find_in_list(list_one, list_two):
"""
Function to find an element from list_one that is in list_two
and returns it. Returns None if nothing is found.
Function taken from A3
Inputs:
list, list
Outputs:
string or None
"""
for element in list_one:
if element in list_two:
return element
return None | f6fbd1ce96ee2e9cb4fed130dd2aa35a19fa68e1 | 28,674 |
def ternary_expr(printer, ast):
"""Prints a ternary expression."""
cond_str = printer.ast_to_string(ast["left"]) # printer.ast_to_string(ast["cond"])
then_expr_str = printer.ast_to_string(ast["middle"]) # printer.ast_to_string(ast["thenExpr"])
else_expr_str = printer.ast_to_string(ast["right"]) # printer.ast_to_string(ast["elseExpr"])
return f'{cond_str} ? {then_expr_str} : {else_expr_str}' | f88fc65b684bff7ad61e0bc64d17b65bbe7735e5 | 28,675 |
def defaultify(value,default):
"""Return `default` if `value` is `None`. Otherwise, return `value`"""
if None == value:
return default
else:
return value | f13b30e0ccc06d09d5be6fe9f82d8d99495f5b32 | 28,677 |
def my_contains(elem, lst):
"""Returns True if and only if the element is in the list"""
return elem in lst | d859f1a26d7f87deef9e11b8d3f3e8648ecc141d | 28,678 |
def repr_author(Author):
"""
Get string representation an Author namedtuple in the format:
von Last, jr., First.
Parameters
----------
Author: An Author() namedtuple
An author name.
Examples
--------
>>> from bibmanager.utils import repr_author, parse_name
>>> names = ['Last', 'First Last', 'First von Last', 'von Last, First',
>>> 'von Last, sr., First']
>>> for name in names:
>>> print(f"{name!r:22}: {repr_author(parse_name(name))}")
'Last' : Last
'First Last' : Last, First
'First von Last' : von Last, First
'von Last, First' : von Last, First
'von Last, sr., First': von Last, sr., First
"""
name = Author.last
if Author.von != "":
name = " ".join([Author.von, name])
if Author.jr != "":
name += f", {Author.jr}"
if Author.first != "":
name += f", {Author.first}"
return name | f15bba99a1c6466a6b3e0fbd30ac32109f6447b5 | 28,679 |
def getFirstPlist(textString):
"""Gets the next plist from a set of concatenated text-style plists.
Returns a tuple - the first plist (if any) and the remaining
string"""
plistStart = textString.find('<?xml version')
if plistStart == -1:
# not found
return ("", textString)
plistEnd = textString.find('</plist>', plistStart + 13)
if plistEnd == -1:
# not found
return ("", textString)
# adjust end value
plistEnd = plistEnd + 8
return (textString[plistStart:plistEnd], textString[plistEnd:]) | 19de59d42661488ad254a7afa8aded4f3f17bf1a | 28,682 |
def _ibp_add(lhs, rhs):
"""Propagation of IBP bounds through an addition.
Args:
lhs: Lefthand side of addition.
rhs: Righthand side of addition.
Returns:
out_bounds: IntervalBound.
"""
return lhs + rhs | b63b538cc1d412932bec86285077f786e5a9cd4e | 28,687 |
def train_model_and_get_test_results(model, x_train, y_train, x_test, y_test, **kwargs):
"""
Train the model on given training data and evaluate its performance on test set
Args:
model: various ML models
x_train: Training data
y_train: Training targets
x_test: Testing data
y_test: Testing targets
kwargs: dictionary that maps each keyword to the value that we pass alongside it
Returns:
Accuracy and predictions made by the specified model
"""
# Instantiate the classification model
if "sample_weight" in kwargs:
model.fit(x_train, y_train.ravel(),
sample_weight=kwargs["sample_weight"])
else:
model.fit(x_train, y_train)
predicted = model.predict(x_test)
# compute the accuracy of the model
accuracy = model.score(x_test, y_test.ravel())
return accuracy, predicted | f3f8de07874796045a1268fd415d822c004a87aa | 28,691 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.