content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def calculate_pct_poi_msgs(series):
"""calculates the percentage of a potential POI's
total messages that are to or from a POI
Args:
series (pandas.core.series.Series): data series associated with a single POI
Returns:
[pandas.core.series.Series]: data series with the added POI mess... | 857e23204e6eab5db36f23d583613dd19bc7ffd4 | 703,543 |
import struct
def _read_int(f, b):
"""
Read an integer of a specified number of bytes from the filestream f
"""
if b == 1:
return struct.unpack('<B', f.read(b))[0]
elif b == 2:
return struct.unpack('<H', f.read(b))[0]
elif b == 4:
return struct.unpack('<I', f.read(b))[0... | 36bcc2ccd4edd61fd9c6a438c3a069e699b7b17a | 703,544 |
def compare_equality(col_1, col_2):
"""
This function compare the equality of two columns
and output an accuracy percentage
"""
return float(col_1.eq(col_2.values).mean()) | adf6e6bb26988c7ee0211669881b2cd8331838da | 703,546 |
def saveForwardState(old_s_tree, new_s_tree, s):
"""Saving the s_current as well as all its successors in the old_s_tree into the new_s_tree.
Parameters
----------
old_s_tree : dict
The old tree.
new_s_tree : dict
The new tree.
s_current : :py:class:`ast_toolbox.mcts.AdaptiveStr... | 1cf8aeac314c2f224a76d9c91c3bf1a8d54fd9df | 703,547 |
import json
import os
import logging
def load_and_save_params(default_params, exp_dir, ignore_existing=False):
"""Update default_params with params.json from exp_dir and overwrite params.json with updated version."""
default_params = json.loads(json.dumps(default_params))
param_path = os.path.join(exp_dir... | 4a0e9c1e24ec914abe1540ad9dd7d655b96c0e39 | 703,549 |
def generate_input_with_unknown_words(file_path):
"""Reads the file with the given file_path.
Replaces every first occurance of a (word, tag) pair with ("<UNK>", tag).
Creates dictionary of all words encountered in following format:
{(word, tag) : count}"""
seen_tuples = []
label_matches = dict()
file_lines = []... | 21479c1953dc1779a28bc49a38de55c383513fbf | 703,550 |
def terminal_values(rets):
"""
Computes the terminal values from a set of returns supplied as a T x N DataFrame
Return a Series of length N indexed by the columns of rets
"""
return (rets+1).prod() | bea1f2a668deac3e915f7531ab68aea207e57d91 | 703,551 |
def getColumnNames(hdu):
"""Get names of columns in HDU."""
return [d.name for d in hdu.get_coldefs()] | 9ac8fefe6fcf0e7aed10699f19b849c14b022d47 | 703,553 |
import torch
def embedding_to_probability(embedding: torch.Tensor, centroids: torch.Tensor, sigma: torch.Tensor) -> torch.Tensor:
"""
Vectorizing this is slower than the loop!!!
# / (e_ix - C_kx)^2 (e_iy - C_ky)^2 (e_iz - C_kz)^2 \
# prob_k(e_i) = exp |-1 * ----... | 133b7b81bb00db2110b6ec9709ab89924dee2dc4 | 703,554 |
def get_url(server_name, listen_port):
"""
Generating URL to get the information
from namenode/namenode
:param server_name:
:param listen_port:
:return:
"""
if listen_port < 0:
print ("Invalid Port")
exit()
if not server_name:
print("Pass valid Host... | 097e347a75eb581ae97734552fa6f9e7d3b11ce6 | 703,555 |
def euler97():
"""Solution for problem 97."""
mod = 10 ** 10
return (1 + 28433 * pow(2, 7830457, mod)) % mod | ab04cf67431a434f147f3615bee5a211b58ccbde | 703,556 |
def latex_code(size):
"""
Get LaTeX code for size
"""
return "\\" + size + " " | 03478f8f62bb2b70ab5ca6ece66d4cdca3595dd6 | 703,557 |
def has_cycle_visit(visiting, parents, adjacency_list, s):
"""
Check if there is a cycle in a graph starting
at the node s
"""
visiting[s] = True
for u in adjacency_list[s]:
if u in visiting:
return True
if u in parents:
continue
parents[u] = s
if has_cycle_visit(visiting, paren... | 5f87f6f39d88cbae93e7e461590002ca6a94aa20 | 703,558 |
def remove_trailing_whitespace(line):
"""Removes trailing whitespace, but preserves the newline if present.
"""
if line.endswith("\n"):
return "{}\n".format(remove_trailing_whitespace(line[:-1]))
return line.rstrip() | 2c5f7b3a35152b89cda6645911569c9d2815f47e | 703,559 |
def process_settings(pelicanobj):
"""Sets user specified Katex settings"""
katex_settings = {}
katex_settings['auto_insert'] = True
katex_settings['process_summary'] = True
return katex_settings | 9799d9ea6bf17fabd1640c4e69ca3b1da5406829 | 703,560 |
import networkx
def make_cross(length=20, width=2) -> networkx.Graph:
"""Builds graph which looks like a cross.
Result graph has (2*length-width)*width vertices.
For example, this is a cross of width 3:
...
+++
+++
...+++++++++++...
...+++++++++++...
...+++++... | f0be683fd8971ea8b3cc0b40977a939c117e9906 | 703,561 |
def print_table(input_dict, title='', header=('Key', 'Value'), style=('', '-')):
"""Print the dict in a table form"""
assert input_dict.__class__ is dict, "Only accept class='dict'"
if input_dict is None:
return None
max_string = 110
key_list = list(input_dict.keys())
val_list = list(ma... | 47844b6526723fbf63bc347ed1487442fc497904 | 703,562 |
def must_be_known(in_limit, out_limit):
"""
Logical combinatino of limits enforcing a known state
The logic determines that we know that the device is fully inserted or
removed, alerting the MPS if the device is stuck in an unknown state or
broken
Parameters
----------
in_limit : ``boo... | 241b66b359643d069aa4066965879bb6ac76f2ae | 703,564 |
def scale(x):
"""Scales values to [-1, 1].
**Parameters**
:x: array-like, shape = arbitrary; unscaled data
**Returns**
:x_scaled: array-like, shape = x.shape; scaled data
"""
minimum = x.min()
return 2.0 * (x - minimum) / (x.max() - minimum) - 1.0 | e5c40a4a840a1fa178a2902378a51bfefc83b368 | 703,565 |
def group_data_by_columns(datasets, columns):
"""
:param datasets: [CxNxSxF]
:param columns: F
:return: CxNxFxS
"""
new_dataset = []
for i in range(len(datasets)):
datalist = []
for row in range(len(datasets[i][0][0])):
row_data = []
for column_idx in ... | 8a73c959501f422c26fe358c05ddc6a574123009 | 703,566 |
def GetStaticPipelineOptions(options_list):
"""
Takes the dictionary loaded from the yaml configuration file and returns it
in a form consistent with the others in GenerateAllPipelineOptions: a list of
(pipeline_option_name, pipeline_option_value) tuples.
The options in the options_list are a dict:
Key i... | d49effbdeb687ec62a2e2296330f66521023944c | 703,567 |
def _field_object_metadata(field_object):
"""Return mapping of field metadata key to value.
Args:
field_object (arcpy.Field): ArcPy field object.
Returns:
dict.
"""
meta = {"object": field_object}
key_attribute_name = {
"alias_name": "aliasName",
"base_name": "b... | 1e653737f1dee41c7ce786735368e55f4908b116 | 703,569 |
def mean_of_cluster(list_of_points):
"""Calculates the center of the list of points
"""
number_of_points = float(len(list_of_points))
vector_total = [float(0), float(0)]
for point in list_of_points:
for index, component in enumerate(point):
vector_total[index] += component
re... | b94b5ea40fb08253bcade35282692bbb58b85e98 | 703,570 |
def range_overlap(a_min, a_max, b_min, b_max):
"""
Neither range is completely greater than the other
"""
return (a_min <= b_max) and (b_min <= a_max) | c05d8b0799f62300760ad69704a5091c3830ad26 | 703,571 |
import json
def read_json(json_file_path: str) -> dict:
"""Takes a JSON file and returns a dictionary"""
with open(json_file_path, "r") as fp:
data = json.load(fp)
return data | 07cb6c606de83b2b51ddcbf64f7eb45d6907f973 | 703,572 |
import os
def _get_user_guide_directory():
"""Returns absolute path to docs/ directory"""
docsdir = os.path.join("docs", "user_guide")
return os.path.abspath(docsdir) | 147294fe005f7d6756aeb4c3579bddf795668087 | 703,573 |
import uuid
def unique_variable_name():
"""Creates a unique variable name. Useful when attempting to introduce
a new token to see if it can fix specific cases of SyntaxError."""
name = uuid.uuid4()
return "_%s" % name.hex | d4b54a8ab76fa8bddd6fe62a735f1dd886e9e62a | 703,574 |
def cleaner_unicode(string):
"""
Objective :
This method is used to clean the special characters from the report string and
place ascii characters in place of them
"""
if string is not None:
return string.encode('ascii', errors='backslashreplace')
else:
return string | f4e2c4b9fa7f4a644e409a5d429531a34bc1c6c2 | 703,575 |
import subprocess
import sys
def subprocess_call(args, cwd, capture_output=False, **kwargs):
"""Calls a subprocess, possibly capturing output."""
try:
if capture_output:
return subprocess.check_output(args, cwd=cwd, **kwargs)
else:
return subprocess.check_call(args, cwd=cwd, **kwargs)
except... | 956837dae6e7b74f1e51cd87e4c920bfe08eb2d0 | 703,576 |
def enthalpy_Shomate(T, hCP):
"""
enthalpy_Shomate(T, hCP)
NIST vapor, liquid, and solid phases
heat capacity correlation
H - H_ref (kJ/mol) = A*t + 1/2*B*t^2 + 1/3*C*t^3 +
1/4*D*t^4 - E*1/t + F - H
t (K) = T/1000.0
H_ref is enthalpy in kJ/mol at 298.15 K... | 05e3f3a35a87f767a44e2e1f4e35e768e12662f7 | 703,577 |
def get_acres(grid, coordinates):
"""Get acres from coordinates on grid."""
acres = []
for row, column in coordinates:
if 0 <= row < len(grid) and 0 <= column < len(grid[0]):
acres.append(grid[row][column])
return acres | e4ba6aabe07d8859481aefaba4d4559f1ec25e96 | 703,578 |
def highest_mag(slide):
"""Returns the highest magnification for the slide
"""
return int(slide.properties['aperio.AppMag']) | d42361c979a5addf0ebf4c7081a284c9bc0477ec | 703,579 |
import re
def enumerate_destination_file_name(destination_file_name):
"""
Append a * to the end of the provided destination file name.
Only used when query output is too big and Google returns an error
requesting multiple file names.
"""
if re.search(r'\.', destination_file_name):
dest... | 6b398597db26a175e305446ac39c363a5077ba96 | 703,581 |
def demistoVersion():
"""Retrieves server version and build number
Returns:
dict: Objects contains server version and build number
"""
return {
'version': '5.5.0',
'buildNumber': '12345'
} | 39ef34f88f44ecfad9d30a80bcdb74ad1833c3ae | 703,582 |
import os
def create_work_name(name):
""" Remove ".nzb" and ".par(2)" """
strip_ext = ['.nzb', '.par', '.par2']
name = name.strip()
if name.find('://') < 0:
name_base, ext = os.path.splitext(name)
# In case it was one of these, there might be more
while ext.lower() in strip_ext... | 5e5405505a7c342ebb372ea53ad8330919b0979a | 703,583 |
def bias_act(x, b=None, dim=1, gain=None, clamp=None):
"""Slow reference implementation of `bias_act()`
"""
# spec = activation_funcs[act]
# alpha = float(alpha if alpha is not None else 0)
gain = float(gain if gain is not None else 1)
clamp = float(clamp if clamp is not None else -1)
# Add... | 3e98d5941d29c78ecd5c46c9ec960f14cedc36e9 | 703,584 |
def combine_envs(*envs):
"""Combine zero or more dictionaries containing environment variables.
Environment variables later from dictionaries later in the list take
priority over those earlier in the list. For variables ending with
``PATH``, we prepend (and add a colon) rather than overwriting.
If... | feb6e00b9c0b1262220339feac6c5ac2ae6b6b17 | 703,585 |
import torch
def generate_square_subsequent_mask(sz):
"""
Generate attention mask using triu (triangle) attention
"""
mask = (torch.triu(torch.ones(sz, sz)) == 1).transpose(0, 1)
mask = (
mask.float()
.masked_fill(mask == 0, float("-inf"))
.masked_fill(mask == 1, float(0.0)... | 5631e89a275eee13c4b01a7b856421f6b45c2588 | 703,586 |
def len_column(table):
"""
Add length column containing the length of the original entry in the seq column.
Insert a number column with numbered entries for each row.
"""
for pos, i in enumerate(table):
i.insert(0, pos)
i.append(len(i[1]))
return table | 5a9215bc2feade70873de6adccd2b4c4b6acfed9 | 703,587 |
def read_maze(file_name):
"""
Reads a maze stored in a text file and returns a 2d list containing the maze representation.
"""
try:
with open(file_name) as fh:
maze = [[char for char in line.strip("\n")] for line in fh]
num_cols_top_row = len(maze[0])
for row ... | 373e121a9dc827307fc6b56350f8b19247115651 | 703,588 |
def sns_certificate(*args):
""" Mock requests to retrieve the SNS signing certificate """
with open('tests/files/certificate.pem') as cert_file:
cert = cert_file.read()
return cert | 6d1198c7ea3c29be28dbecf6affe5c31ab51267a | 703,589 |
def translate_delta(mat, dx, dy):
"""
Return matrix with elements translated by dx and dy, filling the would-be
empty spaces with 0. I feel this method may not be the most efficient.
"""
rows, cols = len(mat), len(mat[0])
# Filter out simple deltas
if (dx == 0 and dy == 0):
return m... | 38492c874bc7bbd59787f4b2d94c2ea0150e69f8 | 703,590 |
def u2(vector):
"""
This function calculates the utility for agent 2.
:param vector: The reward vector.
:return: The utility for agent 2.
"""
utility = vector[0] * vector[1]
return utility | 93b9210db00ee9a3ddca4cd9b447a7348f63a659 | 703,591 |
def counting_sort_integers(values, max_val=None, min_val=None, inplace=False):
"""
Sorts an array of integers using counting_sort.
Let n = len(values), k = max_val+1
"""
if len(values) == 0:
return values if inplace else []
#Runs in O(n) time if max_val is None or min_val is None
if... | d53b00b8753d8adc1782e5941b4b6dcce7c80ca3 | 703,592 |
def xfun(p,B,pv0,f):
"""
Steady state solution for x without CRISPR
"""
return f/(B*p-p/pv0) | 874d7d5a1d0d485aafa6f7298e1d214ca86ea90e | 703,593 |
def pattern_matching(pattern, genome):
"""Find all occurrences of a pattern in a string.
Args:
pattern (str): pattern string to search in the genome string.
genome (str): search space for pattern.
Returns:
List, list of int, i.e. all starting positions in genome where pattern appea... | 86ae704586fbac937e044f41a8831f2669c4e7dc | 703,594 |
import glob
def findLblWithoutImg(pathI, pathII):
"""
:param pathI: a glob path. example: "D:/大块煤数据/大块煤第三次标注数据/images/*.jpg"
:param pathII: a glob path. example: "D:/大块煤数据/大块煤第三次标注数据/labels/*.txt"
:return: num of image which not has label
"""
num = 0
pathI = glob.glob(pathI)
pathII = g... | 30edbff244acb0014b54cf3c85d86a47d779d226 | 703,595 |
import math
def lcf_float(val1, val2, tolerance):
"""Finds lowest common floating point factor between two floating point numbers"""
i = 1.0
while True:
test = float(val1) / i
check = float(val2) / test
floor_check = math.floor(check)
compare = floor_check * test
if... | b4bef1a63984440f43a1b0aa9bf9805cb4bfd466 | 703,596 |
def check_num_row(data):
"""
@param df: dataframe
@return: return 1 if checking condition is true
"""
return data.shape[0] > 10 | 0761c4d31bc3a14132d6c1547d03149bd10013c5 | 703,597 |
def _convert_text_to_logs_format(text: str) -> str:
"""Convert text into format that is suitable for logs.
Arguments:
text: text that should be formatted.
Returns:
Shape for logging in loguru.
"""
max_log_text_length = 50
start_text_index = 15
end_text_index = 5
return... | 4f7ff95a5cd74bdccd41559f58292cc9b1003ba2 | 703,598 |
import random
def generate_random_slug(length=40, prefix=None):
"""
This function is used, for example, to create Coupon code mechanically
when a customer pays for the subscriptions of an organization which
does not yet exist in the database.
"""
if prefix:
length = length - len(prefix... | add5e68d0ed6d3831993410afc5ec7900eb212c4 | 703,599 |
def digits_to_num(L, reverse=False):
"""Returns a number from a list of digits, given by the lowest power of 10 to the highest, or
the other way around if `reverse` is True"""
digits = reversed(L) if reverse else L
n = 0
for i, d in enumerate(digits):
n += d * (10 ** i)
return n | 1648073d46411fd430afea4f40f7fa9f4567793c | 703,600 |
import sys
import os
def executable(name):
"""Return the full path to an executable"""
suffix = ""
folder = "bin"
if sys.platform == "win32":
suffix = ".exe"
folder = os.path.join(folder, "Release")
return os.path.join("..", folder, name + suffix) | 8fbc4aa30e5ad3aeb126f7c5adbbdd62e68091c2 | 703,601 |
def clean_zeros(a, b, M):
""" Remove all components with zeros weights in a and b
"""
M2 = M[a > 0, :][:, b > 0].copy() # copy force c style matrix (froemd)
a2 = a[a > 0]
b2 = b[b > 0]
return a2, b2, M2 | 3e2def6e88a7ac5a67b9849a9dcd2f5f5156fb00 | 703,602 |
import re
def get_cheque_code(cheque: str):
"""Get code"""
if (
re.search(r'BTC_CHANGE_BOT\?start=', cheque)
or not re.search(r'BTC_CHANGE_BOT\?start=', cheque)
and re.search(r'Chatex_bot\?start=', cheque)
):
return re.findall(r'c_\S+', cheque)[0]
elif re.se... | 97d0b3cadfb6010b48ed6fb148083060c50720ff | 703,603 |
def parse_problems(lines):
""" Given a list of lines, parses them and returns a list of problems. """
return [len(p) for p in lines] | 83747e57bddf24484633e38ce27c51c7c8fce971 | 703,605 |
import urllib3
import certifi
def load_content(site, host, links):
"""Tests a site."""
# Security: Verified HTTPS with SSL/TLS
http = urllib3.PoolManager(
cert_reqs='CERT_REQUIRED', # Force certificate check.
ca_certs=certifi.where(), # Path to the Certifi bundle.
)
start_page_sea... | 5a599579133297c2e6ab3231b466f1b6184d22cc | 703,606 |
def get_types_dict():
"""
:return: type name read in as string to type method mapping
"""
return {"str": str, "float": float, "int": int} | 7a386fa63cba73e35672b15c31bc8b2c59361f24 | 703,607 |
def create_class_hierarchy_dict(cls):
"""Returns the dictionary with all members of the class ``cls`` and its superclasses."""
dict_extension_order = cls.__mro__[-2::-1] # Reversed __mro__ without the 'object' class
attrs_dict = {}
for base_class in dict_extension_order:
attrs_dict.update(vars(... | 0378fb3243a48964fcec42fddb38c0664a338ee4 | 703,608 |
from datetime import datetime
def month_to_date(month):
"""
Convert month to date format.
Keyword arguments:
month -- the month to convert to date format
"""
month = datetime.strptime(month, '%Y-%m')
date = month.strftime('%Y-%m-%d') # eg 2018-02-01
date = datetime.strptime(date, '... | e417eefa63430e422a53bd194fbb1e0d5e453c7b | 703,609 |
def encode(string):
"""Encode some critical characters to html entities."""
return string.replace('&', '&') \
.replace('<', '<') \
.replace('>', '>') \
.replace(' ', ' ') \
.replace('\n', ... | faea4b2f2e032b5e05e2c99bc56a1cf35e60b85d | 703,610 |
def rem(x, a):
"""
x: a non-negative integer argument
a: a positive integer argument
returns: integer, the remainder when x is divided by a.
"""
if x == a:
return 0
elif x < a:
return x
else:
return rem(x-a, a) | 22b421c090970810f9aa4d55ff5a700e1301c0b8 | 703,611 |
import platform
import subprocess
import re
import os
def get_env_prefix():
"""
Automatically identify os_type information which use for
install path of bash_completion.d
"""
TARGET_BIN_PATH = '/usr/local/bin/'
os_type = platform.system()
cygwin = r'CYGWIN|cygwin'
if os_type == "Linux... | fd290446484ae0f0392aaf4c34dc2feef0aa3553 | 703,612 |
import subprocess
def check_output(args):
"""
Delegates to subprocess.check_output() if it is available, otherwise
provides a reasonable facsimile.
"""
if 'check_output' in dir(subprocess):
out = subprocess.check_output(args)
else:
proc = subprocess.Popen(args, stdout=subproces... | bbe456c8b3d2e8f1acd0f32478828ce44af7842f | 703,613 |
def demo7(response):
"""在每次请求后运行"""
# eg:修改响应头
print(response)
print('=========== after func run =============')
# response.headers['Content-Type'] = 'application/json;charset=utf-8;'
return response | 86991057bb48f1da33b3417387009d98744d2d94 | 703,614 |
def identity(value):
"""
Node returning the input value.
"""
return value | e1af1346b11bc36a4426ad3c557dc01045657de8 | 703,616 |
import re
def parse_members_for_workspace(toml_path):
"""Parse members from Cargo.toml of the worksapce"""
with open(toml_path, mode='rb') as f:
data = f.read()
manifest = data.decode('utf8')
regex = re.compile(r"^members\s*=\s*\[(.*?)\]", re.S | re.M)
members_block = regex.findall(manif... | 63926ac1eaadc360e2407f2fff5f41b7667e52b4 | 703,618 |
import torch
def steering(taus, n_fft):
""" This function computes a steering vector by using the time differences
of arrival for each channel (in samples) and the number of bins (n_fft).
The result has the following format: (batch, time_step, n_fft/2 + 1, 2, n_mics).
Arguments:
----------
ta... | c33264516e6903d22533c9f23585739438aa5d75 | 703,619 |
def decodeXMLName(name):
"""
Decodes an XML (namespace, localname) pair from an ASCII string as encoded
by encodeXMLName().
"""
if name[0] is not "{": return (None, name.decode("utf-8"))
index = name.find("}")
if (index is -1 or not len(name) > index):
raise ValueError("Invalid enc... | 28a81aed2477b444ac061b21ca838912ee2bf24b | 703,620 |
import argparse
def parse_args() -> argparse.Namespace:
"""Parse user command line arguments."""
parser = argparse.ArgumentParser(
prog="ssacc",
description="Map SSA County Codes to ZIP Codes.",
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
)
parser.add_argument(
... | 0ea9ec39d22c2908e9b72452b5553ca62ab02aa7 | 703,622 |
from typing import Dict
from typing import Any
from typing import List
import copy
def move_to_location(
object_instance: Dict[str, Any],
location: Dict[str, Any],
object_bounds: List[Dict[str, float]],
previous_object: Dict[str, Any]
) -> Dict[str, Any]:
"""Move the given object to a new location... | 079f7367d04d732a93aa2ac18a1255a061e00243 | 703,623 |
import optparse
def parse_args():
"""
Parse command line options into variables
"""
parser = optparse.OptionParser(usage="Usage: %prog [options]")
parser.add_option("--film-urls",
type="string",
dest="urls",
help=("Film URLs to pick from, separated by commas")
)
... | e618915c8c6a6211e208b3bca662ad951c46a507 | 703,626 |
def plural(items_or_count,
singular: str,
count_format='',
these: bool = False,
number: bool = True,
are: bool = False) -> str:
"""Returns the singular or plural form of a word based on a count."""
try:
count = len(items_or_count)
except TypeEr... | 01f397579b60538f25710566507973bdc6422874 | 703,627 |
import sqlite3
def db_setup(db_name):
"""Database setup."""
cxn = sqlite3.connect(db_name, timeout=30.0)
cxn.execute('PRAGMA page_size = {}'.format(2 ** 16))
cxn.execute("PRAGMA journal_mode = WAL")
return cxn | 55092a98aed1e0a42ebf004a116913cfbecfb5f9 | 703,628 |
def role_object_factory(role_name='role.test_role'):
"""Cook up a fake role."""
role = {
'nameI18n': role_name[:32],
'active': 1
}
return role | e79e7b22a83d9da721b074d32878eabeca4054cd | 703,629 |
import itertools
def create_possible_expected_messages(message_template, expected_types):
"""
Some error messages contain dictionaries with error types. Dictionaries
in Python are unordered so it makes testing unpredictable. This
function takes in a message template and a list of types and returns
... | 674dec990e0786d3e313a9b8deec72e37588d8eb | 703,630 |
def load_saved_recipes(filename):
"""
Internal method for reading contens of given file.
"""
contents = []
try:
# Read file line by line, recipe by recipe
with open(filename, 'r') as recipes_file:
contents = recipes_file.readlines()
return contents
... | 60cf9ace8cd3cbcc40aae6fa5c1d2def50bf95b9 | 703,631 |
def GetNetworkConfig(has_external_ip, network):
"""Helper method to create a network config."""
network_interfaces = {
'network': network
}
if has_external_ip:
network_interfaces['accessConfigs'] = [{
'name': 'external-nat',
'type': 'ONE_TO_ONE_NAT'
}]
return network_interfaces | c0ee213c5c289fb2f6eb4b34fc18028233a1d162 | 703,633 |
from operator import inv
def zeros(a):
"""
Return the number of cleared bits in the sequence.
>>> assert zeros([0, 0]) == 2
>>> assert zeros([0, 1]) == 1
>>> assert zeros([1, 0]) == 1
>>> assert zeros([1, 1]) == 0
>>> assert zeros([1, 1, 1, 0, 1]) == 1
>>> assert zeros([0, 1, 0, 0, 0]... | 76f041390dfe43bcc583e39fc7a3e3d761f87c25 | 703,634 |
def escape_special_char(string):
"""
Is called on all paths to remove all special characters but it's not good.
Should be moved in core
Should be called only in get_wrapper_path and unescape_special_char in get_entry
and in script += 'menu_click... in menu_click as it's already done
... | cb3d4bd0d7370ec9c3d76543db8e3aafaf1bd8e8 | 703,635 |
from pathlib import Path
def fp_search_rglob(spt_root="../",
st_rglob='*.py',
ls_srt_subfolders=None,
verbose=False,
):
"""Searches for files with search string in a list of folders
Parameters
----------
spt_root : string... | e8fe03f9549ae77147ec96263411db9273d2c4cb | 703,636 |
def get_minimum(feature):
"""Get minimum of either a single Feature or Feature group."""
if hasattr(feature, "location"):
return feature.location.min()
return min(f.location.min() for f in feature) | aec98f5bc065c6a97d32bc9106d67579f76f7751 | 703,637 |
def isUniqueSFW(str):
"""
Given a string, checks if the string has unique charachters
Note that this solution is inefficient as it takes O(n^2)
"""
l = len(str)
for i in range(l):
for j in range(l):
if i != j and not ord(str[i]) ^ ord(str[j]):
return False
... | 369eddfc360a2661e063183a30c9d511a5deb3de | 703,638 |
def get_3x3_homothety(x,y,z):
"""return a homothety 3x3 matrix"""
a= [x,0,0]
b= [0,y,0]
c= [0,0,z]
return [a,b,c] | 5c6c2d8931334cc13297e787a079499753c1976c | 703,639 |
def scrape_to_list_value(scraped_rows, i, list_name):
"""insert row of rows of scraped data
input i for skipping rows
return value in dollars"""
to_scrape = scraped_rows[i::7]
list_name = []
for i in range(len(to_scrape)):
num = float(to_scrape[i][0].replace(',', '.'))
num_dollar... | 62117d0d78a4fd691baa4163a19962c2fb1443d3 | 703,640 |
def get_nodes_from_vpc_id(vpc_id):
""" calculate node-ids from vpc_id. If not a vpc_id, then single node
returned
"""
try: vpc_id = int(vpc_id)
except ValueError as e: return ["%s" % vpc_id ]
if vpc_id > 0xffff:
n1 = (0xffff0000 & vpc_id) >> 16
n2 = (0x0000ffff & vpc_id)
... | 5c3a6506a721f9d518579df39a91ec38118d5e75 | 703,641 |
def ex_verb_voice(sent, ex_set, be_outside_ex=True):
"""
Finds verb voice feature.
1. One of the tokens in the set must be partisip - VBG
2. One of the tokens in the set must be lemma 'be'
3. VBN's head has lemma 'be'
If none of the tokens is verb, returns string 'None'
@param sent Lis... | 8891a792528af0c44865e4bbc63f269a85df4da9 | 703,642 |
def get_player_actions(game, player):
"""
Returns player's actions for a game.
:param game: game.models.Game
:param player: string
:rtype: set
"""
qs = game.action_set.filter(player=player)
return set(list(qs.values_list('box', flat=True))) | 9b961afbee7c3a0e8f44e78c269f37a9b6613488 | 703,643 |
def create_lkas_ui(packer, main_on, enabled, steer_alert):
"""Creates a CAN message for the Ford Steer Ui."""
if not main_on:
lines = 0xf
elif enabled:
lines = 0x3
else:
lines = 0x6
values = {
"Set_Me_X80": 0x80,
"Set_Me_X45": 0x45,
"Set_Me_X30": 0x30,
"Lines_Hud": lines,
"Ha... | 16c226698160b14194daf63baf61bb3952e1cd59 | 703,644 |
import torch
def get_pytorch_device() -> torch.device:
"""Checks if a CUDA enabled GPU is available, and returns the
approriate device, either CPU or GPU.
Returns
-------
device : torch.device
"""
device = torch.device("cpu")
if torch.cuda.is_available():
device = torch.devic... | 0109f3146c96bec08bbe6fa62e5a8bc5638e461c | 703,645 |
import time
import random
def creat_order_num(user_id):
"""
生成订单号
:param user_id: 用户id
:return: 订单号
"""
time_stamp = int(round(time.time() * 1000))
randomnum = '%04d' % random.randint(0, 100000)
order_num = str(time_stamp) + str(randomnum) + str(user_id)
return order_num | 339764f7dc943c46d959a9bfdc6c48dc9ecd6bef | 703,646 |
def get_rst_title_char(level):
"""Return character used for the given title level in rst files.
:param level: Level of the title.
:type: int
:returns: Character used for the given title level in rst files.
:rtype: str
"""
chars = (u'=', u'-', u'`', u"'", u'.', u'~', u'*', u'+', u'^')
if... | b646b9e0010d87ece7f5c8c53c8abf89ca557a21 | 703,647 |
import os
def toPath(prefix, metric):
"""Translate the metric key name in metric to its OS path location
rooted under prefix."""
m = metric.replace(".", "/") + ".wsp"
return os.path.join(prefix, m) | 161ea82432c9e6a5e23ab9305133156ba35755f3 | 703,648 |
def get_sample_ids(fams):
""" create a ditionary mapping family ID to sample, to subID
Returns:
e.g {'10000': {'p': 'p1', 's': 's1'}, ...}
"""
sample_ids = {}
for i, row in fams.iterrows():
ids = set()
for col in ['CSHL', 'UW', 'YALE']:
col = 'SequencedA... | 443e63b486a1bdb8a64595beda30f75468af7560 | 703,649 |
def calcbw(K, N, srate):
"""Calculate the bandwidth given K."""
return float(K + 1) * srate / N | 13e99bcb729352feb66a34aac66e12b1c5e158ef | 703,651 |
def format_sqlexec(result_rows, maxlen):
"""
Format rows of a SQL query as a discord message, adhering to a maximum
length.
If the message needs to be truncated, a (truncated) note will be added.
"""
codeblock = "\n".join(str(row) for row in result_rows)
message = f"```\n{codeblock}```"
... | 3b98590c72245241ba488e07fdfdd20acae441cf | 703,652 |
import re
def regex_sub_groups_global(pattern, repl, string):
"""
Globally replace all groups inside pattern with `repl`.
If `pattern` doesn't have groups the whole match is replaced.
"""
for search in reversed(list(re.finditer(pattern, string))):
for i in range(len(search.groups()), 0 if ... | 67e909778d9565d498fc3e7b3c9522378e971846 | 703,653 |
def _parse( filepath : str ) -> list:
"""
[summary]
Arguments:
filepath {str} -- [description]
Returns:
list -- [description]
"""
with open( filepath, 'r' ) as f:
raw_data = f.read( ) # not readlines( ), as this needs to be one long string
data = list( map( int, raw_data.split( ) ) )
return data | 6814c4f45aee453f6387761ee7c4f3e64c669b1c | 703,654 |
def stations_level_over_threshold(stations, tol):
"""Returns a list of the tuples, each containing the name of a station at which the relative
water level is above tol and the relative water level at that station"""
output = []
for station in stations:
relative_level = station.relative_water_l... | 87be1329ea8b7e58796ebfe33a6f9e9503777227 | 703,655 |
def deregister_device(device):
"""
Task that deregisters a device.
:param device: device to be deregistered.
:return: response from SNS
"""
return device.deregister() | 44bec0e3ac356f150a0c4a6a0632939a20caafb0 | 703,656 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.