content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
import pathlib
def get_paths(input_dir, glob_ext='*.*', recursive=False):
"""Return a list of the paths of all files in the given directory"""
if recursive:
glob_ext = '**/' + glob_ext
data_root = pathlib.Path(input_dir)
all_paths = list(data_root.glob(glob_ext))
all_paths = [str(path) for... | bf5240d4cc2f8a533998784ebc386cd5a00e8065 | 598,003 |
def format_linebreaks(string):
"""
Replace '\n' linebreaks with '<br />' linebreaks for markdown:
Args:
string: A string
Returns:
string: A string with markdown style linebreaks.
"""
return string.replace("\n", "<br />") | 1b2a7aba80c952fd45d2dab7b706e7b3dcdfbbc3 | 598,007 |
from copy import deepcopy
def clone(obj):
"""
Clone a database object.
:param obj: Original object to be cloned
:return: New, saved object. New object is identical to old *except* for id and pk
Note that id and pk are often the same but can differ when using abstract models or model inheritance.
... | c2f2ca6ab7673783b6fdac20af55519b0678eb65 | 598,008 |
def check_if_ancestor_image_is_inherited(image, ancestor):
"""Helper function that looks for a given ancestor image in the layers of a
provided image. It can be used to check, whether an image uses the expected
FROM-statement
Arguments:
image {docker.images.Image} -- Docker image object to be... | 3181b7162223cb4e61e2e89d595a5ac39d6f88e1 | 598,011 |
def as_lines(content):
"""This function splits given ``content`` into lines if it's a string or
returns it as is if it's a list.
Args:
content: String or list of strings.
Returns:
List of strings.
"""
if isinstance(content, list):
return content
return content.split... | 129d95a35e3e74837d9c168df5bcd4e6c7271d5e | 598,013 |
import hashlib
def get_file_hash(filepath):
"""
Returns the MD5 hash of a local file
"""
file_to_hash = open(filepath, 'rb')
md5 = hashlib.md5()
while True:
current_line = file_to_hash.readline()
if not current_line:
break
md5.update(current_line)
return... | 3e3708752c62370015d7e6ead8499b7e1438d304 | 598,016 |
import math
def cost_lane_change(vehicle_info, predictions, trajectory):
""" Computes cost of changing lanes.
Args:
vehicle_info: A VehicleInfo tuple.
predictions: A dict of predictions for vehicles.
trajectory: A Trajectory tuple.
Returns:
A cost in [0, 1].
"""
#... | f0278f86d30b274d5c725cd790e0c6e294a2d764 | 598,017 |
import time
def retry_delay(deadline, delay, max_delay):
"""For internal use in retry. Sleep as required
and return the new delay or None if retry should time out"""
remaining = deadline - time.time()
if remaining <= 0:
return None
time.sleep(min(delay, remaining))
return min(delay*2, ... | d55673477262cd7cc9bee1ada343fe4ec256e580 | 598,021 |
def convertir_ppm(fila, columna):
"""Conversión de unidad de medición del contaminante de partículas por billón (ppb) a partículas por millón (ppm).
Parameters
----------
fila: serie de pandas
Una fila de un dataframe de pandas.
columna: string (cadena de texto)
El nombre de ... | f71cfb141c3b0baae8c4d18c0c883dd23c3d1127 | 598,022 |
def valid1(s, c, low, high):
"""
Returns True or False depending on whether the number of occurences of the character `c`
in the string `s` is between the integers `low` and `high` inclusive
"""
return low <= s.count(c) <= high | 744f2486ea8fe1340f82f9e35994368f307235ba | 598,027 |
def parse_bool(data):
"""
Return ``True`` if data is one of:: ``'true', 'True', True``. Otherwise,
return ``False``.
"""
return data in ('true', 'True', True) | 0c0bc43ba360772f9b0d4a947d1faf3a976739ba | 598,028 |
def has_controller(thread):
"""Check if the current thread has a controller."""
return hasattr(thread,"thread_controller") | 227fad8c7ef7fad26c4d60a57da2c8bef0f16187 | 598,029 |
import sqlite3
import logging
def setup_db(db_path):
"""
Initialises a local sqlite3 database and create the table required to hold data.
Parameters
-------------
db_path
string : A filepath to a target sqlite database
Returns
-------------
con:
Connection : Returns ... | ff3e1e62323bf7ba7ca42f09859b83663c973211 | 598,030 |
import re
def parsePlasClass(filename):
""" Parse the file into lists of edge names, lengths, and PlasClass scores
"""
with open(filename) as f:
names = []
lengths = []
scores = []
name = ''
for line in f:
splt = line.strip().split('\t')
ed... | 0481c203c03b87c2fd2a69d29f7cafabc876389e | 598,035 |
from typing import Sequence
from pathlib import Path
def _find_capture_info_json_files() -> Sequence[Path]:
"""Return a list of all the capture_info.json files."""
root = Path(__file__).absolute().parent.parent
capture_info_dir = root / "slamcore_utils" / "share" / "capture_infos"
return list(capture_... | ea9964d7e404ba932f38f77c7b9f8b7cccf8b5fa | 598,036 |
import pymysql.cursors
def mysql_conn(
host: str = "localhost",
port: int = 3306,
user: str = "root",
db_name: str = "newbook",
):
"""Establish a PyMySQL connection object
Connect to a MySQL Database to be used with a pnguin RemoteFrame
Args:
host (str): A hostname
port (... | 651803e2e4bb0597f9eba0b698eb847a37c19275 | 598,038 |
def atoi(text):
"""
helper for natural_keys
attempt to convert text to int, or return text
:param text: arbitrary text
:return: int if succeeded to convert, the input text as is otherwise
"""
return int(text) if text.isdigit() else text | a72e8c7ae36556b3d0568df157f95830c503940a | 598,040 |
def the_same_repository(repo_1_info, repo_2_info, check_revision=True):
"""
Given two dicts containing info about repositories, determine if they are the same
repository.
Each of the dicts must have the following keys: `changeset_revisions`( if check revisions is true), `name`, `owner`, and
(either ... | 349fc44206d75f8436a87539eb390d399f3059b2 | 598,041 |
def create_headers(user_id, token=None):
"""Return header dict that is needed to talk to the Emby API.
:param user_id: Emby user ID
:param token: Authentication token for Emby
:type user_id: str
:type token: str
:returns: Headers for requests
:rtype: dict
"""
headers = {}
autho... | a2ec147d938aff451b5bc8b8b75d24421c84100a | 598,044 |
def namefromcycle(cyclenumber, version='1.2'):
"""Return the dataset name corresponding to the given cycle number.
SE 1.0 and 1.1 used dashes; SE 1.2 uses zero-padded integers with
10-digit field width.
"""
if version == '1.2':
return 'cycle%010d' % cyclenumber
else:
return 'c... | 45964c2788acfe6b19451aeb4c5e908732b3b27b | 598,045 |
import threading
def setInterval(func, sec):
"""Python setInterval
用法类似于Javascript的setInterval。
:param func: 定期执行的方法。
:param sec: 定时的时间,秒为单位。
"""
def func_wrapper():
setInterval(func, sec)
func()
t = threading.Timer(sec, func_wrapper)
t.start()
return t | a1a6c4af755b54d9eafdce8f7fcb3d3dfa457940 | 598,046 |
def prefix_lines(lines, prefix):
"""Add the prefix to each of the lines.
>>> prefix_lines(['foo', 'bar'], ' ')
[' foo', ' bar']
>>> prefix_lines('foo\\nbar', ' ')
[' foo', ' bar']
:param list or str lines: A string or a list of strings. If a string is
passed, the string is split ... | 73996b4ff9cd939fb3d096300785cd3490764c6d | 598,051 |
def _gen_fake_split(separator):
"""Returns a callable that splits a with the given separator."""
def _split(path):
sep_index = path.rfind(separator)
if sep_index >= 0:
return (path[:sep_index], path[sep_index + 1:])
else:
return (path, '')
return _split | 729e6b2230228dcf533aa44c5dd110c7bcd621f4 | 598,053 |
def AntelopePf2dict(pf):
"""
Converts a AntelopePf object to a Python dict.
This converts a AntelopePf object to a Python dict by recursively
decoding the tbls.
:param pf: AntelopePf object to convert.
:type md: :class:`~mspasspy.ccore.AntelopePf`
:return: Python dict equivalent to md.
... | cc7b78be2ae352a43f1f1a52b755e2986effaac0 | 598,054 |
import re
def replace(text, bindings):
"""Replace the variables in text with their corresponding bindings.
Args:
text: The text to replace has variables in the form $<KEY>
bindings: A dictionary of binding values keyed by <KEY>.
"""
regex = re.compile(r'\$(\w+)')
return regex.sub(lambda match: bind... | 881dbe17948a52bdc49b56c81c10d57ed0cf29b0 | 598,058 |
def correction_byte_table_q() -> dict[int, int]:
"""Table of the number of correction bytes per block for the correction
level Q.
Returns:
dict[int, int]: Dictionary of the form {version: number of correction
bytes}
"""
table = {
1: 13, 2: 22, 3: 18, 4: 26, 5: 18, 6: 24, 7: ... | 240303c1812429f75731d80f4a51f3aa0a066e6e | 598,070 |
def positive_places(f, xs):
"""Takes as arguments some function f and a list of numbers xs and returns a list
of those-and-only-those elements x of xs for which f(x) is strictly greater than
zero. """
ans = []
for x in xs:
if f(x) > 0:
ans.append(x)
return ans | 25d6e9d678ea14b7ec2ccec808606b9c6e0b780d | 598,073 |
def make_annotations(df_info) -> str:
"""Generates a string to be used for annotation the graph. Data is generated from the `describe` function
in Pandas, and then parsed from the new dataframe.
The annotation string is interpreted as HTML in the Plotly output."""
total_reads = df_info.sum()
ds = df... | 37fabecc7cec4af7ca5f89ac58432a1db372c7e2 | 598,074 |
def update_line(line):
"""
Takes a string line representing a single line of code
and returns a string with print updated
"""
# Strip left white space using built-in string method lstrip()
new_line = line.lstrip()
striped_spaces = len(line)-len(new_line)
# If line is print statement, u... | 12d2dc22d3aebee9c25080b8a496ce5edc9c0e9b | 598,075 |
from typing import List
async def hunter(records: List[str], ioc: str) -> bool:
"""Return if any record in a list of records matches a given IoC.
:param records: A list of network records
:type records: List[str]
:param ioc: An indicator to check against record
:type ioc: str
:return: If any ... | 962a9585b024007c4a27ab0ec083006040cb74d8 | 598,087 |
def mirror_y(clip, apply_to=["mask"]):
"""Flips the clip vertically (and its mask too, by default)."""
return clip.image_transform(lambda img: img[::-1], apply_to=apply_to) | cdb5d6f3f13b939b25af1a616896255269478a48 | 598,090 |
def replace_wildcard(input_list):
"""Method to replace a wildcard `-` in the input values.
This method will replace the wildcard `-` in the input list; the returned
two lists have different values on the position of `-`.
Example: ['0', '-', '1'] => (['0', '0', '1'], ['0', '1', '1'])
Parameters
... | a0d4610c884cbec62f9064a5bb31516141e5f089 | 598,091 |
import math
def _quaternion_length(quat):
"""Calculate the length of a quaternion
:param quat: Blender quaternion object
:rtype: float
"""
return math.sqrt(quat.x * quat.x + quat.y * quat.y +
quat.z * quat.z + quat.w * quat.w) | fadd69b924d623301a0dc604d9aa60e01a8ca9b2 | 598,100 |
def load_jobs(db, experiment_name):
"""load the jobs from the database
Returns
-------
jobs : list
a list of jobs or an empty list
"""
jobs = db.load(experiment_name, 'jobs')
if jobs is None:
jobs = []
if isinstance(jobs, dict):
jobs = [jobs]
return job... | 2ca3b0f2a1e15a00556c212eb4482f73deb149a5 | 598,103 |
def _get_bit(x: int, i: int) -> bool:
"""Returns true iff the i'th bit of x is set to 1."""
return (x >> i) & 1 != 0 | 567ee4edb81ffd648f89dd1b0ed41b11efd21536 | 598,105 |
def _shell_quote(s):
"""Copy of bazel-skylib's shell.quote.
Quotes the given string for use in a shell command.
This function quotes the given string (in case it contains spaces or other
shell metacharacters.)
Args:
s: The string to quote.
Returns:
A quoted version of the string t... | 64d58b7ced621246d193c1b217fdd81a6c258a24 | 598,112 |
def magnitude(row):
"""
Calculates the magnitude of the body's acceleration vector in the row.
"""
return (row[21] ** 2 + row[22] ** 2 + row[23] ** 2) ** 0.5 | 7513cb1471861e4ca390b3ebe15efc4090176333 | 598,113 |
def n_colors(lowcolor, highcolor, n_colors):
"""
Splits a low and high color into a list of n_colors colors in it
Accepts two color tuples and returns a list of n_colors colors
which form the intermediate colors between lowcolor and highcolor
from linearly interpolating through RGB space
"""
... | 9fc57f48c8d1eb0b8cb63eb651a08a8325ce62e9 | 598,114 |
def getSectionData(config, section):
"""Generates a map of key-values for a given section of an INI"""
dict1 = {}
options = config.options(section)
for option in options:
try:
dict1[option] = config.get(section, option)
except:
print("exception on %s!" % option)
... | ad69b5d4f5a01113df7be46fc09ab3897d89b33c | 598,118 |
def evaluate_ops(prim_len: int, sec_len: int,
sparse_rounds: int = -1) -> float:
"""
Evaluates the number of total node pair flow computations needed to calculate the complete
flow in the sample according to the general_flow policy.
:param prim_len: length of the primary set
:param... | bf25a322390d32b5c36f6e0e29b259ff55639da5 | 598,119 |
def database_info(connection):
"""
Parse an SQL string of the format:
database_type://user:password@address:/database
mysql://dbadmin:password@10.0.0.1/nova
"""
db = {}
conn = connection.partition(':')
if conn[1] != ':':
return None
db['type'] = conn[0]
conn = con... | 651c26f72f56e1431b4af052ff3747ff8bf7e93e | 598,121 |
def read_xvg_col(xvg_file, col):
"""Read 1 column of xvg file and return as array column is 0-indexed"""
with open(xvg_file, 'r') as fp:
lines = [line.strip() for line in fp.read().split('\n')]
data = []
for line in lines:
if not line.startswith(('#', '@')) and line != '':
... | 4860648a9a281c9e228925b9a1bf39cc33684672 | 598,123 |
def parityOf( n ):
"""
parityOf - determine if the number of bits is odd or even
Args:
n: the number to be tested.
Returns:
o - if the number has even bits.
1 - if the number has odd bits.
"""
parity = 0
while( n ):
parity ^= (n&1)
n >>= 1
return ... | e8010b20460f92d2546c6c176700baa2600e65cb | 598,124 |
def mul_by_two_or_min_one(n):
"""Simple timeout calculation: multiple the max response time by 2 or at least a minimum of 1 second."""
return max(n * 2, 1) | e938e28d29a73896fa96f4279a4fbd2260f6a22f | 598,127 |
def friendly_since(time_type, since):
"""
Takes a since and, if it is Run-based expressed as Lumi-based,
returns the run number.
Otherwise, returns the since without transformations.
"""
if time_type == "Run" and (since & 0xffffff) == 0:
return since >> 32
else:
return since | c92badfb3cf950aa659d9f4d2224d559baef8111 | 598,129 |
def _KITTIObjectHas3DInfo(obj):
"""Check whether KITTI object has valid 3D bounding box information."""
height, width, length = obj['dimensions']
# KITTI raw data has -1 for all 3 dimensions when no 3D box info is present.
return not (width == -1 or length == -1 or height == -1) | 5f51cd0c9e2a38b2e8f0ec9d7d8c1ae5e07d36ee | 598,133 |
import itertools
def pairwise(iterable):
"""Iterate over the given iterable in pairs.
pairwise([1, 2, 3, 4]) -> (1, 2), (2, 3), (3, 4)
"""
a, b = itertools.tee(iterable)
# Advance b one step
next(b, None)
return zip(a, b) | 95a7f98edc81fb6ff3060148a17ed83cf132899c | 598,136 |
def rm_newline_hyphenation(dfcol):
""" Remove hyphens at the end of lines (continuation character) and merge the text """
return dfcol.str.replace('([a-z])(-\s*\n\s*)([a-z])', r'\1\3', regex=True) | 27760e4209ac77184516ea9ede7e1a7b54be4cfc | 598,144 |
def mean(seq):
"""Return the average of the elements of a sequence."""
return float(sum(seq))/len(seq) if len(seq) > 0 else float('nan') | 66368c61023954c938d930ea7ffeca08d0050681 | 598,145 |
def is_the_only_string_within_a_tag(s):
"""Return True if this string is the only child of its parent tag."""
return (s == s.parent.string) | 42a51c13999aa2b1655c349bc1a77d79b39dfdf6 | 598,147 |
import typing
def create_molecular_formula(atoms: typing.List[str]) -> str:
"""
Creates a molecular formula out of a list of moleules:
Parameters
----------
atoms : List[str]
A list of atoms. Example: ['H', 'O', 'H']
Returns
----------
A molecular formula. Example: 'H2O'
"""
dictionary = {}
for atom ... | 91458bc2c7e99eb67b5eba79e65c7de010e4a670 | 598,149 |
import uuid
def gen_token(max_length=5):
"""
Generate a random token.
"""
return uuid.uuid4().hex[:max_length] | 97eb9e90c62495939a95587daf1812cbde713cd9 | 598,154 |
def get_trader_scada_ramp_rate(trader_id, ramp_rates):
"""
Extract SCADA ramp rate for a given trader. If the SCADA ramp rate is 0
or missing return None.
"""
if (trader_id in ramp_rates.keys()) and (ramp_rates[trader_id] > 0):
return ramp_rates[trader_id]
else:
return None | 02921f1096f930267cbb9c00ce0850632db38a1a | 598,155 |
def pred_diff(y_pred, y):
"""
Returns the difference between the test target and the predicted one, for a future mse calculation.
:param y_pred: the vector of predictions
:param y: the target
:return: the vector difference between y and y_pred
"""
return y - y_pred | 1732e1b133e8fdabbf611a01ced63e0d4914bacc | 598,163 |
def norm3_sqr(x, y, z):
"""
Squared 2-norm for 3d vectors
:param x:
:param y:
:param z:
:return:
"""
return (x * x) + (y * y) + (z * z) | f11c3bd6744aa79592a552bdd3bf7db8896c6060 | 598,165 |
import re
def process_text(transcript:str, remove_apost:bool = False)->str:
"""This function removes punctuation (except apostrophe's) and extra space
from the input `transcript` string and lowers the case.
Args:
transcript (str): input string to be processed
remove_apost (bool): if True... | f4d18aa57839c296cc33d6cac176835f5cc5dafb | 598,168 |
def sort_key(item):
"""Returns a string to sort by for a run.
Meant to be the key function in sorted()
:param item: Run instance
:type item: cloud_snitch.runs.Run
:returns: String to sort by
:rtype: str
"""
return '{}~{}~{}'.format(
item.environment_account_number,
item... | 3895e2a9dba33a960cfc2648742367407f7928f4 | 598,169 |
def are_all_strings_in_text(text, list_of_strings):
"""
:param text: output from convert_pdf_to_text
:type text: list of str
:param list_of_strings: a list of strings used to identify document type
:type list_of_strings: list of str
:return: Will return true if every string in list_of_strings is... | a4ef6a2067e85fdc97c767881f26f9188c1f55ef | 598,173 |
import random
def generate_random_sequence(length, prob_dist=[0.25, 0.25, 0.25, 0.25]):
""" generates a DNA sequence given length according to the given nucleotide distribution """
seq = ''
for p in range(length):
n = random.random()
if n < prob_dist[0]: seq += 'A'
elif n < sum(prob_dist[0:2]): seq += 'C'
... | 35d3eb9e92f2b4cf2ac23d018c44c94c8b1629ce | 598,174 |
def pid_filename(component: str) -> str:
"""Obtain the canonical pid filename for the specified component name."""
return f".lta-{component}-pid" | 02be368a328cfec312a376f79ba2d19ccdf97f3a | 598,180 |
def str_to_int_list(string):
"""
:param str string: A string read by the config file.
:return: A list of integers.
:rtype: list
Utility function used to convert a string to a list of integers
"""
list = []
parts = string.split(',')
for part in parts:
part = part.replac... | 019e25bbe1bc6b6640cfc823bccdadd2ffbf2d2b | 598,182 |
def run_test(f):
"""Prints the test name and runs the test."""
print(f.__name__)
f()
return f | 8bc2b0321feb3a8746ef68285c1b355f6026930f | 598,183 |
def get_hostgroup_type(code):
"""Get hostgroup type from code."""
hostgroup_type = {0: "Not internal", 1: "Internal"}
if code in hostgroup_type:
return hostgroup_type[code] + " (" + str(code) + ")"
return "Unknown ({})".format(str(code)) | b35906e464874c5b58f82bd1ad7fd998b39d9bcc | 598,187 |
def add_nulls_to_vals(columns, vals):
"""Takes a list of columns to be inserted/updated and a value dictionary. Any columns
that are not present in the dictionary keys will be added with a None value, translating
to Null in the db. Used to help input dictionarys
Args:
columns (list of str): co... | 4405f16d20d37863aff8aca3a0187dc9d12e89e7 | 598,189 |
def stop(ctx):
"""Stop robot
Args:
ctx: Context
Returns:
Success: 0
Failure: False
"""
r = ctx.tran.post("/v2/movementservice/robot/movement/stop")
if r[0] != 200:
return False
return r[1] | 2fd6e41137a13fa425f8903530414e2c359430e6 | 598,191 |
def get_square(array, size, y, x, position=False):
""" Returns an square subframe.
Parameters
----------
array : array_like
Input frame.
size : int, odd
Size of the subframe.
y, x : int
Coordinates of the center of the subframe.
position : {Fals... | 13e05a4fb6fd5e4a36180069f4f19192f29d6339 | 598,192 |
def _extract_args(cmd_line, args):
"""
Extract specified arguments and sorts them. Also removes them from the
command line.
:param cmd_line: Array of command line arguments.
:param args: List of arguments to extract.
:returns: A tuple. The first element is a list of key, value tuples represent... | 877ea4a56eaaa81f3b6ebbd6bd727adf91c6d614 | 598,193 |
def add_to_list(list_name, list_to_add, content, begin_index):
"""
Add a new element to a list.
:param list_name: The name of the list.
:param list_to_add: The list to add the element to.
:param content: The input message.
:param begin_index: The beginning index of the entry in the list.
:re... | 99686c8939e5d89e4a48898f09507044e1b857cd | 598,196 |
def pause_flc_policy_on_volume(session, lc_policy_id, volume_id,
return_type=None, **kwargs):
"""
Pause a file lifecycle policy for a given volume.
:type session: zadarapy.session.Session
:param session: A valid zadarapy.session.Session object. Required.
:type lc_po... | 543e8ddfb8eb437a959a22b5b0962e73ba078e6b | 598,197 |
import re
def filter_osd_trace_timestamps(in_str_list):
"""
Remove all timestamps from the OSD-recorded systrace and coretrace log files
"""
filter_expr = re.compile(r'^[0-9a-f]+ ', flags=re.MULTILINE)
return [filter_expr.sub(repl='', string=l) for l in in_str_list] | 1a0ad2d1bc13b66d2947fe7a64e0167c04ba8cc5 | 598,198 |
import math
def rounded_bez(angle):
"""
From https://math.stackexchange.com/questions/1671588/b%C3%A9zier-curve-approximation-of-a-circular-arc.
The control points of a cubic Bezier curve for approximating a circular arc with end points
P0, P1, radius R, and angular span A:
... | b061c6e46eac5abb0a4f05788535e029a12856bc | 598,199 |
import torch
def rand_bbox_minmax(img_shape, minmax, count=1):
"""Min-Max CutMix bounding-box
Inspired by Darknet cutmix impl, generates a random rectangular bbox
based on min/max percent values applied to each dimension of the input image.
Typical defaults for minmax are usually in the .2-.3 for mi... | 2d879b44b70a835738f62ab1a52dd5e90a78d00d | 598,202 |
def validate_coin_selection(selection):
"""Validation function that checks if 'selection' arugment is an int 1-5"""
switcher = {
1: (True, "Quarter"),
2: (True, "Dime"),
3: (True, "Nickel"),
4: (True, "Penny"),
5: (True, "Done")
}
return switcher.get(selection, (F... | 8ad2561cc69448787bc51b75d50df41967a428b3 | 598,204 |
def get_IP_address(request):
"""
Returns the visitor's IP address as a string given the Django ``request``.
"""
# Catchs the case when the user is on a proxy
ip = request.META.get('HTTP_X_FORWARDED_FOR', '')
if ip == '' or ip.lower() in ('unkown', ):
ip = request.META.get('REMOTE_ADDR', ... | c03559829fcf3df647ef08129912bb1e357aa107 | 598,205 |
import hashlib
import json
def dict_to_sha256(dictionary):
"""
Get sha256 hexdigest from a dictionary
:param dictionary: dict
:return: hexdigest
"""
sh = hashlib.sha256(json.dumps(dictionary).encode("utf-8"))
digest = sh.hexdigest()
return digest | 6b63686765f610bb604fa495a9f53f72fb4f8442 | 598,206 |
from typing import List
from typing import Tuple
def get_index_tuple_from_kraus_matrices_indices(
index: int, indices: List[int]
) -> Tuple[int, int]:
"""Get index i, j of Instrument object from a list of numbers corresponding to matrices of Kraus operators.
Parameters
----------
index: int
... | a416e6ceb4304916250222bcfc1547c401fa8b7b | 598,209 |
def join_paths(path, suffix):
"""Joins a path and a suffix into a single path.
Resolves leading and trailing '/'. The suffix can be null.
Examples:
join_paths('abc/def/', '/hij') => 'abc/def/hij'
join_paths('a', 'b/c/d') => 'a/b/c/d'
join_paths('abc/def', None) => 'abc/def'
"""
if not path.endswi... | aab7a2853e9a4d9000b6656b4822672c0cf82f58 | 598,210 |
def compare(args, func):
""" Check if all the numbers in the list satisfy the constraint
Args:
args(list): a list of numbers to be checked
func(function): the constraint function
Return(Boolean): True/False represents if the list satisfies the constraint
"""
for i ... | 5b8d1e8a10a732cfb299208bcb53e181f7d7d20e | 598,213 |
def convert_tree_to_string(ne_tree):
"""Converts a tree into a string"""
return " ".join([w[0] for w in ne_tree]) | c99de4147c981bc443c68d25d7af89cb9e2438e4 | 598,214 |
def decode(line: str) -> list:
"""Generate binary list from string."""
decoded = []
for char in line:
if char == ".":
decoded.append(0)
else: # means char == "#"
decoded.append(1)
return decoded | 7578d2d9672399be891bec488ed242464846bde0 | 598,216 |
def lower_text(sentences):
"""Given a list of sentences, return the sentences where each
character is converted to lowercase."""
return [sentence.lower() for sentence in sentences] | 6fb6b9796f7523f577dfd4382f30059f9e6080de | 598,217 |
from pathlib import Path
def _resolve_code(code_or_file, _load=lambda f: Path(f).read_text()):
"""If `code_or_file` is a filename then load it, otherwise return it as-is."""
if type(code_or_file) is str and ("\n" in code_or_file or len(code_or_file) > 256):
# Probably code
return code_or_file
... | d3834ee831845b360453ca42d55f4c2681d268de | 598,221 |
import json
def json_esc(data: object, indent: int=2) -> str:
"""JSON encode data with indent"""
return json.dumps(data, indent=indent).replace("</", "<\\/") | 3fae572ec22190ab5753b4b0ab18363587a455ee | 598,223 |
def error_app(msg):
"""
A trivial WSGI app that always displays a 500 error with a given message
Parameters:
:msg: The message to display in the response body with the 500 error
"""
def _app(_, start_response):
response_body = msg
status = '500 Error'
response_headers =... | 25caa84792ffaeddd6da817afc540ad41eede923 | 598,224 |
import time
def string_to_date(datestring):
"""Takes a date string, runs time.strptime on it, and returns the
result.
.. Note::
This doesn't do time zone translations.
:param datestring: the string to convert. e.g. "07/09/2011 04:54 pm"
:returns: struct_time
"""
return time.str... | 247a601324fc0b163cbdd5f3b08d243ed3582983 | 598,225 |
from typing import Any
import math
def is_integer(value: Any) -> bool:
""" Returns True if the input consists soley of digits and represents an
integer rather than character data or a float.
'3' is True
'-3' is True
3 is True
-3 is True
3.3... | 34194c25be1edab5f21235d0b853665d50e1d7b4 | 598,228 |
def _extract_user_from_email(raw_username):
"""
Usernames come from the globus provider in the form:
username@login_authority.com
"""
if not raw_username:
return None
return raw_username.split('@')[0] | c6cf3930526649dad9e16e1704945e860db3598a | 598,232 |
def local_rig_path(msg):
"""Gets local path of the rig.
Args:
msg (dict[str, str]): Message received from RabbitMQ publisher.
Returns:
str: Path to local rig.
"""
return msg["rig"] | 1b6a06f86f00213dc9e9b62752bc15950708624d | 598,235 |
import hashlib
def hash_stream(fileobj, hasher=None, blocksize=65536):
"""Read from fileobj stream, return hash of its contents.
Args:
fileobj: File-like object with read()
hasher: Hash object such as hashlib.sha1(). Defaults to sha1.
blocksize: Read from fileobj this many bytes at a time.
... | 5c11fdd2159a6d3887673680446542a41c314c73 | 598,237 |
from datetime import datetime
def to_day_of_week_int(dt: datetime) -> int:
"""
Get day of week of a date. Monday == 0...Sunday == 6.
Parameters
----------
dt : datetime
Represents a datetime in datetime format.
Returns
-------
int
Represents day of week.
"""
... | 1810a7e9a7c38f93d3a3b468a074def79f7ec06f | 598,238 |
import six
import re
def validate_phone(phone, required=False):
"""Validates the specified phone number.
Phone number vlidation is very lax here. Backend will enforce E.164 spec compliance, and
normalize accordingly. Here we check if the number starts with + sign, and contains at
least one alphanumer... | e760e7c1b61253ba7b02d89fce7fc1b4ef440af6 | 598,240 |
def multi_dimensional_fitness(individual):
"""A simple two-dimensional fitness function."""
return pow(individual[0], 2) + pow(individual[1], 3) | 9503c1628c88ec772afcd9f232732612598140a8 | 598,241 |
import json
from typing import OrderedDict
def load_plan(filepath):
"""Load a JSON transfer learning plan.
The named JSON tranfer learning plan file is loaded in a manner that preserves
the entry order imposed when the plan was created. This allows the root entry
to be easily located regardless of th... | d3fe537cc8a21a4a2eb4d9de9c9a84adf8482e0b | 598,245 |
def tamper(payload, **kwargs):
"""
Append a HTTP header 'X-originating-IP' to bypass
WAF Protection of Varnish Firewall
Notes:
Reference: http://h30499.www3.hp.com/t5/Fortify-Application-Security/Bypassing-web-application-firewalls-using-HTTP-headers/ba-p/6418366
Examples:
>> X... | 5c7c077bf262748dd2a50b603422fc7abe336715 | 598,249 |
def title(file):
"""Title of the file."""
return file.name | c709ad4ab272f8a01e058ce38bff993d84eddb16 | 598,253 |
def get_comma_sep_string_from_list(items):
"""Turns a list of items into a comma-separated string.
Args:
items: list. List of the items.
Returns:
str. String containing the items in the list separated by commas.
"""
if not items:
return ''
if len(items) == 1:
... | bf8f925caf66e14b7635ce470ee0f7ce12eceaa0 | 598,254 |
def template_widget(widget, template_engine, kwargs=None):
"""
Return a widget instance using the specified template engine.
"""
if kwargs is None:
kwargs = {}
if 'template_engine' in kwargs:
return kwargs
kwargs['template_engine'] = template_engine
return widget(**kwargs) | 9b26ec8e15f660aceaf1ef85b9dea2be3cd83540 | 598,260 |
def angle_to_pwm(angle, servo_params, axis_index, leg_index):
"""Converts a desired servo angle into the corresponding PWM command
Parameters
----------
angle : float
Desired servo angle, relative to the vertical (z) axis
servo_params : ServoParams
ServoParams object
axis_index ... | 0a0b85dd616861f8ef181cf87cc2fc7f63e21d77 | 598,267 |
import socket
def _ip_to_as_sender(request: str) -> str:
"""
helper function for ``ip_to_as_info`` this sends ``request`` to the server and returns the response
:param request: a request string for whois
:return: the answer formatted cleanly. 1 line per IP
"""
sock = socket.socket(socket.AF_... | 50fa139d96a72cc0a71d22228c5acb16c5daa271 | 598,270 |
def problem_4_5(tree):
""" Write an algorithm to find the ‘next’ node (i.e., in-order successor)
of a given node in a binary search tree where each node has a link to its
parent.
Solution: There are two cases:
1. the node has a right subtree, in which case his immediate successor is
the smalles... | b52ebf22ccec6c8fe3ccd473ace29dd1c47adf4b | 598,272 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.