content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def doc_to_text(doc, sent_delim='\n'):
"""
Convert document object to original text represention.
Assumes parser offsets map to original document offsets
:param doc:
:param sent_delim:
:return:
"""
text = []
for sent in doc.sentences:
offsets = map(int, sent.stable_id.split("... | afdee8854392fa1133db38673118fdbac87314eb | 578,937 |
def save_image(args, image, media_info, output_path):
"""Save the image to `output_path`
"""
image = image.convert("RGB")
try:
image.save(output_path, optimize=True, quality=args.image_quality)
return True
except KeyError:
return False | a001df6c3acdc0b121b115619296e505efe18e57 | 578,938 |
def fmap(f, xs):
"""
Map a function f over the values in an iterable xs and return a list
This in effect is the same function as `map`, only returning a list for
convenience
"""
return list(map(f, xs)) | 2b01ea8a48f8592dfdfcbd494da9339cc1870682 | 578,939 |
import re
def normalised_csv_file(file_path):
"""Returns the text of the file replacing \t with , removing empty lines, etc.
to be processed by the csv module.
"""
file_contents = open(file_path).read()
file_contents = file_contents.replace("\t", ",")
file_contents = re.sub(r' \n', '\n... | df423ee52ee5c6499b833bd2a421e8cc145c927d | 578,942 |
def all_conv_lr_schedule(epoch_num):
""" Learning rate schedule taken from Striving for Simplicity"""
lr = 0.01
if epoch_num < 200:
return lr
elif epoch_num < 250:
return 0.1 * lr
elif epoch_num < 300:
return 0.01 * lr
else:
return 0.001 * lr | 946fd7dd845dd77bc86facc7aaf169245e478d05 | 578,943 |
import requests
def http_get(url):
"""
Sends and caches an HTTP GET request.
:param str url: the URL to request
"""
response = requests.get(url)
response.raise_for_status()
return response | 581fae19107343d24c202fa23d0f82e4230c4d12 | 578,946 |
def encode_all(
header: bytes, stream: bytes, funcs: bytes, strings: bytes, lib_mode: bool
) -> bytes:
"""
Combine the various parts of the bytecode into a single byte string.
Parameters
----------
header: bytes
The bytecode's header data.
stream: bytes
The actual bytecode i... | 9325a01b6b485feb3c634b56df1da9b6c9182e04 | 578,947 |
def build_kde_parameters_matrix(jsons_list):
"""Contructs the list of good QAOA input parameters from jsons provided."""
good_params_matrix = []
for json in jsons_list:
good_params = json["good_params"]
good_params_matrix = good_params_matrix + good_params
return good_params_matrix | facf0297297d1c8aa90119b2caa951f801ef9092 | 578,951 |
import requests
def github_stars(user, repo, token):
"""Get number of github stars a repo has"""
url = "https://api.github.com/repos/%s/%s" % (user, repo)
headers = {"Authorization": "token {}".format(token)}
data = requests.get(url, headers=headers).json()
return data.get("stargazers_count", 0) | 9ea62b970982e4110cada5f4788b914a42b7ba4b | 578,956 |
def mesh_ratio(N):
"""
Calculates the mesh refinement ratio between consecutive meshes.
Arguments:
----------
N: list, Number of elements / avg_density in test (depends on what applies).
Returns:
--------
mesh_ratio: list of float, mesh refinement ratio between consequtive meshes. ... | 610018ee1392d7d2ac4ef99d3309c572a94d4447 | 578,957 |
def calcualte_length(data):
"""
LDAP protocol doesnt send the total length of the message in the header,
it only sends raw ASN1 encoded data structures, which has the length encoded.
This function "decodes" the length os the asn1 structure, and returns it as int.
"""
if data[1] <= 127:
return data[1] + 2
else:... | 7fdb310c2aee5fbf9a642be13fe8021bc365ed85 | 578,959 |
def clone(item, exclude=None, update=None):
"""Return a clone of the SQLA object.
:param item: The SQLA object to copy the attributes from.
:param exclude: If provided, should be an iterable that contains the names
attributes to exclude from the copy. The attributes `created_at` and
`id` ar... | 50a91ddad64df26acf5635c61038f68680a9a46f | 578,967 |
def intervals(nms # list of indices
):
"""
Return intervals between numbers.
::
>>> intervals([1, 2, 3])==[(1, 2), (2, 3)]
True
"""
return list(zip(nms[:], nms[1:])) | 5cedb77bb582caa1ec757068c465797cde717f24 | 578,972 |
def bounds(measurement, uncertainty):
"""Return resolved bounds based on measurement and uncertainty."""
if uncertainty:
return measurement - uncertainty, measurement + uncertainty
else:
return measurement, measurement | 4ba8a5feb141b22cee4fc1f891161cddfef24b38 | 578,973 |
import math
def dcg(labels, at=None):
"""Compute DCG given labels in order."""
result = 0.0
position = 2
for i in labels:
if i != 0:
result += 1 / math.log2(position)
position += 1
if at is not None and (position >= at + 2):
break
return result | 09b7d614991d21faa1ad213aafb039fbc1724bc6 | 578,974 |
def link_fedora_file(sid):
"""
Creates an html link tag to a file in Fedora.
:param sid: a file id
:return: link to the file content
"""
return '<a href="http://easy01.dans.knaw.nl:8080/fedora/objects/{}/datastreams/EASY_FILE/content" target="_blank">{}</a>'\
.format(sid, sid) | ef371306ff69658c611dbad9cfd977e1adc84382 | 578,977 |
def intersects_byid(geoms1, geoms2):
"""
Return a table with a row for each features of *geoms1*, containing the id
of each *geoms2* intersecting features (almost like an intersecting matrix).
Parameters
----------
geoms1: GeoSeries or GeoDataFrame
Collection on which the intersecting t... | 0b2614b78c5293c9b0244fba70c0fd9b0fabbcf3 | 578,978 |
def function_for(mod, command, ending="_command"):
"""
Return a reference to the function for a given command.
"""
return mod.__dict__[command+ending] | 7427aff891e126e613cf7262cc3fcbe1386fc532 | 578,979 |
def bento_archive_path(bento_service, tmpdir): # pylint:disable=redefined-outer-name
"""Create a new TestBentoService, saved it to tmpdir, and return full saved_path
"""
saved_path = bento_service.save(str(tmpdir))
return saved_path | b13869072d65c871f39992804cbd67aaaffb0091 | 578,982 |
def runSafely(funct, fmsg, default, *args, **kwds):
"""Run the function 'funct' with arguments args and
kwds, catching every exception; fmsg is printed out (along
with the exception message) in case of trouble; the return
value of the function is returned (or 'default')."""
try:
return funct... | f68ef7443b60d66737665c0380dcece66fcc5cbe | 578,985 |
def largest_cells(rows):
"""Return a list with the widths of the largest cell of each column."""
transpose = list(zip(*rows))
widths = map(lambda row: map(len, row), transpose)
return list(map(max, widths)) | 02c2b6b2f60ec5cde358298bbd0fa654d718388d | 578,986 |
import json
def read_config_file(filename):
"""
Utility function for reading configuration file (JSON)
"""
data = []
with open(filename, 'r') as file:
data = file.read()
return json.loads(data) | 64ffc1a9f311357f4af991f00d1fd97d31a8f5ce | 578,987 |
def determine_dotnet_tool_name(coreclr_args):
""" Determine the dotnet tool name based on the OS
Args:
coreclr_args (CoreclrArguments): parsed args
Return:
(str) Name of the dotnet tool to use
"""
if coreclr_args.host_os == "OSX" or coreclr_args.host_os == "Linux":
return ... | 8b1d557c730477e4c7898cb3f5d1a89404dec706 | 578,988 |
def Pluralize(num, word, plural=None):
"""Pluralize word based on num.
Args:
num: int, the number of objects to count.
word: str, the word to pluralize.
plural: str, the plural form of word if not "add s"
Returns:
str: the plural or singular form of word in accord with num.
"""
if num == 1:
... | c7a6bdf6287c28767014ed225dd05bbec113aae5 | 578,995 |
def conv_bright_lib_to_ha(brightness) -> int:
"""Convert library brightness scale 0-16 to HA scale 0-255."""
brightness = int(brightness) * 16
if brightness > 255: # force big numbers into 8-bit int range
brightness = 255
return brightness | 08f4e289d8e7113a18d9f84e25f8089a64baafb4 | 578,996 |
def get_implementation_files_size_data(sources_dir, implementation_files_by_size, rows_count):
"""
Builds table rows list containing data about implementation files sizes (largest/smallest).
:param sources_dir: configured sources directory
:param implementation_files_by_size: list of implementation fil... | a3d65837b0eafb69c5a013bf5e6f1c8498e914eb | 578,998 |
def exif2gps(exif_data):
"""
Transform coordinate from DMS into D.D
:param exif_data: image exif data:
:return: degrees in D.D format
"""
if not exif_data:
return None
if isinstance(exif_data[0], tuple):
degree = float(exif_data[0][0] / exif_data[0][1])
else:
degr... | e4ce79a8b63ef700c8eefd4bf9de5debd405fd53 | 578,999 |
import json
def api_exception_to_message(e):
""" Convert API exception to human digestable error message - parsing
out the shed generate message if possible.
"""
message = str(e)
if hasattr(e, "read"):
message = e.read()
try:
# Galaxy passes nice JSON messages as their ... | b2de6377f7dad9973a5b3fa0d9ba824a49317f56 | 579,001 |
def get_year(curr_date):
""" Returns the current year."""
return curr_date.year | 9c76462af0272a527b9866c2c8bdb55d4cbcbc66 | 579,003 |
def letters_to_numbers(letters):
"""
Function that converts a given string into a list of numbers respective to each character.
:param letters: string
:return: numbers: list of numbers
"""
numbers = []
for letter in letters:
tmp = ord(letter) - 97
numbers.append(tmp)
ret... | 621f9df2433e6107f1a5b215b4a03fbbbf91ee47 | 579,007 |
def bc01_to_c01b(input):
"""
This helper method uses dimshuffle on a 4D input tensor assumed to be bc01 format (batch, channels, rows, cols)
and outputs it in c01b format (channels, rows, cols, batch). This operation is used for convolutions.
Parameters
----------
input : Tensor4D
A 4D ... | aa399e8882fd827b7f3ad0b69d7e9f4a1f26c756 | 579,013 |
def text_from_file(file):
"""
If the 'file' parameter is a file-like object, return its contents as a
string. Otherwise, return the string form of 'file'.
"""
try:
s = file.read()
return s
except AttributeError:
return str(file) | afdfa33e4a3d3b83990048fbc01aebc1623b0d89 | 579,014 |
def isLambda(v):
"""
Test if a given value is a lambda function
@type v: Anything (preferable a lambda function)
@param v: Some value
@rtype: Boolean
@return: True, if the value is a lambda function
"""
return isinstance(v, type(lambda: None)) and v.__name__ == '<la... | 80838a1413625e2202cb140c1590bc890cab7e31 | 579,016 |
def string2type(i_val):
"""
Convert an input string to a Python type
"""
# Force value to Python type
try:
return int(i_val)
except ValueError:
try:
return float(i_val)
except ValueError:
if i_val.lower() == 'true':
return True
... | 2baa52ee32243a172358231109d32e2ca49ee163 | 579,017 |
def get_index_values(df, level):
"""Gets index values from a DataFrame MultiIndex.
Args:
df: A DataFrame.
level: The integer position of the level in the MultiIndex, or the name of
the level.
Returns:
Vector of index values.
"""
return df.index.get_level_values(level).values | 10e84ed83d3411f9f7636d71079b892401d2b696 | 579,020 |
import re
def _split_colon(s, maxsplit=1):
"""Split on unescaped colon"""
return re.compile(r'(?<!\\):').split(s, maxsplit=maxsplit) | eea4e9ccffa7d004cdfaff2195bdfa2bef52f656 | 579,021 |
from bs4 import BeautifulSoup
def scrape_keywords(contents, el):
""" Scrape page contents for keywords
Args:
contents (BeautifulSoup): contents to scrape
el (str): element class to look for
Returns list of tags ([str])
"""
soup = BeautifulSoup("<div></div>", "html.p... | 1cde38d4a62da2a59e9862d48955bc5dc4c32456 | 579,025 |
def isbool(value):
"""
check if the value is bool
Parameters
----------
value : any
can accept any value to be checked.
Returns
-------
bool
True if the value is 1 ,0 , True or False.
Flase for anything else.
"""
temp=str(value).lower()
if temp == '... | 2a9e2c9f94d7304fda39ed200f739e98fee59297 | 579,029 |
def split_tgt_sequence(tgt, bos, eos):
"""
Split gold target into previous tokens and prediction target.
For examples in text, `[hello, world, !] -> [<bos>, hello, world, !], [hello, world, !, <eos>]`
Args:
tgt: target sequence
bos: begin-of-sequence index
eos: end-of-sequence i... | ac3a4b784329a7119dc2cd7a47cc603f4e2c0445 | 579,030 |
from typing import List
def get_total_distance(
routes: dict, matrix: List[List[float]], include_origin: bool = True
):
"""
Calulate total distance on a route.
:routes: dict of vehicle routes with ordered stop indicies
:matrix: list of lists of travel distances between nodes (in... | de8b2beb47d1fcd9f6e5f43b5516ee2bb2b829a7 | 579,031 |
def param_check(request):
"""
Check that required parameters were passed.
Args:
request(rest_framework.request.Request): GET request with input parameters.
Returns:
dict: Dictionary with success or error key and a message.
"""
if request.method != "GET":
return {"error... | cfab0f6aedc187e0c442f2ede8eda712d3155c62 | 579,034 |
import requests
import json
def get_store_results(payload) -> list:
"""
Request store results from Google Places API.
:param payload: a dictionary of parameter required for the API request
:precondition: the Google servers respond with either a properly formatted response or a faulty status code
... | 5d79cfb062b3e12a0c7bdf3b9fa170b896920764 | 579,036 |
def shard_filename(path,name):
"""
Renders the filename for a shard
"""
return f'{path}shard{name}.hnsw' | 210d6ee766985ad203a9b4dad15085854f4bb280 | 579,038 |
import math
def fpart(x):
"""Return fractional part of given number."""
return math.modf(x)[0] | e44b9d9cc0dbeea30d8a1041f7bee6695f9a311f | 579,040 |
def average_pair(array, target):
"""
Time: O(n)
Space: O(n)
Returns true if there is a pair of numbers in the array that
when averaged are equal to the target. False otherwise
:param array: positive or negative int or floats
:param target: positive or negative int or float
:return: Bool
... | 67953711a321c9c049886f0d905a4f09d824560f | 579,043 |
def loader_decode_pcr8(cmdline):
"""
Reverse the encoding for a kernel command line we've read from EV_IPL.
"""
assert(cmdline.endswith(b"\0\0"))
return cmdline.decode("utf-16le")[:-1] | 328f78214c29663c12cdfae077f8979b2569d51b | 579,049 |
def row_val_lt(M, col_name, boundary):
"""Picks rows for which cell is less than to a specified value
To be used as a 'func' argument in choose_rows_where, remove_rows_where,
or where_all_are_true (see module documentation).
Parameters
----------
M : numpy.ndarray
structured array
... | 91c9cb371ac942d3b60e7c6f7a2323038011aa11 | 579,050 |
def _map_fragment_list(flist, reflist):
"""
Map all frgaments in flist to the closest
(in RMSD) fragment in reflist.
Returns a list of reflist indices.
@param flist: list of protein fragments
@type flist: [L{Fragment}, L{Fragment}, ...]
@param reflist: list of reference (ie. library) frag... | 71c9e6e51aa4a905c4923177924498943628c5ad | 579,051 |
import random
import string
def device_name_list(min_devices=0, max_devices=10, unique=False):
"""
Return a function that returns a random list of device names based on
parameters.
:param int min_devices: the minimum number of device names to generate
:param int max_devices: the maximum number of... | b23b7a38e9af95ebfa813f5e8bad51b29e2c44e3 | 579,054 |
from typing import Tuple
def calcOptimalVarStopLoss(b: float, vol: float, entry: float) -> Tuple[float, float]:
"""Calculates the optimal stop loss amount using the value at risk approach.
Parameters
----------
b : float
The volatility multiplier.
vol : float
Historical volatilit... | 3c71bc49e6c695702efb8fdfadc63eb89035efc4 | 579,060 |
def getPlayerMove(words, tries):
"""Let the player enter a password guess."""
while True:
print('Enter password: ({} tries remaining)'.format(tries))
move = input().upper()
if move in words:
return move
print('That is not one of the possible passwords listed above.') | 6c57c7b6bc9b2251caf22f09c88a2a8bf8059604 | 579,062 |
def identityFeatureExtractor(state, action):
"""
Return a single-element list containing a binary (indicator) feature
for the existence of the (state, action) pair. Provides no generalization.
"""
featureKey = (state, action)
featureValue = 1
return [(featureKey, featureValue)] | 45a3f9bb52c5c838b7b0b69c2a2eb6707dbc82e2 | 579,064 |
def replace_in_keys(src, existing='.', new='_'):
"""
Replace a substring in all of the keys of a dictionary (or list of dictionaries)
:type src: ``dict`` or ``list``
:param src: The dictionary (or list of dictionaries) with keys that need replacement. (required)
:type existing: ``s... | 2688a1de4dbadc7bbcb81367414b7778f00010c6 | 579,065 |
def rk4(fun, tn, h, yn):
"""Rugge-Kutta 4, single step
Args:
fun (func): function in t (float) and y (ND numpy array)
tn (float): time
h (float): time step
yn (n-d array): values as of tn
Returns:
n-d array: values as of tn+1
"""
k1 = fun(tn, yn)
k2 = fu... | 0ea5d2de075fc319247e80f67b68a62d98bc16c9 | 579,067 |
import csv
def read_dict(filename, key_column_index):
"""Read the contens of a CSV file into a dictionary
and return the dictionary.
Parameters
filename: the name of the CSV file to read.
key_column_index: the index of the column
to use as the keys in the dictionary.
Return... | a4f0356d5b520afd8a840757dc54ee40b2a262e5 | 579,069 |
def get_user_tables(conn):
"""Retrieve all user tables."""
query_string = "select schemaname, relname from pg_stat_user_tables;"
with conn.cursor() as cursor:
cursor.execute(query_string)
tables = cursor.fetchall()
return tables | 36a8b76d2b0ed2c4f00bbdd9d61f6ac0d2ea2e60 | 579,077 |
def get_zpve(freqs):
"""
Return zpve in au for given freq in 1/cm.
"""
zpve = 0.0
for freq in freqs:
freq = float(freq)
zpve += freq
return zpve * 0.5 / 219474.63 | e55f640be5f2aad07a10da21fac83c2a98003201 | 579,078 |
def get_job_args(job):
"""Returns arguments of a job.
:param Job job: An apscheduler.job.Job instance.
:return: task arguments
:rtype: list of str
"""
return job.args[5:] | de73353a2ab6a4a0a3b7e376d490dd33f5eb5c33 | 579,085 |
def CreateProgressBar(iteration, total, prefix = '', suffix = '', decimals = 1, length = 100, fill = '█', printEnd = "\r"):
"""
Creates a progress bar with the given details
:param iteration: Current iteration
:type iteration: int
:param total: Total iterations
:type total: int
:param prefix: Prefix string... | 9be58eaf0e325dbd2d92f3daa6908cc017f9d68b | 579,087 |
def set_shell_access_setting(
self,
shell_access_setting: str,
) -> bool:
"""Set Shell Access setting
.. list-table::
:header-rows: 1
* - Swagger Section
- Method
- Endpoint
* - shell
- POST
- /shell/shellAccessSetting
.. warning::
... | f38bd658901604b46d08bcb9074a7617bfbf3219 | 579,091 |
def check_not_private(input_file):
"""
Check file does not include the Private tag.
"""
allowed = True
private_tag = '<Private>TRUE</Private>'
with open(input_file) as r:
content = r.read()
if 0 <= content.find(private_tag):
allowed = False
return allowed | ad6915a5f70bbedbd2a33bb552aa252dc5cc5e2a | 579,093 |
def _span(r):
"""Distance in a Range1D"""
return abs(r.end - r.start) | 7ff88414d7bbde00174e174e2483df775a6ff332 | 579,094 |
def n_carbon(reaction):
"""number of carbon atoms
Returns
-------
int
number of carbons for all metabolites involved in a reaction
"""
return sum(metabolite.elements.get('C', 0) for metabolite in reaction.metabolites) | 42ca2a4a7fd10d8a84b9125d7efabcb16a07faf1 | 579,097 |
import collections
def average_dicts(d1, d2, ratio):
"""Average 2 dictionaries d1 and d2.
ratio=0 means all d1, and ratio=1 is all d2
Args:
d1: dict
d2: dict
ratio: float
Returns:
OrderedDict
"""
dd = []
assert set(d1.keys()) == set(d2.keys())
for key in d1:
dd.append((key, (1. -... | c44f122b9f095ff03ec04a0e31e6dfa9a88e635f | 579,101 |
import torch
def gradient_overlap(grad, V, num_classes):
"""Compute the overlap of the gradient and an eigenspace.
Mathematical background: We consider a space, spanned by a set of orthonormal
vectors S_V = span(v_1, ..., v_C). This spaces is represented by the (D x C)-matrix
V = (v_1, ..., v_C). The... | 36f50af45a55a0434b6d87998664127d630708a9 | 579,104 |
def extract_dates_parameters(data, date_key):
""" Return a list of dates extracted from the data dictionary along with the modified data dictionary"""
dates = data.pop(date_key)
return dates, data | 71a69461a38ac880a86fe903f1f6fe43eac86306 | 579,105 |
def obtain_models_classes_clafile(cla_file_path):
"""
Takes the path to a .cla file and returns two lists. The returned categories list corresponds to a list of
strings that contains the class values. The second list contains a set of arrays that contains the number of the
models in the corresponding cl... | e95bed4a2418a0834adb64e66c3616c08da8af2a | 579,106 |
def good_row(sudoku_board, row_num, num):
"""
Checks to make sure that a given row in a sudoku is possible if an int
num is placed into that row
"""
rows = [sudoku_board[i, :] for i in range(9)]
if num not in rows[row_num]:
return True
return False | d7728e78c54ca2608362f457e42f3497505a9291 | 579,107 |
def ToDict(obj):
"""Convert model into a json serializable dict."""
# The properties function is part of db.Model.
return dict([(p, str(getattr(obj, p))) for p in obj.properties()]) | 4f39743edd889897da36a1f27eaa987658019a38 | 579,116 |
def flag_invalid_entry(row):
"""Flag entries to be filtered
Args:
row (pandas.Series)
Returns:
filtered (str): '-' for valid entrr, otherwise invalid.
Example:
Case 1:
chr pos rescued ref_count alt_count
chrN 123 by_equivalence 30 ... | 84d867d0d7f1a2b49da50b1d259b01749c75c9f2 | 579,119 |
import logging
def exp_lr_scheduler(optimizer, cur_epoch, lr_decay=0.1, lr_decay_epoch=7):
"""Decay learning rate by a factor of <lr_decay> every <lr_decay_epoch> epochs"""
if ((isinstance(lr_decay_epoch, int) and cur_epoch % lr_decay_epoch == 0) or
(isinstance(lr_decay_epoch, list) and cur_epoch ... | f481f32ad9d2ed1a65850531131a883e20851d1e | 579,125 |
def is_valid_total_length(index,
date_to_sent_mapping,
all_sent_dates,
timeline_properties):
"""
Checks whether adding the sentence in focus would not violate
the constraint of limiting the total number of sentences in a
timel... | 75dda3386a5f5899e2e8c9b418357e4c69c5817f | 579,127 |
import json
def prettify(tags):
"""Format tags for json output."""
return json.dumps(tags, sort_keys=True, indent=4, separators=(",", ": ")) + "\n" | e4f10038524800372b8b46b2e2bab009708d7b09 | 579,128 |
def list_by_context(request, model_cls, context):
"""List records by a given context
"""
model = model_cls(request.model_factory)
offset = int(request.params.get('offset', 0))
limit = int(request.params.get('limit', 20))
kwargs = {}
if 'external_id' in request.params:
kwargs['extern... | 2dfaa976cc96f62ad44f99f1c4686bf02b3b3a28 | 579,130 |
def selectionSort(array):
"""Apply selection sort to an array. Returns a sorted array."""
for i in range(len(array)):
min_index = i
for j in range(i+1, len(array)):
if array[min_index] > array[j]:
min_index = j
array[i], array[min_index] = array[min_index], ar... | cc2ce08c311e59a33f2496cd44e639f656db1340 | 579,136 |
def _json_container_dates(containers):
"""
Moves container "status date" to a JSON friendly value.
Unit tested: test__json_container_dates
:param containers: The containers found from docker ps.
:type containers: list
:returns: The containers found from docker ps, with JSON friendly dates.
... | 25c05068ae56e8f58c98d17308e81b8b1cde3b36 | 579,141 |
def compute_human_action(arbitrator, human_obs, model_free, model_based):
"""Compute human action by compute model-free and model-based separately
then integrate the result by the arbitrator
Args:
arbitrator (any callable): arbitrator object
human_obs (any): valid in human observation space... | b8c24dfd83d0ca9e200a778e6f6798c8ad7e86f5 | 579,145 |
import ipaddress
def get_first_usable(ip_network):
"""Given a network, determine the first usable IP address.
Args:
ip_network (str): An IP network in string format that is able to be converted by `ipaddress` library.
Returns:
str: IP address formatted string with the first usable IP add... | 56dbffc6ab513dd9f2696692b4c7342d3dbf1e00 | 579,147 |
def _extract_int_request(request, param_name):
"""Returns an integer, or None if the parameter doesn't exist or is 'null' """
val = request.GET.get(param_name, None)
if val == '' or val == 'null' or val is None:
return None
else:
return int(val) | dd0475908c8f0c2dc3deb822870dec1850570b19 | 579,149 |
import inspect
import hashlib
def hash_strategy(strategy):
"""
Hash the source code of a strategy
"""
try:
source_code = "".join(inspect.getsourcelines(strategy)[0])
except OSError: # Some classes are dynamically created
source_code = "".join(inspect.getsourcelines(strategy.strate... | 2392302d9941100a0140cd71a26bff1fa7bae06c | 579,152 |
import time
import random
def unique_id(name):
"""
Generate a unique ID that includes the given name,
a timestamp and a random number. This helps when running
integration tests in parallel that must create remote
resources.
"""
return '{0}-{1}-{2}'.format(name, int(time.time()),
... | 878eed98834372a79d1a8d129b9b59f47d0b3d59 | 579,158 |
def metade(n):
"""
Dividir número pela metade
:param n: número a ser dividido
:return: resultado da divisão
"""
n = float(n)
n = n / 2
return n | 10141773e2bda24743dbbb9a83b1095dd369e72c | 579,160 |
def processHoles(code, holes_decls):
"""Finds all hole symbols in the SMT-LIB code of the program and replaces them with
appropriate references to their synthesis functions. Does nothing in case of
verification.
:param code: (str) Source code (in arbitrary language) of the program.
:param holes_dec... | 78daf2434e0638415fbde44f2d9fbeb97bcadab8 | 579,162 |
def concatenate(list_to_summarize, separator=', '):
"""Concatenate strings in a list.
List items that are not strigns will be converted to strings.
"""
for i, x in enumerate(list_to_summarize):
if not isinstance(x, str):
list_to_summarize[i] = str(x)
return separator.join(list_t... | 700d847b75c0c598db7d597237d1ffc74aec9592 | 579,168 |
from pathlib import Path
from typing import List
from typing import Tuple
def read_lines_pairs(filename: Path) -> List[Tuple[str, str]]:
"""Reads a whitespace-delimited file containing two paired entries per line (i.e. a serialized Dict).
Args:
filename (Path): The full path of the file to be read.
... | e43d4206c2905acd43806454c77e4d5433d364a6 | 579,169 |
def get_terminal_subgraph(g):
"""
Return the subgraph induced by terminal nodes in g
:param g:
:return:
"""
terminals = {node for node, d in g.nodes(data=True) if 'nt' not in d}
return g.subgraph(terminals).copy() | dfef760209436efdea0b219dd6d452f153b8d5a7 | 579,177 |
def cropped_to_orginal(pts, length, center, resize):
"""
Get original coordinate of pts inside a cropped image.
Params:
:pts: list of points inside cropped images.
:length: we expect the original image to be a square one,
this value is the size of the image.
:center: center of the c... | b94a3f2347a160268c39a75ea352b83b3be0eedd | 579,182 |
def extra_fields_from_exception(exception):
"""Exception into a dict to be passed to logger
Standardise the way we send exception messages so they can be filtered in
kibana, also make it easy to add extra information in future.
"""
return {
'exception_class': type(exception).__name__,
... | 35e1af98e057f1e7cf90b0fe7445b4d3f97e7d62 | 579,187 |
def cleanup_test_name(name, strip_tags=True, strip_scenarios=False):
"""Clean up the test name for display.
By default we strip out the tags in the test because they don't help us
in identifying the test that is run to it's result.
Make it possible to strip out the testscenarios information (not to
... | 46427eeac8855fe8e77e8d2f77c32ccedc51283c | 579,188 |
def _strip_shape(name: str) -> str:
"""Strip the dimension name."""
if name[0] == "/":
return name[1:]
return name | ba6329bdca1cf4e7c4db7daf0fcbb3c5c5f475b7 | 579,191 |
import random
def generate_cnf(n_vars, clauses, k=3, seed=None):
"""
This function generates a random CNF formula for the Half-SAT problem
Args:
n_vars (int): the number of variables in the formula
clauses (int): the number of clauses that compose the formula
k (int, optional): ... | 3b9936f7d1a55b1095dcead69f73ebecafecf99e | 579,192 |
def norm(module, init_module, p=2, q=2):
"""
Calculates l_pq norm of a parameter matrix
l_p norm of incoming weights to each hidden unit
l_q norm on the hidden units
"""
return module.weight.view(module.weight.size(0), -1).norm(p=p, dim=1).norm(q).item() | 0edf06e1b278cddc6504b75d9adb0ed6bec5d45f | 579,193 |
def PostUploadHook(cl, change, output_api):
"""git cl upload will call this hook after the issue is created/modified.
This hook modifies the CL description in order to run extra GPU
tests (in particular, the WebGL 2.0 conformance tests) in addition
to the regular CQ try bots. This test suite is too large to ru... | 51f66a8ef3616156a1a12fb4694089df84325bc2 | 579,194 |
def stereographic_equal_angle_projection_conv_XY_plane_for_MTs(x,y,z):
"""Function to take 3D grid coords for a cartesian coord system and convert to 2D stereographic equal angle projection."""
X = x / (1-z)
Y = y / (1-z)
return X,Y | f13d7368b7c4f8611ef12f59dc8f0929a68d0bf0 | 579,200 |
def get_direct_url(data: dict) -> str:
"""
Returns the direct video URL from the returned data by YoutubeDL, like
https://r1---sn-vg5obxn25po-cjod.googlevideo.com/videoplayback?...
"""
return data['entries'][0]['url'] | 731d654ffd715dd677046c8362ef09420838d9de | 579,201 |
from pathlib import Path
def get_rel_path(dirpath: Path, basepath: Path = Path().resolve()):
"""
Get dirpath as relative to basepath. This handles corner cases better than
Path.relative_to, uses ".." path notation so that the relative path is
always obtained no matter where the two paths are located. ... | ad3a7fdc117aaecc95e975bbb3a7816bd237a62e | 579,203 |
def pts_from_rect_outside(r):
""" returns start_pt, end_pt where end_pt is _outside_ the rectangle """
return (r[0], r[1]), ((r[0] + r[2]), (r[1] + r[3])) | 615a0c7a546a72a6375a8ae94fe0052922633d12 | 579,205 |
def getParallelStringQuery(numProcesses):
"""
Generates the hint for parallel execution.
"""
parallelString = ''
if numProcesses > 1:
parallelString = ' PARALLEL(' + str(numProcesses) + ') '
return parallelString | 7cf795fef9799ccd98d6c71b2e3d39e9b3dd170f | 579,209 |
def template_used(resp, template_name):
"""
Returns True if the given template was used
"""
for template in resp.templates:
if template.name == template_name:
return True
return False | 3006857a109c0e94db6e48473ab18cee1ea2f04f | 579,211 |
def to(*args, **kwargs):
"""
Returns a closure that applies x.to(*args, **kwargs) to x
"""
def apply_to(x):
return x.to(*args, **kwargs)
return apply_to | f9a52a0cba1513f743190330c46d881d13efa98d | 579,213 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.