content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def normalize_ordinal(ordinal):
"""
Given a string like "first" or "1st" or "1", return the canonical version ('1').
"""
return ordinal[0] if ordinal[0].isdigit() else str('ieho'.index(ordinal[1].lower()) + 1) | eceb5e26c54ce987eb65ce40c711000cc3164086 | 35,548 |
def comp_height(self):
"""Compute the height of the Hole (Rmax-Rmin)
Parameters
----------
self : Hole
A Hole object
Returns
-------
H : float
Height of the hole
"""
(Rmin, Rmax) = self.comp_radius()
return Rmax - Rmin | 4dbab93edbe3d7f277480e96b4a5e885e6e9161e | 35,554 |
import random
def GenerateRandomChoice(choices, prev=None):
"""Generates a random choice from a sequence.
Args:
choices: sequence.
Returns:
A value.
"""
return random.choice(choices) | 1d38dd313b19f235d4ea367e841ce7e74ee8f69b | 35,555 |
def list2pairs(l):
"""
Turns any list with N items into a list of (N-1) pairs of consecutive items.
"""
res = []
for i in range(len(l)-1):
res.append((l[i], l[i+1]))
return res | b1c3770e66354862d2dd96eedd473582549aae96 | 35,556 |
def normalize_br_tags(s):
"""
I like 'em this way.
>>> normalize_br_tags('Hi there')
'Hi there'
>>> normalize_br_tags('Hi <br>there')
'Hi <br />there'
>>> normalize_br_tags('Hi there<br/>')
'Hi there<br />'
"""
return s.replace("<br>", "<br />").replace("<br/>", "<br />") | 21df28ca4a8bfc03375d2e07e8a1b3840d840557 | 35,557 |
def filter_none_values(kwargs: dict) -> dict:
"""Returns a new dictionary excluding items where value was None"""
return {k: v for k, v in kwargs.items() if v is not None} | f5a1f767291a72ebeac7b92c0bbe78b890330916 | 35,558 |
from typing import List
import yaml
def get_training_class_names(training_config_file: str) -> List[str]:
"""get class names from training config file
Args:
training_config_file (str): path to training config file, NOT YOUR MINING OR INFER CONFIG FILE!
Raises:
ValueError: when class_name... | 4caba056481c653f97d5bb0b0f007cea20494412 | 35,563 |
def anticom(A,B):
"""
Compute the anticommutator between matrices A and B.
Arguments:
A,B -- square matrices
Return:
antcom -- square matrix of the anticommutator {A,B}
"""
antcom = A.dot(B) + B.dot(A)
return antcom | 734f435228fe3c69b52f3c5e8cc09e7f79bd01ce | 35,564 |
import json
def json_file_to_dict(file_path):
"""load a dict from file containing JSON
Args:
file_path (str): path to JSON file
Returns:
json_dict (dict): object representation of JSON contained in file
"""
return json.loads(open(file_path, "r").read()) | bf95cdf3ba049718caf2a5ca38ba3293c2eb308e | 35,568 |
import re
def restore_dash(arg: str) -> str:
"""Convert leading tildes back to dashes."""
return re.sub(r"^~", "-", arg) | 63313a006ed934eff1ca83486a3dde4f6ea9ef74 | 35,569 |
import hashlib
def __mysql_password_hash(passwd):
"""
Hash string twice with SHA1 and return uppercase hex digest,
prepended with an asterisk.
This function is identical to the MySQL PASSWORD() function.
"""
pass1 = hashlib.sha1(passwd.encode('utf-8')).digest()
pass2 = hashlib.sha1(pass1)... | f505025ea0459d42f118698c476fa83afb63f382 | 35,572 |
def extract_version_fields(version, at_least=0):
"""
For a specified version, return a list with major, minor, patch.. isolated
as integers.
:param version: A version to parse
:param at_least: The minimum number of fields to find (else raise an error)
"""
fields = [int(f) for f in version.st... | 04209b0029160b19bbdb80d45f560c696214f90a | 35,573 |
def change_rate_extractor(change_rates, initial_currency, final_currency):
""" Function which tests directions of exchange factors and returns the
appropriate conversion factor.
Example
-------
>>> change_rate_extractor(
... change_rates = {'EUR/USD': .8771929824561404},
... ini... | 3ada3badcfa16c06c2a50ba943d67711e48b62a0 | 35,575 |
def get_codebook(ad_bits, codebook):
"""Returns the exhaustive codebooks for a given codeword length
:param ad_bits: codewor length
:type ad_bits: int
:return: Codebook
:rtype: list(str)
"""
return codebook[ad_bits-2] | 331c33e54abe5fd0d71edbc32d5f76d2ec6f03a9 | 35,576 |
def _shiftedWord(value, index, width=1):
"""
Slices a width-word from an integer
Parameters
----------
value: int
input word
index : int
start bit index in the output word
width: int
number of bits of the output word
Returns
-------
An integer with the sliced ... | d3c3ab1e1f34684607fb9f55f807053fd7052be0 | 35,577 |
import copy
def merge(dest, src):
"""Merge two config dicts.
Merging can't happen if the dictionaries are incompatible. This happens when the same path in `src` exists in `dest`
and one points to a `dict` while another points to a non-`dict`.
Returns: A new `dict` with the contents of `src` merged i... | e03bd548294ee8df71dc802672d22085ac85ee83 | 35,578 |
def list_to_number(column):
"""
Turns a columns of 0s and 1s to an integer
Args:
column: List of 0s and 1s to turn into a number
"""
# Cast column integers to strings
column = [str(cell) for cell in column]
# Turn to an integer with base2
return int(''.join(column), 2) | b6176726517133711d12e47ed47d55ef5bc8ab82 | 35,581 |
def matrix_to_string(matrix, header=None):
"""
Returns a pretty and aligned string representation of a NxM matrix.
This representation can be used to print any tabular data, such as
database results. It works by scanning the lengths of each element
in each column and determining the format string d... | 7eb430356357de9d6a6b51c196df4aba29decada | 35,584 |
def SNR_kelly(spiketrain):
"""
returns the SNR of the waveforms of spiketrains, as computed in
Kelly et al (2007):
* compute the mean waveform
* define the signal as the peak-to-through of such mean waveform
* define the noise as double the std.dev. of the values of all waveforms,
each nor... | f827008138e9b02625db02ee6755da3451256d2d | 35,585 |
import math
def my_func(x):
"""
simple function that computes : sin(x) + 2x
Inputs:
1.x: input value (in radians)
Output:
returns y = sin(x) + 2x
"""
y = math.sin(x) + 2.0*x
return y | 15c14af682051d972d16ca3bf14a4f50f54cd79c | 35,586 |
import json
from datetime import datetime
import time
def iso_to_unix_secs(s):
""" convert an json str like {'time': '2022-02-05T15:20:09.429963Z'} to microsecs since unix epoch
as a json str {'usecs': 1644927167429963}
"""
dt_str = json.loads(s)["time"]
dt = datetime.strptime(dt_str, "%Y-%m-%... | 7421e6b1781b712ebc3b8bafd1d96f49c5f1d10c | 35,587 |
import requests
def check_time_response(domain):
"""Return the response time in seconds."""
try:
latency = requests.get(domain, headers={'Cache-Control': 'no-cache'}).elapsed.total_seconds()
return latency
except Exception:
return '?' | be208715ceae98122f7012a2982833e46b6979c7 | 35,595 |
def _safe_delay(delay):
"""Checks that `delay` is a positive float number else raises a
ValueError."""
try:
delay = float(delay)
except ValueError:
raise ValueError("{} is not a valid delay (not a number)".format(delay))
if delay < 0:
raise ValueError("{} is not a valid delay... | ff3014047c5f4bcd7d4054f8af11ccd722401546 | 35,598 |
from typing import Dict
from typing import Any
def bundle_json_get_next_link(bundle_json: Dict[str, Any]) -> str:
"""get the 'next' link from a bundle, if it exists
Args:
bundle_json (Dict[str, Any]): the bundle to examine
Returns:
str: the url of the 'next' bundle or None
"""
fi... | db311eba00952b7d00bf5c9187cc52fb210c5560 | 35,601 |
def strip_headers(post):
"""Find the first blank line and drop the headers to keep the body"""
if '\n\n' in post:
headers, body = post.split('\n\n', 1)
return body.lower()
else:
# Unexpected post inner-structure, be conservative
# and keep everything
return post.lower... | ac5b5a7b06f700a42698b3a65fd4c9017a001f30 | 35,603 |
def check_continuity(array):
"""
Check whether the array contains continous values or not like 1, 2, 3, 4, ..
"""
max_v = max(array)
min_v = min(array)
n = len(array)
# print(n, min_v, max_v)
if max_v - min_v + 1 == n:
# print("Given array has continous values")
retur... | 6b279cce3b332d5c593afe9590800fe3c8472710 | 35,604 |
def get_node_type(conn, graph_node_pkey):
""" Returns the node type of a given graph node"""
c = conn.cursor()
c.execute(
"""
SELECT graph_node_type FROM graph_node WHERE pkey = ?""",
(graph_node_pkey, )
)
return c.fetchone()[0] | f68f29e45127854781c8fe5422ab754014df1d6b | 35,608 |
def getPixelFromLabel(label):
"""
Function to get the pizel from the class label. This reverse mapping is use to generate an image file fom available class labels.
:param label: class label
:type label: int
:return: (r,g,b) equivalent of class label color.
:rtype: tuple
"""
if label == ... | 746ae72f4adff1615f399ff5b591b7013ebdce46 | 35,611 |
import time
def ms_time_to_srt_time_format(d: int) -> str:
"""Convert decimal durations into proper srt format.
ms_time_to_srt_time_format(3890) -> '00:00:03,890'
"""
sec, ms = d // 1000, d % 1000
time_fmt = time.strftime("%H:%M:%S", time.gmtime(sec))
# if ms < 100 we get ...,00 or ...,0 whe... | 3ca2713615b7fb8ef1ea9e9712e0b26b23c5f7e1 | 35,616 |
def format_float(value: float, precision: int = 4) -> str:
"""
Formats a float value to a specific precision.
:param value: The float value to format.
:param precision: The number of decimal places to use.
:return: A string containing the formatted float.
"""
return f'{value:.{precision}f}' | 41ec3acf02f3400fd484c8e6f7a72509d3f20cd9 | 35,618 |
import logging
def TruncateStr(text, max_len=500):
"""Truncates strings to the specified maximum length or 500.
Args:
text: Text to truncate if longer than max_len.
max_len: Maximum length of the string returned by the function.
Returns:
A string with max_len or less letters on it.
"""
if len(... | 2401d6d56c6f99bd64cfd825aca0ab5badca1964 | 35,622 |
def get_parameters(params, t, verbose=True):
"""
Convenience method for the numeric testing/validation system.
Params is a dictionary, each key being a parameter name,
and each value a list of values of length T (the number of trials).
The method returns a list of the argument values for test numb... | 70b624b465022efd9ef29e59b875881387f28935 | 35,625 |
def map_element(element):
"""Convert an XML element to a map"""
# if sys.version_info >= (2, 7):
# return {e.tag: e.text.strip() for e in list(element)}
# return dict((e.tag, e.text and e.text.strip() or "")
# for e in list(element))
return dict((e.tag, e.text) for e in list(element)... | b8a84be91f28757f28622a5909a569d35e38282f | 35,627 |
def _zone_group_topology_location_to_ip(location):
"""Takes a <ZoneGroupMember Location=> attribute and returns the IP of
the player."""
# Assume it is of the form http://ip:port/blah/, rather than supporting
# any type of URL and needing `urllib.parse`. (It is available for MicroPython
# but it req... | e3b038b92d4fcb24650dd6905847c9ca3f1fa13e | 35,628 |
from typing import Union
def transfrom_operand(operand: str) -> Union[str, int, bool]:
"""Transforms operand."""
result = operand.strip()
if result.isdigit():
result = int(result)
elif result in ['True', 'true', 'Yes', 'yes', 'T', 't', 'N', 'n']:
result = True
elif result in ['F... | 64bd30316d7176b01e66cd40d8852806b4da0e7b | 35,629 |
def get_or_create(session, model, **kwargs):
"""
Determines if a given record already exists in the database.
Args:
session: The database session.
model: The model for the record.
**kwargs: The properties to set on the model. The first
specified property will be used to ... | 74c77cfcbee09313b96284c34e59eb0ff1440f0c | 35,630 |
def n_distinct(series):
"""
Returns the number of distinct values in a series.
Args:
series (pandas.Series): column to summarize.
"""
n_distinct_s = series.unique().size
return n_distinct_s | 5f262c376e844cff324b5e0376be91ead8e20c0d | 35,633 |
def get_index_offset_contents(result, source):
"""Return (line_index, column_offset, line_contents)."""
line_index = result['line'] - 1
return (line_index,
result['column'] - 1,
source[line_index]) | 5ee12a8c991ab50c71426cacf8db255f4f938de9 | 35,635 |
def avg_eval_metrics(metrics):
"""Average evaluation metrics (divide values by sample count).
Args:
metrics: evaluation metrics
Returns:
averaged metrics as a dict
"""
n = metrics['sample_count']
metrics['loss'] = metrics['loss_sum'] / n
metrics['error_rate'] = metrics['error_count'] / n
if 't... | cfa3461c94b320a44438483f1d037c0b545cf02a | 35,637 |
import copy
def dreplace(d, fv=None, rv='None', new=False):
"""replace dict value
Parameters
----------
d : dict
the dict
fv : any, optional
to be replaced, by default None
rv : any, optional
replaced with, by default 'None'
new : bool, optional
if true, de... | 86e29b6b3b8839ccf1de26483b71e8cd2e0fd6b8 | 35,642 |
from typing import List
from typing import Any
from typing import Callable
from typing import Optional
def extract_self_if_method_call(args: List[Any],
func: Callable) -> Optional[object]:
"""Check if this is a method rather than a function.
Does this by checking to see if `fu... | e93850cdad0bbe8fccfa1e508d14acd92f980b35 | 35,649 |
def encode_string(s, index):
"""
Transform a string in a list of integers.
The ints correspond to indices in an
embeddings matrix.
"""
return [index[symbol] for symbol in s] | bba25330f6d40b6211d11dda74fed8caa3dcfc16 | 35,650 |
def as_linker_lib_path(p):
"""Return as an ld library path argument"""
if p:
return '-L' + p
return '' | 567509c01a4d24978b22834aeaded4f33762d6fe | 35,653 |
def get_frame(video_camera):
"""
Checks if the camera is open and takes a frame if so.
:param video_camera: A cv2.VideoCapture object representing the camera.
:return: Last frame taken by the camera.
"""
if video_camera.isOpened():
_, frame = video_camera.read()
else:
raise E... | 2c36b77b9f7e907276b397a1225cfa60f027d847 | 35,663 |
def get_pwsh_script(path: str) -> str:
"""
Get the contents of a script stored in pypsrp/pwsh_scripts. Will also strip out any empty lines and comments to
reduce the data we send across as much as possible.
Source: https://github.com/jborean93/pypsrp
:param path: The filename of the script in pypsrp... | 43d1f0e526b9807ab729cb7b2b85ea1340699770 | 35,665 |
def is_numeric(obj):
"""Check whether object is a number or not, include numpy number, etc."""
try:
float(obj)
return True
except (TypeError, ValueError):
# TypeError: obj is not a string or a number
# ValueError: invalid literal
return False | 3cce07df54d6d83410cbd79580cdfdfd29f3edb1 | 35,666 |
def resource_name_for_asset_type(asset_type):
"""Return the resource name for the asset_type.
Args:
asset_type: the asset type like 'google.compute.Instance'
Returns:
a resource name like 'Instance'
"""
return asset_type.split('.')[-1] | 00604d1285e8e275976a026aaf0e7afb200ba1c8 | 35,667 |
def get_merged_gaps(gaps):
"""Get gaps merged across channels/streams
Parameters
----------
gaps: dictionary
contains channel/gap array pairs
Returns
-------
array_like
an array of startime/endtime arrays representing gaps.
Notes
-----
Takes an dictionary of gap... | 59c6c04ca20800040eaa2a4909708b4880fcb11f | 35,668 |
def get_lrmost(T, segs):
"""
Finds the leftmost and rightmost segments of segs in T
"""
l = []
for s in list(T):
if s in segs:
l.append(s)
if len(l) < 1:
return None, None
return l[0], l[-1] | a0af5055292b3253cd27300181e7aee9e0b9653a | 35,669 |
def overall_dwelling_dimensions(
area,
average_storey_height
):
"""Calculates the overall dwelling dimensions, Section 1.
:param area: A list of the areas of each floor.
The first item is the basement, the second the ground floor etc.
See (1a) to (1n).
:ty... | 72408ae8c0aa782b6a6b2f86dd5635f9c9e984c9 | 35,670 |
def speedx(clip, factor = None, final_duration=None):
"""
Returns a clip playing the current clip but at a speed multiplied
by ``factor``. Instead of factor one can indicate the desired
``final_duration`` of the clip, and the factor will be automatically
computed.
The same effect is applied to t... | e6bf9595bc958cd0fc39bab95bef31fe6fba6ba6 | 35,672 |
def binarize_worker(document):
"""Binarizes a BOW document.
Parameters
----------
document : list of (int, float)
A document.
Returns
-------
binarized_document : list of (int, float)
The binarized document.
"""
binarized_document = [(term_id, 1) for term_id, _ in ... | eadf535337dec095b9f287b422541fe5de8ae932 | 35,674 |
import networkx as nx
def split_graph(G):
"""splits graph(s) on interactions and return a dictionary of graphs with interaction as keys."""
# Find all interactions to split the graph on
split_by = "interaction"
split_list = list()
for u, v, d in G.edges(data=True):
split_list.append(d[spl... | 4ac596e472afb57cb3f6094fb0f4166aca4b1a2a | 35,675 |
def test_trainable_parameters_changed(trainer):
"""Performs a training step and verifies that at least one parameter
in every trainable layer has changed."""
print("At least one parameter changed in the trainable layers", end="")
passed, msg = True, ""
trainer.fit(epochs=1, max_steps=1, max_eval_s... | 29a0b0ffab55b62e9cb5ff5d4b29f1b655e99ad9 | 35,677 |
def strategy(history, memory):
"""
Tit for Tat, but it only defects once in a row.
"""
choice = 1
if (
history.shape[1] >= 1
and history[1, -1] == 0
and memory is not None
and 1 == memory
):
choice = 0
return choice, choice | ec4a016acd66374c56b57bbeb1d0e54813edd829 | 35,682 |
def _pixel_to_coords(col, row, transform):
"""Returns the geographic coordinate pair (lon, lat) for the given col, row, and geotransform."""
lon = transform[0] + (col * transform[1]) + (row * transform[2])
lat = transform[3] + (col * transform[4]) + (row * transform[2])
return lon, lat | f610340b5eb2ea652774d753920076f59a6faccd | 35,684 |
def round_to_factor(num: float, base: int) -> int:
"""Rounds floating point number to the nearest integer multiple of the
given base. E.g., for floating number 90.1 and integer base 45, the result
is 90.
# Attributes
num : floating point number to be rounded.
base: integer base
"""
ret... | 3679b884523253cec51659ceaf6f78292f87a401 | 35,685 |
def get_doc_content(content):
"""
Return the doc fields from request (not auth-related fields).
"""
return {
"title": content.get("title"),
"link": content.get("link"),
"tags": content.get("tags"),
"authors": content.get("authors"),
"year": content.get("year"),
... | ffd5037aee65dcc1cc104e8fc47df708fd5e7c64 | 35,687 |
def join_strings(lst):
"""Join a list to comma-separated values string."""
return ",".join(lst) | fbbc195a53d2d4b15012861251d676dbf9369cde | 35,688 |
def l_system(depth, axiom, **rules):
"""Generate L-system from axiom using rules, up to given depth"""
if not depth:
return axiom
# Basic, most straight-forward implementation
# Note 1: it doesn't matter if axiom is a string or a list
# Note 2: consider the difference between .extend()... | ed59af25848c5074be7b1da1a796dcdb0422e87e | 35,689 |
def call_with_ensured_size(method, max_size, arg):
"""
Breaks a list of arguments up into chunks of a maximum size and calls the given method on each chunk
Args:
method (function): the method to call
max_size (int): the maximum number of arguments to include in a single call
arg (an... | e31dfbd03de5e4caabb46241957b98d1b76eee1a | 35,690 |
def safe_str(maybe_str):
"""To help with testing between python 2 and 3, this function attempts to
decode a string, and if it cannot decode it just returns the string.
"""
try:
return maybe_str.decode('utf-8')
except AttributeError:
return maybe_str | f9713f98b4d32558855d46d82c2f5cc9bce568ee | 35,692 |
def get_snapshot(ec2, snapshot_name: str):
"""Returns a snapshot by its name."""
res = ec2.describe_snapshots(Filters=[
{'Name': 'tag:Name', 'Values': [snapshot_name]},
])
if len(res['Snapshots']) > 1:
raise ValueError('Several snapshots with Name=%s found.' % snapshot_name)
snapsh... | cd6076e04fd2c83e50b3a0ac7bc117793c92731d | 35,697 |
from datetime import datetime
def get_datetime_from_timestamp(timestamp):
"""Return datetime from unix timestamp"""
try:
return datetime.fromtimestamp(int(timestamp))
except:
return None | 553d24a532681d139845777cd71ca54fc3e16f96 | 35,701 |
def get_pubmed_id_for_doc(doc_id):
"""Because our doc_id is currently just the PMID, and we intend to KEEP it this way, return the doc_id here"""
return doc_id | a1d9241406b9655553d008ff7839c1f2b730f994 | 35,705 |
def generate_onehot_dict(word_list):
"""
Takes a list of the words in a text file, returning a dictionary mapping
words to their index in a one-hot-encoded representation of the words.
"""
word_to_index = {}
i = 0
for word in word_list:
if word not in word_to_index:
word_... | 1408cfbf8360134b4d9a95165e693a972cc4f4e3 | 35,706 |
def valid_file(path: str) -> bool:
"""
Check if regressi file is valid
:param path: path to the file to test
:return: whether the file is valid or not
"""
with open(path, 'r') as file:
if file.readline() == "EVARISTE REGRESSI WINDOWS 1.0":
return False
else:
... | 81e407fd24a830b32a0ba55bb4e912a2d32d61ef | 35,714 |
import re
def alphanum_key(s):
""" Key func for sorting strings according to numerical value. """
return [int(c) if c.isdigit() else c for c in re.split('([0-9]+)', s)] | c9147a41cad775700db280e92efe500fb6d8469e | 35,719 |
def value_or_default(value, default):
"""
Returns the supplied value of it is non None, otherwise the supplied default.
"""
return value if value is not None else default | d3fdf1cee4029c5617623e2834a6f05d962b2e94 | 35,727 |
import re
def parse_k(msg):
"""Parse create keypoint message and return keypoint number"""
if not re.search(r"KEYPOINT NUMBER", msg):
res = re.search(r"(KEYPOINT\s*)([0-9]+)", msg)
else:
res = re.search(r"(KEYPOINT NUMBER =\s*)([0-9]+)", msg)
if res:
result = int(res.group(2))... | 92f45ea09a7c9e1eecf48664c49218657687a217 | 35,729 |
def confirm(prompt=None, response=False):
"""Prompts for a yes or no response from the user
Arguments
---------
prompt : str, default=None
response : bool, default=False
Returns
-------
bool
True for yes and False for no.
Notes
-----
`response` should be set to th... | 4e60be0b9973de67ee718eb255c10efdbd7666aa | 35,730 |
def READ_RECORD(SFI:int, record:int) -> dict:
"""READ_RECORD(): generate APDU for READ RECORD command
"""
return {'CLA' : '00', 'INS' : 'B2', 'P1' : F"{record:02X}", 'P2' : F"{SFI*8+4:02X}", 'Le' : '00'} | 746e09d86b42eb822b197ebb3ff8f4bb36ad018a | 35,733 |
def transform_vertex(u, phi):
"""
Given a vertex id u and a set of partial isomorphisms phi.
Returns the transformed vertex id
"""
for _phi in phi:
if _phi[0] == u:
return _phi[1]
raise Exception('u couldn\' be found in the isomorphisms') | d35d0a819d795098190f8578b115b04231a53902 | 35,740 |
def write_normal(fname,triplets,na,angd,agr):
"""
Write out ADF data in normal ADF format.
"""
outfile= open(fname,'w')
outfile.write('# 1:theta[i], ')
for it,t in enumerate(triplets):
outfile.write(' {0:d}:{1:s}-{2:s}-{3:s},'.format(it+2,*t))
outfile.write('\n')
for i in range(n... | d12e858060dad0f398beb139aaf9a4edda255807 | 35,741 |
import random
def bomber(length, width, bomb, m, n):
"""
Place bombs randomly (position of first click and its surroundings cannot be bombs)
:param length: length of the board
:param width: width of the board
:param bomb: number of bombs
:param m: horizontal position of first click
:param ... | 52591fe68d7d03e29559072148a945700b6aad06 | 35,743 |
def format_example_name(example):
"""Formats an example command to a function or file name
"""
return '_'.join(example).replace('-', '_').replace(
'.', '_').replace('/examples/', '')[1:] | 223301709fb52aac98e2622c7df760fd3d7056e1 | 35,747 |
def value(card):
"""Returns the numeric value of a card or card value as an integer 1..13"""
prefix = card[:len(card) - 1]
names = {'A': 1, 'J': 11, 'Q': 12, 'K': 13}
if prefix in names:
return names.get(prefix)
else:
return int(prefix) | 534681894f67dc626173d952e7eddb0ecd8da20d | 35,748 |
import re
def make_command(name):
"""Convert a string into a space-less command."""
name = re.sub('[^\w]', ' ', name) # Replace special characters with spaces
name = name.strip().lower()
while " " in name: name = name.replace(' ', ' ') # Replace duplicate spaces
name = name.replace(' ', '-') ... | e1f154f89e0e54ead76a4492325fb1c547043cea | 35,752 |
def add_prefix(name, prefix=None, split='.'):
"""Add prefix to name if given."""
if prefix is not None:
return '{}{}{}'.format(prefix, split, name)
else:
return name | b22ab3ce8a286716579892a4bf9627674aea1f62 | 35,761 |
import torch
def f_get_raster_image(cfg,
images,
history_weight=0.9):
"""
Creates single raster image from sequence of images from l5kit's AgentDataset
Args:
cfg {dict}: Dictionary config.
images: (batch_size, 2*(history_num_frames+... | aff05d51041c909a73a93c9dbef2970e302677b1 | 35,764 |
def a_send(text, ctx):
"""Send text line to the controller."""
ctx.ctrl.send(text)
return True | 7a5b8412f5099138afedc892c893f413ab4eba21 | 35,766 |
def path_info_split(path_info):
"""
Splits off the first segment of the path. Returns (first_part,
rest_of_path). first_part can be None (if PATH_INFO is empty), ''
(if PATH_INFO is '/'), or a name without any /'s. rest_of_path
can be '' or a string starting with /.
"""
if not path_info:... | 2b8429767feee1d271f8370684dddd34362390af | 35,768 |
import time
def unixtime(dt_obj):
"""Format datetime object as unix timestamp
:param dt_obj: datetime.datetime object
:returns: float
"""
return time.mktime(dt_obj.utctimetuple()) | 7b2e6a923be2c05abed0ad8d324e818646e8f0c1 | 35,774 |
def star_wars(x, y, elem, neighbours):
"""Star Wars preset of the Generations family. (345/2/4)"""
red_count = 0
for neighbour in neighbours:
if neighbour == 3:
red_count += 1
if elem == 3: # The cell is alive
if red_count in [3,4,5]:
return 3
else:
... | b9929d132b42744439052600019b852833e2c032 | 35,776 |
import json
def construct_event_json(event, data):
"""
Helper function to construct a payload for sending to clients
"""
return json.dumps([event, data], ensure_ascii=False).encode('utf8') | 0693dacbf3592a6965fda925d8b3eab9c11dddf0 | 35,778 |
def is_private(message) -> bool:
"""Whether message is private."""
# See "type" at https://core.telegram.org/bots/api#chat.
return message.chat.type == 'private' | d45dca82c3a46d25997b1dbde2803fb50d08c871 | 35,780 |
import calendar
def to_timestamp(date):
"""Convert a datetime object into a calendar timestamp object
Parameters
----------
date : datetime.datetime
Datetime object e.g. datetime.datetime(2020, 10, 31, 0, 0)
Returns
-------
cal : calendar.timegm
Calendar timestamp corresp... | 514ea392268dc94aa0a14b1dd5ce04425d1ed3bb | 35,782 |
def title_getter(node):
"""Return the title of a node (or `None`)."""
return node.get('title','') | 0825f4a2d6360d4845b3379ba9ade7a8e5fa11dc | 35,783 |
def get_automl_options_string(args):
""" This function creates a string suitable for passing to another script
of the automl command line options.
The expected use case for this function is that a "driver" script is given
the automl command line options (added to its parser with add_automl_options)... | bfe27e8e76666e0e5ca0f74feef8465234baebe8 | 35,788 |
import torch
def get_normal(xs):
"""Normals of xs.
Args:
xs: tensor [num_xs, 2]
Returns: tensor [num_xs, 2]
"""
return torch.stack([xs[:, 1], -xs[:, 0]], dim=-1) | b8bb383e4750651d391885a898d481e53d80add8 | 35,790 |
def mock_purge_unauth_url(url, request):
"""
Mock a purge request in which the credentials are valid, but the
url that was requested is not allowed
"""
return {'status_code': 403,
'content-type': 'application/json',
'server': 'Apache',
'content': {
... | a15e329f79fb6a004e88624781d8b8e90d438e00 | 35,795 |
import csv
def extract_pids_from_file(pid_file):
"""
Extracts pids from file containing a header and pids in each line
:param pid_file: path to the file containing the pids
:return: list of ints
"""
pids = []
with open(pid_file, 'r') as f:
csv_rows = csv.reader(f)
next(csv... | 77c74ec079d4c55d4c115b5966f415d6ae78e4e6 | 35,796 |
def pythagorean_triplet(a, b, c):
"""
Tests whether a^2 + b^2 = c^2.
"""
return a**2 + b**2 == c**2 | 3bda7322d0a8f4af5d4faa3f4ef5d5c34acbc6d3 | 35,797 |
from pathlib import Path
import filecmp
def are_directories_equal(dir1: Path, dir2: Path) -> bool:
"""Compares two directories recursively.
Files in each directory are
assumed to be equal if their names and contents are equal.
Args:
dir1: The first directory.
dir2: The second directo... | 976fe0ba26c50b67204b9888eec4176a328d114e | 35,799 |
def int16_to_bits(x):
"""
Unpack a 16 bit integer into binary fields. See the syntax for
this here https://docs.python.org/3/library/string.html#format-specification-mini-language
Parameters
----------
x : int16
single integer.
Returns
-------
List of binary fields alig... | 5993bfdae9666d364f9b2629fbbb862965cedddd | 35,803 |
def permute_observation(obs, perm):
"""Given a permutation, shuffle pixels of the observation."""
return obs.flatten()[perm].reshape(obs.shape) | ac18bce7d344b89cbcba8ea22ebcb92ff3f9c0e9 | 35,812 |
def size_to_bytes(size):
""" Return the size as a bytes object.
@param int size: a 32-bit integer that we want to convert to bytes
@rtype: bytes
>>> list(size_to_bytes(300))
[44, 1, 0, 0]
"""
# little-endian representation of 32-bit (4-byte)
# int size
return size.to_bytes(4, "litt... | 722ab782250570779519f8d8fdca4d5b449324d5 | 35,817 |
from typing import Any
def issubclass_safe(candidate: Any, ancestor: Any) -> bool:
"""Returns True the candidate is a subclass of the ancestor, else False. Will return false instead of raising TypeError if the candidate is not a class."""
try:
return issubclass(candidate, ancestor)
except TypeErro... | 54fec7e6861de36015d8264978b76073704080d6 | 35,822 |
import requests
def served(url):
"""Return True if url returns 200."""
r = requests.get(url, allow_redirects=False)
return r.status_code == 200 | 1c4f1025bc36dc6e1b1f7fe1d519e5d557ade813 | 35,823 |
def czyMur(mapObj, x, y):
"""Zwraca True jesli (x,y) pozycja na mapie jest murem,
w.p.p. zwraca False"""
if x < 0 or x >= len(mapObj) or y < 0 or y >= len(mapObj[x]):
return False # (x,y) nie sa na mapie
elif mapObj[x][y] in ('#'):
return True # mur na drodze
return False | 617ebf983c41fdcb5399f57b89d126469e93875e | 35,825 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.