content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def clean_config_for_pickle(full_conf):
"""Clean out any callable method instances, such as the gene_test_callback
parameter passed to geneticalgorithm, as these are not pickleable.
Acts in-place on full_conf parameter.
Inputs:
full_conf: The full_config dict structure, containing a 2-leve... | d3c86957e4ed038ade532dcaa3fe1c4fbffb5825 | 628,073 |
import csv
def read_connections_file(infile):
"""
Reads a two-column CSV file of integers into a list of tuples
corresponding to indices of connected concepts.
:param str infile: Path to the CSV file.
:returns: List of int tuples of connections.
:rtype: list
"""
connections = []
w... | 4b27bf13a5f9ec99bf2b122dfa0c732a7ade09b0 | 628,074 |
def do_enable_unwinder1(unwinders, name_re, flag):
"""Enable/disable unwinders whose names match given regex.
Arguments:
unwinders: The list of unwinders.
name_re: Unwinder name filter.
flag: Enable/disable.
Returns:
The number of unwinders affected.
"""
total = 0
... | 42fe9b8c5a199f9bda0cc460a043968ee62b91b6 | 628,075 |
import torch
def look_back(input_tensor: torch.Tensor) -> torch.Tensor:
"""
Looks back one bucket
"""
shift = torch.cat([input_tensor[:, -1:], input_tensor[:, :-1]], dim=1)
# [batch * head, n_buckets, bucket_length, d_k, rounds]
concat = torch.cat([shift, input_tensor], dim=2)
# [batch * h... | 325a6184304b9e0b27b92a7499605190ee017424 | 628,076 |
def find_package_data():
"""
Find package_data.
"""
return {
'jupyterlab': ['build/*', 'lab.html']
} | aa7ffcb17b2d73fe4e668cafa57ec099f4874fc7 | 628,077 |
from typing import Tuple
def join_float(val: Tuple[float, float]) -> str:
"""Reverse split_float()."""
low, high = val
if low == high:
return str(low)
else:
return '{!s},{!s}'.format(low, high) | b99f9e0f45516a023c62b03f79ead58c26bfdb35 | 628,079 |
import requests
def check_proxy(proxy_ip, proxy_port, protocol):
"""
Функция, которая проверяет прокси, пытаясь сделать запрос на указанный сайт.
Мы используем «wikipedia.org» в качестве теста, так как мы можем проверить анонимность прокси
путем проверки, совпадает ли возвращаемый заголовок «X-Client... | b74d4f9f47625c84b1c26cea031f0514482472dc | 628,080 |
def leapfrog(theta, r, grad, epsilon, f):
""" Perfom a leapfrog jump in the Hamiltonian space
INPUTS
------
theta: ndarray[float, ndim=1]
initial parameter position
r: ndarray[float, ndim=1]
initial momentum
grad: float
initial gradient value
epsilon: float
... | 3386200209693d3cead404776499ef6c60553123 | 628,082 |
import uuid
def get_uuid1():
"""Generate a UUID based on the host ID and current time
Returns:
s: UUID1 string.
"""
uid1 = uuid.uuid1()
s = str(uid1)
return s | b1020758ed48096f2770cbfe8ff2c1dd1273a23b | 628,083 |
import random
def _apply_func_with_prob(func, image, args, prob):
"""Apply `func` to image w/ `args` as input with probability `prob`."""
# Apply the function with probability `prob`.
should_apply_op = random.random() + prob
if should_apply_op >= 1.0:
augmented_image = func(image, *args)
... | fd883ea8996e8ab1e87eb1438ef261ddd1aee597 | 628,084 |
import logging
def get_classifier_input_size(nn_model):
"""Tries to guess the number of input units required by the classifier."""
num_ftrs = None
try:
num_ftrs = nn_model.classifier[0].in_features
except:
try:
num_ftrs = nn_model.classifier.in_features
except:
... | f4c06c1972a40ef0747952a62617673af196a505 | 628,085 |
from typing import Callable
import re
def get_formatter(env_var_name: str) -> Callable[[str], str]:
"""
Returns a formatter function for given environment variablel.
:param env_var_name: name of environment variable
:return: formatting function
"""
if env_var_name.endswith("PATH"):
r... | 3b1faf9748d5a752ff1c579b5458eb042f7b9865 | 628,086 |
def create_empty_board():
""" a function that create an empty board """
return [["." for _ in range(9)] for _ in range(9)] | 1b021d09f403c91b30beb2afff9518fe7d89f2c3 | 628,088 |
def unescape(text):
"""
Do reverse escaping.
"""
text = text.replace('&', '&')
text = text.replace('<', '<')
text = text.replace('>', '>')
text = text.replace('"', '"')
text = text.replace(''', '\'')
return text | 460ed8f856ec5bdbf8d34183b583cae83c478de7 | 628,089 |
from bs4 import BeautifulSoup
def get_soup_from_static_html(html):
"""
Parameters
----------------
html: str/path obj
the path to the html file
Returns
-----------------
soup: bs4 Soup obj
"""
with open(html, 'r') as fh:
soup = BeautifulSoup(fh, 'html.parser')
... | 8f77a4ed75ca64982acbb0c1cb96a2c28de239c6 | 628,090 |
def form_yes_or_no(QUESTION: str, DEFAULT_NO: bool = True) -> bool:
"""
Single yes or no question without recursion.
Credit:
Inspired from
@icamys commented on 29 Nov 2020 on Github,
https://gist.github.com/garrettdreyfus/8153571
"""
CHOICES = " [y/N]: " if DEFAULT_NO else "... | 3ed172bd61bd2e3db0484df845d0b6d9ab77f447 | 628,091 |
def extract_name(fullname):
"""
Reads the csv and extracts names by splitting them as first/last name so that
it can be passed to the API call.
Note: The extra cases could have been avoided while forming the CSV i.e.
improving on the design and structure of web scraper.
"""
full_name = fulln... | 0e911f4abca6244227f62a9646fb2c16c6ec7e53 | 628,092 |
import argparse
def parse_args() -> argparse.Namespace:
"""引数を解析する
Returns:
argparse.Namespace: 引数情報
"""
parser = argparse.ArgumentParser(
prog="test_post.py",
description="tensorflow-serving test script",
add_help=True
)
parser.add_argument(
"--model_n... | cbff0aef4c46090f4ba8920520237a7d24c4d97e | 628,093 |
def unload_words() -> bool:
"""
Removes dictionary json from memory
"""
global WORDS_JSON
WORDS_JSON = None
return True | 16d9731aec934fe37ccf98da9137345d8a223cc6 | 628,094 |
def valid_priority_len(priority):
"""Checks for values with exactly one significant digit
:param float priority:
:return boolean:
"""
result = len(str(priority).rsplit('.')[-1]) == 1
return result | ffc1048d54e5b91cc7b17408514ce4c97941ac6e | 628,097 |
def listAxes(axd):
"""
make a list of the axes from the dictionary of axes
Parameters
----------
axd : dict
a dict of axes, whose values are returned in a list
Returns
-------
list : a list of the axes
"""
if type(axd) is not dict:
if type(axd) is l... | b5e2f2f5341671d1c267d3940893b665555f1a01 | 628,098 |
def product_4x4(b,a) :
"""multiply two 4x4 matrices"""
a1= a[0][0]*b[0][0]+a[0][1]*b[1][0]+a[0][2]*b[2][0]+a[0][3]*b[3][0]
a2= a[0][0]*b[0][1]+a[0][1]*b[1][1]+a[0][2]*b[2][1]+a[0][3]*b[3][1]
a3= a[0][0]*b[0][2]+a[0][1]*b[1][2]+a[0][2]*b[2][2]+a[0][3]*b[3][2]
a4= a[0][0]*b[0][3]+a[0][1]*b[1][3]+a[0][2]*b[2][3]+a[0]... | f8e4b586b6c2812e7c4825134b16e2b31acc8fcb | 628,099 |
def pagetitle(string, remove_first=False, divider=' > '):
"""Convert a string of characters to page-title format.
Args:
string (str): The string to conert.
remove_first (bool, optional): Remove the first instance of the
delimiter of the newly formed title.
Returns:
str:... | 3814a193433d337a37ce5bec6c72cf210970f368 | 628,100 |
def create_business_hours_schedule(api, configuration, api_version, api_exception):
""" Creates a schedule for an activity that occurs during normal business hours.
:param api: The Deep Security API modules.
:param configuration: Configuration object to pass to the api client.
:param api_version: The v... | ed3ac68fcace4ac62431e5eb70a5ce23f52103db | 628,102 |
def images_meta1():
"""Image files metadata set."""
metadata = [
{
"bucket": "object_bucket",
"version_id": "object_version",
"key": "jpgfile.jpg",
"previewer": ""
},
{
"bucket": "object_bucket",
"version_id": "objec... | a4985a7d6b7939bae76e437d81b8ff4995637320 | 628,103 |
def substract_imageMean(data, img_mean):
""" substract image-Mean of the images"""
return data - img_mean | 2e7d6acfa3fa6d544fd83838ab724142ff303754 | 628,104 |
def gen_post_id(reddit_obj_id):
"""
Generates the Elasticsearch document id for a post
Args:
reddit_obj_id (int|str): The id of a reddit object as reported by PRAW
Returns:
str: The Elasticsearch document id for this object
"""
return "p_{}".format(reddit_obj_id) | 558fd8d6d70b80980ff8dc5d92b9d36ddba792d5 | 628,105 |
def convert_md_references(md_text):
"""Method to convert markdown list to references url format"""
if not md_text:
return []
ref_list = []
md_text = md_text.replace("\n", "").strip()
for ref in md_text.split("- "):
if not ref:
continue
parts = ref.split("](")
... | 46c7a81144a4ed10beca3ad0a64ca18cf0403885 | 628,106 |
import numpy
def normalize_array(arr):
"""Normalize the given array to be in range [0,1]."""
minVal = numpy.amin(arr)
maxVal = numpy.amax(arr)
return (arr - minVal) / float(maxVal - minVal) | 68fc4b679ff67a1e35152e5094faf569fa845dd2 | 628,107 |
def collection_to_dict(collection):
"""Utility function to construct collection dict with names."""
return {v.name[:v.name.rfind(':')]: v for v in collection} | a2e022a26e3bf62ddd34dfcc6548b7b18e39dd52 | 628,108 |
def merge_keys(sql_server):
"""
To match with their respective API's, we have a slightly different "merge_keys" value
when a user is using snowflake.
:param sql_server:
:return:
"""
sql_name, _ = sql_server
if sql_name == "snowflake":
return {"list": "list", "sell": "sell"}
... | ddd73ae81d25c9db69146a0968ea868c5e5a6d4d | 628,109 |
def remove_rows_containing_invalid_values(data):
"""
This function clears invalid values.
"""
data.drop(data[(data.bedrooms <= 0) | (data.bathrooms <= 0) |
(data.sqft_living <= 0) | (data.sqft_lot <= 0) |
(data.floors <= 0) | (data.condition <= 0) |
... | 5320c2f296f3b92ee62171806454397213a36845 | 628,110 |
def _ofc(id):
"""OFC ID converter."""
return "ofc-%s" % id | c31e2fb102c0238c943629de98cffeeac127cf29 | 628,111 |
def snake2pascal(target: str) -> str:
"""Convert snake case to pascal case
Args:
target (str)
Returns:
str
"""
return ''.join(map(lambda x: x.title(), target.split('_'))) | 296bf325ba758b869d8040d8a76e82d36ea05d48 | 628,112 |
import argparse
def set_args():
"""
Establish the command line parameters that will be supported when executing this utility.
:return: None
"""
description = 'Assignment Program utility used to apply rules to the MassHeath Spreadsheet.'
parser = argparse.ArgumentParser(description,
... | 82e128c29b5e119873659be0e605ffcea3e76a6b | 628,114 |
def get_plot_title(main, model, prefix=""):
"""
Constructs a sensible plot title from the ``model``.
"""
if main is not None:
main = prefix
title = model.get_title()
if title:
main += f": {title}"
return main | 79c9d5d0b922ebaeba1fab3e593bb7028e1b2582 | 628,115 |
import stat
def calc_mode(
sticky=False,
isuid=True,
isgid=True,
type=stat.S_IFREG,
owner_read=True,
owner_write=True,
owner_exec=True,
group_read=True,
group_write=True,
group_exec=True,
other_read=True,
other_write=True,
other_exec=True,
):
"""helper function to calculate the mode bits of a file."""
... | b46d201deeac317bf8ff1c352784afb0e37715e0 | 628,116 |
import os
def getNetworKitRoot():
"""
Returns an absolute path to the project root (which is derived from the module's absolute path)
"""
return os.path.realpath(os.path.join(os.path.dirname(os.path.realpath(__file__)), "..", "..", "..")) | 389e27bc0d1cbe6a1dcc5bd9211a333e2d42a647 | 628,117 |
import json
def generateArmyData(units_info):
"""
Parameters
----------
units_info : dict
Returns
-------
units : list[dict]
"""
i = 1
units = []
while 'js_barracksSlider{:d}'.format(i) in units_info:
# {"identifier":"phalanx","unit_type_id":303,"costs":{"citizens":1,"wood":27,"sulfur":30,"upkeep":3,"co... | ed451f813b1163e9db1cb8f163c474f33abaa6df | 628,118 |
def get_limit_spec(limit):
"""
Based on an input *limit* string of the form:
<system>.<type>.<direction>.<qualifier>
(where the "qualifier" element is optional) return the various pieces
into a dictionary for convenience.
Parameters
----------
limit : str
The input limit s... | 2d93a83014ccd28f5c93a6578ef9571ba8523c0e | 628,119 |
def unpack_quantity(row, concept, value):
"""Unpack row like {"variable": [{"concept":<concept>, <value>:_i_want_this_}]}
Args:
row (dict): Row of Worldbank API data.
concept (str): The name of the dataset containing the variable.
value (str): The name of the variable to unpack.
Ret... | ce51a37a99f5883ec7af7642dbed13e16f6e3d34 | 628,120 |
def serializeEdge(edge):
"""Return the Edge as native Python datatypes, fit for json.
Edges only reference Knobs, so we have to store their Node id here
to be able to correctly associate it once reconstructed.
"""
return {
"source_nodeId": edge.source.node().uuid,
"source_name": edg... | 58662cdbfd1bc22e0dc4276e5240961dc0d5672a | 628,121 |
def no_preproc(x, **kwargs):
"""Identity function that can be passed used as feature_preproc_fn in Dataset, since lambda is
not pickleable and doesn't take an arbitrary number of params."""
return x | a897759789856c1c86cde61c4de4bedec98c29b7 | 628,123 |
import math
def quaternion_from_matrix(M):
"""Returns the 4 quaternion coefficients from a rotation matrix.
Parameters
----------
M : list[list[float]]
The coefficients of the rotation matrix, row per row.
Returns
-------
[float, float, float, float]
The quaternion coeffi... | 6318208e9186ddbe26cdd1dc6175898918f39969 | 628,124 |
import os
import fnmatch
def getNextFolder(currentFolderPath, pattern):
"""This function returns the path of the folder that directly follows (alphabetically and at the same level) a given
folder having a specific name pattern
This method receives the path of a folder called currentFolderPath and has to ... | 394e0869970172139c72c7e49d79e9d7fc8b4ff9 | 628,125 |
def type_error_tree_roof(df):
"""
Calculate type 1 error and type 2 error.
"""
df.loc['type_1 error','roof'] = (1 - df.loc['Edge','roof']/df.loc[ 'sum','roof'])*100
df.loc['type_2 error','roof'] = (df.loc['Edge','total']-df.loc['Edge','roof'])/ \
(df.loc['su... | 4fa2811cf1a1f28b8d0fb2439dcac865c76e48bd | 628,126 |
def encode_attempt_metrics(attempt, common_tags):
"""Encode the attempt metrics using InfluxDB Line Encoding."""
metrics = []
def escape(value):
"""Escape the value for influxdb."""
return (str(value)
.replace('"', r'\"')
.replace(',', r'\,')
.replace('=', r'\=')
... | 922284875c4ceb0bf0656cd3b7ec71b569bdce1f | 628,127 |
import os
from pathlib import Path
def get_free_bytes(path: Path) -> float:
"""
Get free bytes
"""
statvfs = os.statvfs(path)
free_bytes = statvfs.f_bavail * statvfs.f_frsize
return free_bytes | 88538af41526761f9f8014c0772ef36fd9d3e494 | 628,128 |
def subset_data_for_bounding_box(data, min_lat, max_lat, min_lon, max_lon):
"""
Return a subset of data within the bounding lat/lon box
The function assumes that lat/lon are not coordinates in the data
"""
sub = data.where(
(data.lat > min_lat) & (data.lat <= max_lat) & (data.lon > min_lon) ... | fe483b3232fc5e300ac6c7bd5f29872c125f4c80 | 628,129 |
from unittest.mock import patch
def patch_bond_device(return_value=None):
"""Patch Bond API device endpoint."""
return patch(
"homeassistant.components.bond.Bond.device",
return_value=return_value,
) | c3bde7f64c663997119fecc04e126f3844066bc2 | 628,130 |
import os
def clean_up_dir(files: list) -> list:
"""
:param files: List of files in the project directory
:return: list
Cleans up trashed files and gives original files
"""
original_files = list()
for file in files:
if "rewritten.java" in file:
os.remove(file)
... | 78ffe79e57dffc469fdaca4eae12e66573d7a0dc | 628,131 |
def is_local_ressource(path):
"""
Check if given path is a local ressource.
Arguments:
path (string): Ressource path.
Returns:
bool: True if file path, else False.
"""
if not path.startswith("http://") and not path.startswith("https://"):
return True
return False | a169ad58e0df8f5deca3ed01f1331ae0ab833b7a | 628,132 |
import argparse
import pathlib
def parse_args():
"""Argument parsing function
:return: namespace containing user provided arguments
:rtype: argparse.Namespace
"""
parser = argparse.ArgumentParser(
description="Setup a directory from a template."
)
parser.add_argument(dest="templa... | 7987d777185ee25655dc1c40d4888e86a4902ed2 | 628,134 |
import copy
def instancemethod(f):
"""
Checks if an instance of a class changes while executing f. If so raise an error.
USE AS DECORATOR
:param f: function = method to overload
:return: obj = return of the function
"""
def wrapper(self, *args, **kwargs):
atts = copy.deepcopy(self... | 6b36f848967a297c83e0bd8c1d2bff122249afea | 628,136 |
def strip_signature_from_subject(content):
"""Assume --\n is marker for email signature and return everything before.
"""
return content.split('--')[0] | fe7ecd0ac59f474be0531de85b8144e1248a4e22 | 628,137 |
def arrange_for_response(board_data):
"""
レスポンスできるように成型する
:param board_data: ボードのデータ(DataFrame)
:return: コンマ区切りの文字列に変形して返す
"""
ret_str = ''
for r in range(len(board_data.columns)):
for c in range(len(board_data.index)):
ret_str += str(board_data.iloc[r, c])
if... | 7b9bd5d30cf1225ee1f1f46cd23944831896d8b5 | 628,138 |
import struct
def unpack_int32(bin_data, pos):
""" Convert 4 byte data """
return struct.unpack(">I", bin_data[pos:pos+4])[0] | ddeb718eba9ff6dd3d4f0f07807f9a2b9e37b933 | 628,139 |
def factorial_recursion(integer) -> int:
"""This function calculate factorial using recursion."""
if integer > 1:
return integer * factorial_recursion(integer - 1)
else:
return 1 | 5a1cb9c483d1e181f8c2c469792dc44ca125647c | 628,140 |
import itertools
def compress(string: str) -> str:
"""Return string represented as tuples of characters and their count."""
return " ".join([
"({})".format(", ".join((str(len(list(grp))), char)))
for char, grp in itertools.groupby(string, lambda c: c)
]) | c47f195f2edc193bbfb28196a563a65b02f440d8 | 628,141 |
def _trim_front(strings):
"""
Trims zeros and decimal points
"""
trimmed = strings
while len(strings) > 0 and all([x[0] == ' ' for x in trimmed]):
trimmed = [x[1:] for x in trimmed]
return trimmed | 8e3383d0d166f16816ec98fdca08d9eeb6092d67 | 628,142 |
import os
def md5sum_folder(folder_name):
"""
returns the md5sum of a file using the command `tar -cf - {folder_name} | md5sum`
"""
return os.popen(f'tar -cf - \'{folder_name}\' | md5sum').read() | e29a7c64c9d2bc30c354bd516a5d575b623b0413 | 628,143 |
def display_table(table):
"""Display values in a table format.
table: an iterable of rows, and each row is an iterable of values.
"""
html = ""
for row in table:
row_html = ""
for col in row:
row_html += "<td>{:40}</td>".format(str(col))
html += "<tr>" + row_html ... | 523e22642b8a3eec9c7d538d3077b2feb27e0882 | 628,144 |
from datetime import datetime
def from_datetime(value: datetime) -> str:
"""Convert from datetime to ISO8601-formatted string.
Parameters
----------
value : datetime
The datetime to be converted. Expected in UTC.
Returns
-------
str
ISO8601-formatted string
Examples
... | a6e4b0998f6adeb7edb1f9462de3aa1e18a2e8a4 | 628,145 |
import os
def check_virtualenv(ctx, virtualenv_path):
"""
Check if virtualenv is initialized in virtualenv folder (based on
bin/python file).
"""
r = ctx.run(' '.join([
os.path.join(virtualenv_path, 'bin/python'),
'--version'
]), warn=True, hide='both')
return r.ok | ad71c0f37a35b2f4845b41b68de90dfb427553bc | 628,146 |
def session_status(space):
"""Returns the current session status"""
return space.wrap(space.ec.interpreter.session.status) | c7b2c03f7641622c8ee162aeafdfba07fbfd61b8 | 628,147 |
def get_attack_details(ipal_entry):
"""
Parse the attack-details IPAL field.
The field is expected to have the format "<attack category>;<attack type>".
Example: "2;12".
"""
split = ipal_entry["attack-details"].split(";")
assert (
len(split) == 2
), "'attack-details' field in IP... | b59b1b3f9343e917ed70f102a38d7b99597bad5c | 628,148 |
def little_endian_data() -> bytes:
"""Little endian data fixture."""
return b"\x00\x00\x00\x05\x00\x00\x00\x06" | 83919a672cd1a2c868c7ef61a2d20f3c993f88f4 | 628,149 |
def generate_config(context):
"""Entry point for the deployment resources."""
properties = context.properties
project_id = context.env['project']
dataset_id = properties['datasetId']
location = properties['location']
supported_types = {
'dicomStores': 'dicomStoreId',
'fhirStores': 'fhirStoreId'... | 344e9aae3b355bd844540c338ef124c1b0da601f | 628,150 |
import time
def get_current_time(time_form: str="%Y%m%d%H%M%S"):
"""
get_current_time from time
Args:
time_form: str, string form of return time
Returns:
time_current: str
"""
time_now = int(time.time())
time_local = time.localtime(time_now)
time_current = time.strftime... | 8622ef56b9b885cd50efd83a46f2e94c24ee092f | 628,151 |
def get_marc_as_list(raw_marc):
"""Method takes Solr MARC format and splits into a list of field dictionarys
:param raw_marc: Raw MARC string
:rtype: List of field dictionary
"""
output = []
marc_listing = raw_marc.split("=")
for row in marc_listing:
output.append({'tag':row[0:3],
... | 4f86cb86f50abf4041f3cd16121df610c3671d56 | 628,152 |
def _distribute_data_to_mouse(mouse_data):
"""
This function distributed the mouse object information into the python dictionary object for easier json
parsing process
"""
dict_m = {
'physical_id': mouse_data.physical_id,
'handler': mouse_data.handler,
'gender': mouse_data.ge... | ad2b6399e3294b1decaa25392450fef6ddbfa221 | 628,153 |
import math
def calculate(point1, point2):
"""
Calculate the distance between two points (point1 and point2) on the Earth's surface
using the 'spherical law of cosines' formula.
Input: point1 : two floating point numbers between -180 and 180, where positive indicates North/East
... | adf7f285d285ac575285632816a4778bbf40c9db | 628,154 |
def find_element_in_item_group(element, item_group):
"""
在ItemGroup里面寻找相应的的element
:param element:
:param item_group:
:return:
"""
keyand = item_group.__getattribute__('And')
keyor = item_group.__getattribute__('Or')
keynot = item_group.__getattribute__('Not')
if keyand is not No... | 9341daa17fab02e7fcde2150474660585920f645 | 628,155 |
def outOfFrameCodonsThis(t):
""" report the number of outOfFrameCodonsThis
"""
for a in t.annotations:
if 'outOfFrame' in a.labels:
for l in a.labels:
if l.startswith('outOfFrameCodonsThis'):
return int(l.split('_')[1])
return 0 | 421e2e248a8f539e989bed80cb7f08e367b39661 | 628,156 |
def update_repository_name(repository):
"""Update given repository name so it won't contain any prefix(es)."""
lastSlash = repository.rfind("/")
# make sure we use just the repo name
if lastSlash >= 0 and lastSlash < len(repository) - 1:
return repository[1 + lastSlash:]
else:
retur... | 7d771bc0576ce6c15ba6e0a259bac499077c464a | 628,157 |
def request_input(message, choices):
"""
Request user input.
Parameters
----------
message : str
Message to display
choices : list of str
List of recognized inputs
"""
while True:
choice = input(message).strip().lower()
if choice in choices:
... | df223bc9f584c3e3df0481501473c45925d79583 | 628,158 |
def _append_norm(ktl0, norm_types):
"""Generate human-readable labels for multiple norms."""
ktl = {}
for norm_type in norm_types:
for key, val in ktl0.items():
ktl['%s/%s' % (key, norm_type)] = '%s(%s)' % (val, norm_type)
return ktl | d82c927facc341c150dc63cec3b3e1df9133383f | 628,159 |
def get_rules_with_scope(rules, scope):
"""
from the given collection of rules, select those with the given scope.
args:
rules (List[capa.rules.Rule]):
scope (str): one of the capa.rules.*_SCOPE constants.
returns:
List[capa.rules.Rule]:
"""
return list(rule for rule in rules... | 4922038dc098083085e16c096a40ddae1825e589 | 628,160 |
def _SharedPrefix(pattern1, pattern2):
"""Returns the shared prefix of two patterns.
Args:
pattern1: A handler's pattern string
pattern2: A handler's pattern string
Returns:
The shared prefix of the two patterns, up to the index of the first
wildcard of either pattern. For example, the shared pre... | df19be2b8a24dc5a35df9c144a114b6bd6f0fe4e | 628,162 |
def get_enum_strings(enum_strings, enum_dict):
"""Get enum strings from either `enum_strings` or `enum_dict`."""
if enum_dict:
max_value = max(enum_dict)
return [enum_dict.get(idx, '')
for idx in range(max_value + 1)]
return enum_strings | f7cb8238d0cc7c3c6824ef1c160b01ec213cdd29 | 628,163 |
def file_upload_event():
""" Generates File Upload Event"""
return {
"Records": [
{
"eventVersion": "2.1",
"eventSource": "aws:s3",
"awsRegion": "us-east-1",
"eventTime": "2020-08-19T13:18:56.519Z",
... | 3e012ff908eb279912ac7e1135a33997a3de6dd3 | 628,164 |
from typing import List
def sauvegarde_fichier(nom_fichier : str, Contenu : List[str]) -> None:
"""Précondition : nom_fichier est un nom correct de fichier
Sauvegarde le Contenu comme lignes de texte dans le
fichier identifié par nom_fichier
Attention : si le fichier existe déjà son contenu sera
e... | 17ada0ef80c506199dd93c01080fec5b017cc67f | 628,165 |
def make_columns(repetitions, n_splits):
"""Provides column names for the tables of all predictions (from each
split of each rep).
Parameters
----------
repetitions : int
Repetitions of the n-fold validation
n_splits : int
number of splits in KFold
Returns
-------
l... | 83be90522ffdf0db0175c09318e12d65e585e1a4 | 628,166 |
def id_is_generic(inid, inyear):
"""
Test to see if an ID is one of the generic IDs
:param inid: ID from marine report
:param inyear: year we are checking for
:type inid: string
:type inyear: integer
:return: True if the ID is generic and False otherwise
:rtype: logical
Cer... | 0f458cfc339016a30a115e973d80503686b1e1bd | 628,167 |
def _get_noun_preposition_text(dictionary: dict, text: str) -> str:
"""
Get prepositional details for a noun.
@param dictionary: Dictionary holding the details to be added
@param text: Input noun text
@return: The updated noun text or the original text if no change is warranted
"""
new_text... | 3f56f60c4e048f5172b8650dad30b739276c00ab | 628,168 |
def reduce_broadcast(grad, var_shape):
""" Sum-reduce axes of `grad` so its shape matches `var_shape.
This the appropriate mechanism for backpropagating a gradient
through an operation in which broadcasting occurred for the
given variable.
Parameters
----------
grad... | be365ab0e830b40ff17dbc5816635295a492ae80 | 628,169 |
import torch
def convolve_distance_modulus_with_lf(histogram, lf_number,
distance_mod_dim=-1):
"""Helper function that convolves a histogram as a function of distance modulus with a luminosity function. Distance
modulus dimension should be specified in distance_mod_dim, o... | 1e150967e534b2cb42dd8409917218146f8f5957 | 628,170 |
def merge_dicts(dict1, dict2):
""" Merge two dictionaries.
Parameters
----------
dict1, dict2 : dict
Returns
-------
dict_merged : dict
Merged dictionaries.
"""
dict_merged = dict1.copy()
dict_merged.update(dict2)
return dict_merged | cb792131f1793907e32090e6df5d2d2395410dfa | 628,171 |
def breakPalindrome(self, palindrome):
"""
:type palindrome: str
:rtype: str
"""
p1 = 0
p2 = len(palindrome)-1
new_pal = list(palindrome)
while p1 < p2:
if new_pal[p1] != "a":
new_pal[p1] = "a"
return "".join(new_pal)
p1+=1
p2-=1
if le... | 83b8f8072494ead5050f14968e3d4206456ae5eb | 628,172 |
def select_all_columns_except_some(df, column_names):
"""Select all columns in the dataframe except those specified in ``column_list``.
Args:
df (pd.DataFrame): Dataframe.
column_names (list): List of column names.
Returns:
pd.DataFrame: Dataframe with the columns removed.
... | ee6a345a605da46a6edd9a6808b5edbf48abd211 | 628,173 |
import json
def reject(status_code, **kwargs):
"""
Bad request.
:param int status_code: Rejection status code
:param dict kwargs: Rejection body JSON
:return dict: Rejection response
"""
body = json.dumps(kwargs) if kwargs else ''
headers = {
'content-length': len(body),
... | e68113ed9c92d0c082ed4c146ca2132d3d52bc40 | 628,174 |
def preparePandas(timeData, sampleSizes, name):
"""Create DF for sns-plots"""
preparePd = list()
for time, sample in zip(timeData, sampleSizes):
preparePd.append([str(name),time, sample])
return preparePd | 996daf4cab6ddeaee3801f21e56b4ed24ad5696d | 628,175 |
import torch
def to_torchaudio(tensor, dim: int = -2):
"""Converts complex-like torch tensor to torchaudio style complex tensor.
Args:
tensor (torch.tensor): asteroid-style complex-like torch tensor.
dim(int, optional): the frequency (or equivalent) dimension along which
real and ... | a69fabe2590d73c9d7ca45d478749d722e79ecaa | 628,176 |
def mock_search_tasks(mocker):
"""Patch the helpers so they don't fire celery tasks"""
return mocker.patch("channels.api.search_task_helpers") | 14c3d795607c02e8e917f78663b7339e3c147c7b | 628,177 |
def interpret_data(data: list) -> dict:
"""Transforms json data to be separated per commit."""
reformat = {}
for entry in data:
# Entries that could not be linked to a file
# are ignored.
if not entry["file"]:
continue
sha = entry["satd_sha"]
if sha in... | 2abcd7745bd07530524b86371c762dc7a00b01fb | 628,179 |
def parse_stream(stream):
"""This function parses the contents of a stream to generate a list of lines.
This function removes comments delimited by '#', ingores empty
lines, and leading and trailing whitespace.
Args:
stream : A file that has been open()'d
Returns:
A list of lines.
"""
lines = ... | f428721e03ad6d5cde75df5fd8849e3b5461691d | 628,180 |
def is_pairs(pairs):
"""
returns a check if the data is pairs of key-value tuples
:Parameters:
------------
pairs : tuple
tuples of key-value tuples.
:Returns:
---------
bool
"""
return isinstance(pairs, tuple) and min([isinstance(item, tuple) and len(item) == 2 for ite... | 1e2c691ce79244e8f2bf542aa0c08aae3913c7ae | 628,181 |
def roc(counts):
"""Function computing TPR and FPR.
Output arguments:
=================
tpr : float
True positive rate
fpr : float
False positive rate
"""
tp, fp, tn, fn = counts
return float(tp) / (tp+fn), float(fp) / (fp+tn) | ee8602f94959ef385f30bba841d7d21af886fd99 | 628,182 |
def null_check_fn(struct_path):
"""
Checking Structure from input directory will always return False.
"""
return False | 5d50893ca5c0386ff37b0b122d57bc9c9aeaae67 | 628,183 |
def user_id(msg):
"""
Use the userid from the msg as the user search criteria
Args:
msg (errbot.backends.base.Message): The message from the bot that triggered the LDAP lookup
Returns:
str: The user ID that will be used to search LDAP
"""
if hasattr(msg.frm, "userid"):
... | 43c61915eca4c13d64e9e8a081e9a67fa97437ab | 628,184 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.