content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def miles2km(miles):
"""
Converts miles to kilometers.
Args:
miles: A distance in miles.
Returns:
The equivalent distance in kilometers.
"""
return miles*1.60934 | 77cfb24e230a2670c9f3cc7aea5cdbea94e2ee0b | 661,060 |
def file2list(filename):
"""Load text file and dump contents into a list"""
listOfFiles = open( filename,'r').readlines()
listOfFiles = [i.rstrip('\n') for i in listOfFiles if not i.startswith("#")]
return listOfFiles | 61ca2515eefc8012931369469156180887235c7d | 661,061 |
import re
def validate_url(u: str):
"""
校验url是否有效
:param u:
:return:
"""
if not re.match(r'^http[s]?://\S+$', u):
return False
return True | 6dc89ec1a785c7b986754769d5f52e415265dcd9 | 661,062 |
def calc_student_average(gradebook):
"""
Function that will take in a list of students and return
a list of average grades for each student
"""
return [sum(grades)/len(grades) for grades in gradebook] | d45310b2d26e6ca735a878e6324d60637d2ed65a | 661,063 |
from pathlib import Path
def clean_filepath(filepath):
""" Clean paths loaded from RDF manifest """
return str(Path(str(filepath))).replace("file:", "") | 4cf41a3efc76bbf06e578e4603b4472d19dfece0 | 661,065 |
import os
def inSameDir(f):
"""Decorator to make sure a function is executed in the same directory as `__file__`.
This changes the current working directory using :func:`os.chdir()` and then reverts back afterwards.
"""
def ret(*args, **kw):
"""Decorated function"""
oldwd = os.getcwd()... | 32cd5d6cb1f32f9b813f2b96fde1c64c103df47f | 661,066 |
import torch
def optimizer_to(optimizer, device="cpu"):
"""
Transfer the given optimizer to device
"""
for param in optimizer.state.values():
if isinstance(param, torch.Tensor):
param.data = param.data.to(device)
if param._grad is not None:
param._grad.d... | 4a75e1103f01167c3683e9b34c72fa19cdac57e8 | 661,067 |
def append(base, suffix):
"""Append a suffix to a string"""
return f"{base}{suffix}" | bca492f0a2ed44a670b0bf70132e2214e56bfd88 | 661,068 |
import os
def docker_push():
"""Set whether or not to push from environment variables.
Env:
push: $DOCKER_PUSH
"""
return os.getenv('DOCKER_PUSH') | b18f162aa260c0043169cc9c0883aeaf264ba3a0 | 661,069 |
def train(algorithm, x_data, y_data):
"""train algorithm"""
percent10 = int(len(x_data)*0.1)
# return algorithm.train(np.apply_along_axis(from_data_to_haar, 1, x_data[:percent10]), y_data[:percent10], range(10))
return algorithm.train(x_data[:percent10], y_data[:percent10], range(10)) | bd8554c6a26b1c8cf7c63ea719f908613e21c129 | 661,070 |
import textwrap
def _wrap_text(text):
"""
Wrap text at given width using textwrap module. Indent should consist of
spaces. Its length is deducted from wrap width to ensure exact wrapping.
"""
wrap_max = 80
indent = ' '
wrap_width = wrap_max - len(indent)
return textwrap.fill(text, w... | 1c8ad1401e229bec60eb7b82acecd72811689fc2 | 661,071 |
def bounds_check(session):
"""Pipe used to determine if a value is within the min and max bounds on
the field
:param session: Kim pipeline session instance
"""
max_ = session.field.opts.max
min_ = session.field.opts.min
if max_ is not None and len(session.data) > max_:
raise sess... | aafc59ad059242994651c7dcd96b0c01a26a9c08 | 661,072 |
def behavior_of_return_in_try_finally():
"""
If a finally clause includes a return declaration,
the returned value will be the one of
the declaration of the finally clause return,
not the value of the declaration of the try clause return.
"""
try:
return True
finally:
ret... | 61fb90291e0a56cc718394d04e6f35d2fe4d4742 | 661,073 |
def read_txt_file(fname):
""" read a txt file, each line is read as a separate element in the returned list"""
return open(fname).read().splitlines() | af0be81903c6ffa8a574b8e33b842e62ae4a5bc8 | 661,074 |
def coco_as_image_size(dataset, label):
"""Convert a COCO detection label to the image size.
Args:
label (list of dict): an image label in the VOC detection format.
Returns:
tuple: width, height of image.
"""
if not label:
return None
image_id = label[0]['image_id']
... | 9340bea4feffb753c20ca60e2e587d51118e1744 | 661,075 |
def RK4(f, y_i, t_i, dt):
"""Performs Runge-Kutta integration.
Parameters
----------
f : callable
Derivative function.
y_i : ndarray
Current state.
t_i : float
Current time.
dt : float
Time step.
Returns
-------
y_j : ndarray
State at ... | e4834cae4236725f117786620aa797b9cdc2a963 | 661,076 |
import requests
from bs4 import BeautifulSoup
def scrape_url(url):
"""
Scrap the content from the input URL using Beautiful Soup.
"""
# Retrieve the data using a request
r = requests.get(url)
# Get the content in HTML format
html = r.text
# Parse the HTML file with BS4
soup = Be... | 1ea4f7b035d1c185013a2cb217ac519c758a9189 | 661,078 |
import random
def random_num_generator(length, repeatable=False):
"""
Generate a number in specific length. If repeatable is true, the number in
different position can be the same one.
:type length: int
:param length: the length of the number
:type repeatable: boolean
:param repeatable: ... | 136d8c0d7d9c9b8159b32fcb7abb174b8babbcb4 | 661,080 |
import math
def calculate_open_channel_flow(channel, water_level_outside, water_level_inside):
"""
This functions calculates discharge past a barrier in case it is connected through an open channel
:param channel: connecting body of water between outside water level and inside water level
:param wate... | 848385075ea5cf914864426e516999def4d71c7f | 661,081 |
def get_label_mapped_to_positive_belief(query_result):
"""Return a dictionary mapping each label_id to the probability of
the label being True."""
return {label_id: belief[1] for label_id, belief in query_result.items()} | 49d14b37318fa7b4d1a24ef135d1eaef7c2276a1 | 661,082 |
def get_predictions(results):
"""
:param results:
:return: predictions
"""
predictions = []
for result in results:
prediction = []
if result != "":
for loc in [s.split() for s in result.split(';')]:
start, end = int(loc[0]), int(loc[1])
... | 9b5cf4e674daf6e112c88dd90f07ce06015c5525 | 661,083 |
def load_sentences(file, skip_first=True, single_sentence=False):
""" Loads sentences into process-friendly format for a given file path.
Inputs
-------------------
file - str or pathlib.Path. The file path which needs to be processed
skip_first - bool. If True, skips the first line.
sin... | 7dc454ece4462d40f039f5ae14de2d711a6a582d | 661,084 |
import base64
def base64url_decode(data):
"""
base64-decodes its input, using the modified URL-safe
alphabet given in RFC 4648.
"""
return base64.b64decode(bytes(data, encoding='ASCII'),
altchars='-_') | 372792e910759dcd9516bb410712ad130ba9c276 | 661,086 |
import os
import sys
def get_default_name(defaults):
""" get basefs filesystem name if there is only one fs """
try:
logs = os.listdir(defaults.logdir)
except FileNotFoundError:
sys.stderr.write("Error: logdir '%s' does not exists\n" % defaults.logdir)
sys.exit(3)
else:
... | 2c9a27ef1508cc03b5b8dfa69dc88fd086861487 | 661,087 |
def user(user_create):
"""Exposes Django user object.
Shortcut for `user_create` fixture.
Example::
def test_this(user):
username = user.username
.. note:: User password is accessible via `password_plain` attribute.
"""
return user_create() | 44b79712635b5c8e0dba4aed9c94b2caf3303b0b | 661,088 |
def get_execution_id(evt):
"""
Parameters
----------
evt: the data passed in when the user calls the function
Returns
-------
execution name
"""
return evt['execution_name'] if evt else '' | 914bcc80a0146e0bde9d25c6658088ec01df4d0d | 661,089 |
import re
def ends_with_blank_line(contents):
"""
Returns true if the given string ends with a line that is either empty or
only composed of whitespace.
"""
return re.search('\n\s*\n\Z', contents) is not None | 1426d3de0f04b2028cfc53cdd9b27e2be9c52859 | 661,090 |
def get_native_ranges(my_core, meshset, entity_types):
"""
Get a dictionary with MOAB ranges for each of the requested entity types
inputs
------
my_core : a MOAB Core instance
meshset : a MOAB meshset to query for the ranges of entities
entity_types : a list of valid pyMOAB types to be... | 5e4b0ff3838b11f3838de2dfe8b32828780327f1 | 661,091 |
def get_list_from_file(file_name):
"""read the lines from a file into a list"""
with open(file_name, mode='r', encoding='utf-8') as f1:
lst = f1.readlines()
return lst | a7ac0fdeb6eae012962ba1e96fe390d1ddddfabc | 661,093 |
def _coerce_field_name(field_name, field_index):
"""
Coerce a field_name (which may be a callable) to a string.
"""
if callable(field_name):
if field_name.__name__ == '<lambda>':
return 'lambda' + str(field_index)
else:
return field_name.__name__
return field_... | 65d1b8c5d64627863de89295bdc4413f7bc443eb | 661,094 |
def get_source_inputs(tensor, layer=None, node_index=None):
"""Returns the list of input tensors necessary to compute `tensor`.
Output will always be a list of tensors
(potentially with 1 element).
Arguments:
tensor: The tensor to start from.
layer: Origin layer of the tensor. Will be
de... | 1c8f6eae98bf5325bdc653e125b514defa68c58c | 661,095 |
from typing import List
def compare_lists(local_list: List[str], remote_list: List[str]) -> List[str]:
"""
Comapre local and remote list of files and return the list of local files not stored in remote database.
:param local_list: list of names of local files
:param remote_list: list of names of remot... | 405a9e7e47292fcb93e4fbf07d09aead3023a14c | 661,096 |
def read_to_end(fobj):
"""
Reads lines until the line '@end' is hit.
"""
buffer = []
for line in fobj:
if line.startswith('@end'):
break
if line.startswith('@empty'):
return ''
buffer.append(line.rstrip())
return '\n'.join(buffer) | cd68e35dce3ab0ee9e49ff239131ee3f55c3024a | 661,097 |
def num_param_Gauss(d):
"""
count number of parameters for Gaussian d-dimension.
input
d [int] : dimension of data
"""
return 0.5 * d * (d + 3.0) | 84a967bff81277ec8c391a5a504e3a8a6747a22a | 661,100 |
import os
def get_full_path(file_name):
"""
Get the full path for a file based on this file's directory.
Simply joins a filename with the directory of the file this function is in.
:param file_name: a string object file name.
:return: return a full absolute path string.
"""
module_path = ... | 21ac0bd43d1f99e2df6195f97e8dd2acf706baa2 | 661,101 |
def maximum_value(items, capacity):
"""Dynamic programming solution for 0/1 Knapsack with returned items.
This solution uses O(kN) memory and does not scale well.
"""
n = len(items)
K = [[0 for w in range(capacity + 1)] for i in range(n + 1)]
for i in range(n + 1):
for w in range(capaci... | 029783d1a862640fc51e19f25a7b323e0b566d9f | 661,102 |
def obtain_list_db_tickers(conn):
"""
query our Postgres database table 'symbol' for a list of all tickers in our symbol table
args:
conn: a Postgres DB connection object
returns:
list of tuples
"""
with conn:
cur = conn.cursor()
cur.execute("SELECT id, ticker FR... | 7a6c59c56c6b1c2b15e19438f8c0e1053119c014 | 661,103 |
def update_dict_deep(original, new_values):
""" Updates dict *in-place* recursively, adding new keys in depth
instead of replacing key-value pairs on top levels like `dict.update()` does.
Returns updated dict.
"""
for key in new_values:
if key not in original:
original[key] = new_values[key]
elif isinstance... | f7fcac11f7745ee803ec4f66eb653b31deda657a | 661,104 |
import socket
import struct
def UnpackAlanCoxIP(packed):
"""Convert hex IP addresses to strings.
/proc/net/igmp and /proc/net/udp both contain IP addresses printed as
a hex string, _without_ calling ntohl() first.
Example from /proc/net/udp on a little endian machine:
sl local_address rem_address st tx... | 7bf65fc9dc570ee83d0d0cbc77199c9a908210e7 | 661,105 |
def _get_func_help(func):
"""获取函数帮助信息的第一行"""
if func.__doc__ is None:
return ''
msg = func.__doc__.split("\n")
msg[0] = msg[0].strip()
if len(msg[0]) > 0:
return msg[0]
if len(msg) > 1:
return msg[1].strip()
return '' | 2254718cc67b8ab449e4f4352174aa1fdbaf8a14 | 661,106 |
def get_int_with_default(val, default):
"""Atempts to comvert input to an int. Returns default if input is None or unable to convert to
an int.
"""
if val is None:
return default
try:
return int(val)
except ValueError:
pass
return default | 474b7b7d7c8b2ccd4966740aefbbcd5a5e3a956a | 661,107 |
def limitaxis(c,maxc,minc=0):
"""
Limit value in axis.
:param c: value
:param maxc: max c value.
:param minc: min c value.
:return: limited c value c E [minc,maxc]
"""
if c > maxc:
c = maxc
if c < minc:
c = minc
return c | d02715f22515ccb3d3e8848bde8d0665b72e7531 | 661,108 |
def _get_cache_value(key):
""" Returns a value for a cache key, or None """
address = None
try:
with open(key) as f:
address = f.read()
except FileNotFoundError:
address = None
return address | fccea8e21f8a8bb456d4a45f3f38a5434888b911 | 661,109 |
import random
import string
def RandomString(length):
"""Returns a randomly generated string of ascii letters.
Args:
length: The length for the returned string.
Returns:
A random ascii letters string.
"""
return ''.join([random.choice(string.ascii_letters)
for unused_i in range(l... | 65c6a198887dd7a2916206370201b136f47bfbba | 661,110 |
import subprocess
def command(cmd) -> str:
"""
run a command, get the output
basic time saver, not generally applicable to all linux cmds
Args:
cmd: command being ran
"""
cmda = cmd.split(" ")
print(cmda)
result = subprocess.run(cmda, stdout=subprocess.PIPE)
return (result.st... | b5fa2f911c90a04fda5712523aad34c8c9cd0d76 | 661,111 |
def is_arg_int(arg: str) -> bool:
"""
:param arg: string to try to convert
:return: bool if string can be converted
"""
try:
return bool(int(arg))
except TypeError:
return False | de958829909ee7dfe3796254c204a921ce788df7 | 661,112 |
def addrToText(mac_addr, big_endian=False, sep=""):
"""Convert a mac_addr in bytes to text."""
# Note use of reversed() - macs are returned in an unusual LSB order
# pylint: disable=superfluous-parens
return sep.join(["{:02x}".format(b)
for b in (mac_addr if big_endian else reversed... | f6996ca5804d6de90fcf65675121084cbd17fd90 | 661,113 |
def _flatten_features(rec):
"""Make sub_features in an input rec flat for output.
GenBank does not handle nested features, so we want to make
everything top level.
"""
out = []
for f in rec.features:
cur = [f]
while len(cur) > 0:
nextf = []
for curf in cur... | d84306869a28b7efb61c9b0c4803aab907ce7646 | 661,114 |
def generate_fake_oco_status(random_state, size):
"""
Generate random OCO status, mostly assigned to 200 with some 300 status codes
during a random range between 4 and 50 ticks
"""
values = [200] * size
picked_error_values_indexes = random_state.choice(
size, round(0.001 * len(values)), ... | 3dc056b2f08dd33de9ed2e5736fd2998fb3d14ff | 661,115 |
from typing import List
def find_contiguous_sum(lst: List[int], target: int) -> bool:
"""
Given a sequence of integers and an integer total target, return whether a
contiguous sequence of integers sums up to target.
[1, 3, 1, 4, 23], 8 # True (because 3 + 1 + 4 = 8)
[1, 3, 1,... | ba1f1f04d3541acd34038b027981b7850adbbdcd | 661,117 |
def sort_formula_ids(formula_ids):
"""
task1 formula_id: q_XXX
"""
return sorted(formula_ids, key=lambda x: int(x.partition('_')[2])) | 09da9854499ec976f620d0aff382acb0f5d81380 | 661,121 |
def length_each_vertices(vertices, space="world"):
""" [pm] 頂点間の距離をリストで返す
戻り値リストの n 番目は vertices[n] と vertices[n+1] の距離
Args:
vertices (list[MeshVertex]):
space (str):
Returns:
list[float]:
"""
length_list = []
for i in range(len(vertices)-1):
pnt1 = vert... | 102b741518d6d276240a1f0350cc8a5a159e4455 | 661,122 |
def list_sync(api, instance="", fields="", **params):
# type (ApiClient, str, str) -> list[dict[str]]
"""List all the groups of an instance. If no instance is provided , fetch the customer groups ( = platform feeds in lumapps)
Args:
api: the ApiClient instance to use for requests
instance: ... | 227a52e18a2324e3cd339b572eafa167e3a1fa27 | 661,123 |
def getQABits(image, start, end, newName):
"""
Function that returns an image containing just the specified QA bits.
"""
# Compute the bits we need to extract.
pattern = 0
for i in range(start, end + 1):
pattern = pattern + 2**i
# Return a single band image of the extracted QA bits,... | 8db76b2b673bcd583bf9f9eb0a0fb229da445ce0 | 661,124 |
def is_superset(obj1, obj2, path=""):
"""
Checks whether obj1 is a superset of obj2.
Parameter *obj1*:
Superset object
Parameter *obj2*:
Subset object
Parameter *path*:
Should be "" in initial call
Return value:
Returns a tuple with 2 arguments. The first argument is a boolean which is true, if o... | 01f062e3df86eb51730ecbb25f654299fb9c767d | 661,125 |
def greet(name):
"""
This function greets to
the person passed in as
a parameter
"""
print("Hello, " + name + ". Good morning!")
return("???") | 9871ee05b96a5e153e8e2e3ccd62bfcaf5d6d250 | 661,126 |
def get_file_and_head(filename, n_head=5):
"""Get the contents of a file, and the head.
Parameters
----------
filename: str
The name of the file to read.
n_head: int
The number of lines to include in the head.
"""
with open(filename, "r") as fp:
content = fp.read()
... | 034b6fda7c977ff97ed62644835a0250b030b226 | 661,127 |
import os
import json
def process_schedule(schedule):
"""Read JSON file."""
config = None
if schedule and os.path.exists(schedule) and os.path.isfile(schedule):
with open(schedule, 'r') as f:
config = json.loads(f.read())
if not isinstance(config, list):
raise Valu... | c760fe5e84ffb81c1541ac2e3955c9ffc99518f9 | 661,129 |
def read_file(filename):
"""Parse plain text data into arrays
"""
with open(filename, "r", encoding="utf8") as f:
sentences = f.read().split("\n\n")
data = []
for s in sentences:
tuples = [ln.split() for ln in s.split("\n")]
data.append(tuple(zip(*tuples)))
... | ebbf13a0ba4f2f979e3c9491e23845f14360c112 | 661,130 |
def make_str(s):
"""Casts the input to string. If a string instance is Not given, Ikke gitt or None, return empty string."""
if s == 'Not given':
return ''
if s == 'Ikke gitt':
return ''
if s is None:
return ''
return str(s) | c3af6cb891ec069be1846214ae6af3a7e11ab319 | 661,131 |
import os
def get_last_modified_file_time(path):
"""This method gets the time that the given file was last modified.
:param path: the path to the file
"""
return os.stat(path).st_mtime | 62a9fa7227f126c43d11f533ae547b107e40792a | 661,132 |
def experimento_rendijas(proba,blancos,rendijas):
"""(list, list, int) -> list
Expoerimento probabilistico de rendijas multibles"""
mat = [[0.0 for x in range(blancos+rendijas+1)] for x in range(blancos+rendijas+1)]
cada = blancos//rendijas if blancos%2==0 else (blancos+1)//(rendijas)
repite = Fals... | 05eb7d8c081a78e692ba9175bc175f78d43cd54d | 661,133 |
def get_touchdown(df):
"""
Calculates instance of touchdown (landing).
"""
df = df.copy()
return df.iloc[df['Altitude'].idxmax():][df['Altitude'] <= 2].index[0] | 314aa3f1dfd91fd0f7a287359e48c930b731aa1e | 661,134 |
import pathlib
def check_file(filename: str):
"""
:rtype: pathlib.WindowsPath
"""
try:
file = pathlib.Path(filename).absolute()
if file.exists() and file.is_file():
return file
elif file.exists() and (not file.is_file() or file.is_dir()):
raise IOError(... | 3762c8b74db154210a0169c96e09649fce1c585b | 661,135 |
def total_orgs_participated_year(data):
"""
Returns the total number of organisations participated
in the specified year. The year data is passed as parameter
to the function.
"""
return len(data.keys()) | bc7d15a5aaa70fbbe2edbd098f945b5cb20ba2a2 | 661,136 |
def format_cmd(cmd):
"""If some command arguments have spaces, quote them. Then concatenate the results."""
ans = ""
for val in cmd:
if " " in val or "\t" in cmd:
val = '"' + val + '"'
ans += val + " "
return ans | dcbcd93812fabb742b42fcdd68cbbb88acae224f | 661,137 |
def is_s3_url(path_or_url: str) -> bool:
"""
Test if *path_or_url* is a potential object storage URL.
:param path_or_url: Path or URL to test.
:return: True, if so.
"""
return path_or_url.startswith("https://") \
or path_or_url.startswith("http://") \
or path_or_url.starts... | 40d80e70ea00ef53aeaa30695f92fe69b17024da | 661,138 |
import pathlib
import platform
def data_path() -> str:
"""Get full path of data directory. Currently supporrted only for Linux and Windows
Raises:
ValueError: raised for MacOS, as it's not supported
Returns:
[str]: full path to data directory
"""
scripts_path = str(pathlib.Path(_... | 007ac75e0bc642bdd5d0f115f6d565f0cf610e46 | 661,139 |
import copy
def select_keys(d, keys):
"""Returns a dict containing only those entries in dict whose key is in keys
See also select_paths
:param d: dict to filter
:param keys: a list of keys to select
:returns: a copy of subset of d with only the specified keys
:rtype: dict
"""
return... | 1cc72071cd6c539fef2e53cd2062bb6af0c252b3 | 661,140 |
def replace_forward_slash(file_name):
"""
This method takes a string representing a file name and replaces forward slashes with ":"
This approach is consistent with how other clients deal with attempts to upload files with forward slashes
in the name.
"""
return file_name.replace("/", ":") | 0311edee118b9640c10b89cac95e3a91524aefed | 661,141 |
import re
def replace_citations(target_str, is_blog=False):
"""
replace all shorthand citations {14} in a string with either Jinja2 citation indicators or
superscript citations to render them as they appear in copy.
:param target_str: String to be edited
:param is_blog: boolean (default False) - r... | ab4f414b0227a19b2aac198e3e52cd923ddb0e77 | 661,143 |
def jet_id(jets, options):
"""
Loose jet ID taken from flashgg: https://github.com/cms-analysis/flashgg/blob/dd6661a55448c403b46d1155510c67a313cd44a8/DataFormats/src/Jet.cc#L140-L155
"""
nemf_cut = jets.neEmEF < 0.99
nh_cut = jets.neHEF < 0.99
chf_cut = jets.chHEF > 0
chemf_cut = jets.chEmEF... | d522e56625a93f75460d83673bf89af5968c12eb | 661,144 |
import argparse
def arguments():
"""
The collection of valid argument for this sample.
"""
parser = argparse.ArgumentParser(
description='Send a message to a MQ Light server.')
parser.add_argument(
'-s',
'--service',
dest='service',
type=str,
default... | 744271595e0b0ed6f9bff4d2a4058d9a0cfaaacc | 661,145 |
def get_tokens(flight_list):
"""
Create list of booking tokens to retrieve booking info.
"""
return [i['booking_token'] for i in flight_list] | 863df7f52001154a4ba16e372712f062219b9774 | 661,146 |
import os
def parse_python_path(root_dir, path_str):
"""
The incoming python string should be a string seperated by newlines:
"\n../nsound/nsound_git_ws\n../nsound/nsound_git_ws2"
This should should become a list of strings of absolute paths.
"""
paths = path_str.strip().split('\n')
... | c96a08480a581fad0c035a1e24007255dd7052ca | 661,147 |
def get_element_by_id(_id, group_list):
"""
Use next generator to find element in a group's list by identifier.
"""
return next(e for e in group_list if _id == e["id"]) | 9331de008e7bf40ad6d4fbd1d653159e9b7e079a | 661,148 |
from typing import Optional
from typing import Mapping
def _check_scale_factor(
spatial_data: Optional[Mapping],
img_key: Optional[str],
scale_factor: Optional[float],
) -> float:
"""Resolve scale_factor, defaults to 1."""
if scale_factor is not None:
return scale_factor
elif spatial_d... | bc19441ed69f9020fefdaa6ee87fb8954a429f64 | 661,149 |
from typing import List
def get_param_docstring(docstring: str) -> str:
"""
Get docstring of argument part.
Parameters
----------
docstring : str
Target docstring string.
Returns
-------
param_docstring : str
Argument part docstring.
"""
param_part_started: bo... | 469036274094d33d064c91e1755bfb2924dd4e5f | 661,150 |
def get_new_pos(old_pos):
"""This is a function that converts part-of-speech codes to abbreviated parts-of-speech"""
new_pos = ""
if old_pos.startswith('J'):
new_pos = "a"
elif old_pos.startswith('V'):
new_pos = "v"
elif old_pos.startswith('N'):
new_pos = "n"
elif old_pos... | 875b699ab7877693ae140862b0de98d980e764c0 | 661,151 |
def sanitize_metric_name(metric_name: str) -> str:
"""
Replace characters in string that are not path-friendly with underscore
"""
for s in ["?", "/", "\\", ":", "<", ">", "|", "'", '"', "#"]:
metric_name = metric_name.replace(s, "_")
return metric_name | ea108e806e3dcf7ea300746e1e42610e4e890fe8 | 661,152 |
import os
def _create_version():
"""
Helper function for building the version string
"""
version = "Unknown"
root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
try:
with open(os.path.join(root, "VERSION.txt"), 'r') as f:
version = f.read().strip()
excep... | f49bfa22b67a40dc7909c2078787508911893c03 | 661,153 |
def get_issueshortpath(issuedir):
""" Returns short version of issue dir path"""
path = issuedir.path
return path[path.index(issuedir.journal):] | e29ba5a695bff05ff12b785e3887b53e282d73e3 | 661,155 |
def get_alignment_pdb_chain(alignment):
"""
Returns a string of the chain id, e.g. 'A', 'B', etc.
:param alignment:
:return:
"""
pdb_chain_id = alignment.hit_def.encode('ascii').split()[0]
chain = pdb_chain_id.split('_')[1].upper()
return chain | d322ea53606e8d8e5dd61bd50bf0ad44fbb24182 | 661,156 |
import logging
def prevent_request_warnings(original_function):
"""
If we need to test for 404s or 405s this decorator can prevent the
request class from throwing warnings.
"""
def new_function(*args, **kwargs):
# raise logging level to ERROR
logger = logging.getLogger("django.req... | 59cdc8be4b81c1166c4f71ac6ac8bf98d2ca5e61 | 661,157 |
def strange_sequence(num1, num2):
"""
Write a function that takes two integers num1, num2 and
returns an inner function that takes in an integer limit
which will return a list of all integers from 1 to limit
(both ends are included) but overrides those number with
given rules.
>>> inner = s... | 754fd10476d0ebc4024968da3c0ff23d8b0135f4 | 661,158 |
def __get_sub_xds(ka, ka1):
"""根据上级别线段标记获取本级别最后一个走势的线段"""
xds_l = [x for x in ka.xd if x['dt'] <= ka1.xd[-1]['dt']]
xds_r = [x for x in ka.xd if x['dt'] > ka1.xd[-1]['dt']]
if not xds_r:
xds = [xds_l[-1]]
return xds
if xds_r[0]['fx_mark'] != ka1.xd[-1]['fx_mark'] and len(xds_l) > 0:... | 6bc01758a941ab18e2f6995b0e5e44af9ce8ca7d | 661,159 |
from typing import List
def calculate_magnitude(reduced_form: List[List[int]]) -> int:
"""
Generate the magnitude by reducing from inside out.
Ex: [[9,1], [1,9]]
=> [(9, 2), (1, 2), (1, 2), (9, 2)]
=> [(29, 1), (1, 2), (9, 2)]
=> [(29, 1), (21, 1)]
=> [(129, 0)]
=> ... | b0a67b3423b9094b0423eb552e841ada0b61bf77 | 661,160 |
def process_lines(file_reader, corpus_name:str)->list:
"""Strips and splits the lexicon lines.
The case is kept intact for the 'switchboard' corpus, but is lowered for all others
Args:
file_reader: file reader object of lexicon
corpus_name (str)
Returns:
(list): split lexicon li... | d78867a6c6687a6857e9ab9d05dc689cc36f5b28 | 661,161 |
def documentation_link(chapter):
# type: (str)->str
"""
Creates a link to the documentation.
This method is useful for showing a link to the ZSL documentation in case of any misconfiguration, etc.
:param chapter: Chapter name in to which the link points. Use underscores instead of spaces.
:retu... | 3fa25188811b1fece777e95755e5ebdc5cb1a4b8 | 661,162 |
def stcqt(sig, fr, cqbank):
"""Implement Judith Brown's Constant Q transform.
Parameters
----------
sig: array_like
Signal to be processed.
fr: int
Frame rate in Hz, or int(SR/hop_length).
cqbank: ConstantQ Filterbank class
A pre-defined constant Q filterbank class.
... | dc9b46323c530fafde2e29ca105b8e4ca33e0c18 | 661,164 |
def derive_ppop_state(obj, state_dict):
""" Deriving ppop code and ppop state name
Args:
obj: a dictionary containing the details we need to derive from and to
state_dict: a dictionary containing all the data for State objects keyed by state code
Returns:
Place ... | 0e3aef99a345faeb066c1aeb09ed6700fe09847e | 661,165 |
def get_grid_offset(function, axis):
"""
For a function, return the grid offset for a specified axis.
Parameters
----------
function : devito Function
The function to get the offset of
axis : int
The axis for which offset should be recovered
"""
if function.is_Staggered:... | fbfa549008d1b856dcc560e5d10f9780a116e5bd | 661,166 |
import requests
import time
def unblock_ip(ip, logger, dashboard_log, firewall_ip_and_port):
""" This function unblocks given 'ip' using firewall wrapper.
:param ip: IP to unblock.
:param logger: Logger object.
:param dashboard_log: Log messages which will be shown on dashboard.
:param firewall_i... | 01a49003391eb10e25be016585c64ad989d1af9b | 661,167 |
import pandas as pd
def year_month_day(raw_dates):
"""
Split a date column into three columns: Year, Month, Day
:param raw_dates: a Series of dates as type string or datetime64[ns]
:returns: A DataFrame with columns ['year', 'month', 'day']
"""
# Convert to datetime64[ns] if possible
data... | f2a7d893c76157009fbd8b60d1d1c67d324a6ca6 | 661,168 |
from typing import Any
def test_for_small_float(elem: Any, precision: int) -> bool:
"""
Returns True if 'elem' is a float whose rounded str representation
has fewer significant figures than the numer in 'precision'.
Return False otherwise.
"""
if not isinstance(elem, (float)):
return... | 61b0514106f98e614b4bae7180b7997ab49d532e | 661,169 |
def what_filters(z, fset, wave_lo=1300., wave_hi=2600., picky=True):
"""
Given a redshift and a full filter set, return the filters that probe
the rest UV continuum only.
"""
# Compute observed wavelengths in microns
l1 = wave_lo * (1. + z) * 1e-4
l2 = wave_hi * (1. + z) * 1e-4
... | acd38717a3120c49e830198327728158a7991a95 | 661,170 |
def SplitSequence(seq, size):
"""Split a list.
Args:
seq: sequence
size: int
Returns:
New list.
Recipe From http://code.activestate.com/recipes/425397/ (Modified to not return blank values)
"""
newseq = []
splitsize = 1.0/size*len(seq)
for i in range(size):
newseq.append(seq[int(round... | 7f836854a46a13f99c2aaac72321656df65a837b | 661,171 |
def check_win(player, board):
"""Checks if the inputted player has won"""
# These are all the winning lines/combinations
lines = [
(0, 1, 2),
(3, 4, 5),
(6, 7, 8),
(0, 3, 6),
(1, 4, 7),
(2, 5, 8),
(0, 4, 8),
(2, 4, 6),
]
# For each on... | 39f745c4f1a2b885142fd35825a23eca314a9429 | 661,172 |
def file_hierarchy():
"""Return a sample nested file hierarchy."""
return {
'file_a.txt': 'file_a',
'path': {
'file_b.txt': 'file_b',
'sub': {
'file_c.txt': 'file_c',
'file_d.txt': 'file_d'
}
}
} | 9a66868cc697304359d23764c3d17ff9265d3642 | 661,173 |
def bin_add_U2(bin1, bin2):
"""
Adds two binary numbers in U2
:param bin1: First number in U2
:type bin1: string
:param bin2: Second number in U2
:type bin2: string
:return: Result of adding in U2
:rtype: string
"""
result = ""
moving = 0
for i in range(len(bin1) - 1, ... | 41a12f26647635e12bc28684ed092305c9602839 | 661,174 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.