content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def format_address(msisdn):
"""
Format a normalized MSISDN as a URI that ParlayX will accept.
"""
if not msisdn.startswith('+'):
raise ValueError('Only international format addresses are supported')
return 'tel:' + msisdn[1:] | f5a5cc9f8bcf77f1185003cfd523d7d6f1212bd8 | 5,320 |
def get_nag_statistics(nag):
"""Return a report containing all NAG statistics"""
report = """Constants: {0}
Inputs: {1}
NANDs: {2}
Outputs: {3}
Min. I/O distance: {4}
Max. I/O distance: {5}""".format(
nag.constant_number,
nag.input_number,
nag.nand_number,
nag... | 44d3f32bc0b05d8b1d81c3b32dc140af4fd20aa0 | 5,321 |
def mean(image):
"""The mean pixel value"""
return image.mean() | 176dd8d483008fa1071f0f0be20c4b53ad0e2a5f | 5,322 |
import math
def ellipse_properties(x, y, w):
"""
Given a the (x,y) locations of the foci of the ellipse and the width return
the center of the ellipse, width, height, and angle relative to the x-axis.
:param double x: x-coordinates of the foci
:param double y: y-coordinates of the foci
:param... | 95864eac0feb9c34546eefed5ca158f330f88e3d | 5,324 |
import os
def dir_exists(dir):
"""Test if dir exists"""
return os.path.exists(dir) and os.path.isdir(dir) | f787457f3a03c3e9c605a1753de0ab7c648e4a2c | 5,325 |
import requests
def fetch_data(full_query):
"""
Fetches data from the given url
"""
url = requests.get(full_query)
# Parse the json dat so it can be used as a normal dict
raw_data = url.json()
# It's a good practice to always close opened urls!
url.close()
return raw_data | 576b2548c1b89827e7586542e4d7e3f0cc89051d | 5,326 |
def _get_precision_type(network_el):
"""Given a network element from a VRP-REP instance, returns its precision type:
floor, ceil, or decimals. If no such precision type is present, returns None.
"""
if 'decimals' in network_el:
return 'decimals'
if 'floor' in network_el:
return 'flo... | b3b451a26ec50ce5f2424ea7a3652123ae96321d | 5,327 |
import hashlib
def md5_str(content):
"""
计算字符串的MD5值
:param content:输入字符串
:return:
"""
m = hashlib.md5(content.encode('utf-8'))
return m.hexdigest() | affe4742c2b44a60ef6dafa52d7a330594a70ed9 | 5,328 |
def update_params(old_param, new_param, errors="raise"):
""" Update 'old_param' with 'new_param'
"""
# Copy old param
updated_param = old_param.copy()
for k,v in new_param.items():
if k in old_param:
updated_param[k] = v
else:
if errors=="raise":
... | 95de4e8e1278b07d2bd8ccc61af4e2dc43f87ca2 | 5,329 |
def collections(id=None):
"""
Return Collections
Parameters
----------
id : STR, optional
The default is None, which returns all know collections.
You can provide a ICOS URI or DOI to filter for a specifict collection
Returns
-------
query : STR
A query, which can... | 0cd1704d2ac43f34d6e83a3f9e9ead39db390c2e | 5,331 |
def sanitize_bvals(bvals, target_bvals=[0, 1000, 2000, 3000]):
"""
Remove small variation in bvals and bring them to their closest target bvals
"""
for idx, bval in enumerate(bvals):
bvals[idx] = min(target_bvals, key=lambda x: abs(x - bval))
return bvals | a92b170748b5dbc64c4e62703a3c63103675b702 | 5,332 |
from typing import Dict
import requests
import logging
def get_estate_urls(last_estate_id: str) -> Dict:
"""Fetch urls of newly added estates
Args:
last_estate_id (str): estate_id of the most recent estate added (from last scrape)
Returns:
Dict: result dict in format {estate_id_1: {estat... | d93299002204edc9d26b3c77e2dff1f56f4b93d8 | 5,333 |
def bib_to_string(bibliography):
""" dict of dict -> str
Take a biblatex bibliography represented as a dictionary
and return a string representing it as a biblatex file.
"""
string = ''
for entry in bibliography:
string += '\n@{}{{{},\n'.format(
bibliography[entry]['type'],
... | c8fc4247210f74309929fdf9b210cd6f1e2ece3f | 5,335 |
def check_prio_and_sorted(node):
"""Check that a treap object fulfills the priority requirement and that its sorted correctly."""
if node is None:
return None # The root is empty
else:
if (node.left_node is None) and (node.right_node is None): # No children to compare with
... | 64100fd4ba9af699ab362d16f5bbf216effa2da5 | 5,336 |
import pickle
async def wait_for_msg(channel):
"""Wait for a message on the specified Redis channel"""
while await channel.wait_message():
pickled_msg = await channel.get()
return pickle.loads(pickled_msg) | dca398cb3adeb778458dd6be173a53cdd204bcb9 | 5,337 |
def get_tile_prefix(rasterFileName):
"""
Returns 'rump' of raster file name, to be used as prefix for tile files.
rasterFileName is <date>_<time>_<sat. ID>_<product type>_<asset type>.tif(f)
where asset type can be any of ["AnalyticMS","AnalyticMS_SR","Visual","newVisual"]
The rump is defined as <da... | 15b517e5ba83b2cfb5f3b0014d800402c9683815 | 5,339 |
def preprocess(df):
"""Preprocess the DataFrame, replacing identifiable information"""
# Usernames: <USER_TOKEN>
username_pattern = r"(?<=\B|^)@\w{1,18}"
df.text = df.text.str.replace(username_pattern, "<USERNAME>")
# URLs: <URL_TOKEN>
url_pattern = (
r"https?://(?:[a-zA-Z]|[0-9]|[$-_@.&... | d592d9e56af9ec17dcebede31d458dfdc001c220 | 5,340 |
def layout(mat,widths=None,heights=None):
"""layout"""
ncol=len(mat[0])
nrow=len(mat)
arr=[]
list(map(lambda m: arr.extend(m),mat))
rscript='layout(matrix(c(%s), %d, %d, byrow = TRUE),' %(str(arr)[1:-1],nrow,ncol)
if widths:
rscript+='widths=c(%s),' %(str(widths)[1:-1])
if h... | 813fb351b4e09d4762255ecbbe6f9ee7e050efd0 | 5,341 |
import re
def MatchNameComponent(key, name_list, case_sensitive=True):
"""Try to match a name against a list.
This function will try to match a name like test1 against a list
like C{['test1.example.com', 'test2.example.com', ...]}. Against
this list, I{'test1'} as well as I{'test1.example'} will match, but
... | ad522feba9cabb3407e3b8e1e8c221f3e9800e16 | 5,342 |
def _non_overlapping_chunks(seq, size):
"""
This function takes an input sequence and produces chunks of chosen size
that strictly do not overlap. This is a much faster implemetnation than
_overlapping_chunks and should be preferred if running on very large seq.
Parameters
----------
seq : ... | 15b5d2b4a7d8df9785ccc02b5369a3f162704e9e | 5,344 |
def neighbour(x,y,image):
"""Return 8-neighbours of image point P1(x,y), in a clockwise order"""
img = image.copy()
x_1, y_1, x1, y1 = x-1, y-1, x+1, y+1;
return [img[x_1][y], img[x_1][y1], img[x][y1], img[x1][y1], img[x1][y], img[x1][y_1], img[x][y_1], img[x_1][y_1]] | 8e645f7634d089a0e65335f6ea3363d4ed66235b | 5,348 |
def gravity_effect(position, other_position):
"""Return effect other_position has on position."""
if position == other_position:
return 0
elif position > other_position:
return -1
return 1 | 25130c253cb888057e9b52817cac9cf3778a4c69 | 5,350 |
import fnmatch
def ignore_paths(path_list, ignore_patterns, process=str):
"""
Go through the `path_list` and ignore any paths that match the patterns in `ignore_patterns`
:param path_list: List of file/directory paths.
:param ignore_patterns: List of nukeignore patterns.
:param process: Function t... | 63196e54eb4505cbe12ebf77d2a42fede68c1d0b | 5,351 |
def reachable(Adj, s, t):
"""
Adj is adjacency list rep of graph
Return True if edges in Adj have directed path from s to t.
Note that this routine is one of the most-used and most time-consuming
of this whole procedure, which is why it is passed an adjacency list
rep rather than a list of ver... | dc0ea0c6d2314fa1c40c3f3aa257a1c77892141f | 5,353 |
def concatenate_unique(la, lb):
"""Add all the elements of `lb` to `la` if they are not there already.
The elements added to `la` maintain ordering with respect to `lb`.
Args:
la: List of Python objects.
lb: List of Python objects.
Returns:
`la`: The list `la` with missing elements from `lb`.
""... | 307fde291233727c59e2211afc3e0eed7c8ea092 | 5,354 |
import os
import inspect
def _find_path(image):
"""Searches for the given filename and returns the full path.
Searches in the directory of the script that called (for example)
detect_match, then in the directory of that script's caller, etc.
"""
if os.path.isabs(image):
return image
... | 402a4ee96229db6a94ce77bfca73749509fbd714 | 5,357 |
def create_feature_indices(header):
"""
Function to return unique features along with respective column indices
for each feature in the final numpy array
Args:
header (list[str]): description of each feature's possible values
Returns:
feature_indices (dict): unique feature names as... | a29d8c4c8f3a31ad516216756b7eba7eb4110946 | 5,364 |
def lower(word):
"""Sets all characters in a word to their lowercase value"""
return word.lower() | f96b1470b3ab1e31cd1875ad9cbf9ed017aa0158 | 5,365 |
def _in_dir(obj, attr):
"""Simpler hasattr() function without side effects."""
return attr in dir(obj) | f95e265d278e3014e8e683a872cd3b70ef6133c9 | 5,366 |
import os
def file_exists(work_dir, path):
"""
goal: check if file exists
type: (string, string) -> bool
"""
prev_dir = os.getcwd()
try:
os.chdir(work_dir)
if os.path.exists(path) and os.path.isfile(path):
return True
else:
return False
... | 7bb2e3a4d245908054014cf9210769bf89a7b693 | 5,367 |
def handler_good():
"""Return True for a good event handler."""
return True | 302ea021276cb9be2d5e98c2a09776f4ee53cc97 | 5,369 |
import argparse
def optional_list():
"""Return an OptionalList action."""
class OptionalList(argparse.Action):
"""An action that supports an optional list of arguments.
This is a list equivalent to supplying a const value with nargs='?'. Which itself only allows a single optional
val... | 8e6f84e75c75893862dfbbb93d2d9c75ce229c68 | 5,371 |
def validate_comma_separated_list(argument):
"""Convert argument to a list."""
if not isinstance(argument, list):
argument = [argument]
last = argument.pop()
items = [i.strip(u' \t\n') for i in last.split(u',') if i.strip(u' \t\n')]
argument.extend(items)
return argument | bdf68db95d6070be4ffb5a74a646f5c730c726b4 | 5,372 |
import argparse
def setup():
"""
Parse command line arguments
Returns parsed arguments
"""
parser = argparse.ArgumentParser(description='Search Reddit Thing')
parser.add_argument(
'subreddit',
help="Enter the name of the subreddit to search.")
parser.add_argument(
... | 49748a64532fcedf3fcc96c8a56de224e6daac43 | 5,373 |
def get_holdout_set(train, target_column):
"""This is a sample callable to demonstrate how the Environment's `holdout_dataset` is evaluated. If you do provide a
callable, it should expect two inputs: the train_dataset (pandas.DataFrame), and the target_column name (string). You should
return two DataFrames:... | ba2ea647c287f11f37bc4557ef389ed288b0bb02 | 5,374 |
def getprop(obj, string):
"""
Par exemple 'position.x'
:param string:
:return:
"""
tab = string.split('.')
curr_val = obj
for str in tab:
curr_val = getattr(curr_val, str)
return curr_val | c82f869395129a8b69d1a89cde97ce36fe5affd9 | 5,376 |
import argparse
def get_options():
"""Parses options."""
parser = argparse.ArgumentParser(
description="Dynamic inventory for Decapod.")
group = parser.add_mutually_exclusive_group(required=True)
group.add_argument(
"-l", "--list",
help="List all inventory.",
action="... | c4efc1978dfb735e6e08060400d3752357e924a0 | 5,377 |
import warnings
def tracks(track):
"""
Check if the submitted RGTs are valid
Arguments
---------
track: ICESat-2 reference ground track (RGT)
"""
#-- string length of RGTs in granules
track_length = 4
#-- total number of ICESat-2 satellite RGTs is 1387
all_tracks = [str(tr + 1... | 306b213fc040dbaabf515dfeff7efe45db656549 | 5,378 |
import random
def random_sampling(predictions, number):
"""
This method will return us the next values that we need to labelise
for our training with a random prioritisation
Args:
predictions : A matrix of probabilities with all the predictions
for t... | 22a1b13122bdf5c1b95d2b039458d27a62544f6d | 5,379 |
def get_element_parts(
original_list: list, splitter_character: str, split_index: int
) -> list:
"""
Split all elements of the passed list on the passed splitter_character.
Return the element at the passed index.
Parameters
----------
original_list : list
List of strings to be spli... | 8c663fd64ebb1b2c53a64a17f7d63e842b457652 | 5,380 |
def create_inference_metadata(object_type, boundary_image, boundary_world):
"""
Create a metadata of **each** detected object
:param object_type: Type of the object | int
:param boundary: Boundary of the object in GCS - shape: 2(x, y) x points | np.array
:return: JSON object of each detected object ... | b13f1ad4abc22f3eaca2c81c56ab9cb0eae80aa9 | 5,381 |
from typing import Tuple
from typing import Dict
def parse_line_protocol_stat_key(key: str) -> Tuple[str, Dict[str, str]]:
"""Parseline protocolish key to stat prefix and key.
Examples:
SNMP_WORKER;hostname=abc.com,worker=snmp-mti
will become:
("SNMP_WORKER", {"hostname": "abc.com", "... | a6806f7dd67fb2a4734caca94bff3d974923f4b2 | 5,382 |
def add_without_punctuation(line, punctuation):
"""Returns the line cleaned of punctuation.
Param:
line (unicode)
Returns:
False if there are not any punctuation
Corrected line
"""
cleaned_line = line.translate(str.maketrans('', '', punctuation))
if line != cleaned_line... | 20dafde21efad966f8ea1be0da928594e2ee5cc4 | 5,384 |
from typing import Callable
def there_is_zero(
f: Callable[[float], float], head: float, tail: float, subint: int
) -> bool:
"""
Checks if the function has a zero in [head, tail], looking at subint
subintervals
"""
length = tail - head
step = length / subint
t = head
a = f(head)
... | dd80c55d4be5fed2e3100672ea63862014b0f8cc | 5,385 |
def acknowledgements():
"""Provides acknowlegements for the JRO instruments and experiments
Returns
-------
ackn : str
String providing acknowledgement text for studies using JRO data
"""
ackn = ' '.join(["The Jicamarca Radio Observatory is a facility of the",
"Ins... | 013727319d43baaec57461995af8a683b5f02278 | 5,386 |
def list_vmachines(vdc):
"""
Returns:
list: vmachines info
"""
return vdc.to_dict()["vmachines"] | b3ce74c5b6f7d6d9f109a884f0c050ffae840e70 | 5,387 |
import os
def abspaths(paths):
"""
an wrapper function of os.path.abspath to process mutliple paths.
"""
return [os.path.abspath(p) for p in paths] | ae3591a11ee152a0ca2eb342644749c669c8d78e | 5,389 |
def zero_at(pos, size=8):
"""
Create a size-bit int which only has one '0' bit at specific position.
:param int pos: Position of '0' bit.
:param int size: Length of value by bit.
:rtype: int
"""
assert 0 <= pos < size
return 2**size - 2**(size - pos - 1) - 1 | 7ebdcc1ac9db4ad934108f67a751b336b4f18011 | 5,391 |
import torch
def get_bert_model():
"""
Load uncased HuggingFace model.
"""
bert_model = torch.hub.load('huggingface/pytorch-transformers',
'model',
'bert-base-uncased')
return bert_model | 51b49255fe4b1291d538251c8c199bd570fb1a31 | 5,392 |
def md5s_loaded(func):
"""Decorator which automatically calls load_md5s."""
def newfunc(self, *args, **kwargs):
if self.md5_map == None:
self.load_md5s()
return func(self, *args, **kwargs)
return newfunc | 9eba943b939c484280b6dca79cf79fc04337f0ab | 5,393 |
def get_categories(categories_file):
""" Group categories by image
"""
# map each category id to its name
id_to_category = {}
for category in categories_file['categories']:
id_to_category[category['id']] = category['name']
image_categories = {}
for category in categories_file['annot... | 10377ea688c2e33195f137cc9470cadd6eb2b9e7 | 5,396 |
def unpack_uid(uid):
"""
Convert packed PFile UID to standard DICOM UID.
Parameters
----------
uid : str
packed PFile UID as a string
Returns
-------
uid : str
unpacked PFile UID as string
"""
return ''.join([str(i-1) if i < 11 else '.' for pair in [(ord(c) >> 4... | cb131f3df386c40382cf70ddee5125f901de5fa8 | 5,398 |
import os
def read_links(ls):
"""Returns list of objects with source and target"""
return list(map(lambda el: {"source": el, "target": os.readlink(el)}, ls)) | 9768106043c706ed37b90de9289325f0574096db | 5,399 |
from typing import Counter
def generate_samples(n_samples, func, *args, **kwargs):
"""Call a function a bunch of times and count the results.
Args:
n_samples: Number of time to call the function.
func: The function results are counted from.
*args
**args: The arguments to pass ... | 625c2bf6713420e26704d2c2842504343be09434 | 5,400 |
def capitalize_1(string):
"""
Capitalizes a string using a combination of the upper and lower methods.
:author: jrg94
:param string: any string
:return: a string with the first character capitalized and the rest lowercased
"""
return string[0].upper() + string[1:].lower() | 9ad830a6d38e19b195cd3dff9a38fe89c49bd5c8 | 5,401 |
def get_url_and_token(string):
""" extract url and token from API format """
try:
[token, api] = string.split(":", 1)
[_, _, addr, _, port, proto] = api.split("/", 5)
url = f"{proto}://{addr}:{port}/rpc/v0"
except Exception:
raise ValueError(f"malformed API string : {string}"... | f3abd327c9de2d098100e539f701bf2fff1742f5 | 5,403 |
import json
def handle_error(ex, hed_info=None, title=None, return_as_str=True):
"""Handles an error by returning a dictionary or simple string
Parameters
----------
ex: Exception
The exception raised.
hed_info: dict
A dictionary of information.
title: str
A title to b... | 4b7bc24c9b4fd83d39f4447e29e383d1769e6b0f | 5,405 |
def getLineagesFromChangeo(changeodb, print_summary):
"""subsets the changeo_db output by bracer by only those cells which are within lineages (non singletons)"""
df = changeodb
_df = df[df.CLONE != "None"] # get rid of unassigned cells (no BCR reconstructed)
_df = (df.CLONE.value_counts() > 1) #find cl... | 1a497b084118ce0993cf6509889831cab78d2a36 | 5,407 |
def command(cmd, label, env={}):
"""Create a Benchpress command, which define a single benchmark execution
This is a help function to create a Benchpress command, which is a Python `dict` of the parameters given.
Parameters
----------
cmd : str
The bash string that makes up the command
... | 487e7b8518ae202756177fc103561ea03ded7470 | 5,409 |
import re
def get_text(string):
"""
normalizing white space and stripping HTML markups.
"""
text = re.sub('\s+',' ',string)
text = re.sub(r'<.*?>',' ',text)
return text | 5ef04effe14ee9b0eee90de791b3e3f3be6c15e3 | 5,410 |
import struct
def decode_ia(ia: int) -> str:
""" Decode an individual address into human readable string representation
>>> decode_ia(4606)
'1.1.254'
See also: http://www.openremote.org/display/knowledge/KNX+Individual+Address
"""
if not isinstance(ia, int):
ia = struct.unpack('>H', ... | 6f107f47110a59ca16fe8cf1a7ef8f061bf117c7 | 5,411 |
from pathlib import Path
def _validate_magics_flake8_warnings(actual: str, test_nb_path: Path) -> bool:
"""Validate the results of notebooks with warnings."""
expected = (
f"{str(test_nb_path)}:cell_1:1:1: F401 'random.randint' imported but unused\n"
f"{str(test_nb_path)}:cell_1:2:1: F401 'IPy... | 4baa419ad4e95bf8cc794298e70211c0fa148e5b | 5,412 |
def _split_uri(uri):
"""
Get slash-delimited parts of a ConceptNet URI.
Args:
uri (str)
Returns:
List[str]
"""
uri = uri.lstrip("/")
if not uri:
return []
return uri.split("/") | 91b48fff83041fe225a851a9e3016e3722bd9771 | 5,413 |
import time
def current_date(pattern="%Y-%m-%d %H:%M:%S"):
"""
获取当前日期
:param: pattern:指定获取日期的格式
:return: 字符串 "20200615 14:57:23"
"""
return time.strftime(pattern, time.localtime(time.time())) | 9a554e91e0842fe52f822f4403366695c92a609b | 5,414 |
def isValidPasswordPartTwo(firstIndex: int, secondIndex: int, targetLetter: str, password: str) -> int:
"""
Takes a password and returns 1 if valid, 0 otherwise. Second part of the puzzle
"""
bool1: bool = password[firstIndex - 1] == targetLetter
bool2: bool = password[secondIndex - 1] == targetLetter
... | 81f85c3848909b5037f13ed641ec3a1b77dff3b1 | 5,415 |
def pre_process(cpp_line):
"""预处理"""
# 预处理
cpp_line = cpp_line.replace('\t', ' ')
cpp_line = cpp_line.replace('\n', '')
cpp_line = cpp_line.replace(';', '')
return cpp_line | 4c0db8ae834286106472aba425c45a8eeded3183 | 5,416 |
import os
def _safe_clear_dirflow(path):
"""
Safely check that the path contains ONLY folders of png files,
if any other structure, will simply ERROR out.
Parameters
----------
path: str
string to the path to the folders of data images to be used
"""
print("Clearing {}...".fo... | af92454143fee21c497e1dca2c268c9cb915dbd2 | 5,418 |
from functools import cmp_to_key
def order(list, cmp=None, key=None, reverse=False):
""" Returns a list of indices in the order as when the given list is sorted.
For example: ["c","a","b"] => [1, 2, 0]
This means that in the sorted list, "a" (index 1) comes first and "c" (index 0) last.
"""
... | 7bcc6f44f02be4fb329b211b5caadf057d6d9b9a | 5,419 |
def numentries(arrays):
"""
Counts the number of entries in a typical arrays from a ROOT file,
by looking at the length of the first key
"""
return arrays[list(arrays.keys())[0]].shape[0] | e3c9f2e055f068f12039741ff9bb1091716263d5 | 5,420 |
import re
def split_range_str(range_str):
"""
Split the range string to bytes, start and end.
:param range_str: Range request string
:return: tuple of (bytes, start, end) or None
"""
re_matcher = re.fullmatch(r'([a-z]+)=(\d+)?-(\d+)?', range_str)
if not re_matcher or len(re_matcher.groups(... | a6817017d708abf774277bf8d9360b63af78860d | 5,428 |
import sys
import os
import asyncio
def runner(fun, *args):
"""
Generic asyncio.run() equivalent for Python >= 3.5
"""
if sys.version_info >= (3, 7):
if os.name == "nt" and sys.version_info < (3, 8):
asyncio.set_event_loop_policy(asyncio.WindowsProactorEventLoopPolicy())
re... | 1893c46c40e1d42fc4927b0fb3d240c209405318 | 5,430 |
def read_custom_enzyme(infile):
"""
Create a list of custom RNase cleaving sites from an input file
"""
outlist = []
with open(infile.rstrip(), 'r') as handle:
for line in handle:
if '*' in line and line[0] != '#':
outlist.append(line.rstrip())
return outlist | 144c6de30a04faa2c9381bfd36bc79fef1b78443 | 5,431 |
def min_equals_max(min, max):
"""
Return True if minimium value equals maximum value
Return False if not, or if maximum or minimum value is not defined
"""
return min is not None and max is not None and min == max | 1078e9ed6905ab8b31b7725cc678b2021fc3bc62 | 5,433 |
def infer_app_url(headers: dict, register_path: str) -> str:
"""
ref: github.com/aws/chalice#485
:return: The Chalice Application URL
"""
host: str = headers["host"]
scheme: str = headers.get("x-forwarded-proto", "http")
app_url: str = f"{scheme}://{host}{register_path}"
return app_url | f3c0d1a19c8a78a0fd2a8663e2cb86427ff8f61b | 5,435 |
import random
def mutationShuffle(individual, indpb):
"""
Inputs : Individual route
Probability of mutation betwen (0,1)
Outputs : Mutated individual according to the probability
"""
size = len(individual)
for i in range(size):
if random.random() < indpb:
swap_... | dea67e03b2905f1169e1c37b3456364fb55c7174 | 5,436 |
import json
import os
import subprocess
def adjust(*args, stdin=None):
"""run 'adjust' with the current directory set to the dir where this module is found.
Return a tuple (exitcode, parsed_stdout), the second item will be None if stdout was empty. An exception is raised if the process cannot be run or parsin... | 262d757520ff97a666df62b0700391acc03a42ba | 5,437 |
import os
def read_STAR_Logfinalout(Log_final_out):
"""
Log_final_out -- Folder or Log.final.out produced by STAR
"""
if os.path.isdir(Log_final_out):
Log_final_out = Log_final_out.rstrip('/')
dirfiles = os.listdir(Log_final_out)
if 'Log.final.out' in dirfiles:
... | 9599a71624f5b65092cf67fd28c9dd3d7f44e259 | 5,438 |
import socket
def validate_args(args):
""" Checks if the arguments are valid or not. """
# Is the number of sockets positive ?
if not args.number > 0:
print("[ERROR] Number of sockets should be positive. Received %d" % args.number)
exit(1)
# Is a valid IP address or valid name ?
tr... | 37a77f59ae78e3692e08742fab07f35cf6801e54 | 5,439 |
from typing import Any
def ifnone(x: Any, y: Any):
"""
returns x if x is none else returns y
"""
val = x if x is not None else y
return val | f2c7cf335ff919d610a23fac40d6af61e6a1e595 | 5,441 |
import re
def _rst_links(contents: str) -> str:
"""Convert reStructuredText hyperlinks"""
links = {}
def register_link(m: re.Match[str]) -> str:
refid = re.sub(r"\s", "", m.group("id").lower())
links[refid] = m.group("url")
return ""
def replace_link(m: re.Match[str]) -> str:... | c7c937cdc04f9d5c3814538978062962e6407d65 | 5,442 |
def fibonacci(n: int) -> int:
"""
Calculate the nth Fibonacci number using naive recursive implementation.
:param n: the index into the sequence
:return: The nth Fibonacci number is returned.
"""
if n == 1 or n == 2:
return 1
else:
return fibonacci(n - 1) + fibonacci(n - 2) | 08de1ff55f7cada6a940b4fb0ffe6ba44972b42d | 5,443 |
import subprocess
def get_current_SSID():
"""Helper function to find the WiFi SSID name.
Returns:
str: Wifi SSID name("" on Exception).
"""
try:
p = subprocess.Popen(["iwgetid", "-r"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, err = p.communicate()
return ou... | f88021770d292cf21d7de7221efc4c0aef0099b5 | 5,444 |
def compute_reference_gradient_siemens(duration_ms, bandwidth, csa=0):
"""
Description: computes the reference gradient for exporting RF files
to SIEMENS format, assuming the gradient level curGrad is desired.
Theory: the reference gradient is defined as that gradient for which
a 1 cm slice is... | 65cf8bd8e805e37e5966170daeae90594e45595e | 5,445 |
def read_config(lines):
"""Read the config into a dictionary"""
d = {}
current_section = None
for i, line in enumerate(lines):
line = line.strip()
if len(line) == 0 or line.startswith(";"):
continue
if line.startswith("[") and line.endswith("]"):
current_s... | 613ed9291ab6546700b991fc9a5fc301c55ae497 | 5,446 |
import logging
def _filter_all_warnings(record) -> bool:
"""Filter out credential error messages."""
if record.name.startswith("azure.identity") and record.levelno == logging.WARNING:
message = record.getMessage()
if ".get_token" in message:
return not message
return True | f16490ef39f9e3a63c791bddcba1c31176b925b7 | 5,447 |
def _parse_slice_str(slice_str):
"""Parses the given string as a multidimensional array slice and returns a
list of slice objects and integer indices."""
is_valid = False
if len(slice_str) > 2:
is_valid = slice_str[0] == "[" and slice_str[-1] == "]"
sliced_inds = []
if is_valid:
slice_str_list = ... | 6eb7a6b5d1dc2ee57e878b37be70e1e75d7d6ecc | 5,449 |
def AverageZComparison(x, y):
""" Take the average of second and third element in an array and compare
which is bigger. To be used in conjunction with the sort function. """
xsum = x[1]+x[2]
ysum = y[1]+y[2]
if xsum < ysum:
return -1
if xsum > ysum:
return 1
return 0 | 84c9e7b92df4b3e4914c769293f71790def5e4dd | 5,450 |
from pathlib import Path
def parse_taxid_names(file_path):
"""
Parse the names.dmp file and output a dictionary mapping names to taxids
(multiple different keys) and taxids to scientific names.
Parameters
----------
file_path : str
The path to the names.dmp file.
Returns
----... | 1d136f73a56ac8d3c02fd53c6e7928a39440e27a | 5,451 |
def convert_dict_id_values_to_strings(dict_list):
"""This function ensures that the ``id`` keys in a list of dictionaries use string values.
:param dict_list: List (or tuple) of dictionaries (or a single dictionary) containing API object data
:type dict_list: list, tuple, dict, None
:returns: A new dic... | 7d1348910e5802c928b94bc74d71f3ce35770215 | 5,453 |
import os
def FileExtensionMatch(filePath, supportedFileTypeList):
"""
Check whether the file extension matches any of the supported file types.
Parameters
----------
filePath : string
File path
supportedFileTypeList : list
List of supported file extensions
"""
return (os.path.splite... | bdab68917ead387269f52a51465f500a581967f6 | 5,454 |
from typing import List
def count_pairs(array: List[int], difference: int) -> int:
"""
Given an array of integers, count the number of unique pairs of integers that have a given difference.
These pairs are stored in a set in order to remove duplicates.
Time complexity: O(n^2).
:param array: is th... | e027e8885f4c4531da9b7dab7de8e84a7004c913 | 5,457 |
from json import dumps
def GetJson(data):
"""
将对象转换为JSON
@data 被转换的对象(dict/list/str/int...)
"""
if data == bytes: data = data.decode('utf-8')
return dumps(data) | 372b501f5ada7254efab10447dcbdc91c8799408 | 5,458 |
def binary_tail(n: int) -> int:
""" The last 1 digit and the following 0s of a binary representation, as a number """
return ((n ^ (n - 1)) + 1) >> 1 | 63460cef7b39b7e7ee2ec880810ff71d82be01e9 | 5,459 |
from datetime import datetime
def time_left(expire_date):
"""Return remaining days before feature expiration or 0 if expired."""
today_dt = datetime.today()
expire_dt = datetime.strptime(expire_date, "%d-%b-%Y")
# Calculate remaining days before expiration
days_left_td = expire_dt - today_dt
... | 652acd27b0d4fa9b21321df4ff8ce6ce15b97ed6 | 5,460 |
def video_id(video_id_or_url):
"""
Returns video id from given video id or url
Parameters:
-----------
video_id_or_url: str - either a video id or url
Returns:
--------
the video id
"""
if 'watch?v=' in video_id_or_url:
return video_id_or_url.split('watch?v=')[1]
e... | 9f680ac621e1f5c6314a6a3e97093d786fa7ea33 | 5,461 |
import typing
def cast_to_str(some_value: typing.Any, from_type: typing.Any) -> typing.Any:
"""Just helper for creating suitable test assets."""
if from_type == bytes:
return some_value.decode()
return str(some_value) | 9157873a74d0d02b919d047710c1d4ccee4121a6 | 5,462 |
def sum_errors(dic):
"""Helper function to sum up number of failed jobs per host.
Assumes that dic is in the form
:param dict dic: {"error_code1":count1, "error_code2":count2, etc.}
:return int: Sum of all values in dic
"""
return sum(value for key, value in dic.iteritems()) | 0d2bc9df58e5bf9639a331d64061de4c0a5aa4ed | 5,463 |
def alternate(*iterables):
"""
[a[0], b[0], ... , a[1], b[1], ..., a[n], b[n] ...]
>>> alternate([1,4], [2,5], [3,6])
[1, 2, 3, 4, 5, 6]
"""
items = []
for tup in zip(*iterables):
items.extend([item for item in tup])
return items | ed3b0c8a32de8d88fc24b8bb08012a0900b37823 | 5,464 |
def tex_initial_states(data):
"""Initial states are texed."""
initial_state = []
initial_state = [''.join(["\lstick{\ket{", str(data['init'][row]),"}}"]) for row in range(len(data['init']))]
return data, initial_state | cd1758b594ee854cfb7854ec742dc177a43b54b7 | 5,465 |
def FanOut(num):
"""Layer construction function for a fan-out layer."""
init_fun = lambda rng, input_shape: ([input_shape] * num, ())
apply_fun = lambda params, inputs, **kwargs: [inputs] * num
return init_fun, apply_fun | 7e6d07319be600dabf650a4b87f661bf20832455 | 5,466 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.