content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def uptime_seconds(uptime_list):
"""
Convert a list of the following form:
[years, weeks, days, hours, minutes]
To an uptime in seconds
"""
years = uptime_list[0]
weeks = uptime_list[1]
days = uptime_list[2]
hours = uptime_list[3]
minutes = uptime_list[4]
# No leap day ca... | abf29658193ab373c8e7e8c722fe308d3642c176 | 40,835 |
def _load_coverage_exclusion_list(path):
"""Load modules excluded from per-file coverage checks.
Args:
path: str. Path to file with exclusion list. File should have
one dotted module name per line. Blank lines and lines
starting with `#` are ignored.
Returns:
list(s... | da20f154a3ad754c344a378889ce913760743d5a | 40,837 |
def avg(rows: list, index: int):
"""
This is used to calculate the skill average and the slayer average of the whole guild
:param (list) rows: A list containing more lists which are used to calculate the average
:param (index) index: The index in the list of the value to calculate
:returns (str): Th... | e4a0dbb81e911c114b99e411c7d81209a8d0728f | 40,843 |
from typing import Iterable
def const_col(dims: Iterable[int]) -> str:
"""
Name of an constant columns.
Parameters
----------
dims
Dimensions, that describe the column content.
Returns
-------
name: str
Column name.
Example
-------
>>> from rle_array.test... | 52aecf5872f6444bf0155f0556ce39b2250ce758 | 40,847 |
import re
def file_id (s):
"""Return a conventional file name from a pseudo-file name.
(ast/FooBar.hh -> ast/foo-bar.hh)."""
return re.sub ("([a-z])([A-Z])", "\\1-\\2", s).lower () | 316248c3cb701466ba9189b1a8bf24ee21384042 | 40,848 |
def GetDefaultPanelBorder(self):
"""
Default panel border is set to 0 by default as the child control
will set their borders.
"""
return 0 | abbe52bd59c73ed92a278336c6dd38c1ce0c927e | 40,851 |
def get_service_state_name(state):
"""
Translate a Windows service run state number to a friendly service run state name.
"""
return {
1: 'Stopped',
2: 'Start Pending',
3: 'Stop Pending',
4: 'Running',
5: 'Continue Pending',
6: 'Pause Pending',
7:... | 153bfb340ca20335aa476021d31a9918fb00f1f4 | 40,856 |
def mkdown_p(text):
"""
Generates the markdown syntax for a paragraph.
"""
return '\n'.join([line.strip() for line in text.splitlines()]) + '\n' | ac511acb8bb81ad37aac7897763584d062662d99 | 40,859 |
def get_first_selected_text(view):
"""Gets a copy of the given view's first buffer selection"""
first_selected_region = view.sel()[0]
buffer_text = view.substr(first_selected_region)
return buffer_text, first_selected_region | 74b4508f900c87789ebf41b66f31f5a3d41157b1 | 40,871 |
def create_transcript_objects(refseq_db, nms_in_refseq):
"""Retrieve Transcript objects from RefSeq db"""
transcripts = []
for id in nms_in_refseq:
t = refseq_db.by_id(id)
transcripts.append(t)
return transcripts | f1422ebd14eccc1b1f26cefefad1c734e06cb81b | 40,872 |
def check_params(params):
""" Checks if the parameters are defined in the domain [0, 1].
:param params: parameters (u, v, w)
:type params: list, tuple
:raises ValueError: input parameters are outside of the domain [0, 1]
"""
tol = 10e-8
# Check parameters
for prm in params:
if p... | a0b8225addd1d499719d26461b2ada79b4d27a8c | 40,874 |
def apply_tf(data, tf):
"""Apply function `tf` (transformation function) if specified
and return result. Return unmodified data in other case"""
if tf:
return tf(data)
else:
return data | 86d381f5df2362cd614ec252fd2650f2e0086d0d | 40,878 |
import collections
def get_gt_distribution(experience, get_block):
"""
Get the ground-truth distribution of an experience buffer.
:param experience: List of transitions.
:param get_block: Function that returns the ground-truth state-action block for each transition.
:return: ... | 6dcba0e714d9d98a530c16fcfa12679980b46871 | 40,881 |
import math
def cost_to_time(cost, avg_seek_time=8, avg_latency=4):
"""
Converts a disk I/O metric to a milliseconds.
:param cost: The disk I/O metric to convert.
:param avg_seek_time: The average seek time in milliseconds.
:param avg_latency: The average latency in milliseconds.
:return: A di... | 9ec86fef8b1b76260bbb2fe58b539d1dc8164b52 | 40,882 |
def VLerp(startv, endv, t=0.5):
""" Linear interpolation between 2 vectors. """
if t <= 0.0 or t > 1.0:
raise ValueError("E: t must satisfy 0<t<1, but is %f" % t)
return (startv + (t * (endv - startv))) | c64dec9b0b966c0b25f6da00392239389e714a30 | 40,883 |
def get_next_deriv(xi, step, n, deriv, func):
"""
(d_theta/d_xi)i+1 = (d_theta/d_xi)i - ([ (2 /xi)i . (d_theta/d_xi)i ] + theta^n ) * d_xi
"""
return deriv - step * ((2./xi)*deriv + func**n) | 9393131ff5872c8da2fc519611d6fc075ef4ffa5 | 40,885 |
def read_emojis(emojis):
""" Returns a dictionary of emojis in the format of name: url. """
items = []
for k, v in emojis['emoji'].items():
if v.startswith('http'):
items.append((k, v))
return items | b8e80fc07cc287f3eff547b111aaaa16989309ce | 40,886 |
def _prepare_cov_source(cov_source):
"""
Prepare cov_source so that:
--cov --cov=foobar is equivalent to --cov (cov_source=None)
--cov=foo --cov=bar is equivalent to cov_source=['foo', 'bar']
"""
return None if True in cov_source else [path for path in cov_source if path is not True] | 8287d28c5d82568ee226d89250524b75e81b69d8 | 40,900 |
import time
def last_hour(unixtime, hours=1):
"""Check if a given epochtime is within the last hour(s).
Args:
unixtime: epoch time
hours (int): number of hours
Returns:
True/False
"""
seconds = hours * 3600
# sometimes bash histories do not contain the `time` column
... | 1ce3ddb73f0316cf36979c1ee7f1269ae55d0d4c | 40,904 |
def format_stats(stats):
"""Given a dictionary following this layout:
{
'encoded:label': 'Encoded',
'encoded:value': 'Yes',
'encoded:description': 'Indicates if the column is encoded',
'encoded:include': True,
'size:label': 'Size',
's... | 38b0f19f216d85f57c48a2e4b35a00dfa784d962 | 40,907 |
def get_customer_events(customerId, transcript):
"""
Get all the customer event rows from transcript dataframe
Parameters
----------
customerId: Customer Id.
transcript : The transcript dataframe containing events of all customers
Returns
-------
A dataframe with only ro... | bf925440e1f43fe715f498e824ebf98180a23858 | 40,916 |
def get_valid_step(current_step: int, max_step: int) -> int:
"""
Checks if the current step is within boundaries and returns a corrected step.
:param current_step: The current step to check.
:param max_step: The maximum allowed step.
:return: A corrected step between 1 and the maximum step.
"""... | aa668ef490bce37ac890c767b604e14f4b5d5ed9 | 40,920 |
def phaseplot_values(species):
"""
A convenience function to get a dictionary of values, to allow generalization of the PhasePlot class.
The keys you can pull for phase plots are `x`, `v_x`, `v_y` and `v_z`.
Parameters
----------
species : Species
A species to draw data from
Retur... | 9b7458eb4634bbd7e6b337ecadc0a3db20911d45 | 40,925 |
def get_pagination(current_page_number, total_number_pages):
"""
Generate a pagination dictionary given a page number
:param current_page_number: current page to paginate
:param total_number_pages: total number of pages in the current model
:return: dictionary of pagination
"""
previous_page... | cbe5052fead77f1b034452841ae2468373cd4860 | 40,926 |
def assort_values(d):
"""
Collect every values stored in dictionary, then return them as a set
:param d:
:return:
"""
values = set()
for key in d.keys():
values |= set(d[key])
return values | b9cf4a705d92aa414bd38e05204764b71bf2e683 | 40,928 |
import struct
def read_vary(stream, data_size_type="B"):
"""!
@brief Read variable length data from stream.
@param stream Data stream.
@param data_size_type Type of data size in Python's struct module representation.
@return Data in byte array.
"""
# Read data size
data_size_size = st... | 9aa8a29470dad880b3f9b718a34c80eb28e2110e | 40,931 |
from typing import Optional
from enum import Enum
def enum_parse(enum_cls: type, value: str) -> Optional[Enum]:
"""Try to parse a string value to an Enum member."""
if not issubclass(enum_cls, Enum):
raise TypeError("Can only be used with classes derived from enum.Enum.")
if value in enum_cls.__me... | f932e9d941daed3a970273c91a2d45abf0261e17 | 40,932 |
def strip_trailing_zero(value):
"""Like builtin "floatformat" but strips trailing zeros from the right (12.5 does not become 12.50)"""
value = str(value)
if "." in value:
return value.rstrip("0").rstrip(".")
return value | 201c3ee4014db53a613d23131f8d4caad4cab638 | 40,933 |
def get_company(company_id, company_dict):
"""
Get the entry for a key from the company table
"""
return company_dict[company_id] | b2f682cf702dbd6877e46cf98b106b9e058fe4fb | 40,936 |
def find_list_index(a_list, item):
"""
Finds the index of an item in a list.
:param a_list: A list to find the index in.
:type a_list: list
:param item: The item to find the index for.
:type item: str
:return: The index of the item, or None if not in the list.
:rtype: int | None
"""... | c9eb862b4af3eb113cca9ee55edda05b9fbfa8fe | 40,940 |
def horizontal_flip(img):
"""Flip the image along the horizontal axis."""
return img[:, ::-1, :] | 7aa0defa82efc835848f5f8d2b73191d63476a74 | 40,944 |
def clip_zero_formatter(tick_val, tick_pos):
"""Tick formatter that returns empty string for zero values."""
if tick_val == 0:
return ''
return tick_val | 263cd9104f8f8e2332c55454e3fee274afe2ec4a | 40,945 |
def uri_scheme_behind_proxy(request, url):
"""
Fix uris with forwarded protocol.
When behind a proxy, django is reached in http, so generated urls are
using http too.
"""
if request.META.get("HTTP_X_FORWARDED_PROTO", "http") == "https":
url = url.replace("http:", "https:", 1)
return... | 873ac1c70627fc8e8dd0cb2b86dec99246bb9344 | 40,949 |
def remove_last_cycles_from_summary(s, last=None):
"""Remove last rows after given cycle number
"""
if last is not None:
s = s.loc[s.index <= last, :]
return s | 811c73cce5d107a6a3c8fcae71c320c548ee6755 | 40,952 |
def list_all_regions(session):
"""Returns all regions where Lambda is currently supported"""
return session.get_available_regions("lambda") | 6368a3a357826f49978a06705270bc0124f64b0e | 40,958 |
def get_center_indices(data, centers):
"""
Outputs the indices of the given centroids in the original dataset.
In case multiple similar arrays are present in the dataset, the first
match is returned. Required since K++ initializer outputs the
actual centroid arrays while the kmedoids implementation... | 78521413a8272a6fb6ce4dcd69b0b7418b937efa | 40,968 |
async def get_pr_for_commit(gh, sha):
"""Find the PR containing the specific commit hash."""
prs_for_commit = await gh.getitem(
f"/search/issues?q=type:pr+repo:python/cpython+sha:{sha}"
)
if prs_for_commit["total_count"] > 0: # there should only be one
return prs_for_commit["items"][0]
... | c8abfbc613748d88b224db2523b15535169da118 | 40,969 |
def underlying_function(thing):
"""Original function underlying a distribution wrapper."""
return getattr(thing, '__wrapped__', thing) | c83ce77b08b1eec84f13b9ba439203fcc045f098 | 40,972 |
def get_factor(units, unit_id):
"""
Returns the factor of a Unit-Config
"""
if not units:
return None
for unit in units:
if unit.id == unit_id:
if unit.to_base_function:
return unit.to_base_function
return unit.factor | c941556cba4baa08569c89c9c90edc5f620b5346 | 40,973 |
def write(scope, filename, lines, mode=['a']):
"""
Writes the given string into the given file.
The following modes are supported:
- 'a': Append to the file if it already exists.
- 'w': Replace the file if it already exists.
:type filename: string
:param filename: A filename.
:typ... | 4c5b905dabd35211a95d6af1ea82967a8ae6ae44 | 40,974 |
def get_direction_per_spike(df, cells, value_query, threshold=1):
"""
For a list of cells in a dataframe, return a list of values that are
associated with spiking activity.
:param df: Dataframe containing the spiking activity, and the values
to be queried
:param cells: List of cells (dataframe c... | 18ebb4992df35b58106bbe85b883c7a13e8ff73f | 40,976 |
def calculate(power):
"""Returns the sum of the digits of the number 2 to the power of the specified number"""
answer = sum(list(map(int, str((2 ** power)))))
return answer | 5f0146e2c885c8c4636a6765a2b8e567e758928a | 40,981 |
from bs4 import BeautifulSoup
def is_html_text(txt):
"""
Check is input text is html or not
Args:
txt (str): input text
Returns:
bool: Returns True if html else False.
"""
return bool(
BeautifulSoup(txt, "html.parser").find()
) | 1fb303e79bf1fd8773bc4cc03aaee304e9987aca | 40,987 |
import random
def mod_hosts_map(cloud_map, n, **kwargs):
"""
Selects n random hosts for the given stack and modifies/adds
the map entry for those hosts with the kwargs.
"""
population = cloud_map.keys()
# randomly select n hosts
hosts = random.sample(population, n)
# modify the hosts... | 87f766df9701a9da4988aae0ac272cd32c31b011 | 40,988 |
def dist(v1, v2):
""" distance between two vectors. """
d = ((v2.x - v1.x)**2 + (v2.y - v1.y)**2) ** 0.5
return d | d06b3fb6543a1531d71db7345912153008e7e7d1 | 40,990 |
def array_shape(x) -> tuple[int, ...]:
"""Return the shape of 'x'."""
try:
return tuple(map(int, x.shape))
except AttributeError:
raise TypeError(f"No array shape defined for type {type(x)}") | efceb1a84ff05b94d2aa2e89c7956a96e4337090 | 40,995 |
def reset_slider(modal_open, selected_confidence):
"""
Reset the confidence slider range value to [0, 60] after closing the
modal component.
Parameters
----------
modal_open : bool
A boolean that describes if the modal component is open or not
selected_confidence : list of float
... | e6a43415eb56e8a77ef8cb3a1b58f71e4bf9443c | 40,996 |
def get_type_check(expected_type):
"""
Any -> (Any -> bool)
:param expected_type: type that will be used in the generated boolean check
:return: a function that will do a boolean check against new types
"""
return lambda x: type(x) is expected_type | 3e16e7fdf7461702cef4835d0bcfb2ed4131dac8 | 40,998 |
def fmt(x, pos):
"""
Format color bar labels
"""
if abs(x) > 1e4 or (abs(x) < 1e-2 and abs(x) > 0):
a, b = f"{x:.2e}".split("e")
b = int(b)
return fr"${a} \cdot 10^{{{b}}}$"
elif abs(x) > 1e2 or (float(abs(x))).is_integer():
return fr"${int(x):d}$"
elif abs(x) > ... | 02e5c2ecbcbfcd50d40b06ee7792275aa4e32ae3 | 41,000 |
def is_binarystring(s):
"""Return true if an object is a binary string (not unicode)"""
return isinstance(s, bytes) | 9d4950b7c11b4055460236076200c13a6d51127a | 41,001 |
def is_superset(token, tokens):
"""If a token is a superset of another one, don't include it."""
for other in tokens:
if other == token:
continue
if other in token:
return True
return False | c9530f43ab9f9c123b3cff10b043376a280c57f5 | 41,002 |
import torch
def mu_inverse(y):
""" Inverse operation of mu-law transform for 16-bit integers. """
assert y.min() >= -1 and y.max() <= 1
return torch.sign(y) / 32768. * ((1 + 32768.) ** torch.abs(y) - 1) | d4af6953e6770d52597cf49e40bda1abbbbf057f | 41,005 |
def spherical(h, r, sill, nugget=0):
"""
Spherical variogram model function. Calculates the
dependent variable for a given lag (h). The nugget (b) defaults to be 0.
Parameters
----------
h : float
The lag at which the dependent variable is calculated at.
r : float
Effect... | 074575957faf3a047c649fa31e6f0cc4ff7c4fdf | 41,011 |
def get_from_session(request):
"""
Get user from request's session.
"""
return request.environ['beaker.session'].get('user') | 30ad13274797fe3cb183ae1a11e6d07fa83fdf12 | 41,014 |
def S_convolute_values(_data_list, _transformer):
"""
Returns new data samples where values are transformed by transformer values.
"""
c_data = []
ds = len(_data_list)
ts = len(_transformer)
if ds != ts:
return []
for i in range(ds):
c_data.append(_data_list[i] + _tran... | c13a2750999e4aa144f610a905f96d845b6dbfcc | 41,023 |
def get_valid_entries(board, row, col):
"""Checks valid entries for given cell in sudoku
params : board : list (sudoku 9 X 9)
: row : int
: col : int
returns : list (list of valid entries)
"""
used_entries = [0] * 10
used_entries[0] = 1
block_row = row // 3
block_col = col /... | 4c9178cf4c859dbfc8957c19cbf0ba5f60df5786 | 41,027 |
import json
def get_error_msg(exception) -> str:
"""
Parse the http response body to get relevant error message
"""
http_response_body = json.loads(exception.body.decode("utf-8"))
exception_msg = http_response_body["message"]
return exception_msg | 6a98431a163ef6f6ec453182fe68b0ebdad41969 | 41,029 |
import six
def _add_simplify(SingleActionType, BulkActionType):
"""
Add .simplify method to "Bulk" actions, which returns None for no rows, non-Bulk version for a
single row, and the original action otherwise.
"""
if len(SingleActionType._fields) < 3:
def get_first(self):
return SingleActionType(s... | b67d24d63df7ee8de56cc9c47ae64150373fef3b | 41,030 |
import json
def read_inputs(jpath):
"""
read_inputs reads the input json file and stores it information in a dictionary
Parameters
----------
jpath : string
the input JSON file
Returns
-------
paths: dict
Returns a dictionary of the json file
"""
with open(jp... | f3f91db4a60d8267df0b6a8ff0e3b722864c4055 | 41,031 |
def get_author_name(pypi_pkg):
"""Get author's name"""
author_name = pypi_pkg["pypi_data"]["info"]["author"]
return author_name | 7c4ff935af36824a954605846d8a91bd927470c4 | 41,033 |
def _cleanup_frame(frame):
"""Rename and re-order columns."""
frame = frame.rename(columns={'Non- Hispanic white': 'White'})
frame = frame.reindex(['Asian', 'Black', 'Hispanic', 'White'],
axis=1)
return frame | 7a25ee47e726314de57dc80d103a0189d3583024 | 41,037 |
def frmt_db_lctn(location):
""" Formats the database location into nicer, more readable style
:param location: sms deposit location
:returns: Formated sms deposit location
"""
if location:
return location.replace("_", " ").replace('-', ' ').title() | 709b77c96eaa6aa43211445cc03279a28f84cd56 | 41,039 |
import pkg_resources
def riptide_assets_dir() -> str:
""" Path to the assets directory of riptide_lib. """
return pkg_resources.resource_filename('riptide', 'assets') | 6c82e359d46bb6a82cbf01559574c07629acc23b | 41,040 |
def signal_to_noise_limit_tag_from_signal_to_noise_limit(signal_to_noise_limit):
"""Generate a signal to noise limit tag, to customize phase names based on limiting the signal to noise ratio of
the dataset being fitted.
This changes the phase name 'phase_name' as follows:
signal_to_noise_limit = None ... | b659aac99a4c728219818d8a5dc9f0fd14defcfd | 41,046 |
import re
def check_rules(rules, text_list, current_labels, fallback_label):
"""Finds rule's match in a text and returns list of labels to attach.
If no rule matches returns False for match and fallback label will be attached.
Args:
rules (list): List of rules
text_list (list): List o... | 5a244532510e1898bef9a6f98d556e4c2e4b7b09 | 41,047 |
def Base_setTextValue(self, param):
"""
- name: input username
setTextValue:
text: |
multi line text1
multi line text2
id: elementid1
"""
txt = self.getvalue(param)
if txt is None:
raise Exception("text not set: param=%s" % (param))
elem = self.f... | 3030ed2241364002246f0c8c1fadf3c244658eff | 41,048 |
from datetime import datetime
def get_Mk_global(date):
"""
Based on the script BackRuns_OneSite_ByDay.ksh, calculating the globalMetMk value
:param date: datetime object
:return: integer representing the globalMetMk value
"""
seconds = int(datetime.strftime(date, "%s"))
if seconds < 1136... | c05e5dffb2219358147184be28123349071994fc | 41,050 |
def tf_b(tf, _):
"""Boolean term frequency."""
return 1.0 if tf > 0.0 else 0.0 | fddd407e4e04f9d3a890303431e462731a79cb3c | 41,051 |
def dump_netrc(self):
"""Dump the class data in the format of a .netrc file."""
rep = ''
for host in self.hosts.keys():
attrs = self.hosts[host]
rep = rep + 'machine ' + host + '\n\tlogin ' + str(attrs[0]) + '\n'
if attrs[1]:
rep = rep + 'account ' + str(attrs[1])
... | 08cb24400c7857006f2d2ae226a002485e0cc975 | 41,054 |
import torch
def image_positional_encoding(shape):
"""Generates *per-channel* positional encodings for 2d images.
The positional encoding is a Tensor of shape (N, 2*C, H, W) of (x, y) pixel
coordinates scaled to be between -.5 and .5.
Args:
shape: NCHW shape of image for which to generate positional ... | b5187f9a97ade7fdad06d54e7a308e7ede8fcf9a | 41,055 |
def list_keys(client, bucket, prefix, token=None):
"""
Recursive function used to retrieve all the object keys that match with a given prefix in the given S3 bucket.
:param client: Client for the Amazon S3 service.
:param bucket: The S3 bucket name.
:param prefix: The prefix used for filtering.
... | 3fa42dccf36dd3c2c8e76a71a1add0d28b0abe98 | 41,057 |
def RepairMissingData(time_series, first_value):
"""Given a list of time series value in a string format, replace missing
values. If the first time point is missing, set it to first_value. This
should be 1 if the log transform will be taken or 0 otherwise. If later
time points are missing, set them to ... | c2075048c662ecba2c37a95ea12513b105a05d16 | 41,059 |
def replace_stop(sequence):
"""
For a string, replace all '_' characters with 'X's
Args:
sequence (string)
Returns:
string: '_' characters replaced with 'X's
"""
return sequence.replace('_', 'X') | e4f0356b5b6b8c2101540c275215e0527ba909c4 | 41,060 |
from pathlib import Path
def tmpfile(tmpdir, request):
"""Path to an empty temporary file."""
path = Path(tmpdir / 'temp.' + request.param)
path.touch()
return path | 14194a46b8799f967a2ad6ac89cea3f4a3ddbddc | 41,062 |
def test_function(a:int, b:int) -> int:
"""Adds two numbers together
Args:
a (int): Number 1
b (int): Number 2
Returns:
int: Sum of both numbers
"""
return a + b | 76d76743c02600f665b7c0ee28a08bc4e0784238 | 41,063 |
def check_abc_lec_status(output):
"""
Reads abc_lec output and determines if the files were equivelent and
if there were errors when preforming lec.
"""
equivalent = None
errored = False
for line in output:
if "Error: The network has no latches." in line:
errored = True
... | 5c2c17e91fed34d46bf911d404e16efe40adebdf | 41,064 |
from typing import List
from typing import Any
import random
def get_random_sample(items: List[Any], k: int) -> List[Any]:
"""
Thin wrapper around ``random.sample`` that takes the min of ``k`` and ``len(items)``
when sampling, so as to avoid a ``ValueError``.
"""
return random.sample(items, min(k,... | 6fe2c5df8a2d8fa34a8f694e1108ce096c91dd4c | 41,068 |
import math
def projectionVolume(R1, R2, y1, y2):
"""Return the projected volume of a shell of radius R1->R2 onto an
annulus on the sky of y1->y2.
this is the integral:
Int(y=y1,y2) Int(x=sqrt(R1^2-y^2),sqrt(R2^2-y^2)) 2*pi*y dx dy
=
Int(y=y1,y2) 2*pi*y*( sqrt(R2^2-y^2) - sqrt(R1^2-y^2) ) dy... | fc09c74fdb6c80d76df1dd996357b5f8cd9eab83 | 41,075 |
def prepend(value: str, char="_"):
"""Prepend a string to a value if the value doesn't already start with that string
Examples:
>>> prepend('a')
'_a'
>>> prepend('_a')
'_a'
>>> prepend('my_str', '--')
'--my_str'
>>> prepend('---my_str', '-')
'---m... | 05a82a8d6dbedb550069610ba47eb0a6f545f925 | 41,078 |
def _is_right(a, b, p):
"""given a line (defined by points a and b) and a point (p),
return true if p is to the right of the line and false otherwise
raises a ValueError if p lies is colinear with a and b
"""
ax, ay = a[0], a[1]
bx, by = b[0], b[1]
px, py = p[0], p[1]
value = (bx - ax) *... | 6d630eadc77587de60ef6aefff3cac01d9ba3191 | 41,085 |
def boundary(info, error, otype, oslots, rank):
"""Computes boundary data.
For each slot, the nodes that start at that slot and the nodes that end
at that slot are collected.
Boundary data is used by the API functions
`tf.core.locality.Locality.p`.
and
`tf.core.locality.Locality.n`.
P... | b6927dc374fa638b42fb7e85742f074cba7ab88a | 41,087 |
def standard_x(x_train, x_test=None):
"""
Data normalization (centering and variance normalization).
:param x_train: training data
:type x_train: np.ndarray
:param x_test: testing data
:type x_test: np.ndarray | None
:return: normalized data
:rtype: np.ndarray | (np.ndarray, np.ndarray)... | 181ae9a64b0ed444a4ef49f933cf1d2490763fe5 | 41,088 |
def _offset(offset, size):
"""Calculate the start of a member of `size` after `offset` within a
struct."""
return ((size - (offset % size)) % size) + offset | 97e277def96dab568d6f2cbe1fd7111d0cac6427 | 41,091 |
def precision_to_string(precision):
"""Translates a precision number (represented as Python string) into a descriptive string"""
if precision == "16":
return "Half"
elif precision == "32":
return "Single"
elif precision == "64":
return "Double"
elif precision == "3232":
... | 7f7d9b099091944d4fae1c007d83c375770a6b20 | 41,094 |
def get_ideological_topic_means(objective_topic_loc,
objective_topic_scale,
ideological_topic_loc,
ideological_topic_scale):
"""Returns neutral and ideological topics from variational parameters.
For each (k,v), we ... | 3c0681e4b2834a34b0a0c97e5638bf0237d5272c | 41,098 |
def get_gamma_function(gamma):
"""
:param gamma: desired factor gamma
:return: Returns the lambda function of the gamma adjust operation
"""
return lambda x: pow(x / 255, gamma) * 255 | 48175cacc3c41fcac4da9dfdf7bc475c2f813bb6 | 41,099 |
import re
def replace_initials(s):
"""
For a string s, find all occurrences of A. B. etc and replace them with A B etc
:param s:
:return: string with replacements made
"""
def repl_function(m):
"""
Helper function for re.sub
"""
return m.group(0)[0]
t = re... | da08a0d154e683b9e3ffa4ebd1332a8a855b05be | 41,100 |
def me_check(pr, fa, ma, ref_count=False):
"""
Simplest possible way to check ME
-1 for skipped sites ('.' or hom-ref in all samples
0 for consistent
1 for inconsistent
"""
pr = pr.split(':')[0].split('/')
fa = fa.split(':')[0].split('/')
ma = ma.split(':')[0].split('/')
if '.' i... | c133b42140c36c1ad5dcffa252dc939048493e6f | 41,101 |
def get_model_queue_data(job):
"""
Formats the queued model data to return to the server
:return: [(id:int, model_id:int, title:str, progress:int, max_progress:int), ...]
"""
return (job.get_id(), job.get_info().get("model_id"), job.get_title(), job.get_progress(), job.get_max_progress()) | 07aad5c6c5b20b66a4cad585069739b058b96d44 | 41,102 |
import random
def roll_unweighted_die(weights=None):
"""Returns the result of an unweighted die.
This uses a fair
Args:
weights: (integer array) a collection of the percentage chances each
result of the die has. The number of sides is determined by
the number of... | 34a8502677b21b59c380bf7fa62eab8aac67959a | 41,108 |
import hashlib
def md5checksum(afilepath):
""" md5checksum
Calculates the MD5 checksum for afilepath
"""
with open(afilepath, 'rb') as filehandler:
calc_md5 = hashlib.md5()
while True:
data = filehandler.read(8192)
if not data:
break
... | d8d4711e4657514672e455a3374e3ec400636259 | 41,109 |
def move_to_end(x, dim):
"""
Moves a specified dimension to the end.
"""
N = len(x.shape)
if dim < 0:
dim = N + dim
permute_indices = list(range(N))
permute_indices.remove(dim)
permute_indices.append(dim)
return x.permute(permute_indices) | dad4bbceb2c6e5519afee2a3d94e5b06cec222bb | 41,112 |
def _find_t(e, annotations):
"""
Given an "E" annotation from an .ann file, find the "T" annotation.
Because "E" annotations can be nested, the search should be done on deeper
levels.
:param e: (string) the "E" annotation we want to find the target of.
:param annotations: (dict) the dict of an... | b10c097ed98548d6a51447e3dd23140deef44818 | 41,117 |
def screenRegion(gfx, region=(0.0, 0.0, 1.0, 1.0)):
"""(gfx, 4-tuple of floats) -> (4-tuple of ints)
Determine the absolute coordinates of a screen region from its
relative coordinates (coordinates from 0.0 to 1.0)
"""
w, h = gfx.getSize()
x1 = (w - 1) * region[0]
y1 = (h - 1) * region[1]
... | 35ef5e208bc1cd6279adaf2fef6b7dfc74830dfe | 41,119 |
def split(iterable, function):
"""
Split an iterable into two lists according to test function
:param iterable iterable: iterable of values to be split
:param function function: decision function ``value => bool``
:returns: tuple(
list with values for which function is `True`,
list ... | ede20fcc80bd126410a8417d1e91dee2e530c9af | 41,121 |
def split_dictionary(output_dict):
"""Splits a dictionary into two lists for IDs and its full file paths
Parameters
----------
output_dict : dictionary
A dictionary with keys: 'id_llamado' and 'fullpath'
Returns
-------
Two lists
Two lists of 'id_llamado' and 'fullp... | 33958b60a0e7ca02595c688b1cf7642b6d8a56cb | 41,125 |
def get_content(html_code):
""" Separates the message section from the content section and returns the for further process
:parameters
html_code (str) html code of the downloaded
:returns
tuple (lists) the tuple returned contains two lists of strings. Each list ite... | debaab77f55d9328cd037d6fffc51c8a7f67758a | 41,130 |
def read_words_from_file(path):
"""
Reads the content of a file and returns the content, split by space-character.
:param path: The path of the file.
:return: A list of words in this file.
"""
file_obj = open(path, "r")
content = file_obj.read()
return content.split(" ") | 960ff1d54b0c37211fc06879a74124ff2e60872a | 41,132 |
def should_trade(strategy, date, previous_trade_date):
"""Determines whether a trade is happening for the strategy."""
# We invest the whole value, so we can only trade once a day.
if (previous_trade_date and
previous_trade_date.replace(hour=0, minute=0, second=0) ==
date.replace(hour=0... | 8c52eb554673bb0badff4a55c8e3a11cf9392a47 | 41,140 |
import random
def form_batches(batch_size, idx):
"""Shuffles idx list into minibatches each of size batch_size"""
idxs = [i for i in idx]
random.shuffle(idxs)
return [idxs[i:(i+batch_size)] for i in range(0,len(idxs),batch_size)] | 2afdc93202f553b29a8f4c68dcf6e226816d9de0 | 41,145 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.