content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def create_outlier_mask(df, target_var, number_of_stds, grouping_cols=None):
"""
Create a row-wise mask to filter-out outliers based on target_var.
Optionally allows you to filter outliers by group for hier. data.
"""
def flag_outliers_within_groups(df, target_var,
... | 95a7e3e5a0cb8dcc4aa3da1af7e9cb4111cf6b81 | 3,239 |
def binary_search(x,l):
""" Esse algorítmo é o algorítmo de busca binária, mas ele retorna
qual o índice o qual devo colocar o elemento para que a lista
permaneça ordenada.
Input: elemento x e lista l
Output: Índice em que o elemento deve ser inserido para manter a ordenação da lista
"""
lo... | 457c403ffeb2eb5529c2552bdbe8d7beee9199f2 | 3,240 |
import os
import requests
def get_port_use_db():
"""Gets the services that commonly run on certain ports
:return: dict[port] = service
:rtype: dict
"""
url = "http://www.iana.org/assignments/service-names-port-numbers/service-names-port-numbers.csv"
db_path = "/tmp/port_db"
if not os.pat... | 4462ef74b5575905b75980827d5a5bb5ed05aee8 | 3,241 |
def generate_config(context):
""" Generate the deployment configuration. """
resources = []
name = context.properties.get('name', context.env['name'])
resources = [
{
'name': name,
'type': 'appengine.v1.version',
'properties': context.properties
}
... | 9a997b87a8d4d8f46edbbb9d2da9f523e5e2fdc6 | 3,242 |
def remove_end_same_as_start_transitions(df, start_col, end_col):
"""Remove rows corresponding to transitions where start equals end state.
Millington 2009 used a methodology where if a combination of conditions
didn't result in a transition, this would be represented in the model by
specifying a trans... | f4b3ddca74e204ed22c75a4f635845869ded9988 | 3,243 |
def sieve(iterable, inspector, *keys):
"""Separates @iterable into multiple lists, with @inspector(item) -> k for k in @keys defining the separation.
e.g., sieve(range(10), lambda x: x % 2, 0, 1) -> [[evens], [odds]]
"""
s = {k: [] for k in keys}
for item in iterable:
k = inspector(item)
... | 6ebb76dfb3131342e08a0be4127fba242d126130 | 3,244 |
def divide(x, y):
"""A version of divide that also rounds."""
return round(x / y) | 1bf9e5859298886db7c928613f459f163958ca7b | 3,246 |
def dot(u, v):
"""
Returns the dot product of the two vectors.
>>> u1 = Vec([1, 2])
>>> u2 = Vec([1, 2])
>>> u1*u2
5
>>> u1 == Vec([1, 2])
True
>>> u2 == Vec([1, 2])
True
"""
assert u.size == v.size
sum = 0
for index, (compv, compu) in enumerate(zip(u.store,v.st... | e431800750c8f7c14d7412753814e2498fdd3c09 | 3,247 |
def fix_lng_degrees(lng: float) -> float:
"""
For a lng degree outside [-180;180] return the appropriate
degree assuming -180 = 180°W and 180 = 180°E.
"""
sign = 1 if lng > 0 else -1
lng_adj = (abs(lng) % 360) * sign
if lng_adj > 180:
return (lng_adj % 180) - 180
elif lng_adj < -... | bde58152883874095b15ec38cfb24ea68d73c188 | 3,248 |
import typing
import inspect
def resolve_lookup(
context: dict, lookup: str, call_functions: bool = True
) -> typing.Any:
"""
Helper function to extract a value out of a context-dict.
A lookup string can access attributes, dict-keys, methods without parameters and indexes by using the dot-accessor (e.... | a2090f2488ee10f7c11684952fd7a2498f6d4979 | 3,249 |
import os
import subprocess
def linux_gcc_name():
"""Returns the name of the `gcc` compiler. Might happen that we are cross-compiling and the
compiler has a longer name.
Args:
None
Returns:
str: Name of the `gcc` compiler or None
"""
cc_env = os.getenv('CC')
if cc_env... | 47cf0ee9af4b1b7c9169632b86bc9b5e1db96ad3 | 3,252 |
def old_func5(self, x):
"""Summary.
Bizarre indentation.
"""
return x | 5bc9cdbc406fa49960613578296e81bdd4eeb771 | 3,253 |
def get_str_cmd(cmd_lst):
"""Returns a string with the command to execute"""
params = []
for param in cmd_lst:
if len(param) > 12:
params.append('"{p}"'.format(p=param))
else:
params.append(param)
return ' '.join(params) | a7cc28293eb381604112265a99b9c03e762c2f2c | 3,255 |
def calculate_score(arr):
"""Inside calculate_score() check for a blackjack (a hand with only 2 cards: ace + 10) and return 0 instead of the actual score. 0 will represent a blackjack in our game.
It check for an 11 (ace). If the score is already over 21, remove the 11 and replace it with a 1"""
... | 0890c55068b8a92d9f1f577ccf2c5a770f7887d4 | 3,256 |
def calculate_phase(time, period):
"""Calculates phase based on period.
Parameters
----------
time : type
Description of parameter `time`.
period : type
Description of parameter `period`.
Returns
-------
list
Orbital phase of the object orbiting the star.
"... | a537810a7705b5d8b0144318469b249f64a01456 | 3,257 |
import os
def _check_shebang(filename, disallow_executable):
"""Return 0 if the filename's executable bit is consistent with the
presence of a shebang line and the shebang line is in the whitelist of
acceptable shebang lines, and 1 otherwise.
If the string "# noqa: shebang" is present in the file, th... | 205fa2bc88b4c80899223e691b6f9cd00492c011 | 3,260 |
def deconstruct_DMC(G, alpha, beta):
"""Deconstruct a DMC graph over a single step."""
# reverse complementation
if G.has_edge(alpha, beta):
G.remove_edge(alpha, beta)
w = 1
else:
w = 0
# reverse mutation
alpha_neighbors = set(G.neighbors(alpha))
beta_neighbors = set... | fa32a325fd49435e3191a20b908ac0e9c3b992f8 | 3,261 |
def metadata_columns(request, metadata_column_headers):
"""Make a metadata column header and column value dictionary."""
template = 'val{}'
columns = {}
for header in metadata_column_headers:
columns[header] = []
for i in range(0, request.param):
columns[header].append(templa... | ca1f89935260e9d55d57df5fe5fbb0946b5948ac | 3,262 |
def get_nodeweight(obj):
"""
utility function that returns a
node class and it's weight
can be used for statistics
to get some stats when NO Advanced Nodes are available
"""
k = obj.__class__.__name__
if k in ('Text',):
return k, len(obj.caption)
elif k == 'ImageLink' and obj... | 1ab88f73621c8396fca08551dd14c9a757d019ad | 3,263 |
def CMYtoRGB(C, M, Y):
""" convert CMY to RGB color
:param C: C value (0;1)
:param M: M value (0;1)
:param Y: Y value (0;1)
:return: RGB tuple (0;255) """
RGB = [(1.0 - i) * 255.0 for i in (C, M, Y)]
return tuple(RGB) | cfc2c7b91dd7f1faf93351e28ffdd9906613471a | 3,264 |
from typing import Any
import json
def json_safe(arg: Any):
"""
Checks whether arg can be json serialized and if so just returns arg as is
otherwise returns none
"""
try:
json.dumps(arg)
return arg
except:
return None | 97ac87464fb4b31b4fcfc7896252d23a10e57b72 | 3,265 |
import math
def h(q):
"""Binary entropy func"""
if q in {0, 1}:
return 0
return (q * math.log(1 / q, 2)) + ((1 - q) * math.log(1 / (1 - q), 2)) | ad3d02d6e7ddf622c16ec8df54752ac5c77f8972 | 3,266 |
from typing import IO
def write_file(filename: str, content: str, mode: str = "w") -> IO:
"""Save content to a file, overwriting it by default."""
with open(filename, mode) as file:
file.write(content)
return file | 5d6b7ac1f9097d00ae2b67e3d34f1135c4e90946 | 3,267 |
def get_list(_list, persistent_attributes):
"""
Check if the user supplied a list and if its a custom list, also check for for any saved lists
:param _list: User supplied list
:param persistent_attributes: The persistent attribs from the app
:return: The list name , If list is custom or not
"""... | 497fa8427660bafa3cc3023abf0132973693dc6e | 3,268 |
import socket
import re
def inode_for_pid_sock(pid, addr, port):
"""
Given a pid that is inside a network namespace, and the address/port of a LISTEN socket,
find the inode of the socket regardless of which pid in the ns it's attached to.
"""
expected_laddr = '%02X%02X%02X%02X:%04X' % (addr[3], a... | 4d47d9de118caa87854b96bf759a75520b8409cb | 3,269 |
def nicer(string):
"""
>>> nicer("qjhvhtzxzqqjkmpb")
True
>>> nicer("xxyxx")
True
>>> nicer("uurcxstgmygtbstg")
False
>>> nicer("ieodomkazucvgmuy")
False
"""
pair = False
for i in range(0, len(string) - 3):
for j in range(i + 2, len(string) - 1):
if ... | 7c543bbd39730046b1ab3892727cca3a9e027662 | 3,270 |
from typing import Union
def multiple_choice(value: Union[list, str]):
""" Handle a single string or list of strings """
if isinstance(value, list):
# account for this odd [None] value for empty multi-select fields
if value == [None]:
return None
# we use string formatting ... | aae54f84bc1ccc29ad9ad7ae205e130f66601131 | 3,271 |
def CleanFloat(number, locale = 'en'):
"""\
Return number without decimal points if .0, otherwise with .x)
"""
try:
if number % 1 == 0:
return str(int(number))
else:
return str(float(number))
except:
return number | 03ccc3bfe407becf047515b618621058acff37e7 | 3,273 |
def getGlobals():
"""
:return: (dict)
"""
return globals() | 0fa230d341ba5435b33c9e6a9d9f793f99a74238 | 3,274 |
def arith_relop(a, t, b):
"""
arith_relop(a, t, b)
This is (arguably) a hack.
Represents each function as an integer 0..5.
"""
return [(t == 0).implies(a < b),
(t == 1).implies(a <= b),
(t == 2).implies(a == b),
(t == 3).implies(a >= b),
(t == 4).implies(a > b),
... | 8b06d545e8d651803683b36facafb647f38fb2ff | 3,276 |
import collections
def get_duplicates(lst):
"""Return a list of the duplicate items in the input list."""
return [item for item, count in collections.Counter(lst).items() if count > 1] | 8f10226c904f95efbee447b4da5dc5764b18f6d2 | 3,277 |
import math
def regular_poly_circ_rad_to_side_length(n_sides, rad):
"""Find side length that gives regular polygon with `n_sides` sides an
equivalent area to a circle with radius `rad`."""
p_n = math.pi / n_sides
return 2 * rad * math.sqrt(p_n * math.tan(p_n)) | 939ff5de399d7f0a31750aa03562791ee83ee744 | 3,279 |
def dbl_colour(days):
"""
Return a colour corresponding to the number of days to double
:param days: int
:return: str
"""
if days >= 28:
return "orange"
elif 0 < days < 28:
return "red"
elif days < -28:
return "green"
else:
return "yellow" | 46af7d57487f17b937ad5b7332879878cbf84220 | 3,280 |
def read_requirements_file(path):
""" reads requirements.txt file """
with open(path) as f:
requires = []
for line in f.readlines():
if not line:
continue
requires.append(line.strip())
return requires | ab224bd3adac7adef76a2974a9244042f9aedf84 | 3,281 |
import threading
def thread_it(obj, timeout = 10):
""" General function to handle threading for the physical components of the system. """
thread = threading.Thread(target = obj.run())
thread.start()
# Run the 'run' function in the obj
obj.ready.wait(timeout = timeout)
# Clean u... | 02ed60a560ffa65f0364aa7414b1fda0d3e62ac5 | 3,282 |
def obj_setclass(this, klass):
"""
set Class for `this`!!
"""
return this.setclass(klass) | 4447df2f3055f21c9066a254290cdd037e812b64 | 3,283 |
def trimAlphaNum(value):
"""
Trims alpha numeric characters from start and ending of a given value
>>> trimAlphaNum(u'AND 1>(2+3)-- foobar')
u' 1>(2+3)-- '
"""
while value and value[-1].isalnum():
value = value[:-1]
while value and value[0].isalnum():
value = value[1:]
... | e9d44ea5dbe0948b9db0c71a5ffcdd5c80e95746 | 3,285 |
def _median(data):
"""Return the median (middle value) of numeric data.
When the number of data points is odd, return the middle data point.
When the number of data points is even, the median is interpolated by
taking the average of the two middle values:
>>> median([1, 3, 5])
3
>>> median... | f05a6b067f95fc9e3fc9350b163b3e89c0792814 | 3,288 |
def generate_styles():
""" Create custom style rules """
# Set navbar so it's always at the top
css_string = "#navbar-top{background-color: white; z-index: 100;}"
# Set glossdef tip
css_string += "a.tip{text-decoration:none; font-weight:bold; cursor:pointer; color:#2196F3;}"
css_string += "a.ti... | 44b36321dedba352c6aa30a352c7cd65cca1f79a | 3,289 |
def kilometers_to_miles(dist_km):
"""Converts km distance to miles
PARAMETERS
----------
dist_km : float
Scalar distance in kilometers
RETURNS
-------
dist_mi : float
Scalar distance in kilometers
"""
return dist_km / 1.609344 | 61707d483961e92dcd290c7b0cd8ba8f650c7b5b | 3,290 |
import requests
import time
def SolveCaptcha(api_key, site_key, url):
"""
Uses the 2Captcha service to solve Captcha's for you.
Captcha's are held in iframes; to solve the captcha, you need a part of the url of the iframe. The iframe is usually
inside a div with id=gRecaptcha. The part of the url we ... | e610a265d03be65bfd6321a266776a8102c227d0 | 3,295 |
def _cifar_meanstd_normalize(image):
"""Mean + stddev whitening for CIFAR-10 used in ResNets.
Args:
image: Numpy array or TF Tensor, with values in [0, 255]
Returns:
image: Numpy array or TF Tensor, shifted and scaled by mean/stdev on
CIFAR-10 dataset.
"""
# Channel-wise means and std devs cal... | 286ab555d30fd779c093e3b8801821f8370e1ca8 | 3,296 |
def boolean(entry, option_key="True/False", **kwargs):
"""
Simplest check in computer logic, right? This will take user input to flick the switch on or off
Args:
entry (str): A value such as True, On, Enabled, Disabled, False, 0, or 1.
option_key (str): What kind of Boolean we are setting. W... | d62b36d08651d02719b5866b7798c36efd2a018f | 3,297 |
def case_insensitive_equals(name1: str, name2: str) -> bool:
"""
Convenience method to check whether two strings match, irrespective of their case and any surrounding whitespace.
"""
return name1.strip().lower() == name2.strip().lower() | 28b7e5bfb5e69cf425e1e8983895f1ad42b59342 | 3,298 |
def ensure_listable(obj):
"""Ensures obj is a list-like container type"""
return obj if isinstance(obj, (list, tuple, set)) else [obj] | bdc5dbe7e06c1cc13afde28762043ac3fb65e5ac | 3,299 |
def merge_dicts(*dicts: dict) -> dict:
"""Merge dictionaries into first one."""
merged_dict = dicts[0].copy()
for dict_to_merge in dicts[1:]:
for key, value in dict_to_merge.items():
if key not in merged_dict or value == merged_dict[key]:
merged_dict[key] = value
... | b32a9f4bed149144a3f75b43ed45c8de4351f3d1 | 3,300 |
import calendar
def convert_ts(tt):
"""
tt: time.struct_time(tm_year=2012, tm_mon=10, tm_mday=23, tm_hour=0,
tm_min=0, tm_sec=0, tm_wday=1, tm_yday=297, tm_isdst=-1)
>>> tt = time.strptime("23.10.2012", "%d.%m.%Y")
>>> convert_ts(tt)
1350950400
tt: time.struct_time(tm_year=1513, tm_mon=1... | a3c2f5ae3d556290b6124d60fd4f84c1c2685195 | 3,301 |
def cmd(f):
"""Decorator to declare class method as a command"""
f.__command__ = True
return f | 3bdc82f0c83b0a4c0a0dd6a9629e7e2af489f0ae | 3,303 |
def small_prior():
"""Give string format of small uniform distribution prior"""
return "uniform(0, 10)" | fb636b564b238e22262b906a8e0626a5dff305d1 | 3,304 |
def skip_device(name):
""" Decorator to mark a test to only run on certain devices
Takes single device name or list of names as argument
"""
def decorator(function):
name_list = name if type(name) == list else [name]
function.__dict__['skip_device'] = name_list
return functio... | 1bacdce5396ada5e2ba7a8ca70a8dfb273016323 | 3,305 |
from typing import Iterable
from typing import Any
from typing import Tuple
def tuple_from_iterable(val: Iterable[Any]) -> Tuple[Any, ...]:
"""Builds a tuple from an iterable.
Workaround for https://github.com/python-attrs/attrs/issues/519
"""
return tuple(val) | 7880b1395f14aa690f967b9548456105b544d337 | 3,308 |
def sensitivity_metric(event_id_1, event_id_2):
"""Determine similarity between two epochs, given their event ids."""
if event_id_1 == 1 and event_id_2 == 1:
return 0 # Completely similar
if event_id_1 == 2 and event_id_2 == 2:
return 0.5 # Somewhat similar
elif event_id_1 == 1 and eve... | b04c5fa27ef655dd3f371c3ce6ef0410c55dd05b | 3,309 |
def duracion_promedio_peliculas(p1: dict, p2: dict, p3: dict, p4: dict, p5: dict) -> str:
"""Calcula la duracion promedio de las peliculas que entran por parametro.
Esto es, la duración total de todas las peliculas dividida sobre el numero de peliculas.
Retorna la duracion promedio en una cadena de ... | a8cfcc96a43480ee6830cc212343a33148036c5d | 3,310 |
def _to_test_data(text):
"""
Lines should be of this format: <word> <normal_form> <tag>.
Lines that starts with "#" and blank lines are skipped.
"""
return [l.split(None, 2) for l in text.splitlines()
if l.strip() and not l.startswith("#")] | 8f0bae9f81d2d14b5654622f1493b23abd88424d | 3,311 |
def align2local(seq):
"""
Returns list such that
'ATG---CTG-CG' ==> [0,1,2,2,2,3,4,5,5,6,7]
Used to go from align -> local space
"""
i = -1
lookup = []
for c in seq:
if c != "-":
i += 1
lookup.append(i)
return lookup | aa914a60d5db7801a3cf1f40e713e95c98cd647e | 3,313 |
import os
def get_system_path():
""" Get the system path as a list of files
Returns:
List of names in the system path
"""
path = os.getenv('PATH')
if path:
return path.split(os.pathsep)
return [] | 766931b403444c584edf71d053f5b3f5de6bf265 | 3,315 |
def parsec_params_list_to_dict(var):
"""
convert parsec parameter array to dictionary
:param var:
:return:
"""
parsec_params = dict()
parsec_params["rle"] = var[0]
parsec_params["x_pre"] = var[1]
parsec_params["y_pre"] = var[2]
parsec_params["d2ydx2_pre"] = var[3]
parsec_para... | 4ea4b4d2c0cbcb8fb49619e103b09f354c80de6a | 3,316 |
def parse_msiinfo_suminfo_output(output_string):
"""
Return a dictionary containing information from the output of `msiinfo suminfo`
"""
# Split lines by newline and place lines into a list
output_list = output_string.splitlines()
results = {}
# Partition lines by the leftmost ":", use the s... | 6883e8fba9a37b9f877bdf879ebd14d1120eb88a | 3,317 |
import time
import json
async def ping(ws):
"""Send a ping request on an established websocket connection.
:param ws: an established websocket connection
:return: the ping response
"""
ping_request = {
'emit': "ping",
'payload': {
'timestamp': int(time.time())
... | 587d2a72cbc5f50f0ffb0bda63668a0ddaf4c9c3 | 3,319 |
def target(x, seed, instance):
"""A target function for dummy testing of TA
perform x^2 for easy result calculations in checks.
"""
# Return x[i] (with brackets) so we pass the value, not the
# np array element
return x[0] ** 2, {'key': seed, 'instance': instance} | 131560778f51ebd250a3077833859f7e5addeb6e | 3,321 |
def prop_GAC(csp, newVar=None):
"""
Do GAC propagation. If newVar is None we do initial GAC enforce
processing all constraints. Otherwise we do GAC enforce with
constraints containing newVar on GAC Queue
"""
constraints = csp.get_cons_with_var(newVar) if newVar else csp.get_all_cons()
pruned... | a1c576cfd9920a51eb9b9884bd49b4e8f4194d02 | 3,322 |
def submit_only_kwargs(kwargs):
"""Strip out kwargs that are not used in submit"""
kwargs = kwargs.copy()
for key in ['patience', 'min_freq', 'max_freq', 'validation',
"max_epochs", "epoch_boost", "train_size", "valid_size"]:
_ = kwargs.pop(key, None)
return kwargs | e93a4b8921c5b80bb487caa6057c1ff7c1701305 | 3,323 |
import os
def convert_rscape_svg_to_one_line(rscape_svg, destination):
"""
Convert R-scape SVG into SVG with 1 line per element.
"""
output = os.path.join(destination, 'rscape-one-line.svg')
cmd = (r"perl -0777 -pe 's/\n +fill/ fill/g' {rscape_svg} | "
r"perl -0777 -pe 's/\n d=/ d=/g' |... | 7f561dcd1b9c6e540bb96fab363781dad73db566 | 3,324 |
def bags_with_gold( parents_of, _ ):
"""
Starting from leaf = 'gold', find recursively its parents upto the root and add them to a set
Number of bags that could contain gold = length of the set
"""
contains_gold = set()
def find_roots( bag ):
for outer_bag in parents_of[ bag ]:
... | 3fd2b1c260d41867a5787a14f0c50a9b5d1a2f08 | 3,325 |
def get_netcdf_filename(batch_idx: int) -> str:
"""Generate full filename, excluding path."""
assert 0 <= batch_idx < 1e6
return f"{batch_idx:06d}.nc" | 5d916c4969eb96653ea9f0a21ab8bec93ebcfafa | 3,326 |
def close(x, y, rtol, atol):
"""Returns True if x and y are sufficiently close.
Parameters
----------
rtol
The relative tolerance.
atol
The absolute tolerance.
"""
# assumes finite weights
return abs(x-y) <= atol + rtol * abs(y) | bd2597c0c94f2edf686d0dc9772288312cb36d83 | 3,328 |
def min_spacing(mylist):
"""
Find the minimum spacing in the list.
Args:
mylist (list): A list of integer/float.
Returns:
int/float: Minimum spacing within the list.
"""
# Set the maximum of the minimum spacing.
min_space = max(mylist) - min(mylist)
# Iteratively find ... | b8ce0a46bacb7015c9e59b6573bc2fec0252505d | 3,330 |
def has_even_parity(message: int) -> bool:
""" Return true if message has even parity."""
parity_is_even: bool = True
while message:
parity_is_even = not parity_is_even
message = message & (message - 1)
return parity_is_even | 8982302840318f223e9c1ab08c407d585a725f97 | 3,331 |
def mock_mkdir(monkeypatch):
"""Mock the mkdir function."""
def mocked_mkdir(path, mode=0o755):
return True
monkeypatch.setattr("charms.layer.git_deploy.os.mkdir", mocked_mkdir) | e4e78ece1b8e60719fe11eb6808f0f2b99a933c3 | 3,332 |
import zipfile
import os
def zip_dir_recursively(base_dir, zip_file):
"""Zip compresses a base_dir recursively."""
zip_file = zipfile.ZipFile(zip_file, 'w', compression=zipfile.ZIP_DEFLATED)
root_len = len(os.path.abspath(base_dir))
for root, _, files in os.walk(base_dir):
archive_root = os.pa... | 79dc58f508b2f1e78b2cc32208471f75c6a3b15c | 3,333 |
def reautorank(reaumur):
""" This function converts Reaumur to rankine, with Reaumur as parameter."""
rankine = (reaumur * 2.25) + 491.67
return rankine | aec2299999e9798530272939125cb42476f095c3 | 3,335 |
import re
def is_sedol(value):
"""Checks whether a string is a valid SEDOL identifier.
Regex from here: https://en.wikipedia.org/wiki/SEDOL
:param value: A string to evaluate.
:returns: True if string is in the form of a valid SEDOL identifier."""
return re.match(r'^[0-9BCDFGHJKLMNPQRSTVWXYZ]{6}... | 207ff94a4df99e7a546440cef1242f9a48435118 | 3,337 |
def get_img_size(src_size, dest_size):
"""
Возвращает размеры изображения в пропорции с оригиналом исходя из того,
как направлено изображение (вертикально или горизонтально)
:param src_size: размер оригинала
:type src_size: list / tuple
:param dest_size: конечные размеры
:type dest_size: lis... | 133dab529cd528373a1c7c6456a34cf8fd22dac9 | 3,339 |
def _get_split_idx(N, blocksize, pad=0):
"""
Returns a list of indexes dividing an array into blocks of size blocksize
with optional padding. Padding takes into account that the resultant block
must fit within the original array.
Parameters
----------
N : Nonnegative integer
Total ... | 21935190de4c42fa5d7854f6608387dd2f004fbc | 3,340 |
import pkg_resources
def _get_highest_tag(tags):
"""Find the highest tag from a list.
Pass in a list of tag strings and this will return the highest
(latest) as sorted by the pkg_resources version parser.
"""
return max(tags, key=pkg_resources.parse_version) | 8d2580f6f6fbb54108ee14d6d4834d376a65c501 | 3,342 |
import warnings
def disable_warnings_temporarily(func):
"""Helper to disable warnings for specific functions (used mainly during testing of old functions)."""
def inner(*args, **kwargs):
warnings.filterwarnings("ignore")
func(*args, **kwargs)
warnings.filterw... | 5e19b8f51ca092709a1e1a5d6ff0b2543a41e5e1 | 3,343 |
def norm(x):
"""Normalize 1D tensor to unit norm"""
mu = x.mean()
std = x.std()
y = (x - mu)/std
return y | ea8546da2ea478edb0727614323bba69f6af288d | 3,344 |
import re
def formatKwargsKey(key):
"""
'fooBar_baz' -> 'foo-bar-baz'
"""
key = re.sub(r'_', '-', key)
return key | 24c79b37fdd1cd6d73ab41b0d2234b1ed2ffb448 | 3,345 |
import re
def _remove_invalid_characters(file_name):
"""Removes invalid characters from the given file name."""
return re.sub(r'[/\x00-\x1f]', '', file_name) | 49a9f668e8142855ca4411921c0180977afe0370 | 3,346 |
import os
def write_curies(filepaths: dict, ontoid: str, prefix_map: dict, pref_prefix_map: dict) -> bool:
"""
Update node id field in an edgefile
and each corresponding subject/object
node in the corresponding edges
to have a CURIE, where the prefix is
the ontology ID and the class is
... | d574142a634b9a4998f8b887e4bc309661c5625e | 3,348 |
def items(dic):
"""Py 2/3 compatible way of getting the items of a dictionary."""
try:
return dic.iteritems()
except AttributeError:
return iter(dic.items()) | 2664567765efe172591fafb49a0efa36ab9fcca8 | 3,351 |
import random
import logging
import time
def request_retry_decorator(fn_to_call, exc_handler):
"""A generic decorator for retrying cloud API operations with consistent repeatable failure
patterns. This can be API rate limiting errors, connection timeouts, transient SSL errors, etc.
Args:
fn_to_cal... | 0813cc19d9826275917c9eb701683a73bfe597f9 | 3,352 |
def as_string(raw_data):
"""Converts the given raw bytes to a string (removes NULL)"""
return bytearray(raw_data[:-1]) | 6610291bb5b71ffc0be18b4505c95653bdac4c55 | 3,353 |
import math
def generate_trapezoid_profile(max_v, time_to_max_v, dt, goal):
"""Creates a trapezoid profile with the given constraints.
Returns:
t_rec -- list of timestamps
x_rec -- list of positions at each timestep
v_rec -- list of velocities at each timestep
a_rec -- list of accelerations a... | 5851cfab06e20a9e79c3a321bad510d33639aaca | 3,354 |
import six
def str_to_bool(s):
"""Convert a string value to its corresponding boolean value."""
if isinstance(s, bool):
return s
elif not isinstance(s, six.string_types):
raise TypeError('argument must be a string')
true_values = ('true', 'on', '1')
false_values = ('false', 'off',... | c228321872f253ce3e05c6af9284ec496dea8dcf | 3,355 |
import os
import re
import sys
def help(user_display_name, module_file_fullpath, module_name):
"""Generate help message for all actions can be used in the job"""
my_path = os.path.dirname(module_file_fullpath)
my_fname = os.path.basename(module_file_fullpath)
my_package = module_name.rsplit(u'.')[-2]... | d76d0a2c07f7d60d1f9409281dc699d402fa1dd7 | 3,356 |
def winner(board):
"""
Returns the winner of the game, if there is one.
"""
#looking horizontal winner
i = 0
while i < len(board):
j = 1
while j <len(board):
if board[i][j-1]==board[i][j] and board[i][j] == board[i][j+1]:
return board[i][j]
... | 31ab2cf04dfe269598efdd073762505643563a96 | 3,358 |
import socket
def _nslookup(ipv4):
"""Lookup the hostname of an IPv4 address.
Args:
ipv4: IPv4 address
Returns:
hostname: Name of host
"""
# Initialize key variables
hostname = None
# Return result
try:
ip_results = socket.gethostbyaddr(ipv4)
if len(... | 7771887dbfcd60e73b8fce0ce4029fcd7058a7d1 | 3,359 |
def sessions(request):
"""
Cookies prepeocessor
"""
context = {}
return context | 562f4e9da57d3871ce780dc1a0661a34b3279ec5 | 3,360 |
import six
import base64
def Base64WSEncode(s):
"""
Return Base64 web safe encoding of s. Suppress padding characters (=).
Uses URL-safe alphabet: - replaces +, _ replaces /. Will convert s of type
unicode to string type first.
@param s: string to encode as Base64
@type s: string
@retur... | cb28001bddec215b763936fde4652289cf6480c0 | 3,361 |
def onlyWikipediaURLS(urls):
"""Some example HTML page data is from wikipedia. This function converts
relative wikipedia links to full wikipedia URLs"""
wikiURLs = [url for url in urls if url.startswith('/wiki/')]
return ["https://en.wikipedia.org"+url for url in wikiURLs] | df9ecbb73dfc9a764e4129069a4317517830307a | 3,362 |
import fcntl
import os
def SetFdBlocking(fd, is_blocking):
"""Set a file descriptor blocking or nonblocking.
Please note that this may affect more than expected, for example it may
affect sys.stderr when called for sys.stdout.
Returns:
The old blocking value (True or False).
"""
if hasattr(fd, 'file... | 58d1496152cc752b59e8abc0ae3b42387a2f8926 | 3,363 |
def RetrieveResiduesNumbers(ResiduesInfo):
"""Retrieve residue numbers."""
# Setup residue IDs sorted by residue numbers...
ResNumMap = {}
for ResName in ResiduesInfo["ResNames"]:
for ResNum in ResiduesInfo["ResNum"][ResName]:
ResNumMap[ResNum] = ResName
ResNumsList = []
... | e9f522af368a8a058792b26f9cf53b1114e241ef | 3,366 |
import requests
import json
def search(keyword, limit=20):
"""
Search is the iTunes podcast directory for the given keywords.
Parameter:
keyword = A string containing the keyword to search.
limit: the maximum results to return,
The default is 20 results.
... | 922cd7dfaea30e7254c459588d28c33673281dac | 3,367 |
import torch
def permute(x, in_shape='BCD', out_shape='BCD', **kw):
""" Permute the dimensions of a tensor.\n
- `x: Tensor`; The nd-tensor to be permuted.
- `in_shape: str`; The dimension shape of `x`. Can only have characters `'B'` or `'C'` or `'D'`,
which stand for Batch, Channel, or extra Dim... | e74594df581c12891963e931999563374cd89c7d | 3,373 |
import re
def fullmatch(regex, string, flags=0):
"""Emulate python-3.4 re.fullmatch()."""
matched = re.match(regex, string, flags=flags)
if matched and matched.span()[1] == len(string):
return matched
return None | 72de0abe5c15dd17879b439562747c9093d517c5 | 3,374 |
def myFunction(objectIn):
"""What you are supposed to test."""
return objectIn.aMethodToMock() + 2 | 1907db338a05f2d798ccde63366d052404324e6f | 3,376 |
def get_training_set_count(disc):
"""Returns the total number of training sets of a discipline and all its
child elements.
:param disc: Discipline instance
:type disc: models.Discipline
:return: sum of training sets
:rtype: int
"""
training_set_counter = 0
for child in disc.get_desc... | 9b28a9e51e04b559f05f1cc0255a6c65ca4a0980 | 3,377 |
def _async_attr_mapper(attr_name, val):
"""The `async` attribute works slightly different than the other bool
attributes. It can be set explicitly to `false` with no surrounding quotes
according to the spec."""
if val in [False, 'False']:
return ' {}=false'.format(attr_name)
elif val:
... | 79e72067b244d705df9aa09a78db656f0847938c | 3,378 |
def print_pos_neg(num):
"""Print if positive or negative in polarity level
>>> print_pos_neg(0.8)
'positive'
>>> print_pos_neg(-0.5)
'negative'
"""
if num > 0:
return "positive"
elif num == 0:
return "neutral"
else:
return "negative" | 414aa98f54a2f01af24d591ae47ec4f394adf682 | 3,379 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.