content stringlengths 39 9.28k | sha1 stringlengths 40 40 | id int64 8 710k |
|---|---|---|
def _point_to_bytes(point, compressed = True):
""" Point serialisation.
Serialization is the standard one:
- O2 x for even x in compressed form
- 03 x for odd x in compressed form
- 04 x y for uncompressed form
"""
if compressed:
b = point.x.to_bytes(32,'bi... | 1a0c88c894d001354b342b7a2debea2b7299c4b3 | 269,036 |
def command(cmd, *parameters):
"""
Helper function. Prints the gprMax #<cmd>: <parameters>. None is ignored
in the output.
Args:
cmd (str): the gprMax cmd string to be printed
*parameters: one or more strings as arguments, any None values are
ignored
Returns:
s ... | 5e0dbec3daf11708cb5235e2d08cfae88ef27abf | 684,421 |
def ConfigToNumElectrons(config, ignoreFullD=0, ignoreFullF=0):
""" counts the number of electrons appearing in a configuration string
**Arguments**
- config: the configuration string (e.g. '2s^2 2p^4')
- ignoreFullD: toggles not counting full d shells
- ignoreFullF: toggles not counting ful... | 9e244503f4119a170963851595a24790c04e5911 | 454,573 |
def pipe(*fns):
"""
Given a list of queryset functions as *args, return a new queryset function
that calls each function in turn, passing the return value of each as the
argument to the next.
"""
def piped(queryset):
for fn in fns:
queryset = fn(queryset)
return quer... | a19645ead8eb0cace9b86cb20673844b53f2ee3b | 575,931 |
def lin_interpolate(x, x0, x1, y0, y1):
"""Linear interpolation formula
Notes
-----
Given two x values and their corresponding y values, interpolate for
an unknown y value at x
Parameters
----------
x : `float`
The x value at which the y value is unknown \n
x0 : `fl... | 53a63536e6fe86668a45b00a57204c648e0d0b8a | 518,041 |
import math
def x_round(x):
"""Round up time in 15 minutes
"""
return math.ceil(x * 4) / 4 | 88e5d9f36d4a3087682445ea94e835dedced73a0 | 161,779 |
import functools
import operator
def _has_pattern_match(name: str, patterns) -> bool:
"""Check if name matches any of the patterns"""
return functools.reduce(
operator.or_,
map(lambda r: r.search(name) is not None, patterns),
False) | 1dd6ad54ee35db20b6fcec0495e4c4ef61788aa0 | 697,341 |
def create_input_obj(val, cols_list, input_type=None, condition=False):
"""
Used to generate larger input objects for the query creation e.g., by iterating in a list
Example use: create_input_obj(1, "uid")
Output form: [{"val": uid, "cols": ["uid"], "type": "exact", "condition": True}]
"""
input... | 4184ec72924caf2f9f24c4d69ed3ce67b3e959cc | 550,898 |
def expand_pv(pv):
""" Returns the LCS Process Variable in full syntax AADDDNNNCMM as a string
where AA is two character area,
DD is device type,
NNN is device number,
C is channel type,
MM is channel number
Returns partial PVs when input string is incomplete.
... | f41dc8cf20dd55ed1cb0103c42ce67301ec93372 | 666,846 |
def text_getter(obj):
"""
Return the text of an individual DOM node.
Parameters
----------
obj : node-like
A DOM node.
Returns
-------
text : str or unicode
The text from an individual DOM node.
"""
return str(obj.text) | 1b9e8cb91a9732549e96818492b5413e9c782a73 | 368,413 |
def readlines(filename):
"""
Read a file and return the contents as a list of lines.
Arguments:
filename name of the file to read
Returns:
A list of stripped lines.
"""
with open(filename) as infile:
lines = infile.readlines()
return [l.strip() for l in lines] | 1ed5d90a9548d6f33eb5f06f821def0c581b3da2 | 517,541 |
def increase_by_1_loop(dummy_list):
"""
Increase the value by 1 by looping through each value in the list
Return
------
A new list containing the new values
Parameters
----------
dummy_list: A list containing integers
"""
secondlist=[]
for i in range(0,len(dummy_list)):
... | bd4295778fd993372a208b9df4b96040994d2af1 | 203,935 |
def _lower_locale(self, locale):
"""
Converts the given locale string value
to the lower version of it.
:type locale: String
:param locale: The lower locale string value to
be converted.
:rtype: String
:return: The lower locale string value.
"""
# converts the locale to lower, ... | dee74cb9b1472dcb18b3187f3f4954782b51a9e4 | 302,510 |
def _nt_sum(cobj, prop, theta):
"""
Create sum expressions in n-t forms (sum(n[i]*theta**t[i]))
Args:
cobj: Component object that will contain the parameters
prop: name of property parameters are associated with
theta: expression or variable to use for theta in expression
Retur... | 7ef4674b27069d2e254ef2cb1839fbc67c571029 | 694,537 |
def dm2skin_getNumberOfNonZeroElements(list):
"""Returns the number of non-zero elements in the given list"""
return int(sum([1 for x in list if x != 0.0])) | 34d0fe0c1ddcc02895e8bb2ac93db7ffa101aa1b | 205,751 |
def uniq(seq):
"""Return unique elements in the input collection, preserving the order.
:param seq: sequence to filter
:return: sequence with duplicate items removed
"""
seen = set()
return [x for x in seq if not (x in seen or seen.add(x))] | 2180b6aac4760d31503a9d4c7f2b3cf528d2a4f2 | 26,267 |
def parse_line_comment(lang, state, keep_tokens=True):
"""
Returns the single-line comment at the beginning of state.line,
otherwise the empty string.
Args:
lang (Language):
Syntax description for the language being parsed.
state (State):
Parser state
keep_tokens (bool... | acc224e7723a541b62ae44b347c8bd4fb853467a | 151,461 |
from typing import List
def piecewise_volume_conversion(
ul: float, sequence: List[List[float]]) -> float:
"""
Takes a volume in microliters and a sequence representing a piecewise
function for the slope and y-intercept of a ul/mm function, where each
sub-list in the sequence contains:
... | 87dc40bd9d09e95081ab6ed49ea550a8e9b59c9e | 639,514 |
def trace_dispatch(trace, command, func):
"""
Returns a wrapper for ``func`` which will record the dispatch in the trace
log.
"""
def dispatch(event):
func(event)
trace.recordEvent(command, event)
return dispatch | 4bc8f1915d4583fccbb7ea86081ff4a334404b3d | 206,169 |
def __collinear(a, b, c, thresh=1e-10):
"""Checks if 3 2D points are collinear."""
x1,y1 = a; x2,y2 = b; x3,y3 = c
return abs(x1*(y2-y3)+x2*(y3-y1)+x3*(y1-y2)) < thresh | 681e5bd535dfc6cfe113217a10cc46bf741dc069 | 454,063 |
from typing import Counter
def count_repeated(sequence: list, nth_repeated: int) -> str:
"""
>>> sequence = ['Algorithms','Algorithm','Python','Python','The','Python','The']
>>> nth_repeated = 2
>>> print(count_repeated(sequence, nth_repeated))
The
"""
return "" if nth_repeated < 1 else Co... | efbf614677a3d3f71e724a89e64168525035b001 | 96,244 |
def is_valid_service_exploit(e):
"""
Check whether service exploit is valid
"""
if type(e) != list or len(e) != 2:
return False
if type(e[0]) != float or (type(e[1]) != float and type(e[1]) != int):
return False
if e[0] < 0 or e[0] > 1 or e[1] < 0:
return False
return... | 32498755893b8a7884e0ea6e0170ff3a9dbdcb54 | 284,855 |
def intersect(index, keys):
""" Utility method to compute the intersection of all the sets in index
that correspond to the given keys keys.
Args:
index, hash for format {key -> set()}
keys, list of strings
Returns:
set, the intersection of all the sets in index that correspond to... | 3a885e7f3822a5f2c9bcc3e0558d060fc61bf17b | 669,573 |
def curve(t, acc_t, fast_t, dec_t, slow_t, fast, slow):
"""Returns a speed value between 0 and fast for a given t
t is the time (a float in seconds), from zero at which point acceleration starts
typically t would be incrementing in real time as the door is opening/closing
acc_t is the accelerat... | 646ddccdd8d27d3fc949469868afb1c59ff9b740 | 668,196 |
def filter_key_in_values(rows, key, values):
"""
Return all the `rows` whose value for `key` is in the list `values`.
"""
if isinstance(values, str):
values = [values]
return list(filter(lambda r: r[key] in values, rows)) | 60a4e7a8794640c6a1052b0b2c61b70ed69cc1e3 | 193,793 |
import torch
def squeeze_expand_dim(tensor, axis):
""" helper to squeeze a multi-dim tensor and then
unsqueeze the axis dimension if dims < 4"""
tensor = torch.squeeze(tensor)
if len(list(tensor.size())) < 4:
return tensor.unsqueeze(axis)
else:
return tensor | c33b1fd38215e931f4fbe7c386350a4d50f043b4 | 353,014 |
import re
def compile_matcher(regex):
"""Returns a function that takes one argument and returns True or False.
Regex is a regular expression. Empty regex matches everything. There
is one expression: if the regex starts with "!", the meaning of it is
reversed.
"""
if not regex:
retur... | 6632de458c4e95f3009d9a01233d144c6b7d5752 | 87,394 |
def _cache_key_func(system, method):
"""Construct cache key for a given system and method pair."""
if not isinstance(method, str):
method = method.__name__
return (f"{type(system).__name__}.{method}", id(system)) | 1016bf0662b08eb05af4cb0d92b8541cbc1e062b | 377,787 |
import random
def new_episode(client, carla_settings, position, vehicle_pair, pedestrian_pair, set_of_weathers):
"""
Start a CARLA new episode and generate a target to be pursued on this episode
Args:
client: the client connected to CARLA now
carla_settings: a carla settings object to be ... | d66c1c6409cf6413d4d5851f3f8fd1e510944a58 | 590,515 |
def __getTriangleCentroid(triangle):
"""
Returns the centroid of a triangle in 3D-space
"""
# group the xs, ys, and zs
coordGroups = zip(triangle[0], triangle[1], triangle[2])
centroid = tuple([sum(coordGroup)/3.0 for coordGroup in coordGroups])
return centroid | 004c8a4d24e20ea223741120748d379cb6d990f8 | 401,638 |
import re
def is_bible_verse(s: str) -> bool:
"""
Does a text contain reference to a part of the Bible?
example: is_bible_verse("text filler blah blah 1 Mark 23: 45-67 ") -> True
"""
re_pattern = r"((?:\d +)?[A-Za-z]+) +(\d\d?) +(\d\d?-\d\d?|\d\d?)(?: +|$)"
s = s.replace(';', ' ').replace('... | f11f2c3a7ee6d702b870cc63beed0c5739923fe4 | 370,720 |
import math
def vector_coordinates(phi, theta):
""" Returns 3D vector which points to the pixel location inside a sphere. """
return (math.cos(phi) * math.cos(theta), # X
math.sin(phi), # Y
math.cos(phi) * math.sin(theta)) | 05e0ac2242d2e860017ea0420bfc453c53643549 | 551,339 |
def solution(x: int, a: list) -> int:
"""
Finds the earliest time at which a frog can cross a river.
:param x: Number of positions a leaf can fall.
:param a: A list of positions.
:returns: The time which a frog can get from position 0 to position X+1
or -1 if it can never reach it.
... | 29bbc9a17757830cacefc83e214d399c9a536240 | 115,006 |
def remove_sorting_column(player_data_list):
"""Remove sorting qualifier column.
Args:
player_data_list: list with player data
Returns:
player data list with sorting column removed
"""
return [entry[:-1] for entry in player_data_list] | 34794441e69a6df58b1bdc829ec03e645f3883b2 | 103,526 |
def generate_username(membersuite_object):
"""Return a username suitable for storing in auth.User.username.
Has to be <= 30 characters long. (Until we drop support for
Django 1.4, after which we can define a custom User model with
a larger username field.)
We want to incorporate the membersuite_i... | 6fd3d1afbd37e309582dab39bfd2c76190423118 | 309,422 |
import re
def initials(phrase):
"""
Return a string composed of the first letter of each word in the phrase
"""
return re.sub(r'(?:^| +)(\S)\S*', r'\1', phrase) | 207262f695584c968244688dce407b2d3be59c4e | 364,248 |
def gen_node_name_filter(node_names):
"""Generates a drydock compatible node filter using only node names
:param node_names: the nodes with which to create a filter
"""
return {
'filter_set_type': 'union',
'filter_set': [
{
'filter_type': 'union',
... | 5472057b4884d696e6167a30b96d57c8abf3019f | 325,096 |
def middle(t):
"""
Return a new list that doesn't include the first or last elements from the original.
"""
res = t
del(res[0])
del(res[-1])
return res | 8811c5c5ad99444a2caaad42591d46ccdee6e2d5 | 494,915 |
def set_bit(value, index, high=True):
"""Set the index:th bit of value.
Args:
value (int): Number that will have bit modified.
index (int): Index of bit to set.
high (bool): True (default) = set bit high, False = set bit low
"""
mask = 1 << index
value &= ~mask
if high:
... | 1962921fe45a0099ed2c11bc055c35a482accaf1 | 379,534 |
def alignment_params(screen):
"""
Takes a camera screen dictionary as input. Locates all scaffold intersections
and calculates their alignment parameter (distance from left edge * distance
from top edge).
Returns the sum of the alignment parameters and an updated screen showing their positions.... | 3344bee1ad0ac0696a9113b536e8eed5445e6578 | 289,775 |
def lagrangeg(mu, r2, tau):
"""Compute 1st order approximation to Lagrange's g function.
Args:
mu (float): gravitational parameter attracting body
r2 (float): radial distance
tau (float): time interval
Returns:
float: Lagrange's g function value
"""
... | a9f295e6fdfd966c14126aba46f09903bac18f0a | 552,883 |
def is_ask_help(text: str) -> bool:
"""
A utility method to tell if the input text is asking for help.
"""
sample_phrases = [
"help", "help me", "i need help", "i'm lost", "i am lost"
]
text = text.strip()
return any(text == phrase for phrase in sample_phrases) | 994ac984c69b77c869f0f28c5ee77a082e76c909 | 629,353 |
def clean_predictor_name(predictor: str) -> str:
"""Strip-off redundant suffix (e.g. "_enc" or "_bin") from the predictor
name to return a clean version of the predictor
Args:
predictor (str): Description
Returns:
str: Description
"""
return (predictor.replace("_enc", "").repla... | 1854c7747a0670ee4b40b0d8b7db755f8fced00c | 580,982 |
def check_ascending(ra, dec, vel, verbose=False):
"""
Check if the RA, DEC and VELO axes of a cube are in ascending order.
It returns a step for every axes which will make it go in ascending order.
:param ra: RA axis.
:param dec: DEC axis.
:param vel: Velocity axis.
:returns: Step for R... | 89e9fb25eab2e0684d18b0c5123cce831521f03b | 654,344 |
def hacktoberfest_events(tablerows):
"""This function takes the list of tablerows as input and performs
scraping of required elements as well as stores the scraped data
into a dictionary and returns that dictionary
Args:
tablerows (list): Lis of tablerows of the target elements.
"""
... | 7c1437eaab58bccffc4ff0b59a2d0255f47e746d | 284,035 |
import re
def is_same_gws(path1, path2):
"""
Check that two paths both start with the same group workspace name.
It's assumed that both paths are both in either the old-style or both
in the new-style format.
:param str path1: The first path
:param str path2: The second path
:returns: Tru... | e198bf8449021c8c264ae126d1b5ad9deab77089 | 169,183 |
def get_setting_name_and_refid(node):
"""Extract setting name from directive index node"""
entry_type, info, refid = node['entries'][0][:3]
return info.replace('; setting', ''), refid | f72908c1f3adfc1d37f4760a240f68c66031dc19 | 30,643 |
from typing import Dict
def response_success(response: Dict) -> bool:
"""
Parse a response from a request issued by any botocore.client.BaseClient
to determine whether the request was successful or not.
:param response:
:return: boolean
:raises: KeyError if the response is not an AWS response
... | 467e2e3f8e2279c936d447dda0a499ed4b5792cf | 64,051 |
def format_datetime_for_google_timestamp(dt):
"""
Formats a datetime for use in a Google API request that expects a timestamp
(e.g.: file watch expiration – https://developers.google.com/drive/api/v3/reference/files/watch#request-body)
Args:
dt (datetime.datetime):
Returns:
int: Th... | 25512d5c57773a7bfb2e0d67ad39a6c902da75fd | 287,591 |
def strip_node_name(node_name):
"""Strips off ports and other decorations to get the underlying node name."""
if node_name.startswith("^"):
node_name = node_name[1:]
return node_name.split(':')[0] | 8a0e3f863e4026f9f996493b839463e6d3772238 | 614,958 |
from typing import Tuple
import re
def parse_hp_condition(hp_condition: str) -> Tuple[int, int, str]:
"""
HPと状態異常を表す文字列のパース
:param hp_condition: '50/200' (現在HP=50, 最大HP=200, 状態異常なし) or '50/200 psn' (状態異常の時)
:return: 現在HP, 最大HP, 状態異常('', 'psn'(毒), 'tox'(猛毒), 'par', 'brn', 'slp', 'frz', 'fnt'(瀕死))
"... | cbe9ec75efbae1b144836cc8129fdc3256e0dccf | 31,686 |
def get_ORM_instance(ORM_class, session, instance):
"""
Given an ORM class and *either an instance of this class, or the name attribute of an instance
of this class*, return the instance
"""
if isinstance(instance, str):
return session.query(ORM_class).filter(ORM_class.name == instance).one(... | 5b3427147b6934704b300ec5026254e6bce1e2a6 | 527,236 |
import string
import random
def generate_random(size):
"""Generate random printable string"""
_range = range(size)
_alphabet = string.ascii_uppercase + string.digits + ' _+=\'"~@!#?/<>'
return ''.join(random.choice(_alphabet) for _ in _range) | fa326d3d2c6da582e2449780ac9c468ceb418658 | 438,801 |
def DetermineHotlistIssuePosition(issue, issue_ids):
"""Find position of an issue in a hotlist for a flipper.
Args:
issue: The issue PB currently being viewed
issue_ids: list of issue_id's
Returns:
A 3-tuple (prev_iid, index, next_iid) where prev_iid is the
IID of the previous issue in the total... | 7a3d8f95aff29875a97c416139bc918a663b596a | 257,125 |
def as_ctrait(obj):
""" Convert to CTrait if the object knows how, else raise TraitError.
Parameters
----------
obj
An object that supports conversion to `CTrait`. Refer
documentation for when the object supports this conversion.
Returns
-------
ctrait.CTrait
A CTra... | bbb4a176f6bcfc57ff31f79e219d836378b77a98 | 553,220 |
def get_upload_location(instance, filename):
"""
This method provides a filename to store an uploaded image.
Inputs:
instance: instance of an Observation class
filename: string
returns:
string:
"""
psr = instance.pulsar.jname
beam = instance.beam
utc = instance.utc.utc_ts.st... | 2bbf76d02e8b26ec703d5b4047074b3c05957407 | 120,452 |
import math
def selection_policy(node, c_uct):
"""
Given a tree node, determine which
child to move to when performing MCTS;
c_uct: constant for UCT algorithm
"""
if node.is_leaf():
return node
max_child = None
max_val = float('-inf')
total_visit = 1
for edge in no... | cd19ae5876bdc71fa0083ed4a3c40502b00b4526 | 356,419 |
def wildcard_match(pattern: str, text: str, partial_match: bool = False) -> bool:
"""
Adapted and fixed version from: https://www.tutorialspoint.com/Wildcard-Pattern-Matching
Original by Samual Sam
Wildcards:
'?' matches any one character
'*' matches any sequence of zero or more characters
"... | 5248efaee755f8df5fc62d5ef5360d29fadf7016 | 391,097 |
def memory_test(used,total,percentage=25):
"""Tests the sensor used memory against the total memory size.
@param used_memory -- the used memory of the sensor.
@param total_memory -- the total memory of the sensor.
@return -- a string flag
"PASS" if the used memory is 25% or less of the t... | ee9b12db33154b525ba06fb36f70f8d817a2b89d | 276,013 |
import dill as pickle
def load(file, **kwds):
"""load an object that was stored with dill.temp.dump
file: filehandle
mode: mode to open the file, one of: {'r', 'rb'}
>>> dumpfile = dill.temp.dump([1, 2, 3, 4, 5])
>>> dill.temp.load(dumpfile)
[1, 2, 3, 4, 5]
"""
mode = kwds.pop('mode'... | c334ab5df5c3a254f90a3c6319e305c525eac5ef | 305,872 |
def getDimensions(self):
"""Gets the number of rows and columns of the map"""
return (self.__numrows__, self.__numcols__) | fa56d7ec97ba237fb41cc70bbbb7a2348a621f04 | 25,165 |
def decode_version(packed):
"""Decode packed R version number into a human readable format.
"""
v = packed // 65536
packed %= 65536
p = packed // 256
packed %= 256
s = packed
return (v, p, s) | 7c4806e84398531256de4cb58a88f81f7f79800f | 386,334 |
from bs4 import BeautifulSoup
def remove_html_tags(html_doc, lines_concat = True):
""" Remove html tags from input strings
>>> sample_doc = '''<html><head><title>The Dormouse's story</title></head>
... <body><p class="title"><b>A Mad Tea-Party</b></p></body>
... </html>'''
>>> remove_html_tags(sam... | c4eed789396794ce98292dc3452d39f2b656a37d | 417,200 |
def capitalize_each_word(s, delimiter):
"""Capitalize each word seperated by a delimiter
Args:
s (str): The string to capitalize each word in
delimiter (str): The delimeter words are separated by
Returns:
str: The modified string
"""
return delimiter.join([w.capitalize() fo... | c74e17d277ca17d9763e2ca905da13337479fbd6 | 511,469 |
def _GetKeys(data):
"""Get the keys of a H5Dataset or numpy compound data type."""
if hasattr(data, 'keys'):
return set(data.keys())
elif hasattr(data, 'dtype') and data.dtype.names:
return set(data.dtype.names)
else:
return None | 2dd3e09c1f2bfdfd0e053e6ebb229a2bc6b78967 | 563,786 |
def parse_literal(x):
"""
return the smallest possible data type for a string or list of strings
Parameters
----------
x: str or list
a string to be parsed
Returns
-------
int, float or str
the parsing result
Examples
--------
>>> isinstance(parse_liter... | 14bb312074b06d3b8d5e9e66652050d9247700af | 630,263 |
def squeeze(data: object) -> object:
"""
Overview:
Squeeze data from tuple, list or dict to single object
Example:
>>> a = (4, )
>>> a = squeeze(a)
>>> print(a)
>>> 4
"""
if isinstance(data, tuple) or isinstance(data, list):
if len(data) == 1:
... | 7ed444dcee6e52f9159c7817a2b7d6058bb78ad0 | 478,204 |
def find_prefix(root, prefix):
"""
Checks & returns
1. If the prefix exists in any of the words we added so far
2. If yes, then how may words actually have the prefix
"""
if not root.children:
return (False, 0)
node = root
for char in prefix:
for child in node.c... | 064023317feb5cd380fbabf09e2b2821541dad72 | 161,645 |
def createMotifsDictionary(filename, padding=100):
"""
Storing Motif Information into a dictionary: {chrN: [(start1, stop1), (start2, stop2)..]}
:param filename: # motifs filename
:param padding: # left and right start/stop padding (concerned about peaks 100bp from a known motif)
:return motifDic... | e80978aef8fc4bfdf6d46eaf8c5e79ba90f1d66b | 564,006 |
def dumps(blackbird):
"""Serialize a blackbird program to a string.
Args:
blackbird (BlackbirdProgram): a :class:`BlackbirdProgram` object
Returns:
str: the serialized Blackbird program
"""
return blackbird.serialize() | f3e8bedcd84d2579c0966f7d4843a626099c25a9 | 649,191 |
from datetime import datetime
def parse_timestamp(time_str):
"""
There are three datetime string formats in eMammal, and some have an empty field.
Args:
time_str: text in the tag ImageDateTime
Returns:
datetime object, error (None if no error)
"""
if time_str == '' or tim... | 634d47fbcffe72164b62b2f46e80b8504db21b3d | 55,429 |
def get_fuzzer_benchmark_key(fuzzer: str, benchmark: str):
"""Returns the key in coverage dict for a pair of fuzzer-benchmark."""
return fuzzer + ' ' + benchmark | 1ad42f2c8c01e63b16855eb7dc9fb5cdb2821ec0 | 508,225 |
def parse_policy(policy):
"""Parses a policy of nested list of tuples and converts them
into a tuple of nested list of lists. Helps with TF serializability."""
op_names = [[name for name, _, _ in subpolicy] for subpolicy in policy]
op_probs = [[prob for _, prob, _ in subpolicy] for subpolicy in policy]
... | 79df1fdb9825cfbe35ca59e3a2e9700a3bcf26d6 | 602,513 |
def inv_index_map(k):
"""
The inverse index map used mapping the from 1D index to 2D index
Parameters
----------
k : int
1D index.
Returns
-------
i : int
the index in the 2D case.
d : int
the dimension to use for the 2D index.
"""
return k // 2, k ... | fca39108b224794351f2dd4fd647572b8d947070 | 232,499 |
def turn(orient_index, direction):
"""
change the current orientation according to
the new directions
Args:
orient_index (int): index in the orient list for the
current orientations
direction (str): R or L
Returns:
int
"""
if direction == 'R':
or... | 9b781296038d2650bf08f5f5c85757d0763c2511 | 544,006 |
def complement(x):
""" Computes complement of a probability/parameter
Parameters
----------
x : {float, int}
Returns
-------
out : {float, int}
Complement
"""
out = 1 - x
return out | 8f7221c10081c39a57bf51a5ad40baf423ce98db | 544,743 |
def getGenomeSegmentGroups(genomeSegmentIterator, contigsExcludedFromGrouping = None) :
"""
Iterate segment groups and 'clump' small contigs together
@param genomeSegmentIterator any object which will iterate through ungrouped genome segments)
@param contigsExcludedFromGrouping defines a set of contigs... | b6e2ebc49d98d02a56feb8983c9e2a684496078a | 378,506 |
def get_affected_enduse(strategy_vars, name):
"""Get all defined affected enduses of a scenario variable
Arguments
---------
strategy_vars : dict
Dict with all defined strategy variables
name : str
Name of variable to get
Returns
-------
enduses : list
AFfected ... | 30675c28f615b0e91c1884e858fa449371c235d5 | 572,425 |
def dict_by_class(obj_list):
""" Create a `dict` keyed by class from a list of objects
Args:
obj_list (:obj:`list`) list of objects
Returns:
:obj:`dict`: mapping from object class to list of objects of that class
"""
obj_dict = {}
for obj in obj_list:
cls = obj.__class_... | e9fe759a162bdb4119157105c57cb45e5bac4764 | 562,496 |
def density_of_sky_fibers(margin=1.5):
"""Use positioner patrol size to determine sky fiber density for DESI.
Parameters
----------
margin : :class:`float`, optional, defaults to 1.5
Factor of extra sky positions to generate. So, for margin=10, 10x as
many sky positions as the default r... | 44c8f5c5773471923637146c7aa14b7fb2b95a2e | 199,093 |
def str_round(num, n):
"""Round a number to n digits and return the result as a string."""
num = round(num, n)
format = "%."+str(max(n, 0))+"f"
return format % num | a58ee6ac9bbc37c6f8e438af40ff334ef9356a08 | 296,529 |
import json
def read_secret_file(file_path):
""" Reads the content of the secret file and returns the secret key. """
with open(file_path, 'r') as secret_file:
content = secret_file.read()
obj = json.loads(content)
return obj['secret_key']
print('Secret key faile failed to open!!... | e0a0cc0ad3c9c6342cc157894de5176129aac475 | 84,442 |
def group_names(user):
"""Returns a list of group names for the user"""
return list(user.groups.all().values_list('name', flat=True)) | 5d9147bd176d2fb15e0027bc31330e7b3dce8c71 | 396,823 |
def num_states(spin_str_element):
"""
This function evaluates de spin number string, formatted as s=a/b and
returns the number of states 2*s + 1.
In the table we have three type of strings:
1. spin numbers integers formatted with 1 or 2 characters, e.g s=1, and s=10.
2. spin numbers formatted ... | 8c92f10f955a2ca9eb12a895f9a7281b454b3345 | 561,359 |
def merge(source, destination):
"""
Merges 2 dicts recursively.
If leaves are lists, they are extended.
If leaves are ints, floats, strs, they are concatenated
into a string, if the leaves are not the same.
"""
for key, value in source.items():
if isinstance(value, dict):
... | 7f771e83c5f89fa641fa79f863f4382ac5cc0ead | 49,610 |
def generateJobName(key):
"""
Transcribe job names cannot contains spaces. This takes in an S3
object key, extracts the filename part, replaces spaces with "-"
characters and returns that as the job-name to use
"""
# Get rid of leading path, and replace [SPACE] with "-"
response = key
... | c52cc4d3417f85c55ab69f63016608b0ff4ff7ca | 693,468 |
def parse_author(a):
"""Parses author name in the format of `Last, First Middle` where
the middle name is sometimes there and sometimes not (and could just be an initial)
Returns: author name as `F. M. Last`
"""
a = a.split(', ')
last = a[0].strip()
fm = a[1].split(' ')
first =... | f35a202c21d4b9424abc4516b06b4bca9991a4af | 393,461 |
import math
def get_distance(x1: int, y1: int, x2: int, y2: int) -> float:
"""
it returns the distance between two points
:param x1: int
:param y1: int
:param x2: int
:param y2: int
:return: float
"""
return math.sqrt(((x1 - x2) ** 2 + (y1 - y2) ** 2)) | ce3bb0cb85564205b83830b2532713938328c142 | 101,083 |
def find_title_row(table_object):
"""
Searches for the topmost non-empty row.
:param table_object: Input Table object
:type table_object: ~tabledataextractor.table.table.Table
:return: int
"""
for row_index, empty_row in enumerate(table_object.pre_cleaned_table_empty):
if not empty_... | f2ab697409330a411428c459719aa5d597c9b032 | 257,337 |
def innerHTML(element):
"""
Return the HTML contents of a BeautifulSoup tag.
"""
return element.decode_contents(formatter="html") | 8ac3686e6aa549abf051ae749b43a74286a6892d | 444,231 |
import hashlib
def get_typeid(typeinfo):
"""Compute the CallSiteTypeId from a typeinfo string"""
return int.from_bytes(hashlib.md5(typeinfo.encode("ascii")).digest()[:8], "little") | bb4a0e24aa549770a1cb6fb0a93612724296acf4 | 389,626 |
def decode_string(string, encoding=None):
"""Decode a string with specified encoding
:type string: str or bytes
:param string: string to decode
:param str encoding: encoding of string to decode
:rtype: str
:return: decoded string
"""
if isinstance(string, str):
return string
... | cb2e65ae8c1db9bdab1c876b9031ee4c108e2e7b | 307,597 |
def _get_items( # nosec
get_items, items_key, params=None, next_token=None, next_token_key="NextToken"
):
"""
Recursive generic function call which concatenates results.
Returns a list of items from the same items_key in response.
If response contains a next token, get_items is called again, and i... | 4ca53eb6550aaaf03b3d2df7b615e5197c7455c0 | 401,079 |
import requests
def fetch(url):
"""Fetch a URL
Arg:
url: A string in the URL form.
Returns:
The response in text
"""
resp = requests.get(url)
return resp.text | 56148e3e6b08d85d90fcb3ba01b4d778833fd4ae | 302,562 |
import math
def find_nproc(n, min_n_per_proc=25):
"""
Find number of processors needed for a given number grid points in WRF.
Parameters
----------
n : int
number of grid points
min_n_per_proc : int, optional
Minimum number of grid points per processor. The default is 25.
... | 7671b05298f8b0f982a4017313550941829c8297 | 437,667 |
def eq(a, b):
"""Check for equality between a and b.
Return boolean.
**** args ****
a, b:
python objects on which a test for equality will work
"""
if a == b:
return True
else:
return False | 67fa355c4eb17fe4458f1f527338aec9b98f5f6d | 535,016 |
def eval_dist_at_powseries(phi, f):
"""
Evaluate a distribution on a powerseries.
A distribution is an element in the dual of the Tate ring. The
elements of coefficient modules of overconvergent modular symbols
and overconvergent `p`-adic automorphic forms give examples of
distributions in Sage... | ada2a765ad594cd729414b3313a2aa25054cc5d8 | 189,381 |
def xy2i(cx,cy):
"""Translate chess square to integer coordinate"""
x="abcdefgh".index(cx)
y=int(cy)-1
return (7-x)*8+y | c7d7772a120384108ddea35c5462cc1db78ea40f | 414,307 |
def _PickSymbol(best, alt, encoding):
"""Chooses the best symbol (if it's in this encoding) or an alternate."""
try:
best.encode(encoding)
return best
except UnicodeEncodeError:
return alt | ccc2289c0258fa4983cc7bf45a6d94d628eb7d13 | 226,387 |
def get_preferred_indices(y_pos, labels, preferred_sensors):
"""Get indices of preferred sensor sets in plot.
Args:
y_pos (list): list of y positions used for sensors in plot.
labels (list-like): sensor set labels associated with y_pos.
preferred_sensors (list-like): preferred sensor se... | 2e83f1d4ef9dc62be093396d992033e95b5c9561 | 543,993 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.