content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def _extractRGBFromHex(hexCode):
"""
Extract RGB information from an hexadecimal color code
Parameters:
hexCode (string): an hexadecimal color code
Returns:
A tuple containing Red, Green and Blue information
"""
hexCode = hexCode.lstrip('#') # Remove the '#' from the string
... | e1d67b4f2004e5e2d4a646a3cc5dc49a1e8cd890 | 705,723 |
def get_user_partition_groups(course_key, user_partitions, user, partition_dict_key='name'):
"""
Collect group ID for each partition in this course for this user.
Arguments:
course_key (CourseKey)
user_partitions (list[UserPartition])
user (User)
partition_dict_key - i.e. 'i... | 3bb2f76f4a48ce0af745637810903b8086b2fc02 | 705,725 |
import collections
def factory_dict(value_factory, *args, **kwargs):
"""A dict whose values are computed by `value_factory` when a `__getitem__` key is missing.
Note that values retrieved by any other method will not be lazily computed; eg: via `get`.
:param value_factory:
:type value_factory: A function fr... | f7d4898e62377958cf9d9c353ed12c8d381f042f | 705,727 |
def build_or_passthrough(model, obj, signal):
"""Builds the obj on signal, or returns the signal if obj is None."""
return signal if obj is None else model.build(obj, signal) | bee9c8557a89a458cf281b42f968fe588801ed46 | 705,728 |
import requests
import json
def warc_url(url):
"""
Search the WARC archived version of the URL
:returns: The WARC URL if found, else None
"""
query = "http://archive.org/wayback/available?url={}".format(url)
response = requests.get(query)
if not response:
raise RuntimeError()
... | afc24876f72915ba07233d5fde667dd0ba964f5a | 705,729 |
def set_attrib(node, key, default):
"""
Parse XML key for a given node
If key does not exist, use default value
"""
return node.attrib[key] if key in node.attrib else default | 0e21b6b0e5a64e90ee856d4b413084a8c395b070 | 705,732 |
def is_order_exist(context, symbol, side) -> bool:
"""判断同方向订单是否已经存在
:param context:
:param symbol: 交易标的
:param side: 交易方向
:return: bool
"""
uo = context.unfinished_orders
if not uo:
return False
else:
for o in uo:
if o.symbol == symbol and o.side == side:... | 42363c8b3261e500a682b65608c27537b93bcfb1 | 705,733 |
import math
def gvisc(P, T, Z, grav):
"""Function to Calculate Gas Viscosity in cp"""
#P pressure, psia
#T temperature, °R
#Z gas compressibility factor
#grav gas specific gravity
M = 28.964 * grav
x = 3.448 + 986.4 / T + 0.01009 * M
Y = 2.447 - 0.2224... | 5ff1ad63ef581cea0147348104416913c7b77e37 | 705,738 |
def is_base(base_pattern, str):
"""
base_pattern is a compiled python3 regex.
str is a string object.
return True if the string match the base_pattern or False if it is not.
"""
return base_pattern.match(str, 0, len(str)) | d0b0e3291fdbfad49698deffb9f57aefcabdce92 | 705,741 |
def predicate(line):
"""
Remove lines starting with ` # `
"""
if "#" in line:
return False
return True | ff7d67c1fd7273b149c5a2148963bf898d6a3591 | 705,752 |
def sort_list_by_list(L1,L2):
"""Sort a list by another list"""
return [x for (y,x) in sorted(zip(L2,L1), key=lambda pair: pair[0])] | 04b7c02121620be6d9344af6f56f1b8bfe75e9f3 | 705,755 |
def unpack_singleton(x):
"""Gets the first element if the iterable has only one value.
Otherwise return the iterable.
# Argument:
x: A list or tuple.
# Returns:
The same iterable or the first element.
"""
if len(x) == 1:
return x[0]
return x | cf551f242c8ea585c1f91eadbd19b8e5f73f0096 | 705,756 |
from typing import List
from typing import Dict
def make_car_dict(key: str, data: List[str]) -> Dict:
"""Organize car data for 106 A/B of the debtor
:param key: The section id
:param data: Content extract from car data section
:return: Organized data for automobile of debtor
"""
return {
... | 671cb2f82f15d14345e34e9823ea390d72cf040a | 705,757 |
import struct
def get_array_of_float(num, data):
"""Read array of floats
Parameters
----------
num : int
Number of values to be read (length of array)
data : str
4C binary data file
Returns
-------
str
Truncated 4C binary data file
list
List of flo... | 92a0a4cc653046826b14c2cd376a42045c4fa641 | 705,762 |
def cver(verstr):
"""Converts a version string into a number"""
if verstr.startswith("b"):
return float(verstr[1:])-100000
return float(verstr) | 1ad119049b9149efe7df74f5ac269d3dfafad4e2 | 705,765 |
def _replace_oov(original_vocab, line):
"""Replace out-of-vocab words with "UNK".
This maintains compatibility with published results.
Args:
original_vocab: a set of strings (The standard vocabulary for the dataset)
line: a unicode string - a space-delimited sequence of words.
Returns:
a unicode ... | 2e2cb1464484806b79263a14fd32ed4d40d0c9ba | 705,768 |
def geq_indicate(var, indicator, var_max, thr):
"""Generates constraints that make indicator 1 iff var >= thr, else 0.
Parameters
----------
var : str
Variable on which thresholding is performed.
indicator : str
Identifier of the indicator variable.
var_max : int
An uppe... | 319f18f5343b806b7108dd9c02ca5d647e132dab | 705,773 |
import torch
def compute_accuracy(logits, targets):
"""Compute the accuracy"""
with torch.no_grad():
_, predictions = torch.max(logits, dim=1)
accuracy = torch.mean(predictions.eq(targets).float())
return accuracy.item() | af15e4d077209ff6e790d6fdaa7642bb65ff8dbf | 705,779 |
def gm_put(state, b1, b2):
"""
If goal is ('pos',b1,b2) and we're holding b1,
Generate either a putdown or a stack subtask for b1.
b2 is b1's destination: either the table or another block.
"""
if b2 != 'hand' and state.pos[b1] == 'hand':
if b2 == 'table':
return [('a_putdown... | c9076ac552529c60b5460740c74b1602c42414f2 | 705,780 |
def get_child(parent, child_index):
"""
Get the child at the given index, or return None if it doesn't exist.
"""
if child_index < 0 or child_index >= len(parent.childNodes):
return None
return parent.childNodes[child_index] | 37f7752a4a77f3d750413e54659f907b5531848c | 705,782 |
def get_renaming(mappers, year):
"""Get original to final column namings."""
renamers = {}
for code, attr in mappers.items():
renamers[code] = attr['df_name']
return renamers | 33197b5c748b3ecc43783d5f1f3a3b5a071d3a4e | 705,784 |
async def clap(text, args):
""" Puts clap emojis between words. """
if args != []:
clap_str = args[0]
else:
clap_str = "👏"
words = text.split(" ")
clappy_text = f" {clap_str} ".join(words)
return clappy_text | 09865461e658213a2f048b89757b75b2a37c0602 | 705,785 |
def remove_extra_two_spaces(text: str) -> str:
"""Replaces two consecutive spaces with one wherever they occur in a text"""
return text.replace(" ", " ") | d8b9600d3b442216b1fbe85918f313fec8a5c9cb | 705,786 |
def load_utt_list(utt_list):
"""Load a list of utterances.
Args:
utt_list (str): path to a file containing a list of utterances
Returns:
List[str]: list of utterances
"""
with open(utt_list) as f:
utt_ids = f.readlines()
utt_ids = map(lambda utt_id: utt_id.strip(), utt_... | 6a77e876b0cc959ac4151b328b718ae45522448b | 705,787 |
def compute_flow_for_supervised_loss(
feature_model,
flow_model,
batch,
training
):
"""Compute flow for an image batch.
Args:
feature_model: A model to compute features for flow.
flow_model: A model to compute flow.
batch: A tf.tensor of shape [b, seq, h, w, c] holding a batch of triple... | a74f392c1d4e234fdb66d18e63d7c733ec6669a7 | 705,788 |
import itertools
def labels_to_intervals(labels_list):
"""
labels_to_intervals() converts list of labels of each frame into set of time intervals where a tag occurs
Args:
labels_list: list of labels of each frame
e.g. [{'person'}, {'person'}, {'person'}, {'surfboard', 'person'}]
Retu... | 65b63ea3e6f097e9605e1c1ddb8dd434d7db9370 | 705,791 |
def get_wolfram_query_url(query):
"""Get Wolfram query URL."""
base_url = 'www.wolframalpha.com'
if not query:
return 'http://{0}'.format(base_url)
return 'http://{0}/input/?i={1}'.format(base_url, query) | 0122515f1a666cb897b53ae6bd975f65da072438 | 705,792 |
def compute_diff(old, new):
"""
Compute a diff that, when applied to object `old`, will give object
`new`. Do not modify `old` or `new`.
"""
if not isinstance(old, dict) or not isinstance(new, dict):
return new
diff = {}
for key, val in new.items():
if key not in old:
... | f6e7674faa2a60be17994fbd110f8e1d67eb9886 | 705,798 |
def default_rollout_step(policy, obs, step_num):
"""
The default rollout step function is the policy's compute_action function.
A rollout step function allows a developer to specify the behavior
that will occur at every step of the rollout--given a policy
and the last observation from the env--to d... | a6e9dff784e46b9a59ae34334a027b427e8d230a | 705,801 |
import glob
def find_file(filename):
"""
This helper function checks whether the file exists or not
"""
file_list = list(glob.glob("*.txt"))
if filename in file_list:
return True
else:
return False | 42895e66e258ba960c890f871be8c261aec02852 | 705,802 |
def true_fov(M, fov_e=50):
"""Calulates the True Field of View (FOV) of the telescope & eyepiece pair
Args:
fov_e (float): FOV of eyepiece; default 50 deg
M (float): Magnification of Telescope
Returns:
float: True Field of View (deg)
"""
return fov_e/M | 7735135d326f3000ac60274972263a8a71648033 | 705,808 |
def air_density(temp, patm, pw = 0):
"""
Calculates the density of dry air by means of the universal gas law as a
function of air temperature and atmospheric pressure.
m / V = [Pw / (Rv * T)] + [Pd / (Rd * T)]
where:
Pd: Patm - Pw
Rw: specific gas constant for water vapour ... | 1af7afbf562fec105566a2c934f83c73f0be1173 | 705,812 |
def getblock(lst, limit):
"""Return first limit entries from list lst and remove them from the list"""
r = lst[-limit:]
del lst[-limit:]
return r | 8d230dec59fe00375d92b6c6a8b51f3e6e2d9126 | 705,815 |
import functools
import warnings
def ignore_python_warnings(function):
"""
Decorator for ignoring *Python* warnings.
Parameters
----------
function : object
Function to decorate.
Returns
-------
object
Examples
--------
>>> @ignore_python_warnings
... def f()... | 438e54fe927f787783175faacf4eb9608fd27cf0 | 705,816 |
def get_requirements(extra=None):
"""
Load the requirements for the given extra from the appropriate
requirements-extra.txt, or the main requirements.txt if no extra is
specified.
"""
filename = f"requirements-{extra}.txt" if extra else "requirements.txt"
with open(filename) as fp:
... | 7ce9e348357925b7ff165ebd8f13300d849ea0ee | 705,817 |
def _format_mojang_uuid(uuid):
"""
Formats a non-hyphenated UUID into a whitelist-compatible UUID
:param str uuid: uuid to format
:return str: formatted uuid
Example:
>>> _format_mojang_uuid('1449a8a244d940ebacf551b88ae95dee')
'1449a8a2-44d9-40eb-acf5-51b88ae95dee'
Must have 32 charac... | 517071b28f1e747091e2a539cd5d0b8765bebeba | 705,818 |
def get_word(path):
""" extract word name from json path """
return path.split('.')[0] | e749bcdaaf65de0299d35cdf2a2264568ad5051b | 705,821 |
import json
def readJsonFile(filePath):
"""read data from json file
Args:
filePath (str): location of the json file
Returns:
variable: data read form the json file
"""
result = None
with open(filePath, 'r') as myfile:
result = json.load(myfile)
return result | cf15e358c52edcfb00d0ca5257cf2b5456c6e951 | 705,825 |
def get_namespace_leaf(namespace):
"""
From a provided namespace, return it's leaf.
>>> get_namespace_leaf('foo.bar')
'bar'
>>> get_namespace_leaf('foo')
'foo'
:param namespace:
:return:
"""
return namespace.rsplit(".", 1)[-1] | 0cb21247f9d1ce5fa4dd8d313142c4b09a92fd7a | 705,826 |
def sort(list_):
"""
This function is a selection sort algorithm. It will put a list in numerical order.
:param list_: a list
:return: a list ordered by numerial order.
"""
for minimum in range(0, len(list_)):
for c in range(minimum + 1, len(list_)):
if list_[c] < list_[mini... | 99007e4b72a616ae73a20358afc94c76e0011d3e | 705,827 |
def __charge_to_sdf(charge):
"""Translate RDkit charge to the SDF language.
Args:
charge (int): Numerical atom charge.
Returns:
str: Str representation of a charge in the sdf language
"""
if charge == -3:
return "7"
elif charge == -2:
return "6"
elif charge ... | 1bfda86ee023e8c11991eaae2969b87a349b7f7e | 705,833 |
def get_volumetric_scene(self, data_key="total", isolvl=0.5, step_size=3, **kwargs):
"""Get the Scene object which contains a structure and a isosurface components
Args:
data_key (str, optional): Use the volumetric data from self.data[data_key]. Defaults to 'total'.
isolvl (float, optional): Th... | 836fb5f3158ed5fe55a2975ce05eb21636584a95 | 705,838 |
def reduce_aet_if_dry(aet, wat_lev, fc):
""" Reduce actual evapotranspiration if the soil is dry. If the water level
in a cell is less than 0.7*fc, the rate of evapo-transpiration is
reduced by a factor. This factor is 1 when wat_lev = 0.7*fc and
decreases linearly to reach 0 when wat_lev... | 170462a23c3903a390b89963aa6ce21839e5d44b | 705,839 |
def get_python3_status(classifiers):
"""
Search through list of classifiers for a Python 3 classifier.
"""
status = False
for classifier in classifiers:
if classifier.find('Programming Language :: Python :: 3') == 0:
status = True
return status | b4bf347dc0bbf3e9a198baa8237f7820cbb86e0b | 705,845 |
def ratings_std(df):
"""calculate standard deviation of ratings from the given dataframe
parameters
----------
df (pandas dataframe): a dataframe cotanis all ratings
Returns
-------
standard deviation(float): standard deviation of ratings, keep 4 decimal
"""
std_value = df['ratings... | b1bf00d25c0cee91632eef8248d5e53236dd4526 | 705,847 |
import hashlib
def _hash(file_name, hash_function=hashlib.sha256):
"""compute hash of file `file_name`"""
with open(file_name, 'rb') as file_:
return hash_function(file_.read()).hexdigest() | 463d692116fbb85db9f1a537cbcaa5d2d019ba05 | 705,848 |
def _get_perf_hint(hint, index: int, _default=None):
"""
Extracts a "performance hint" value -- specified as either a scalar or 2-tuple -- for
either the left or right Dataset in a merge.
Parameters
----------
hint : scalar or 2-tuple of scalars, optional
index : int
Indicates wheth... | d67a70d526934dedaa9f571970e27695404350f2 | 705,849 |
def sentences_from_doc(ttree_doc, language, selector):
"""Given a Treex document, return a list of sentences in the given language and selector."""
return [bundle.get_zone(language, selector).sentence for bundle in ttree_doc.bundles] | d9c09249171d5d778981fb98a8a7f53765518479 | 705,855 |
def file_to_list(filename):
"""
Read in a one-column txt file to a list
:param filename:
:return: A list where each line is an element
"""
with open(filename, 'r') as fin:
alist = [line.strip() for line in fin]
return alist | 33bee263b98c4ff85d10191fa2f5a0f095c6ae4b | 705,857 |
def gen_model_forms(form, model):
"""Creates a dict of forms. model_forms[0] is a blank form used for adding
new model objects. model_forms[m.pk] is an editing form pre-populated
the fields of m"""
model_forms = {0: form()}
for m in model.objects.all():
model_forms[m.pk] = form(instanc... | 28bf3f007a7f8f971c18980c84a7841fd116898f | 705,858 |
def cleanFAAText(origText):
"""Take FAA text message and trim whitespace from end.
FAA text messages have all sorts of trailing whitespace
issues. We split the message into lines and remove all
right trailing whitespace. We then recombine them into
a uniform version with no trailing whitespace.
... | ea9882e24c60acaa35cae97f8e95acb48f5fd2a6 | 705,861 |
def _read_hyperparameters(idx, hist):
"""Read hyperparameters as a dictionary from the specified history dataset."""
return hist.iloc[idx, 2:].to_dict() | b2a036a739ec3e45c61289655714d9b59b2f5490 | 705,863 |
def disassemble_pretty(self, addr=None, insns=1,
arch=None, mode=None):
"""
Wrapper around disassemble to return disassembled instructions as string.
"""
ret = ""
disas = self.disassemble(addr, insns, arch, mode)
for i in disas:
ret += "0x%x:\t%s\t%s\n" % (i.addr... | 39bddf246b880decbc84015ef20c5664f88d917e | 705,870 |
def IOU(a_wh, b_wh):
"""
Intersection over Union
Args:
a_wh: (width, height) of box A
b_wh: (width, height) of box B
Returns float.
"""
aw, ah = a_wh
bw, bh = b_wh
I = min(aw, bw) * min(ah, bh)
area_a = aw * ah
area_b = bw * bh
U = area_a + area_b - I
... | 92580147eac219d77e6c8a38875c5ee809783790 | 705,872 |
import re
def check_pre_release(tag_name):
"""
Check the given tag to determine if it is a release tag, that is, whether it
is of the form rX.Y.Z. Tags that do not match (e.g., because they are
suffixed with someting like -beta# or -rc#) are considered pre-release tags.
Note that this assumes tha... | 8e24a0a61bfa6fe84e936f004b4228467d724616 | 705,875 |
def _get_target_connection_details(target_connection_string):
"""
Returns a tuple with the raw connection details for the target machine extracted from the connection string provided
in the application arguments. It is a specialized parser of that string.
:param target_connection_string: the connection... | 5e6ee870c0e196f54950f26ee6e551476688dce9 | 705,876 |
import codecs
def read(filepath):
"""Read file content from provided filepath."""
with codecs.open(filepath, encoding='utf-8') as f:
return f.read() | bff53fbb9b1ebe85c6a1fa690d28d6b6bec71f84 | 705,878 |
import inspect
def is_bound_builtin_method(meth):
"""Helper returning True if meth is a bound built-in method"""
return (inspect.isbuiltin(meth)
and getattr(meth, '__self__', None) is not None
and getattr(meth.__self__, '__class__', None)) | a7a45f0f519119d795e91723657a1333eb6714e4 | 705,879 |
def vocabulary_size(tokens):
"""Returns the vocabulary size count defined as the number of alphabetic
characters as defined by the Python str.isalpha method. This is a
case-sensitive count. `tokens` is a list of token strings."""
vocab_list = set(token for token in tokens if token.isalpha())
return ... | 5e26e1be98a3e82737277458758f0fd65a64fe8f | 705,882 |
def get_transit_boundary_indices(time, transit_size):
""" Determines transit boundaries from sorted time of transit cut out
:param time (1D np.array) sorted times of transit cut out
:param transit_size (float) size of the transit crop window in days
:returns tuple:
[0... | cd3775d72690eb4539e0434b0ac7f715d14374a6 | 705,883 |
def _computePolyVal(poly, value):
"""
Evaluates a polynomial at a specific value.
:param poly: a list of polynomial coefficients, (first item = highest degree to last item = constant term).
:param value: number used to evaluate poly
:return: a number, the evaluation of poly with value
"""
#return numpy.polyval... | 0377ba0757439409824b89b207485a99f804cb41 | 705,885 |
def odd_desc(count):
"""
Replace ___ with a single call to range to return a list of descending odd numbers ending with 1
For e.g if count = 2, return a list of 2 odds [3,1]. See the test below if it is not clear
"""
return list(reversed(range(1,count*2,2))) | 2f90095c5b25f8ac33f3bb86d3f46e67932bc78a | 705,886 |
def outside_range(number, min_range, max_range):
"""
Returns True if `number` is between `min_range` and `max_range` exclusive.
"""
return number < min_range or number > max_range | dc3889fbabb74db38b8558537413ebc5bc613d05 | 705,887 |
from typing import Any
def device_traits() -> dict[str, Any]:
"""Fixture that sets default traits used for devices."""
return {"sdm.devices.traits.Info": {"customName": "My Sensor"}} | 1ccaeac4a716706915654d24270c24dac0210977 | 705,889 |
def get_parser_args(args=None):
"""
Transform args (``None``, ``str``, ``list``, ``dict``) to parser-compatible (list of strings) args.
Parameters
----------
args : string, list, dict, default=None
Arguments. If dict, '--' are added in front and there should not be positional arguments.
... | 41b607a6ebf12526efcd38469192b398419327bf | 705,894 |
def set_name_line(hole_lines, name):
"""Define the label of each line of the hole
Parameters
----------
hole_lines: list
a list of line object of the slot
name: str
the name to give to the line
Returns
-------
hole_lines: list
List of line object with label
... | a57667f269dac62d39fa127b2a4bcd438a8a989b | 705,895 |
def is_reserved(word):
"""
Determines if word is reserved
:param word: String representing the variable
:return: True if word is reserved and False otherwise
"""
lorw = ['define','define-struct']
return word in lorw | 0b0e3706bcafe36fc52e6384617223078a141fb2 | 705,901 |
import csv
def read_csv_from_file(file):
"""
Reads the CSV data from the open file handle and returns a list of dicts.
Assumes the CSV data includes a header row and uses that header row as
fieldnames in the dict. The following fields are required and are
case-sensitive:
- ``artist``
... | 89cfce0be6270076230051a6e852d1add3f4dcaf | 705,904 |
import hashlib
import six
def make_hashkey(seed):
"""
Generate a string key by hashing
"""
h = hashlib.md5()
h.update(six.b(str(seed)))
return h.hexdigest() | 38d088005cb93fc0865933bbb706be171e72503a | 705,905 |
def fix(x):
"""
Replaces spaces with tabs, removes spurious newlines, and lstrip()s each
line. Makes it really easy to create BED files on the fly for testing and
checking.
"""
s = ""
for i in x.splitlines():
i = i.lstrip()
if i.endswith('\t'):
add_tab = '\t'
... | ecd3a4d7f470feae1b697025c8fbf264d5c6b149 | 705,906 |
def get_ngram_universe(sequence, n):
"""
Computes the universe of possible ngrams given a sequence. Where n is equal to the length of the sequence, the resulting number represents the sequence universe.
Example
--------
>>> sequence = [2,1,1,4,2,2,3,4,2,1,1]
>>> ps.get_ngram_universe(sequence, 3)
64
"""
# if... | 3dbfe1822fdefb3e683b3f2b36926b4bb066468f | 705,907 |
def cartToRadiusSq(cartX, cartY):
"""Convert Cartesian coordinates into their corresponding radius squared."""
return cartX**2 + cartY**2 | 3fb79d2c056f06c2fbf3efc14e08a36421782dbd | 705,909 |
def unique_entity_id(entity):
"""
:param entity: django model
:return: unique token combining the model type and id for use in HTML
"""
return "%s-%s" % (type(entity).__name__, entity.id) | c58daf9a115c9840707ff5e807efadad36a86ce8 | 705,910 |
def variable_to_json(var):
"""Converts a Variable object to dict/json struct"""
o = {}
o['x'] = var.x
o['y'] = var.y
o['name'] = var.name
return o | 86497a7915e4825e6e2cbcfb110c9bc4c229efed | 705,913 |
def getOrElseUpdate(dictionary, key, opr):
"""If given key is already in the dictionary, returns associated value.
Otherwise compute the value with opr, update the dictionary and return it.
None dictionary are ignored.
>>> d = dict()
>>> getOrElseUpdate(d, 1, lambda _: _ + 1)
2
>>> print(d)
{... | 95454d7ca34d6ae243fda4e70338cf3d7584b827 | 705,915 |
def filt_all(list_, func):
"""Like filter but reverse arguments and returns list"""
return [i for i in list_ if func(i)] | 72010b483cab3ae95d49b55ca6a70b0838b0a34d | 705,920 |
def _rav_setval_ ( self , value ) :
"""Assign the valeu for the variable
>>> var = ...
>>> var.value = 10
"""
value = float ( value )
self.setVal ( value )
return self.getVal() | 80ad7ddec68d5c97f72ed63dd6ba4a1101de99cb | 705,921 |
def bb_to_plt_plot(x, y, w, h):
""" Converts a bounding box to parameters
for a plt.plot([..], [..])
for actual plotting with pyplot
"""
X = [x, x, x+w, x+w, x]
Y = [y, y+h, y+h, y, y]
return X, Y | 10ea3d381969b7d30defdfdbbac0a8d58d06d4d4 | 705,924 |
from typing import Counter
def count_items(column_list:list):
"""
Contar os tipos (valores) e a quantidade de items de uma lista informada
args:
column_list (list): Lista de dados de diferentes tipos de valores
return: Retorna dois valores, uma lista de tipos (list) e... | 06cf25aed4d0de17fa8fb11303c9284355669cf5 | 705,925 |
def to_graph(grid):
"""
Build adjacency list representation of graph
Land cells in grid are connected if they are vertically or horizontally adjacent
"""
adj_list = {}
n_rows = len(grid)
n_cols = len(grid[0])
land_val = "1"
for i in range(n_rows):
for j in range(n_cols):
... | ebdd0406b123a636a9d380391ef4c13220e2dabd | 705,926 |
import re
def _remove_comments_inline(text):
"""Removes the comments from the string 'text'."""
if 'auto-ignore' in text:
return text
if text.lstrip(' ').lstrip('\t').startswith('%'):
return ''
match = re.search(r'(?<!\\)%', text)
if match:
return text[:match.end()] + '\n'
else:
return tex... | 463e29e1237a88e91c13a58ffea1b2ccdafd4a1d | 705,929 |
import fcntl
def has_flock(fd):
"""
Checks if fd has flock over it
True if it is, False otherwise
:param fd:
:return:
:rtype: bool
"""
try:
fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
except BlockingIOError:
return True
else:
return False | 9ae997d06a12d73a659958bc2f0467ebdf0142b7 | 705,937 |
import json
def assertDict(s):
""" Assert that the input is a dictionary. """
if isinstance(s,str):
try:
s = json.loads(s)
except:
raise AssertionError('String "{}" cannot be json-decoded.'.format(s))
if not isinstance(s,dict): raise AssertionError('Variable "{}" is not a dictionary.'.forma... | 302defb4e1eecc9a6171cda0401947e3251be585 | 705,942 |
import ast
from typing import Tuple
from typing import List
from typing import Any
def get_function_args(node: ast.FunctionDef) -> Tuple[List[Any], List[Any]]:
"""
This functon will process function definition and will extract all
arguments used by a given function and return all optional and non-optional... | a4fe9dccedd5684050a7d5e7949e384dd4021035 | 705,943 |
def index_containing_substring(list_str, substring):
"""For a given list of strings finds the index of the element that contains the
substring.
Parameters
----------
list_str: list of strings
substring: substring
Returns
-------
index: containing the substring or -1
"""
... | 2816899bc56f6b2c305192b23685d3e803b420df | 705,945 |
def calculate_n_inputs(inputs, config_dict):
"""
Calculate the number of inputs for a particular model.
"""
input_size = 0
for input_name in inputs:
if input_name == 'action':
input_size += config_dict['prior_args']['n_variables']
elif input_name == 'state':
i... | 78d750ff4744d872d696dcb454933c868b0ba41e | 705,950 |
def all_not_none(*args):
"""Shorthand function for ``all(x is not None for x in args)``. Returns
True if all `*args` are not None, otherwise False."""
return all(x is not None for x in args) | 2d063f39e253a78b28be6857df08d8f386d8eb4a | 705,954 |
import logging
import requests
def scrape_page(url):
"""
scrape page by url and return its html
:param url: page url
:return: html of page
"""
logging.info('scraping %s...', url)
try:
response = requests.get(url)
if response.status_code == 200:
return response.t... | a09eb79ce6abe25e4eb740dcfeb7a4debfca0b88 | 705,959 |
def get_all_applications(user, timeslot):
"""
Get a users applications for this timeslot
:param user: user to get applications for
:param timeslot: timeslot to get the applications.
:return:
"""
return user.applications.filter(Proposal__TimeSlot=timeslot) | 40aec747174fa4a3ce81fe2a3a5eee599c81643a | 705,961 |
import importlib
def get_dataset(cfg, designation):
"""
Return a Dataset for the given designation ('train', 'valid', 'test').
"""
dataset = importlib.import_module('.' + cfg['dataset'], __package__)
return dataset.create(cfg, designation) | 3f872d6407110cf735968ad6d4939b40fec9167d | 705,962 |
def RestrictDictValues( aDict, restrictSet ):
"""Return a dict which has the mappings from the original dict only for values in the given set"""
return dict( item for item in aDict.items() if item[1] in restrictSet ) | 4333c40a38ad3bce326f94c27b4ffd7dc24ae19c | 705,963 |
def abs_length_diff(trg, pred):
"""Computes absolute length difference
between a target sequence and a predicted sequence
Args:
- trg (str): reference
- pred (str): generated output
Returns:
- absolute length difference (int)
"""
trg_length = len(trg.split(' '))
pr... | b5baf53609b65aa1ef3b1f142e965fa0606b3136 | 705,966 |
import re
def parse_msig_storage(storage: str):
"""Parse the storage of a multisig contract to get its counter (as a
number), threshold (as a number), and the keys of the signers (as
Micheline sequence in a string)."""
# put everything on a single line
storage = ' '.join(storage.split('\n'))
s... | 6e04091721177cdd3d40b86717eb86ebbb92a8ff | 705,967 |
from functools import reduce
from operator import add
def assemble_docstring(parsed, sig=None):
"""
Assemble a docstring from an OrderedDict as returned by
:meth:`nd.utils.parse_docstring()`
Parameters
----------
parsed : OrderedDict
A parsed docstring as obtained by ``nd.utils.parse_... | 90553c468a2b113d3f26720128e384b0444d5c93 | 705,968 |
import torch
def log_cumsum(probs, dim=1, eps=1e-8):
"""Calculate log of inclusive cumsum."""
return torch.log(torch.cumsum(probs, dim=dim) + eps) | 7f1ab77fd9909037c7b89600c531173dab80c11e | 705,970 |
def race_from_string(str):
"""Convert race to one of ['white', 'black', None]."""
race_dict = {
"White/Caucasian": 'white',
"Black/African American": 'black',
"Unknown": None,
"": None
}
return race_dict.get(str, 'other') | 1d38469537c3f5f6a4a42712f5ec1dbd26a471bd | 705,971 |
from typing import List
def normalize(value: str) -> str:
"""Normalize a string by removing '-' and capitalizing the following character"""
char_list: List[str] = list(value)
length: int = len(char_list)
for i in range(1, length):
if char_list[i - 1] in ['-']:
char_list[i] = char_... | 52c1c8b5e950347cf63ed15d1efde47046b07873 | 705,973 |
def binary_str(num):
""" Return a binary string representation from the posive interger 'num'
:type num: int
:return:
Examples:
>>> binary_str(2)
'10'
>>> binary_str(5)
'101'
"""
# Store mod 2 operations results as '0' and '1'
bnum = ''
while num > 0:
bnum = str... | dde400323fccb9370c67197f555d9c41c40084a6 | 705,979 |
def compute_phot_error(flux_variance, bg_phot, bg_method, ap_area, epadu=1.0):
"""Computes the flux errors using the DAOPHOT style computation
Parameters
----------
flux_variance : array
flux values
bg_phot : array
background brightness values.
bg_method : string
backg... | 4470277ebc41cce0e2c8c41c2f03e3466473d749 | 705,980 |
def weighted_sequence_identity(a, b, weights, gaps='y'):
"""Compute the sequence identity between two sequences, different positions differently
The definition of sequence_identity is ambyguous as it depends on how gaps are treated,
here defined by the *gaps* argument. For details and examples, see
`... | 8face090454e984d0d4b9ea5fe78b6600a6e6b03 | 705,983 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.