content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
from dateutil.tz import tzlocal, gettz
def to_system_time(dt):
"""
Converts a timezone aware datetime object to an object to be used in the messagebus scheduler
:param dt: datetime object to convert
:return: timezone aware datetime object that can be scheduled
"""
tz = tzlocal()
if dt.tzi... | 82557530afbe30219da37d631d5cef21e9af316a | 655,162 |
import torch
def to_gpu(x):
"""Move `x` to cuda device.
Args:
x (tensor)
Returns:
torch.Variable
"""
x = x.contiguous()
if torch.cuda.is_available():
x = x.cuda(non_blocking=True)
return torch.autograd.Variable(x) | 3740f42fc3d642a5dcfaa603791817c81e74e7a3 | 655,164 |
import math
def floor_with_place(value, keep_decimal_place):
"""
無條件捨去小數點後 N 位
Args:
value(float): 數值
keep_decimal_place(2): 要保留到小數點第幾位, e.g 2,表示保留到第二位,後面的位數則無條件捨去
"""
scale_value = math.floor(value * pow(10, keep_decimal_place))
result = scale_value / pow(10, keep_decimal_place)
return result | e36875b424d99a928aa08e4758a28f2acdaf8a2a | 655,170 |
def ci_equals(left, right):
"""Check is @left string is case-insensative equal to @right string.
:returns: left.lower() == right.lower() if @left and @right is str. Or
left == right in other case.
"""
if isinstance(left, str) and isinstance(right, str):
return left.lower() == right.lower()
... | d3b927b196b3a1e0e9be8562f78b92191566a668 | 655,176 |
def get_trig_val(abs_val: int, max_unit: int, abs_limit: int) -> int:
"""Get the corresponding trigger value to a specific limit. This evenly
devides the value so that the more you press the trigger, the higher the
output value.
abs_val - The current trigger value
max_unit - The maximum value to re... | c965594555fb28ba3c85713d538ad7c47abdd705 | 655,178 |
def transpose(g):
"""Fonction qui, à l'aide d'une grille sous forme de liste contenant des listes, retourne une nouvelle grille
pour laquelle on a inversé les colonnes et les lignes de la grille d'origine.
Paramètre(s):
- g list: Grille à transposer sous la forme de liste de liste. La liste parente... | b9f7be8b0c6e1699230be7b238113ea764c90735 | 655,179 |
import random
def complete(subjects, seed=None):
""" Create a randomization list using complete randomization.
Complete randomization randomly shuffles a list of group labels. This
ensures that the resultant list is retains the exact balance desired.
This randomization is done in place.
Args:
... | 60cadade7b6d00b027bfc2a5524f664a67d2f879 | 655,181 |
def str_to_int(num_str):
"""
Converts string into number.
Parameters:
num_str: a string to be converted into number
Returns:
numeric value of the string representing the number
"""
if num_str.lower().startswith('0x'):
return int(num_str[2:], 16)
return int(num_str... | 460bb299eee9f5dbdc7528db8249af54956c0a4a | 655,189 |
from typing import List
def scale_prev_up_to_1(prev_vals: List[float], fraction: float):
"""
Apply a percentage to the previous value, saturating at one or zero
"""
val = prev_vals[-1] * fraction
if val > 1:
return 1
elif val < 0:
return 0
else:
return val | 2a7b8946c4d12595e1f633fbb3c7789b07f97205 | 655,191 |
def manhattan_distance(start, end):
"""Calculate the Manhattan distance from a start point to an end point"""
return abs(end.x - start.x) + abs(end.y - start.y) | 16dfa01c72a883106e8db0b9a41b274d4e38a37a | 655,195 |
def parse_alignment(alignment):
"""
Parses an alignment string.
Alignment strings are composed of space separated graphemes, with
optional parentheses for suppressed or non-mandatory material. The
material between parentheses is kept.
Parameters
----------
alignment : str
The a... | 8069f798238d917f09a7e894ce21c8c1213b5faa | 655,196 |
def highlight_single_token(token):
"""Highlight a single token with ^."""
return {token.start_row: " " * token.start_col + "^" * len(token.string)} | d2c0287d423bbb41731d3847e211f3eee8233ee7 | 655,199 |
def voter_notification_settings_update_doc_template_values(url_root):
"""
Show documentation about voterNotificationSettingsUpdate
"""
required_query_parameter_list = [
{
'name': 'api_key',
'value': 'string (from post, cookie, or get (in that order))', # b... | ad2fda6cfb0d2d228b6fc6ae6b18d71026728157 | 655,203 |
import re
def parse_gitmodules(input_text):
"""Parse a .gitmodules file and return a list of all the git submodules
defined inside of it. Each list item is 2-tuple with:
- submodule name (string)
- submodule variables (dictionary with variables as keys and their values)
The input should be a ... | 0c0f1dda715f1f0db4418c0762137b40842a74ab | 655,204 |
def is_clockwise(vertices):
"""
Returns whether a list of points describing a polygon are clockwise or counterclockwise.
is_clockwise(Point list) -> bool
Parameters
----------
vertices : a list of points that form a single ring
Examples
--------
>>> is_clockwise([Point((0, 0)), Point... | 643ff81227c7c0a958fba4867cd80b7d33d9588c | 655,205 |
import yaml
def yaml_from_dict(dictionary):
"""convert a Python dictionary to YAML"""
return yaml.dump(dictionary) | c33ebdd7c64ca4862618cd65134df772e67386e4 | 655,207 |
def _GetOrAddArgGroup(parser, help_text):
"""Create a new arg group or return existing group with given help text."""
for arg in parser.arguments:
if arg.is_group and arg.help == help_text:
return arg
return parser.add_argument_group(help_text) | b66d2c36b08d1676161f48dfd30254efa70fc942 | 655,214 |
import re
def parse_show_arp(raw_result):
"""
Parse the 'show arp' command raw output.
:param str raw_result: vtysh raw result string.
:rtype: dict
:return: The parsed result of the show arp command in a \
dictionary of the form. Returns None if no arp found or \
empty dictionary:
... | bdba95d2dbb5d742b629f2c5b43c58295c4017f4 | 655,215 |
def quote(s: str) -> str:
"""
Quotes the '"' and '\' characters in a string and surrounds with "..."
"""
return '"' + s.replace('\\', '\\\\').replace('"', '\\"') + '"' | c852970bdc6aee2068e3c064dd476d8ebc9c9cfe | 655,216 |
import re
def remove_structure_definitions(data):
"""
Remove lines of code that aren't representative of LLVM-IR "language"
and shouldn't be used for training the embeddings
:param data: input data as a list of files where each file is a list of strings
:return: input data with non-representative ... | c88074e1470bad0229e31292d4e309b75eba415c | 655,218 |
def normalise_list(
l: list,
d: int,
f: int = 1,
) -> list:
"""Normalise a list according to a given displacement
Parameters
----------
l : list
The list of values
n : int, optional
The displacement, by default 0
Returns
-------
list
The normalis... | a8a16073a52c48aed03108e9d7f47524003fbf92 | 655,221 |
def assert_time_of_flight_is_positive(tof):
"""
Checks if time of flight is positive.
Parameters
----------
tof: float
Time of flight.
"""
if tof <= 0:
raise ValueError("Time of flight must be positive!")
else:
return True | 54f85189ca8b25f0447ccbca60179a2eff41b018 | 655,223 |
def int2mac(integer, upper=False):
"""
Convert a integer value into a mac address
:param integer: Integer value of potential mac address
:param upper: True if you want get address with uppercase
:return: String mac address in format AA:BB:CC:DD:EE:FF
"""
def format_int():
return zip... | e5d020c2f1151f1235a8700606a3edb369dc3afd | 655,224 |
def filter_phrases(input_str, filter_list):
"""
Filters out phrases/words from the input string
:param input_str: String to be processed.
:return: string with phrases from filter_list removed.
"""
for phrase in filter_list:
input_str = input_str.replace(phrase,'')
return input_str | 1e5ee006a665f6b9660e17e2f9d0dff187023b49 | 655,225 |
def build_mpi_call_str(task_specs,common_options,format_opts=None,runner='mpiexec'):
"""Summary
Args:
task_specs (list): List of strings, each containing an MPI task description, eg
e.g: ['-n {nrunners} python3 awrams.module.example {pickle_file}']
common_options ... | a63ed5c05e31d51b42913157f8a3f448477ef80d | 655,226 |
def get_channel_dim(input_tensor, data_format='INVALID'):
"""Returns the number of channels in the input tensor."""
shape = input_tensor.get_shape().as_list()
assert data_format != 'INVALID'
assert len(shape) == 4
if data_format == 'NHWC':
return int(shape[3])
elif data_format == 'NCHW':
return int(... | cdd2dfd7e270395566527742042050c922b48b94 | 655,228 |
def index_of_square(square):
"""
Index of square
Args:
square (String): Square in chess notation e.g. f7
Returns:
Int: Index of square in bitboard
"""
line = ord(square[0].lower()) - ord('a')
row = int(square[1])
idx = 8 * (row - 1) + line
return idx | e48d344168254828e4b6fdff2c18f2f472db89f2 | 655,234 |
def _check_attribute(obj, attr, typ, allow_none=False):
"""Check that a given attribute attr exists in the object obj and
is of type typ. Optionally, allow the attribute to be None.
"""
if not hasattr(obj, attr):
return False
val = getattr(obj, attr)
return isinstance(val, typ) or (allo... | 7925e92ce5b7b68660e9a5519d7de993e393afa5 | 655,235 |
def join(func):
"""Decorator that joins characters of a returned sequence into a string."""
return lambda *args: ''.join(func(*args)) | c561a9167da83c88355cb3e8458df7b5c80453c7 | 655,237 |
def divide(value, divisor):
"""
Divide value by divisor
"""
v = float(value)
d = float(divisor)
return v / d | 2c251cf80842c3c0222fa612eaf7c2520c6913d8 | 655,238 |
import warnings
def datastream_does_not_exist_warning(sensor_type, operation):
"""Warn about not existing datastreams."""
message = 'The datastream "{}" does not exist for the current session.\
The performed operation "{}" will have not effect'.format(
sensor_type, operation
)
return warn... | d635f1978c6ee84561a4193920a0c9863c8fde03 | 655,240 |
def getWAMP(rawEMGSignal, threshold):
""" Wilson or Willison amplitude is a measure of frequency information.
It is a number of time resulting from difference between the EMG signal of two adjoining segments, that exceed a threshold.::
WAMP = sum( f(|x[i] - x[i+1]|)) for n = 1 --> n-1
... | 3e47e63d09c6d4ae1db2fe5e7fafa028c238dcf5 | 655,242 |
def fileGroupName(filePath):
"""
Get the group file name. foo.0080 would return foo
"""
return filePath.split('.')[0] | be43b8ce497b46ad79b153e686c1ed3b78ea6509 | 655,243 |
def _min_filter(path_data, min_genes, min_transcripts):
"""
Return `True` is path_data has more than min_genes and min_transcripts.
"""
if min_genes > 1:
if len(path_data.Genes) < min_genes:
return False
if min_transcripts > 1:
if len(path_data.Transcripts) < min_transcri... | dcb1bc496b1a22fd8dc6394dd2d7119db7e7e09d | 655,246 |
def InvertDictionary(origin_dict):
"""Invert the key value mapping in the origin_dict.
Given an origin_dict {'key1': {'val1', 'val2'}, 'key2': {'val1', 'val3'},
'key3': {'val3'}}, the returned inverted dict will be
{'val1': {'key1', 'key2'}, 'val2': {'key1'}, 'val3': {'key2', 'key3'}}
Args:
origin_dict:... | 1fa11a1a9843ffe7bf97a3cf0c57775f7d26b584 | 655,250 |
from typing import List
import re
def split(sentence: str) -> List[str]:
"""
Split a string by groups of letters, groups of digits,
and groups of punctuation. Spaces are not returned.
"""
return re.findall(r"[\d]+|[^\W\d_]+|[^\w\s]+", sentence) | d8e8e3ac0a0b00c4346eedef29693a5d66a7f3a4 | 655,252 |
def get_user_name(email: str) -> str:
"""Returns username part of email, if valid email is provided."""
if "@" in email:
return email.split("@")[0]
return email | 8dfbed701a7e4c2f87f5d1e8bc481e44494de955 | 655,254 |
from typing import List
def rotate_right(sequence: List[int]) -> List[int]:
"""
Shifts the elements in the sequence to the right, so that the last element of the sequence becomes the first.
>>> rotate_right([1,2,3,4,5])
[5, 1, 2, 3, 4]
>>> rotate_right([1])
[1]
>>> rotate_right([])
[]... | a936fd2ed35b03c0a67738d457ff2748d46a52cc | 655,257 |
import itertools
def get_all_combinations(elements):
""" get all combinations for a venn diagram from a list of elements"""
result = []
n = len(elements)
for i in range(n):
idx = n - i
result.append(list(set(itertools.combinations(elements, idx))))
return result | d6423d46fe8104fdb0f338446c8f91c655e89062 | 655,259 |
def calc_theta_int_inc(theta_int_ini, delta_theta_int_inc):
"""
Eq. (1) in [prEN 15316-2:2014]
:param theta_int_ini: temperature [C]
:type theta_int_ini: double
:param delta_theta_int_inc: temperature [C]
:type delta_theta_int_inc: double
:return: sum of temperatures [C]
:rtyp... | 35ee8827750bb4e74b534c9577d216bc0dc79150 | 655,261 |
from typing import Sequence
def evaluate_poly(poly: Sequence[float], x: float) -> float:
"""Evaluate a polynomial f(x) at specified point x and return the value.
Arguments:
poly -- the coeffiecients of a polynomial as an iterable in order of
ascending degree
x -- the point at which to eva... | deaff8810fccb4b75d4c18316ec19e70e15ed8c3 | 655,262 |
from typing import Optional
import html
def unescape_string(value: Optional[str]) -> Optional[str]:
"""Perform HTML unescape on value."""
if value is None:
return value
return html.unescape(str(value)) | d3bbb43fa7677bb87e5b45f2678d4f0e2a4ee21e | 655,269 |
def split(target_name):
"""Split a target name. Returns a tuple "(build_module, name)".
The split is on the first `:`.
Extra `:` are considered part of the name.
"""
return target_name.split(':', 1) | 3f0da32429be382cc736b591b1b8aa1c72060628 | 655,277 |
def validate(config):
"""
Validate the beacon configuration
"""
# Configuration for aix_account beacon should be a dictionary
if not isinstance(config, dict):
return False, "Configuration for aix_account beacon must be a dict."
if "user" not in config:
return (
False,... | a18e90904646a90c5ec1d1e11533eeeb25c49e25 | 655,279 |
def calc_closest_point_w_linestr(point, linestr):
"""
Calculate closest point between shapely LineString and Point.
Parameters
----------
point : object
Shapely point object
linestr : object
Shapely LineString object
Returns
-------
closest_point : object
Sh... | 4df35993dddba1185ac984a79245a1692a537e57 | 655,281 |
def _compute_time(index, align_type, timings):
"""Compute start and end time of utterance.
Adapted from https://github.com/lumaku/ctc-segmentation
Args:
index: frame index value
align_type: one of ["begin", "end"]
Return:
start/end time of utterance in seconds
"""
mid... | d2efc4768d4779e8452afdc2015fffbd30d14ffe | 655,282 |
import math
def lcc_simp(seq):
"""Local Composition Complexity (LCC) for a sequence.
seq - an unambiguous DNA sequence (a string or Seq object)
Returns the Local Composition Complexity (LCC) value for the entire
sequence (as a float).
Reference:
Andrzej K Konopka (2005) Sequence Complexity ... | 3eb7765d991fbd8bcad06275cfa9487fdd1920f7 | 655,283 |
from typing import List
def right(lst: List[int], idx: int) -> int:
"""Return right heap child."""
right_idx = idx * 2 + 2
if right_idx < len(lst):
return right_idx
else:
return -1 | b69301c7326eaa3fa00a9635fed8424942470e48 | 655,284 |
def get_temp_dir(app_name):
"""Get the temporary directory for storing fab deploy artifacts.
Args:
app_name: a string representing the app name
Returns:
a string representing path to tmp dir
"""
return '/tmp/.fab-deploy-{}'.format(app_name) | 3c4ff6725c2fafb02ecb74ae21e8e2fff3f84ab2 | 655,288 |
def command( *args ):
"""
Returns the command as a string joining the given arguments. Arguments
with embedded spaces are double quoted, as are empty arguments.
"""
cmd = ''
for s in args:
if cmd: cmd += ' '
if not s or ' ' in s:
cmd += '"'+s+'"'
else:
... | 3412deb9c2b8ca842a2ddec587b4e4a3d1862eb9 | 655,290 |
def find_nearest(dataframes, x, npoints=5):
"""
Function that will take a list of dataframes, and
return slices of the dataframes containing a specified
number of closest points.
"""
nearest = [
df.loc[(df["Frequency"] - x).abs().argsort()[:npoints]] for df in dataframes
... | a46d117602952720db77a5de5aacbeb5335c012b | 655,292 |
def threept_center(x1, x2, x3, y1, y2, y3):
"""
Calculates center coordinate of a circle circumscribing three points
Parameters
--------------
x1: `double`
First x-coordinate
x2: `double`
Second x-coordinate
x3: `double`
Third y-coordinate
y1: `double`
... | ddb71ed0c380105daeb13c681057f099a7195c2e | 655,295 |
def _clean_name(name):
"""Strip surrounding whitespace."""
return name.strip() | ba2aa25fb57ac76de43475b56e587222f38f63c7 | 655,300 |
import calendar
def short_month(i, zero_based=False):
""" Looks up the short name of a month with an index.
:param i: Index of the month to lookup.
:param zero_based: Indicates whether the index starts from 0.
:returns: The short name of the month for example Jan.
>>> from dautils import ts
... | 98667ffff6b70eec23662bc8b87b55614ee52766 | 655,301 |
def delete_double_undervotes(tally):
"""
Delete all double undervotes from a ballot dictionary tally
If a double undervote occurs, delete it and all
subsequent positions from ballot.
Args:
dictionary {tally}: dictionary mapping ballots to nonnegative reals
Returns:
dictionary ... | 984a474ba76881bcb1234022d3614df05b5be524 | 655,302 |
from typing import List
def parse_timeseries(
timeseries_str, time_input_unit="minute", time_output_unit="second"
) -> List[List[float]]:
"""Create a list of 2-list [timestep (seconds), value (mm/hour)]."""
if not timeseries_str:
return [[]]
output = []
for line in timeseries_str.split():
... | 90c498650adf5764a6e7e4fedc1bcf7da454f192 | 655,305 |
def authz_query(authz, field='collection_id'):
"""Generate a search query filter from an authz object."""
# Hot-wire authorization entirely for admins.
if authz.is_admin:
return {'match_all': {}}
collections = authz.collections(authz.READ)
if not len(collections):
return {'match_none... | d45612fa67e7a9ae687264f287f505078131f27d | 655,309 |
def mul(a, b):
"""return the multiply of a and b"""
return a * b | 8de0602e05ce4e9be09e2c2b598a8b0f24bd446a | 655,312 |
def _solve_expx_x_logx(tau, tol, kernel, ln, max_steps=10):
"""Solves the equation
log(pi/tau) = pi/2 * exp(x) - x - log(x)
approximately using Newton's method. The approximate solution is guaranteed
to overestimate.
"""
# Initial guess
x = kernel.log(2 / kernel.pi * ln(kernel.pi / tau))
... | 7bf52853949de19f7cac1f19173f6591129cfe6b | 655,313 |
import json
def json_from_text(text_file):
"""JSON to dictionary from text file."""
tmp = open(text_file, "r")
data = json.load(tmp)
return data | ace88043662571103f989366bd9e186ce518255e | 655,317 |
def student_ranking (student_scores, student_names):
"""Organize the student's rank, name, and grade information in ascending order.
:param student_scores: list of scores in descending order.
:param student_names: list of names in descending order by exam score.
:return: list of strings in format ["... | 40320644c68540b2676f89164e812d961eb85df2 | 655,318 |
def find_heuristic_position(child_partition):
"""
This function finds the starting position of different heuristics in a combined game payoff matrix.
:param child_partition:
:return:
"""
position = {}
i = 0
for method in child_partition:
position[method] = (i, i+child_partition[m... | 943582f95a2491ca6f2f02e3088a399e673f208f | 655,320 |
import time
import random
def _custom_libname(filetype, salt_len=2):
"""
Choose a custom name for library file
Format:
filetype: file extensiion
cur_time: current time
salt: salt_len number of digits
<cur_time>_<salt>.<filetype>
Args:
filety... | f6edf0c0ced94a0e418519a353c96d521934b763 | 655,321 |
def to_bytes(obj):
"""Convert object to bytes"""
if isinstance(obj, bytes):
return obj
if isinstance(obj, str):
return obj.encode('utf-8')
return str(obj).encode('utf-8') | 94435faaccc0ce43d5a3faf77b5319158c5b6cfa | 655,322 |
def IsPureVirtual(fname):
"""
Returns true if a header file is a pure virtual (no implementation)
Pure virtual header files are designated as such by the phrase "Pure virtual"
at the first line
Input:
fname - File name
"""
f = open(fname)
fl = f.readline()
f.close()
return f... | f92181a1a49fe2db4bbfc1e93191f61620378a41 | 655,324 |
def _compose2(f, g):
"""Compose 2 callables"""
return lambda *args, **kwargs: f(g(*args, **kwargs)) | 1e63b293657e31ad88da1b0b54ba5c78b3af2dbc | 655,330 |
import hashlib
def get_md5_hash(value):
"""Returns the md5 hash object for the given value"""
return hashlib.md5(value.lower().encode("utf-8")) | 0238a169cd31b09ade156898511408f49de0eef7 | 655,333 |
def cap(value: float, minimum: float, maximum: float) -> float:
"""Caps the value at given minumum and maximum.
Arguments:
value {float} -- The value being capped.
minimum {float} -- Smallest value.
maximum {float} -- Largest value.
Returns:
float -- The capped value or the... | 14d78f11a674b8dac5595621a09b237d5fb3a71d | 655,334 |
import re
def partial_path_match(path1, path2, kwarg_re=r'\{.*\}'):
"""Validates if path1 and path2 matches, ignoring any kwargs in the string.
We need this to ensure we can match Swagger patterns like:
/foo/{id}
against the observed pyramid path
/foo/1
:param path1: path of a url
... | abf236654db3bae15a6bcf086f3b73f4e3d69b3f | 655,337 |
def compute_checksum(datafile):
"""Checksum is the sum of the differences between the
minimum and maximum value on each line of a tab delimited
data file.
"""
checksum = 0
with open(datafile, 'rb') as f:
for line in f:
# Remove trailing newline, split on tabs
nums... | 0029db606cd7412a0f629d27923a09885c411a48 | 655,338 |
def comp_length(self):
"""Compute the length of the line
Parameters
----------
self : Segment
A Segment object
Returns
-------
length: float
lenght of the line [m]
Raises
------
PointSegmentError
Call Segment.check()
"""
self.check()
z1 =... | bceae383cfed23f113459676b950d7d58f7b6108 | 655,341 |
def is_filtered(variant):
"""Returns True if variant has a non-PASS filter field, or False otherwise."""
return bool(variant.filter) and any(
f not in {'PASS', '.'} for f in variant.filter) | e7795c87f84978b58eeedf88f71c599a18d55508 | 655,344 |
def subhourly_energy_delivered_rule(mod, prj, tmp):
"""
If no subhourly_energy_delivered_rule is specified in an operational type
module, the default subhourly energy delivered is 0.
"""
return 0 | 00fd10d99e174f2b5b3dde7dcaf71ea424937232 | 655,352 |
def gini_index(data, feature_name):
"""
Calculates the gini index of the feature with the given name.
:param data: the data to analyze
:param feature_name: the name of the feature to anlyze
:return: the gini index of the specified feature
"""
gini_index = 1
for value_count in data... | 84ac1905b8e5a8436703b77b61c7f2e864dec266 | 655,355 |
def sum_stats(stats_data):
"""
Summarize the bounces, complaints, delivery attempts and rejects from a
list of datapoints.
"""
t_bounces = 0
t_complaints = 0
t_delivery_attempts = 0
t_rejects = 0
for dp in stats_data:
t_bounces += dp['Bounces']
t_complaints += dp['Com... | 671f9f229432475ccfe27ded62ac6fafbb96c6e0 | 655,356 |
def epdir(episode: int) -> str:
"""
Returns the episode folder name given an episode number.
:param episode: The episode number
:return: A formatted string of the episode folder name.
"""
return f"ep{episode}" | 1db504a507c18f443421f1744643705dab163982 | 655,358 |
def logistic_map(pop, rate):
"""
Define the equation for the logistic map.
Arguments
---------
pop: float
current population value at time t
rate: float
growth rate parameter values
Returns
-------
float
scalar result of logistic map at time t+1
"""
... | 8e216b5958740d4762497939f6a73f858b7d80ad | 655,359 |
import socket
def open_port(host=''):
""" Return a probably-open port
There is a chance that this port will be taken by the operating system soon
after returning from this function.
"""
# http://stackoverflow.com/questions/2838244/get-open-tcp-port-in-python
s = socket.socket(socket.AF_INET, ... | 47adc831149b5bc5e4a6cde82b2ad7cd21c34d15 | 655,362 |
import math
def eq2gal(ra,dec):
"""
Convert Equatorial coordinates to Galactic Coordinates in the epch J2000.
Keywords arguments:
ra -- Right Ascension (in radians)
dec -- Declination (in radians)
Return a tuple (l, b):
l -- Galactic longitude (in radians)
b -- Galactic latitude (in radians)
"""
# RA(rad... | a2413e65232003957d383d387eb124a00fe68e79 | 655,364 |
def lpad(s, l):
""" add spaces to the beginning of s until it is length l """
s = str(s)
return " "*max(0, (l - len(s))) + s | f903e9beea4cbc43bd2453f9f768923b3e088a07 | 655,365 |
def sort_cells_closest(start_cell, cells):
"""
Description:
Returns a sorted list of cells by 'closest' based on the given start cell
Args:
start_cell (tuple): Coordinates (x, y) of the reference cell
cells (list): List of (x, y) tuples that are the cells to compare
Returns:
... | 72b2c591e8e0a1b70374779660ccb6e1884aab25 | 655,369 |
def _SplitStep(user_name):
"""Given a user name for a step, split it into the individual pieces.
Examples:
_SplitStep('Transform/Step') = ['Transform', 'Step']
_SplitStep('Read(gs://Foo)/Bar') = ['Read(gs://Foo)', 'Bar']
Args:
user_name: The full user_name of the step.
Returns:
A list repres... | bf8cc02a4efebeff284bba7cb5d86a43112b7998 | 655,372 |
from typing import Union
from typing import List
def _get_error_list(_errors: dict) -> Union[List, None]:
"""
This method return a list of errors,
if any exists
:param _errors: Dict of errors
:return: List of errors or None
"""
errors = []
for err in _errors:
errors.append({
... | 30c76c11aeab175d63066a5a29747c05ff7b550a | 655,374 |
def format_commands(commands):
"""
This function format the input commands and removes the prepend white spaces
for command lines having 'set' or 'delete' and it skips empty lines.
:param commands:
:return: list of commands
"""
return [
line.strip() if line.split()[0] in ("set", "del... | 2a5e2032bac0b53e404fc72d5c5030cb736da1e9 | 655,383 |
import re
def _validateStart(value, match):
"""
Make sure that the characters preceding an ISBN number do not invalidate the match. The match is considered to
be invalid if it is preceded by any alphanumeric character.
:param value: String that was being searched
:param match: MatchObject ret... | 07ddfc18198887cbd5e5dce4b3fc2448fbe12ad7 | 655,385 |
import operator
def array_combine(a, b, op=operator.and_, func=lambda x: x):
""" Returns op(func(a), func(b)) if a and b are both not None;
if one is None, then returns func() on the non-None array;
if both are None, then returns None.
"""
if a is not None and b is not None:
return op(func... | caec67e8a75a082ddbafbc369473062923935bf6 | 655,388 |
def serializer_workbook_path() -> str:
""" Path to excel workbook used by serializer tests. """
return 'tests/data/serializer/test.xlsx' | c11e38dc5581635261b13bb3b94022e16da29632 | 655,389 |
def dic_value(input_dic, key, default=None):
"""
Returns the value from the dic. If input_dic is not a dict, or there is no such key, then returns default
"""
if isinstance(input_dic, dict):
value = input_dic.get(key, default)
else:
value = default
return value | c88733e041acbb2ec61ab0d5f5d4bd90d9033b53 | 655,399 |
def list_dict(l):
"""
return a dictionary with all items of l being the keys of the dictionary
"""
d = {}
for i in l:
d[i]=None
return d | c9f4fab5fb06246fa597ccf2bb45349b46ab39d3 | 655,401 |
def train_and_test_partition(inputs, targets, train_part, test_part):
"""
Splits a data matrix (or design matrix) and associated targets into train
and test parts.
parameters
----------
inputs - a 2d numpy array whose rows are the data points, or can be a design
matrix, where rows are t... | a41829faecf34256ef2ae6d80c0fe72713832cb4 | 655,402 |
import struct
def parse_hdr(data):
"""
Parse L2CAP packet
0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7
-----------------------------------------------------------------
| length | channel id |
-------------------------------------... | 447ca1530451824fac7e001c7c6cdebf83d44eb2 | 655,408 |
import re
def get_capitalization_pattern(word, beginning_of_sentence=False):
"""Return the type of capitalization for the string.
Parameters
----------
word : str
The word whose capitalization is determined.
beginning_of_sentence : Optional[bool]
True if the word appears at the be... | 53cfeecf92afa77ebb76602a1f619a18753dacf7 | 655,409 |
def readout_tbinfo(line):
"""
Builds the dict for tb info from line provided by qemu
"""
split = line.split("|")
tb = {}
tb["id"] = int(split[0], 0)
tb["size"] = int(split[1], 0)
tb["ins_count"] = int(split[2], 0)
tb["num_exec"] = int(split[3], 0)
tb["assembler"] = split[4].repla... | 2384fb8ecb189116d959fa835a1a78ed8a7dc3f1 | 655,415 |
from typing import Any
from pathlib import Path
def tmp_path(tmpdir: Any) -> Path:
"""Convert py.path.Local() to Path() objects."""
return Path(tmpdir.strpath) | 4abad0093eeff9c4e3721641b79cf0dd0e5e4c1e | 655,418 |
import random
def random_range(n, total):
"""Return a randomly chosen list of n positive integers summing to total.
Each such list is equally likely to occur."""
dividers = sorted(random.sample(range(1, total), n - 1))
return [a - b for a, b in zip(dividers + [total], [0] + dividers)] | 4ee02ffd2b5d96d344642cd92b51ad77bf3a46ca | 655,419 |
def file_to_list(file):
"""Take each line of a file, strip it, and append to a list"""
return [line.strip() for line in open(file)] | 3a8b05c8c1e0d9447c9098a8adce39ca382a166e | 655,421 |
def override(cls):
"""Decorator for documenting method overrides.
Args:
cls: The superclass that provides the overridden method. If this
cls does not actually have the method, an error is raised.
Examples:
>>> from ray.rllib.policy import Policy
>>> class TorchPolicy(Po... | d427593fde1cac4bf6cc582adcf909e46302ff7b | 655,427 |
import imp
def create_module(problem_data):
"""Creates a new module for storing compiled code.
Parameters
----------
problem_data - dict
Problem data dictionary
Returns
-------
New module for holding compiled code
"""
problem_name = problem_data['problem_name']
module... | 961bdaea85382d2a0f9f2a3d8f49a69c26819c07 | 655,429 |
import torch
def transform_homogeneous(matrices, vertices):
"""Applies batched 4x4 homogenous matrix transformations to 3-D vertices.
The vertices are input and output as as row-major, but are interpreted as
column vectors multiplied on the right-hand side of the matrices. More
explicitly, this funct... | 47c3d9a51188a28c88b489b02d4173c4ebddb46a | 655,430 |
def no_cleanup(value, args):
"""Default cleanup function, returns the unchanged value."""
return value | 67662efb7e52709bfc15d131fc4f597e7490e9e0 | 655,431 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.