content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def gather_file_lines(filename):
"""Read all file lines into a list in memory"""
with open(filename, 'r') as mdf:
return mdf.readlines() | 4e1fcf629746fd70c0cf57daeb31344c95fdb8a0 | 579,496 |
def add42(number: int) -> int:
"""
Add 42 to number.
>>> add42(100)
142
"""
return number + 42 | afbd42d90b366dd9db777c5f312c29e8375c3950 | 579,499 |
def get_package_filename(pkg):
""" From a repository object, return the name of the RPM file. """
return '%s-%s-%s.%s.rpm' % (pkg.name, pkg.version, pkg.release, pkg.arch) | 0edf6df76c712993b4378290d48fa2bf29fa7867 | 579,502 |
from pathlib import Path
def is_icon_file(f: Path, sap_code: str, name_pattern: str) -> bool:
"""Determine if icon file is the right file
:param f (Path): icon file path
:param sap_code (str): Adobe SAP code for product being processed
:paaram name_pattern (str): icon filename pattern to test"""
r... | 6b5723c3b6c0296cbe9a5d2daaaaa959a09bfb0c | 579,504 |
import socket
def bytes_to_ip(packed_ip):
"""
Convert packed ip byte string to dotted string representation.
"""
return socket.inet_ntoa(packed_ip) | dbd6348417b4b5a76df96c15c033640866b24ed0 | 579,505 |
def convert_ktoe_gwh(data_ktoe):
"""Conversion of ktoe to gwh
Parameters
----------
data_ktoe : float
Energy demand in ktoe
Returns
-------
data_gwh : float
Energy demand in GWh
Notes
-----
https://www.iea.org/statistics/resources/unitconverter/
"""
dat... | 272bb67cd7cc54ef24c4bde245fa2ecd67d04336 | 579,508 |
def _maximal_matching_qubo(G, edge_mapping, magnitude=1.):
"""Generates a QUBO that when combined with one as generated by _matching_qubo,
induces a maximal matching on the given graph G.
The variables in the QUBO are the edges, as given my edge_mapping.
ground_energy = -1 * magnitude * |edges|
inf... | 1d3a0ef2730855624fd63130af09ad2163eab48c | 579,514 |
def removeListIntervals(l, intervals):
"""
This function will remove portions of text according to string intervals.
You have to apply `text = reduceBlank(text, keepNewLines=True)` just after.
:example:
>>> removeListIntervals(['a', 'b', 'c', 'd', 'e'], [(1, 2), (3, 4)])
['a', 'c', 'e']
"""
newL = []
cur... | fbcaca38fb86b0a91081c6f76aa169965af028d2 | 579,516 |
def second_valid_numeral(request):
"""
Fixture that yields back all valid numerals (inclusive) for the "second" field.
"""
return request.param | 176225dd7211055e391c1959d75abc0bd56c5eeb | 579,518 |
def MergeComponents(components):
"""Given a list of components, merges components with the same hierarchy.
For components with same hierarchy, return the most fine-grained component.
For example, if components are ['Blink', 'Blink>Editing'], we should only
return ['Blink>Editing'].
"""
if not components or... | 189308f4ddda3489234936286da22e4260449a10 | 579,519 |
import attr
def optional_field(field_type):
"""Define an optional field of the specified `field_type`.
Parameters
----------
field_type : type
The expected type of the field when not ``None``.
Returns
-------
Any
An ``attrs`` attribute, with a default value set to ``None`... | 61338f214cdbdbfc2576fdc790ae42e994e79983 | 579,523 |
def is_user_authenticated(handler):
"""Check if the current user is authenticated."""
current_user = getattr(handler, 'current_user', False)
return bool(current_user) | 79628c2dfc303a1bb159069c22c75e7eef51c19c | 579,524 |
def inline_permission_denied_message(message="Not enough permissions"):
"""Returns a an inline html element that signals insufficient permissions"""
return f'<span style="font-style:italic;color:#aaa"><span class="fa fa-lock"> </span> {message}</span>' | 4b72afe58d0aff28ff4836498e668d05bc6f0c23 | 579,526 |
def voltage(adc):
"""Convert 10-bit ADC integer value to a voltage"""
MAX = 1023
REF = 3.3 # volts
return float(adc)/MAX * REF | eb6467f26a1bff98d4a974e1ea595dac894b83ea | 579,529 |
def Fm(fb, fc):
"""
Compute a Bark filter around a certain center frequency in bark.
Args:
fb (int): frequency in Bark.
fc (int): center frequency in Bark.
Returns:
(float) : associated Bark filter value/amplitude.
"""
if fc - 2.5 <= fb <= fc - 0.5:
return 10**(... | 561d7de17ac7878444ac3349c2af3ab6ad14b057 | 579,531 |
from pathlib import Path
def exists(path) -> bool:
"""
Check path or file exists (use os.path.exists)
Args:
path: path or file
"""
if not path: return False
return Path(path).is_dir() or Path(path).is_file() | 00d25caf420bdd52e299777692bbe417af49266f | 579,532 |
import re
def preamble(line):
"""
Converting Org preambles (#+TITLE, #+AUTHOR .etc) to Md format (title ======, **Author** .etc)
:return:
"""
if re.match("#\+TITLE:", line): # Pandocs's syntax doesn't work, thus html is used
line = f'<center><font size="+10">{line.replace("#+TITLE:", "")}... | b2ca25acd5563afcd5985df001913ab6ee9f6797 | 579,534 |
def distro_uri(distro_name):
"""
Get distro URI of main ROS distribution files.
:param distro_name: name of distro, e.g. 'diamondback'
:returns: the SVN/HTTP URL of the specified distro. This function should only be used
with the main distros.
"""
return "http://svn.code.sf.net/p/ros-dry... | 0ce85270af38e3e0c414793003402527beffb6c6 | 579,535 |
def get_longer_word(word1: str, word2: str) -> str:
"""Returns the "longer" of word1, word2
Complexity:
c = min(len(word1),len(word2))
Time: O(c)
- Since lexicographical string comparisons are
character-by-character
Space: O(1)
Args:
word1:
w... | 36efb613c40903ebf5fea6f344447d6cfe01dd9a | 579,540 |
def max_key(my_dict):
"""Returns the key of the maximum value in a dictionary."""
# there are many ways in Python to do this
# this one only uses functions that we learned
# in the lecture
max_key = None
for key, value in my_dict.items():
if max_key == None or my_dict[key] > my_dict[m... | a2597b2b51a6fe2722387c72b81fc50116e841d8 | 579,541 |
def validate_indices(indices, datastore):
"""Returns a list of valid indices.
This function takes a list of indices, checks to see if they exist
and then returns the list of indices that exist within the datastore.
Args:
indices (list): List of indices.
datastore (ElasticsearchDataStor... | 5f424f2a35e10711af20768e07ef303753604636 | 579,543 |
def arg_k_max(lst, k):
"""Renvoie les indices des k plus grands éléments de `lst`"""
res = []
for n, val in enumerate(lst):
if len(res) < k:
res.append((n, val))
res.sort(reverse=True, key=lambda x: x[1])
elif res[-1][1] < val:
res.pop()
res.ap... | c5020417a48685084117099173d6328938f6e22c | 579,544 |
import yaml
def proj_conf_data(path_project_conf):
"""
Read and parse raw Project configuration data.
:param str path_project_conf: path to file with Project configuration data
:return Mapping: the data parsed from the configuration file written,
a Mapping form of the raw Project config text ... | 7a2ad878c898ddb08d3bfd64b9521a9ae49c7ff3 | 579,547 |
def conv2d_output_shape(height, width, filter_height, filter_width, out_channels, stride):
"""Calculates the output shape of Conv2d
Args:
height (int): Height of the input.
width (int): Width of the input.
filter_height (int): Height of the filter.
filter_width (int): Width ... | e938989f8f5f1318913771abf4206ad6a39ca322 | 579,551 |
import warnings
def override(func):
"""This is a decorator which can be used to check that a method override a method of the base class.
If not the case it will result in a warning being emitted."""
def overrided_func(self, *args, **kwargs):
bases_functions = []
for base in self.__class__... | 587dfecdcfe73b41f9ea3dc1ab6f2d3b5e76f243 | 579,552 |
from typing import Union
from pathlib import Path
def _get_epoch_images(epoch_path: Union[str, Path],
image_type: str,
image_dir: str
) -> list:
"""
Get all available images in a given epoch.
Args:
epoch_path: Path to the epoch of ... | 1ad1dd7e58f381ca48dcb531b48a839540f64183 | 579,553 |
def get_command_syntax(task_name):
"""Return an example command syntax string in .rst format"""
return f"``$ cci task run {task_name}``\n\n" | 3fdaf8fb8d7ade961c6698d0108809bbb349e22a | 579,554 |
def is_list_or_tuple(obj):
""" Determine whether an object is an iterable list or tuple """
return isinstance(obj, (list, tuple)) | 3de58f06c9fa57586c90f61573101282ed601597 | 579,555 |
def DF(s, k):
"""
Return a set in a list shape
of distinct factors of length
k of the string s
--------
Parameters:
s (str)
k (int)
eg:
DF("BANANA", 2)
Output:
['NA', 'BA', 'AN']
"""
n=len(s)
return... | ceec3320f69ba580fd8701baa5b46bbd46181b61 | 579,556 |
def update_options_from_config(opt, file):
"""Read a config and update dictionnary opt"""
data = file.readlines()
for line in data:
key, val = line.split('=')
opt[key.strip()] = val.strip() #remove whitespace
return opt | b904377f6a113e5014599078e07f4abab79022fc | 579,557 |
from typing import Dict
def partial_widths(self) -> Dict[str, float]:
"""
Returns a dictionary for the partial decay widths of the scalar
mediator.
Returns
-------
width_dict : dictionary
Dictionary of all of the individual decay widths of the scalar
mediator as well as the to... | 2408a2eb6b205ed919532c55e0a292bd8243a9de | 579,558 |
def get_stock_chart(symbol):
"""Get a URL for the stock chart."""
return f"https://finviz.com/chart.ashx?t={symbol}&ty=c&ta=1&p=d" | 78bbb76f3865e98908ed9aec73234877fd91cbdc | 579,560 |
def ordinal(n: int) -> str:
"""
Return the ordinal representation of the given number, e.g. 1st, 2nd, etc.
"""
if 10 <= n <= 20:
return str(n) + "th"
d = n % 10
if 1 <= d <= 3:
return str(n) + ["st", "nd", "rd"][d - 1]
return str(n) + "th" | 961db13d03205ccb874ee72dd87c146c50cc8e26 | 579,561 |
def check_results(results, expected):
"""
Compare the two MoonLight results dictionaries: one from
moonlight_solution.json and the other from the execpted result.
"""
# Mapping of result keys to their data types
keys_to_compare = dict(corpus_size=int,
solution_size=int... | cc880c646b19f0e9394ff58c15daa808150f2a09 | 579,562 |
def bgr_to_rgb(image):
"""Swap blue and red channel in an image."""
image = image.copy()
tmp = image[..., 0].copy()
image[..., 0] = image[..., 2]
image[..., 2] = tmp
return image | 1e056fc5bf4b4c77abd9b183b3261675faa5d3b6 | 579,564 |
def process(messages):
"""
Implements Data Pairing pipeline.
:param messages: Sequence of detected queries and replies.
:return: List of paired queries with replies.
"""
result = []
query = (None, True) # each query consists of value and flag if it was paired
for message in messages:
... | 53f21a14315f15f992410022de7cf64bf290ccd9 | 579,566 |
def countchars(text : str) -> dict:
"""
Return the frequency of characters in the specified text
Parameters:
text (str): Single text
Returns:
frequencies (dict): Frequency per character
"""
frequencies = {}
for char in text:
if char in frequencies:
frequ... | e0c60edbf7131bc282fe04eb06db2321fc66c7ec | 579,567 |
def get_small_joker_value(deck_of_cards):
""" (list of int) -> int
Return the second largest value in deck_of_cards
as the value of small joker.
>>> get_small_joker_value([1, 4, 7, 10, 13, 16, 19, 22, 25, 28, 3, 6, 9, \
12, 15, 18, 21, 24, 27, 2, 5, 8, 11, 14, 17, 20, 23,... | 4de8fe9b9b674a38d435b841900e5acb4a8ad2e6 | 579,569 |
def SumCoeffsOverIndexList(summing_list, A):
"""Returns the sum of the coefficient and summing lists mulitplied
element-wise.
"""
return sum(A[i] * summing_list[i] for i in range(len(summing_list))) | 6f5fec8ecbdc63c7064a3d5127a7e5abb3bdc995 | 579,577 |
def invalidates_cache(fn):
"""
Clears all cached properties after the decorated function is called.
Useful when changing external (third-party) state that requires
reverification. (e.g.: decorate a "modify_something" method with this.)
"""
def wrapped(self, *args, **kwargs):
r = fn(self,... | e97631bd9d1d3e134bf1789d34bdbbfe325e049b | 579,578 |
def set_lat_long(feature):
"""Set the latitude and longitude of the feature centroid."""
centroid = feature.geometry().centroid(1e-2)
return feature.set({
'latitude': centroid.coordinates().get(1),
'longitude': centroid.coordinates().get(0)
}) | 978dd262ed995f21908227588bd91b78ceaaf8a0 | 579,580 |
def _get_sorted_col_indices(select_columns, column_names):
"""Transforms select_columns argument into sorted column indices."""
names_to_indices = {n: i for i, n in enumerate(column_names)}
num_cols = len(column_names)
for i, v in enumerate(select_columns):
if isinstance(v, int):
if v < 0 or v >= num_... | 2bd0d6429265e6c9f410bb8fdd1628856883426f | 579,585 |
def _NextMaintenanceToCell(zone):
"""Returns the start time of the next maintenance or ''."""
maintenance_events = zone.get('maintenanceWindows', [])
if maintenance_events:
next_event = min(maintenance_events, key=lambda x: x.get('beginTime'))
return next_event.get('beginTime') + '--' + next_event.get('en... | 1b34435d238db297c128ec88f487e785ecd33142 | 579,586 |
def _count_complex(complex_string):
"""
Returns number of complex numbers in string (formatted according to
SeisComp3 XML schema type "ComplexArray"). Raises an Exception if string
seems invalid.
"""
counts = set()
for char in '(,)':
counts.add(complex_string.count(char))
if len(... | c7637a2948ed8ac8577e20ac019f61618b5751d5 | 579,590 |
def enum2dict(obj, key_filter=None):
"""
PyCapture2 enumerated values are stored as classes making it difficult to
check the values within them. This function can be used to take a class
and return it's attributes as a dict.
Parameters
----------
obj : class
A PyCapture2.<ENUMERATED... | 08968a4716bcdd9a96a3b4fa4c47ffbece2a8acd | 579,597 |
def _score_mers(mers: list, consensus: str) -> int:
"""
Calculate the score of a mer list
"""
result = 0
for mer in mers:
for i in range(len(mer)):
if mer[i] != consensus[i]:
result += 1
return result | ab57ba2ad9b2362a0569831bffefd95614aadf70 | 579,599 |
from typing import AnyStr
def convert_character_to_number(character: AnyStr) -> int:
"""
convert_character_to_number turns a character into its number
value, starting with the space character on the ASCII table
Args:
character (AnyStr): character that will be turned into a number
Returns... | d59de8bc49e1be2ae3c19384c30761a86550062a | 579,603 |
def rivers_with_station(stations):
"""for Task1D, to return a set of river names for given stations (no dublicates)"""
list_1d=[]
for i in range(len(stations)):
if stations[i].river not in list_1d:
list_1d.append(stations[i].river)
else:
pass
return list_1d | 8421606ec43b1f15ef74364e81ca2b25e32dc81a | 579,604 |
from datetime import datetime
import uuid
def _get_file_name() -> str:
"""
Create a random file name.
Returns:
str:
Randomised file name.
"""
return f'{datetime.now().strftime("%d-%m-%Y_%I-%M-%S_%p")}_{str(uuid.uuid4())[:8]}.avro' | 3fb18df2c9b6326037b4aa3d9576ef7f8b87209b | 579,606 |
def get_linestyles(n, on=True):
"""Get a list of matplotlib linestyles
Parameters
----------
n : :obj:`int`
Number of linestyles to output
Returns
-------
:any:`list`
list of linestyles
"""
if not on:
return [None] * n
list_linestyles = [
(0, ()... | 04e1e3841208d10c7776521434591b63e3415aa5 | 579,608 |
def numeric_menu(options):
"""
Asks the user for numeric input based on an input dictionary of options.
:param options: (dict) a numerical selection menu.
E.g.: {1: 'Do this',
2: 'Do that'}
"""
if type(options) != dict:
raise TypeError('numeri... | 516568ee19dafef30bf75b8e15dea85bb5c9416f | 579,613 |
def get_batch(data, current_batch_index, batch_size, fixed_batch_size=True, continuous_batches=False):
"""
This function returns a batch of data with the correct size and taken from the correct place.
Input:
data: list, holds any type of data that we need to get a batch from;
... | c48e42c92497738beed8a4737d6e638c831ced5d | 579,620 |
def config_lookup_paths(fake_fs):
"""
:return: Returns configuration lookup paths list for overall consistency in tests.
Method also create paths in the fake file system.
"""
lookup_paths = ["/decoy/config", "/work/config"]
for l_path in lookup_paths:
fake_fs.fs.makedirs(l_path, exist_ok... | ef14ded4ae40295f4d2032cef617acbe13fb773f | 579,623 |
def un_unicode(d):
""" transform unicode keys to normal """
return dict((str(k), v) for (k,v) in d.items()) | 3f248a447fd620849fcbbd4f869dd5b412f378da | 579,625 |
def subdict(keys, dict_):
"""
Creates a subdictionary given a list of keys and a dictionary.
Parameters
----------
keys : list
Keys to extract from `dict_`.
dict_ : dict
The dictionary from which to extract values.
Returns
-------
dict
A dictionary whose ele... | 12c4e364b99368498ef2a69a3d00dee04d38e5d7 | 579,626 |
def main(request, response):
"""
Returns a response with a Set-Cookie header based on the query params.
The body will be "1" if the cookie is present in the request and `drop` parameter is "0",
otherwise the body will be "0".
"""
same_site = request.GET.first("same-site")
cookie_name = reque... | f775d4cc63ec19ee9ec53d273924fc1b5b56b7c3 | 579,627 |
def metro_para_milimetros(metros):
""" Recebe um valor em metros, e retorna o valor em milímetros"""
milimetros = metros * 1000
return milimetros | 576d3fbf2a69ac543793884f8c5075be8e846e0a | 579,630 |
import jinja2
def render_template(
env: jinja2.Environment,
template: str,
context: dict
) -> str:
"""
Render a template given the jinja environment.
"""
return env.from_string(template).render(context) | 54890f2970a9bbc76e2b65a93b8c31878dd70e31 | 579,632 |
def VersionValue(val):
"""Function for comparing version values
Args:
val (string): version number of the program (Eg: 2.3.1)
Returns:
int: converts the number to an int (Eg: 2.3.1 becomes 231)
"""
NewVal = str(val).replace(".","")
if len(NewVal) == 2:
return int(str(Ne... | 70731093f05caef2425d9c7950ff5afebf5008cb | 579,635 |
def to_grn(entity: str, name: str) -> str:
"""returns a Graylog GRN formatted entity name"""
return f"grn::::{entity}:{name}" | f91587ab161bafb58796bc5cb6bc8e50be94d21c | 579,636 |
def f(map, key):
"""
A function decorator that results in the specified function being added
to the specified map under the specified key.
"""
def decorator(function):
map[key] = function
return function
return decorator | 88d6f6a3f3e3fcb12dd37b318d2f567840ba9884 | 579,647 |
def sum_pow(p, n_begin, n_end):
"""
Power summation, N inclusive.
\sum_{n=N_begin}^{N_end} p^n
"""
return (p**(n_end+1) - p**n_begin) / (p - 1.0) | 9d59b71adf5b6615d5784c5acc6201fbce472426 | 579,657 |
import re
def guess_filename(node):
"""Infer a filename for the Gist based on the node's name.
If the node hasn't been renamed, return an empty string.
:param node: Node the snippet comes from
:type node: :class:`hou.Node`
:return: Suggested filename
:rtype: str
"""
if not re.match(
... | ee8ff00c1af850cf2eaf574d22f690bdb0b7c781 | 579,658 |
from datetime import datetime
def calc_date_params(backdate, setdate):
"""
Returns the calculated date given user's request
Tests frequently need to mock times, this returns the calculated time,
either by adjusting from utcnow (via backdate), using the given value
(in setdate) or using the value ... | 6a60988f9d8c8fe1d320c01630f584b02d9b28a7 | 579,659 |
def hue_brightness_to_hass(value):
"""Convert hue brightness 1..254 to hass format 0..255."""
return min(255, round((value / 254) * 255)) | c63f9dabb5fb38212fbe18fed5150c5f902323b7 | 579,662 |
def default_func(entity, attribute, value):
"""
Look in the entity for an attribute with the provided value.
First real object attributes are checked, then, if available,
extended fields. If neither of these are present, return ``False``.
"""
try:
return getattr(entity, attribute) == val... | b62052eb2f0adb6f35813b1082a5c23bd79fcaa7 | 579,666 |
def compute_time(signal, fs):
"""Creates the signal correspondent time array.
Parameters
----------
signal: nd-array
Input from which the time is computed.
fs: int
Sampling Frequency
Returns
-------
time : float list
Signal time
"""
time = range(len(si... | 80bd26711cda603d7715f7f7fc66b08aebf60996 | 579,668 |
def is_palindrome(head):
"""
Returns true if the linked list is a palindrome, false otherwise.
Uses 2 pointers to traverse the linked list, reverses the second half
and compares nodes on both sides of the split one by one
>>> linked_list = LinkedList()
>>> is_palindrome(linked_list.head)
Tru... | 08e33b3eb5ea99733e8ed40733f23689a7c43976 | 579,669 |
import json
import logging
def load_config() -> dict:
"""
Loads configuration information from bot.conf.
Specifically, bot.conf contains all information on what prefix is used
to call the bot, which channel entries are posted in each week, which
channel updates should be posted in, the bot key use... | 4bec849816fb15c857b35272eef8792c54567968 | 579,676 |
def MSE(gridA,gridB):
""" A function to calculate mean square error or difference between two grids
"""
diff=gridA.subtract(gridB)
mse=diff.multiply(diff)
return mse | f641f1f0b1b470b8a6570137fa8286157ffc1901 | 579,679 |
def bitmask_bool(bitmask, value):
"""
Returns True or False depending on whether a particular bit has been set.
Microsoft uses bitmasks as a compact way of denoting a number of boolean
settings. The second bit, for example, might be the ADS_UF_ACCOUNTDISABLE
bit, so if the second bit is a 1, then ... | c50f5cce45397bef317b79864f736ca6db014106 | 579,684 |
def index_to_letter(index):
""" Convert a 1-index to a letter in the alphabet: 1 -> a,... """
return chr(ord('a') + index - 1) | 21bf7bcebebc078a1cf948efba8c6c298295abac | 579,685 |
import mpmath
def logbinomial(n, k):
"""
Natural logarithm of binomial(n, k).
Examples
--------
>>> import mpmath
>>> mpmath.mp.dps = 25
>>> from mpsci.fun import logbinomial
Compute the log of C(1500, 450).
>>> logbinomial(1500, 450)
mpf('912.5010192350457701746286796')
... | 392538da347495d40e4103ff1030405af8659761 | 579,689 |
def _list_check(maybe_str):
""" Turns argument into list/tuple"""
if not isinstance(type(maybe_str),(list,tuple)):
return [maybe_str]
return maybe_str | 36501308ff1abe49a4f3767a2aac6fdf3e677c82 | 579,693 |
import math
def rounds_sig(value, sig=3):
"""Round a float to sig significant digits & return it as a string.
Parameters
----------
value: float
The float that is to be rounded.
sig: int
The number of significant figures.
Returns
----------
str:
The rounded out... | 50b63d59b6d77c0adf8e9bb44c284f8fab9046de | 579,696 |
import math
def l2(p, q):
"""
Compute the L2 distance between two multinomial distributions specified as
dictionaries of counts.
"""
totalp = sum(p.values())
totalq = sum(q.values())
p_pnq = sum((v / totalp - q.get(k, 0.0) / totalq)**2 for k, v in p.items())
q = sum((v / totalq)**2 for... | d6a1908f8b13e395c71ab99fb72ffe18d78658fa | 579,700 |
def test_result_group_sort_key(test_result_group):
"""
Used to sort result test groups by their name.
Parameters
----------
test_result_group : ``ResultGroup``
Test result group to get sort key of.
Returns
-------
sort_key : `tuple` (`str`, `str`)
"""
case = tes... | 623e2898f12918b2e6baba7357e4a5d49975354f | 579,701 |
import copy
def merge_id_dicts(dicttuple):
"""
Merges two id dictionary (efficiently).
Args:
dicttuple (tuple): Tuple of two id dictionaries.
Returns:
dict: New merged dictionary
"""
dict1, dict2 = dicttuple
new = copy.deepcopy(dict1)
for key, value in dict2.items():
new.setdefault(key, []).extend(val... | 39df02dcea2c6df35a7ef9fdd95b3076d753e657 | 579,705 |
import functools
def _closedrepr(oldmethod):
"""Decorate string representation method to handle closed nodes.
If the node is closed, a string like this is returned::
<closed MODULE.CLASS at ADDRESS>
instead of calling `oldmethod` and returning its result.
"""
@functools.wraps(oldmethod)... | ce1e81fba75ec3240561336858f13f45945ae2a2 | 579,713 |
def get_value(cards):
"""
Calculate the value of a set of cards. Aces may be counted as 11 or 1, to avoid going over 21
"""
result = 0
aces = 0
for c in cards:
result += c.value
if c.rank == "Ace":
aces += 1
while result > 21 and aces > 0:
result -= 10
... | 0729b357a9316544f6633d865510faa89d0170e8 | 579,714 |
import requests
def get_locale_content(locale: str) -> bytes:
"""
A simple download and return response function.
Input files:
https://github.com/NLnetLabs/Internet.nl/blob/master/translations/nl/main.po
-> https://raw.githubusercontent.com/NLnetLabs/Internet.nl/master/translations/nl/main.po
... | 2a3d1e4757eba23c59eccaa15cd1640ad99e36ef | 579,715 |
def copyFrom(path_to_copy_from: str):
"""This built-in function returns the value of 'path_to_copy_from' key.
"""
def transform_function(current_value: object, record: dict, complete_transform_schema: dict,
custom_variables: dict):
composed_key = (path_to_copy_from,)
... | 1287abda8f0332ce8548a37284d42d05267d5787 | 579,716 |
from typing import Optional
def prompt_string(prompt_msg: str,
error_msg: Optional[str] = "Input not valid.") -> str:
"""Prompts the user for input, repeating until input is provided."""
input_data: str = input(prompt_msg)
while len(input_data.strip()) == 0:
print(error_msg)
... | bb70399cb325e7d406841c337b75dbaf4a3b326a | 579,722 |
def get_rst_bold(text):
"""
Return text bold
"""
return f"**{text}** " | 128f75b7e16cfb7078b8fee0f24add4f304b2c84 | 579,724 |
def selectinload(loadopt, attr):
"""Indicate that the given attribute should be loaded using
SELECT IN eager loading.
This function is part of the :class:`.Load` interface and supports
both method-chained and standalone operation.
examples::
# selectin-load the "orders" collection on "Use... | 1b94e9188f840b11cbd47fe8bd18f7fd138169bf | 579,728 |
def compare_val(expected, got):
""" Compare values, throw exception if different. """
if expected != got:
raise Exception("expected '%s', got '%s'" % (expected, got))
return True | d4dd4f32d5d0a0d0819b6bbf2a9e6fd7135896cf | 579,730 |
from typing import Dict
def _pop_args(src: Dict, *args, **kwargs):
"""
Pop args from the `src` dictionary based on specified keys in `args` and (key, default value) pairs in `kwargs`.
"""
return tuple([src.pop(i) for i in args] + [src.pop(k, v) for k, v in kwargs.items()]) | 8396bd37d2d0031358a7f76b086f1687ce37d5a5 | 579,731 |
def label_to_range(label):
"""
Convert label to range
Parameters:
-----------
label: list of integers
must be in the form of [1, 1, ..., 1, 2, 2, ..., 2, ..., C, C, ..., C]
i.e. nondecreasing numbers starting from 1, each element is greater
than the previous element by at mo... | 4c7ceab7a5d6f89acd7f8db4a0deb8f2fa25d6b9 | 579,733 |
import collections
def create_features(inp_sequence):
"""Create a feature vector composed of unary and pairwise counts."""
# count[1:4] represents the single token counts
# Example: count[I] = #I in `inp_sequence`
# count[5:20] represents the pairwise token counts
# Example: count[4*I + J] = #IJ in `inp_se... | 61fc9decf3bbbb64c28e277821a4e126d9666c56 | 579,734 |
from typing import Union
from typing import List
def normalize_condition(when: 'Union[str, List[str]]') -> 'str':
"""
Normalize `when` directive.
For example:
'hoge is fuga' -> 'hoge is fuga'
['hoge is fuga', 'poyo is fuga'] -> 'hoge is fuga and poyo is fuga'
:param when: A condition t... | 1187380af7487d17e76b5d7057bd19a1366f32d0 | 579,735 |
from datetime import datetime
def datetime_range_inclusive(min, max, format):
"""
Return a value check function which raises a ValueError if the supplied
value when converted to a datetime using the supplied `format` string is
less than `min` or greater than `max`.
"""
dmin = datetime.strpti... | 92fe58094dcc9cf8ed11c5b829614ca83b1acc76 | 579,744 |
from operator import mod
def is_julian_leap_year(j_year):
"""Return True if Julian year 'j_year' is a leap year in
the Julian calendar."""
return mod(j_year, 4) == (0 if j_year > 0 else 3) | 92803f50c6b3903e42c17a37755c1968abe08ad4 | 579,749 |
def joinname(base, num, ext):
"""Join temporary file name parts."""
return '{}-{}{}'.format(base, num, ext) | 35388871eb85209c5d677132aa0ba19ddf0e0ca0 | 579,753 |
def center_series(series):
"""
Centers a series. Centering involves subtracting the series
mean from each entry in series, resulting in a new total mean
of 0.
Parameters
------------
series : pd.Series
Returns
----------
tuple
A tuple containing (1) the mean ... | 329e75fc0e65bdfafa1612d454950817cb8848d6 | 579,755 |
def ComputeSpeedIndex(completeness_record):
"""Computes the speed-index from a completeness record.
Args:
completeness_record: list(CompletenessPoint)
Returns:
Speed-index value.
"""
speed_index = 0.0
last_time = completeness_record[0][0]
last_completness = completeness_record[0][1]
for time, ... | a03a8137cf4b4695143b153cf0894fd50828fb4a | 579,761 |
def select_by_hour(df, hour="All"):
"""
This function takes in a string designating a time window and returns instances from a dataframe which fall
within this time window.
Required argument:
- df: pandas dataframe, contains movie showtimes
Optional argument:
- hour: string, designates a t... | c79c596d75b0c33c68ecb30efdf6031abb340ab0 | 579,765 |
def data_ready(req, cache):
"""
Checks that all required data are in the data_cache
:param req: string or list of string containing the keys of required data in cache
:param cache: dictionary with the computed data
:return: Boolean indicating whether all required data are in cache
"""
if no... | 795a66f9ae81953f2ebcf57a953cc38b318ee232 | 579,766 |
def prepend_all(stack, list):
"""
Prepend all of the items in the given stack onto the head of the
given list. (Naturally tail-recursive.)
For example:
prepend_all([3, 2, 1], [4, 5]) -> [1, 2, 3, 4, 5]
"""
if stack == ():
return list
else:
head, tail = stack
... | a68ca7ae428ddee25331e1bfaa3abfb134c8303b | 579,772 |
def bpmToMs(bpm):
"""
Method:
Convert BPM to ms, where ms is the time in milliseconds between 2 beats.
Argument:
bpm (int or float) : the bpm to convert.
Return:
(int or float) : Time between 2 beats in ms.
"""
if bpm <= 0:
return 0
els... | fb9536c6b3638d0b5ccc6f1d49fbf11e6e5cabf7 | 579,776 |
def bilinear_interpolation(n1, n2, n3, n4, x, y):
"""
Bilinear interpolation of value for point of interest (P).
:param n1: value at node 1
:param n2: value at node 2
:param n3: value at node 3
:param n4: value at node 4
:param x: interpolation scale factor for x axis
:param y: interpol... | dda4474bbd7bbf744a265be7be79fff5f70ee7b8 | 579,780 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.