content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def get_rows_compl(me, typeM, typeE):
"""Get complicating constraints: i.e., mixed M and E fluxes"""
def is_complicating(met):
rtypes = [type(r) for r in met.reactions]
hasM = sum( [(ri in typeM) for ri in rtypes ] ) > 0
hasE = sum( [(ri in typeE) for ri in rtypes] ) > 0
hasME =... | d6a1bdae921e0341a88bf4326e7dc5feb63c7ce5 | 660,626 |
def rotateFromExifMetadata(image):
""" This function autorotates a picture """
try:
exif = image._getexif()
except AttributeError as e:
print("Could not get exif - Bad image!")
return image
(width, height) = image.size
if not exif:
if width > height:
return image.rotate(90)
else:
... | d861842143b93d5f878a96e9c8a6d296e685de73 | 660,627 |
def decoder(input_string):
""" decode the input into numbers
Parameters
----------
input_string : string
String to convert to code points
Returns
-------
output_string : numbers into list
"""
output =[]
temp = input_string
for i in range(len(temp)):... | af883a7960e00dea639b2ad02a58cac4b11a0145 | 660,628 |
def getYInside(x):
"""
Funcion para generar una parabola con el embone hacia arriba ^
:param x: valor de x
:return: valor de y
"""
return -5*(x**2) + 5*x - 1 | e314f89e3702f7f59994fde1384a5b5e446f20c2 | 660,629 |
import math
def linear_regression_tortuosity(x, y, sampling_size=6, retry=True):
"""
This method calculates a tortuosity measure by estimating a line that start and ends with the
first and last points of the given curve, then samples a number of pixels from the given line
and calculates its determinat... | 988dad7d2b46ade347c99e4c4db9bf441b448d3d | 660,630 |
def count_user(data_list):
"""
Function count the users.
Args:
data_list: The data list that is doing to be iterable.
Returns:
A list with the count value of each user type.
"""
customer = 0
subscriber = 0
for i in range(len(data_list)):
if data_list[i][5] ... | ccd4218efe017c4bebe332c9a258de61f03ec097 | 660,631 |
import copy
def getAllBuildersWithControl(builders,control_objects):
"""
Returns an array of DynamicSimulationBuilders (with len(builder)*len(control) elements) that have all the properties as the ones supplied in the builders array, but with control_bojects specified in the control array
"""
res = []... | 00275bdfd51e6d97278a466402f4979f4f989874 | 660,632 |
import base64
def encode_access_id(token_str: str, replica: str) -> str:
"""
Encode a given token as an access ID using URL-safe base64 without padding.
Standard base64 pads the result with equal signs (`=`). Those would need to
be URL-encoded when used in the query portion of a URL:
>>> base64.... | 0e927008f5346eaff01741918ef8ac50c9bfd40b | 660,633 |
def expand_suggested_responses(instrument, lookups, *responses):
"""
Maps any {'_suggested_response': pk} values to the SuggestedResponse by that id, as long as it
is present in the ``lookups`` dict.
"""
values = []
for response in responses:
data = response # Assume raw passthrough by... | 06fce35c585716142489bcaf55339cabc36be9b6 | 660,634 |
def hash_filter(first_hits, second_hits):
"""
This function filters the second network using dictionaries
:param first_hits: Network from first query
:param second_hits: Network from second query
:return: filtered network
"""
protein_filtered = {}
# Now filter
# Protein
for in... | 63167de066db25fa75215ffb7b6187d98e12e8b9 | 660,635 |
import fsspec
from typing import Optional
from typing import Set
from typing import List
def _get_objects_in_path(
fs: fsspec.AbstractFileSystem,
path: str,
target_type: Optional[str] = None,
extensions: Optional[Set[str]] = None
) -> List[str]:
"""Get all objects of a specific typ... | 73c05da142ac04637e992f6871b6fad851d8b9a2 | 660,636 |
def get_property_by_name(pif, name):
"""Get a property by name"""
return next((x for x in pif.properties if x.name == name), None) | b3800921adb2d2275bede664f0f1697b6def2b72 | 660,637 |
from typing import List
from typing import Tuple
def return_to_previous_meeting(
student_names: List[str], individual_seconds: int, previous_individual_seconds: int
) -> Tuple[List[str], int, int]:
"""Rotates the queue backwards.
Parameters
----------
student_names : List[str]
The list of... | 4578ab4a07ae3f3fb927c8783b7f4e0c4cba1829 | 660,638 |
import hashlib
def check_if_infected(hash_value, file):
"""
Checks if the previously infected file's hash value
matches its current hash (namely checks if infected file is changed later)
"""
real_hash = hashlib.sha256(file.encode())
return real_hash.hexdigest() == hash_value | b07184ed5b8c3142c91f6a9f4653a99816c5aced | 660,639 |
def pathcombine(path1, path2):
"""Joins two paths together.
This is faster than `pathjoin`, but only works when the second path is relative,
and there are no backreferences in either path.
>>> pathcombine("foo/bar", "baz")
'foo/bar/baz'
"""
if not path1:
return path2.lstrip()
... | 7566c119db5c87904a8d2fd32666ffd63aa186a2 | 660,640 |
def _scale(column, new_range):
"""
Scale list of values to a given range (the original range is assumed to be [min(column), max(column)]).
"""
old_range = (column.min(), column.max())
return (((column - old_range[0]) * (new_range[1] - new_range[0])) / (old_range[1] - old_range[0])) + new_range[0] | dd612904ac21eff845b62d13a6831a9ecd02c542 | 660,641 |
def knights():
"""
Returns a string "Knights who say Ni!".
>>> knights()
'Knights who say Ni!'
"""
return 'Knights who say Ni!' | 5d06f45308b66b207c3de0f288aa76c7909121b9 | 660,642 |
import argparse
def get_inputs_arg():
"""Creates Command line arguments"""
parser = argparse.ArgumentParser(add_help=True)
parser.add_argument('--data_dir', type=str, default='flowers',
help='Path images folder')
parser.add_argument('--save_dir', type=str, default='checkpoin... | 9091e56a869a3fe6560652c03f52dff06348af2a | 660,643 |
import argparse
import os
import requests
def parse_arguments():
"""
Takes arguments from the command line and checks whether
they have been parsed correctly
"""
parser = argparse.ArgumentParser()
parser.add_argument(
"-m",
"--model",
type=str,
help="Path to YA... | 2dab720011aec1b25729bd969a40ec64a841f495 | 660,644 |
def dominance(counts):
"""Dominance = 1 - Simpson's index, sum of squares of probs.
Briefly, gives probability that two species sampled are the same."""
freqs = counts/float(counts.sum())
return (freqs*freqs).sum() | 5027b5476027006028453e4ceb6309faa76fb2c7 | 660,645 |
def _split_series_episode(title):
"""Return the series and the episode titles; if this is not a
series' episode, the returned series title is empty.
This function recognize two different styles:
"The Series" An Episode (2005)
"The Series" (2004) {An Episode (2005) (#season.episode)}"""
s... | 06547be6b0ef206e8bd7eef3d59051ca01e0bba0 | 660,646 |
from typing import Iterable
from functools import reduce
import operator
def prod(iterable: Iterable) -> float:
"""Returns the product of the elements of an iterable."""
return reduce(operator.mul, iterable, 1) | 5bb7d725003a3b696d3aef45377e6d682a4be022 | 660,647 |
def drop_table(table: str) -> str:
"""
drop_table is used for dropping a table
:param table: the table to drop
:return:
"""
sql_query = f"DROP TABLE {table};"
return sql_query | 384cdee1686ca5b06d213f29ec948ceeb0574fb7 | 660,648 |
def division_euclidienne_dichotomique(a, b):
"""Renvoie le quotient q et le reste r de la division euclidienne de a par b"""
n = 0
while 2 ** n * b <= a:
n += 1
inf = 2 ** (n - 1)
sup = 2 ** n
for i in range(1, n):
mid = (inf + sup) / 2
if mid * b <= a:
inf =... | 9c7aeb8f8e77363e7853e7223cc648191a9e72a7 | 660,649 |
import argparse
def parse_args():
"""
"""
parser = argparse.ArgumentParser(description='PyTorch QAT')
parser.add_argument('--tl','--transfer_learning',action='store_true',help='used to map weights correctly')
parser.add_argument('--iter',default=300, type=int, help='no of iterations')
parser.a... | 3e245ca370713006874b1424c2292177c5cf9e19 | 660,650 |
import re
def sanitize_id(string):
"""Remove characters from a string which would be invalid
in XML identifiers
Parameters
----------
string : str
Returns
-------
str
"""
string = re.sub(r"\s", '_', string)
string = re.sub(r"\\|/", '', string)
return string | 33a4ef04298bb7795af55656c190c7dc50620c37 | 660,651 |
from typing import List
def chunk_to_end(l:List, n:int)-> List[List]:
""" Break list in to evenly sized chunks
:param n: Size of batches
"""
rl = list(reversed(l))
chunks = [ list(reversed(rl[x:x + n])) for x in range(0, len(rl), n) ]
return list(reversed(chunks[:-1])) | 96b82d3989ef4ff3db6e0c4ab67761afe4dd063c | 660,652 |
def subMatrix(A,B):
"""subtraction two matrices"""
return [[A[i][j] - B[i][j] for j in range(len(A))] for i in range(len(B))] | 580f4844791b909e623fbfb978de1ae188b436a7 | 660,653 |
def get_control_interval_mask(control_dates, time_interval):
"""Returns a mask for control dates that affect the given time interval."""
mask_prehistory = control_dates <= time_interval[0]
if not any(mask_prehistory):
raise ValueError('First control date {} is later than the beginning of time interv... | 6a9f908c629b4a030932054094d5c1bfdeb7f9f2 | 660,654 |
import string
import itertools
def euler30():
"""Solution for problem 30."""
# sum(fifth(digits)) = n
# nb_digits * fifth(0) < sum(fifth(digits)) <= nb_digits * fifth(base - 1)
# base ^ (nb_digits - 1) <= n < base ^ nb_digits
# => base ^ (nb_digits - 1) <= nb_digits * fifth(base - 1)
# with ba... | e77d08dd56573eba6b1362687e6a77cd6ab6d31c | 660,656 |
import copy
def prepareGoogleNet_Food101_ECOC_loss(model_wrapper):
"""
Prepares the GoogleNet model for inserting an ECOC structure after removing the last part of the net
:param model_wrapper:
:return:
"""
# Remove all last layers (from 'inception_5a' included)
layers_to_delete = ['incept... | 42f067172b00928aad1ec7f8cd163b70b17af343 | 660,658 |
def mini_help(n):
"""
=> Exibe a docstring do comando que recebe
:param n: o comando a ser pesquisado
:return: a ajuda interactiva (help) do parametro
"""
r = len('Acedendo ao manual do comando')+len(n)+6 #este trecho
print('~'*r) #de codigo
print(f' Acedendo ao manual do comando {n}') #pode ser
print... | 6d60ed299470f270d2295b2029e4833257edf2d5 | 660,659 |
def function2():
"""
Return 2
"""
return 2 | 6de0d981c71049ea2535e3f01cdc299ae74e5a33 | 660,660 |
import random
import string
def random_mutate(word, mutations, no_punct, alpha):
"""Randomly mutate the word with 'mutations' frequency.
If no_punct is true, leave punctuation unaltered."""
letters = list(word) # split the current word in a list
num_mutations = round(mutations * len(letters))
... | 9c50d168834b6872500616d70645aebabef315e7 | 660,662 |
def get_gem_group(sample_def):
""" Get the GEM group from a sample def.
Defaults to 1 if the gem_group is specified as None.
Args:
sample_def (dict): Sample def
Returns:
int: GEM group
"""
gg = sample_def['gem_group'] or 1
return int(gg) | 6b37c25e52292d98e16e579d5d5688a33620b62f | 660,663 |
def rinse(M, d=1e-14):
"""
This function removes any entries in a list or array that
are closer to zero than d is. It is used in the gauss function
to avoid division by near-zero values. By default d is set
to be equal to 10^-14.
"""
m = len(M)
if type(M[0]) == list:
n = len(M[0... | a62a2a02bc878066cecec212c4499fa00df629ae | 660,664 |
def clean_space(string):
"""
Replace underscores by spaces, replace non-breaking space by normal space,
remove exotic whitespace, normalize duplicate spaces, trim whitespace
(any char <= U+0020) from start and end.
Method adapted from org.dbpedia.extraction.util.WikiUtil class (extraction-framework ... | 1286f16d8d22ff2e996ed53aed79fff5ff10469e | 660,665 |
def get_figure_height(width, ratio=0.6):
"""Compute and return figure height with a ratio."""
return width*ratio | ac5a1c3259007b5dcccb9f40c0c9241b5d8c192d | 660,666 |
import re
def process_content(string):
"""
Process the content string data,
if the string is nan (empty), replace it by ''
else check if '#*;' in string, replace it by right symbol,
and if the meaning of '&#*;' is unknow, return the wrong info
Paras:
string: the context
... | f97249a7356dc9010d478a83ad9569960afb102f | 660,667 |
def split_caps(key):
""" splits a string using capital letters as separator
eg split_caps('ExampleString') returns ['Example', 'String']
"""
b = False
lst = []
x = 0
for i, ch in enumerate(key):
if i > 0 and ch.isupper():
temp = key[x:i]
if b and not temp... | 54ce52c322db4d77192fd143bb2f1b13edf51159 | 660,668 |
def _as_float_string(f):
"""Takes a floating point number and returns it as a formatted string"""
return "%.2f" % f if f is not None else 'nil' | 09d53a2d407830a24dd6f4d8b5f1def6d42f22c4 | 660,669 |
def extract_keywords(icss):
"""Helper function
Parameters
----------
icss : string
comma-separated string
Returns
-------
kws : list of string
set of keywords
paramdict : dict
dict of {parameterized_keyword: parameter_valu... | 215609119de40f34dce3733c0bae3b4b4c20d86b | 660,670 |
def ip_net_namespace_mode(function):
"""Decorator: get clissh_instance for class methods.
"""
def wrapper(*args, **kwargs):
"""Add "ip netns exec " prefix to all commands to forward them into network namespace.
"""
if "command" in kwargs:
command_line = kwargs.pop("com... | 196a263351d19de3da351f773a69b965855558b5 | 660,671 |
import unittest
import os
def suite():
"""Return a list of tests"""
loader = unittest.TestLoader()
directory = os.path.join(os.path.dirname(os.path.abspath(__file__)), '..')
return loader.discover(directory, 'test_*.py') | 457ce6c58f92b6cfb8470da59f464deaf5b5c85b | 660,672 |
import os
def simplify_path(path: str) -> str:
"""Simplify a path by removing ../"""
if path.find('..') < 0:
return path
separator = os.sep
keep_folders = path.split(separator)
found = True
while found:
pos = -1
folders = keep_folders
for i in range(len(folde... | 242acffdbdb0b58d65c1d93d205c778c99d46922 | 660,673 |
def _static(job, t):
"""Static priority assignment according to task IDs (smaller is higher priority)"""
if job.task.id is None:
raise ValueError(f"Cannot use task ID {job.task.id} as priority!")
return job.task.id | abd287f7ab888761c62c2f0a325491d0338a54a3 | 660,674 |
def remove_mean_values(points):
"""Calculate integer mean values of the 2D array and removing it from the data.
:param points: The points defining the ellipse.
:type points:
:return: Points, mean X integer coordinate, mean Y integer coordinate
:rtype: tuple
"""
x_mean = int(points[:, 0].me... | 9673cff304bccd199a9db985da40aef11d4d236c | 660,675 |
def hello_world():
"""Hello world function"""
return 'Hello World! Testing deployer(again)' | e27e3cff1fb613105f5c492f6b032a03057052e0 | 660,677 |
def CreateFeedItemAddOperation(name, price, date, adgroup_id,
ad_customizer_feed):
"""Creates a FeedItemOperation.
The generated FeedItemOperation will create a FeedItem with the specified
values and AdGroupTargeting when sent to FeedItemService.mutate.
Args:
name: the value... | 0499a55b232c0376e77ef1c6c3428ff2bef0040c | 660,678 |
def range_limit(u, range=[-5, 5]):
"""
Returns a logical vector that is True where the values of `u` are
outside of `range`.
Parameters
----------
u : xarray.DataArray
The timeseries data to clean.
range : list
Min and max magnitudes beyond which are masked
Returns
--... | 05face2fb4a10557331b7c6c157e17f688e6f917 | 660,679 |
def read_data(filename="data/input4.data"):
"""
Load the raw datafile
"""
with open(filename) as f:
lines = f.read().splitlines()
return lines | 0ddf56cf3b82c7f8da51361383d0b518ccc2c0dd | 660,680 |
def unify_strings(token_list):
"""Unify string literals into a single token"""
tokens_new = []
inside_string = False
for token in token_list:
# Single-word string
if token.count('"') == 2:
tokens_new.append(token)
continue
# Multi-word string
if... | 76a12c3b86ea2a1758f97a14d995b122cf559cf0 | 660,681 |
import numpy
def framing(sig, win_size, win_shift=1, context=(0, 0), pad='zeros'):
"""
:param sig: input signal, can be mono or multi dimensional
:param win_size: size of the window in term of samples
:param win_shift: shift of the sliding window in terme of samples
:param context: tuple of left a... | 925f5f4579f50cabd3950c9201f8b8de61c10103 | 660,682 |
def expansionhunter_expected():
""":return: Returns dictionary with expected results for ExpansionHunter - NORMAL."""
return {
"AR": "Normal - repeat AR observed: 24/25. Normal range: 9 - 35. Expansion range: 38 - 62.",
"FMR1": (
"Normal - repeat FMR1 observed: 17/17. "
"... | c18cd3bd0fb9d083880bab081933313eeb57b330 | 660,683 |
def identity(x):
"""
pickable equivalent of lambda x: x
"""
return x | 9b9b3e93f3a51bcd90ae6fd9e7f3bc671d5ddd01 | 660,684 |
def get_posted_files(db):
"""
Extracts a set of image file names for persisted tweets.
The application's expected image file format is ``an-image-name-without-the-path.png``. So,
it does not include the path to the image file in the saved string.
Args:
db: TinyDB instance.
Returns:
... | e4500a0dcac87df1415a3a4347bb0970b5072710 | 660,686 |
def is_descendant_of(node1, node2, include_self=False):
"""
Return whether the first argument is a descendant of the second argument.
If using this tag to determine whether menu entries should be active or
not ``include_self=True`` should be specified.
"""
# Strings mean that either node1 or no... | 1e9a875d9bdc81b4c1e4a99f1d25b503ad5296b7 | 660,687 |
def calculer_temps_segment(distance, v, deriver_v, limite, pas):
"""
Renvoie le temps et la vitesse après le parcours d'un segment.
distance : flottant, distance à parcourir
v : flottant, vitesse intiale
deriver_v : fonction, renvoie la dérivée de la vitesse
limite : flottant, limit... | 3da1ec025d3240a765d9d07e0eafa7df5a414be1 | 660,688 |
from typing import List
def run(expressions: List):
"""Run a sequence of commands, or evaluate a sequence of expressions."""
result = None
for expression in expressions:
result = eval(expression)
return result | 5a8e0f55fe84165c937e414762eb53f19aa85155 | 660,689 |
import subprocess
def list_committed_files():
"""List all files which are commited in the repo located
in directory"""
command = "git ls-tree --full-tree --name-only -r HEAD".split(" ")
output = subprocess.check_output(command, universal_newlines=True)
return [line for line in output.split("\n") i... | 6c6774b885b09bf8c77b0833681a32d07ce2bf7c | 660,690 |
from typing import Sequence
from typing import List
def _purge_tags(tags: Sequence[str]) -> List[str]:
"""
Purge tags. Remove duplicate and sort tags
:param tags: A sequence of tags
:return: purged tags
"""
return sorted(set({key.strip().lower() for key in tags if key})) | 27407a0c91b24ef9673d1278094892cad99214ad | 660,691 |
def file_2_str(fpath, decode=None):
"""
从文件读取字符串
"""
with open(fpath, 'rb') as f:
context = f.read()
if decode is not None:
context = context.decode(decode, 'ignore')
return context | 648d1ee33b11a375936acf2cc04d86d3956ed18a | 660,692 |
def select_from_dict(original_dict, allowed_keys):
"""
>>> select_from_dict({"spam": 1, "eggs": 2, "pizza": 3}, allowed_keys=("pizza", "spam"))
{'spam': 1, 'pizza': 3}
>>> select_from_dict({"spam": 1, "eggs": 2, "pizza": 3}, allowed_keys=())
{'spam': 1, 'eggs': 2, 'pizza': 3}
"""
if len(allo... | 73f49a266150d62631baa09937306657d965e852 | 660,693 |
def prepare_inputs(data):
""" change the channel dimension for data
Args:
data (tensor): (num_examples_per_class, height, width, channels)
Returns:
data (tensor): (num_examples_per_class, channels, height, width)
"""
if type(data) == list:
return data
if l... | c19327579fe40e973cd3aa81cffc3c6bb181efac | 660,694 |
def poly2str(coeffs, powcoeffs, var='s', eps = None):
"""Converts a Fractional Order transfer function polynomial to a string
Output:
String
Arguments:
Coefficients, Power Coefficients and string value of Transform 'z' or 's'[Optional].
's' is default, 'eps'[Optional] = Number of De... | 1e898cef0febb39ce7e152e5a02465c5b69e7259 | 660,695 |
def path_emission(iterable, emission=0):
"""Construct a common emission from an iterable of :class:`Material` objects
Parameters
----------
iterable: list_like
List of :class:`Material` objects
emission: scalar or :class:`~lentil.radiometry.Spectrum`, optional
Emission collected up... | dbaf144b9c20ad407848ee5a8a72a4036999eeb2 | 660,696 |
def comp_surface_magnets(self):
"""Compute the surface of the magnets (if any)
Parameters
----------
self : HoleM53
A HoleM53 object
Returns
-------
Smag: float
Surface of the Magnets [m**2]
"""
S = 0
if self.magnet_0:
S += self.H2 * self.W3
if sel... | 770d1d7e795934f2393945245a0aa3b4d0e931d7 | 660,697 |
def data_map():
"""A data_map for testing PDProcessor."""
return [
('string', 'String', 'format_uppercase'),
('float', 'Float', None),
('integer', 'Integer', None),
('date', 'Date', 'format_date')
] | e7a7dccb9f532f7ad75f9df6857d903ee20664ce | 660,698 |
def timeout_from_marker(marker):
"""Return None or the value of the timeout."""
timeout = None
if marker is not None:
if len(marker.args) == 1 and len(marker.kwargs) == 0:
timeout = marker.args[0]
elif len(marker.args) == 0 and len(marker.kwargs) == 1 and "timeout" in marker.kwa... | 8d0f56eeba1d5c06bcaa0123923a0ded75da9eba | 660,699 |
def get_color(score: float) -> str:
"""Return a colour reference from a pylint score"""
colors = {
"brightgreen": "#4c1",
"green": "#97CA00",
"yellow": "#dfb317",
"yellowgreen": "#a4a61d",
"orange": "#fe7d37",
"red": "#e05d44",
"bloodred": "#ff0000",
... | 0344694ea66b1e8c0191b5f7a72fe9fcd83b4912 | 660,700 |
def get_romb_offset(rom_slot, rom_split, rom_bases, roms_file=False):
"""
Get ROM slot offset in SPI Flash or ROMS.ZX1 file
:param rom_slot: ROM slot index
:param rom_split: Slot number where rom binary data is split in two
:param rom_bases: Offsets for ROM binary data
:param roms_file: If True,... | 73b4014644c636c50af06a16837b2cc15c6aa9af | 660,701 |
def add(a, b):
"""
A function that adds two integers
:param a: (int) The first integer
:param b: (int) The second integer
:return: (int) The sum of a and b
:raises: AttributeError, if a and b are not integers
"""
if not isinstance(a, int) or not isinstance(b, int):
raise Attribu... | 4f3725e3d1ace5e31fd80f8d26d6835bfff8d77a | 660,702 |
def annotate(the_type, the_value):
"""
This method is a pass-through function that returns `the_value`, used to hint TorchScript
compiler the type of `the_value`. It is a no-op when running outside of TorchScript.
Though TorchScript can infer correct type for most Python expressions, there are some cas... | bc048bb4fb7e6210488a2035004b43017f4c0c09 | 660,703 |
def filter_reserved(res):
"""
Filter reserved IP.
:param res:
:return:
"""
try:
if res['data']['state'] == 'RESERVED':
res['status'] = 'FAIL'
res['message'] = 'Host records cannot be added if ip address is reserved.'
return res
except (TypeError, KeyEr... | 9deca40b629617df2ca2b2b53e79b770d3fec3b2 | 660,705 |
def clean_data(df,categories):
"""
This function cleans the dataframes df and categories
input: df, categories
outputs:- categories: dataframe after being worked conveniently to represent the categories
- df: dataframe after being conveniently cleaned
"""
categories =categories[... | eb62d547f0753a93b8883d77bef494abbf339689 | 660,706 |
def internal_gains (
metabolic_gains,
lighting_gains,
appliances_gains,
cooking_gains,
pumps_and_fans_gains,
losses,
water_heating_gains
):
"""Calculates Internal Gains, Section 5.
:param metabolic_gains: Calculated using table 5. See (66... | 63d23485b5445b3d3aa24cad94682cf7632f466f | 660,707 |
def number_of_tokens():
""" Number of tokens pre-registered in the test Registry. """
return 1 | e109498139cf0308a58c3f67797583b80d7515ae | 660,708 |
def cron_trigger_dict(ts_epoch, ts_2_epoch):
"""A cron trigger as a dictionary."""
return {
"year": "2020",
"month": "*/1",
"day": "*/1",
"week": "*/1",
"day_of_week": "*/1",
"hour": "*/1",
"minute": "*/1",
"second": "*/1",
"start_date": ts... | 724654fa9538011e4e288cd080926ab9b21dcfa0 | 660,709 |
def lighten(color, shades=1):
"""
Lightens a given color by a number of shades.
Args:
color(tuple): the RGBA color.
shades(int): the number of shades to add to the color value.
Return:
The lightened color.
"""
r, g, b, a = color
return min(r + shades, 255), min(g + ... | 6ec2d1e51506b2b35eed540bf2d580792d4b0557 | 660,710 |
def repeated_letter(word: str) -> dict:
"""
Check if a word has repeated letters.
Args:
word (str): Word to check.
Returns:
dict: {
'A':{1,2},
'B':{0,3},
etc.
} # Dictionary of repeated letters and the indices where they are repeated.
"""... | 9b02784e96a5e2fd84ffd77397e54be4088a26bc | 660,711 |
def eval_one_max(traj, individual):
"""The fitness function"""
traj.f_add_result('$set.$.individual', list(individual))
fitness = sum(individual)
traj.f_add_result('$set.$.fitness', fitness)
traj.f_store() # We switched off automatic storing, so we need to store manually
return (fitness,) | 2be6af31273cccf8770fa8346d3dd25f3c15c272 | 660,712 |
def with_error_on_no_name():
"""WithErrorOnNoName some ingesters, when creating a Writer, do not return an error if
the descriptor does not have a valid name on the descriptor. Passing WithErrorOnNoName
tells the writer to return an error instead of passing the data to a nil writer.
"""
def func(opt... | b93c08cd4b501644198ff14d78fa4940d2405bd1 | 660,713 |
def get_graph_no_active_edges(graph):
"""
Get a molecular graph without the active edges
Arguments:
graph (nx.Graph):
Returns:
(nx.Graph):
"""
graph_no_ae = graph.copy()
active_edges = [edge for edge in graph.edges
if graph.edges[edge]['active'] is True... | 03459b65765f4962c651d82902502a1676eca39d | 660,714 |
def fraction_justified_and_finalized(validator):
"""Compute the fraction of justified and finalized checkpoints in the main chain.
From the genesis block to the highest justified checkpoint, count the fraction of checkpoints
in each state.
"""
# Get the main chain
checkpoint = validator.highest... | 9b228962f83eeb548a35e48b2c67565146572dff | 660,715 |
def split_virtual_offset(virtual_offset):
"""Divides a 64-bit BGZF virtual offset into block start & within block offsets.
>>> (100000, 0) == split_virtual_offset(6553600000)
True
>>> (100000, 10) == split_virtual_offset(6553600010)
True
"""
coffset = virtual_offset >> 16
uoffset = vi... | 2ad833efcad3ed8c1675397baf89ab63734ac11a | 660,716 |
def _enum_to_index(enum, key):
"""Enums, by default, are not int-comparable, so use an ad-hoc mapping of
enum key to its int position"""
return list(enum).index(key) | 307f335ceeb42449e2fce939107bd4b40dcd93ca | 660,717 |
def log2(x):
"""
[Definition] 对x做以2为低的对数运算
[Category] 元素级
"""
# if ~np.array((x > 0)).all():
# raise OpException('NANs exist in function log2()!')
return 'log2(%s)' %x | 87d6dd0c3bf7bc40bcfb42ee6078eaeb0ba3ee10 | 660,718 |
def map_headers(wb_obj):
"""
Returns a nested dictionary with the location and name of each
column header
"""
sheets = wb_obj.sheetnames
return_value = {}
ignore_this = ["Main", "Commands", "Settings", "Errors"]
for sheet in sheets:
if sheet not in ignore_this:
row = ... | 474155679ab52aae94cf7ddb7664cd806560223e | 660,719 |
from pathlib import Path
import sqlite3
import warnings
def check_inputs(options):
""" Checks the input options provided by the user and makes sure that
they are valid. Throw an error with descriptive help message if not."""
# Make sure that the input database exists!
database = options.database
... | d215bdb1d7c4600c30d42bd249a0ee85ef1e2371 | 660,720 |
def parse_edges_and_weights(
data: str, start_string: str = "Distance", end_string: str = "# Source",
) -> list:
"""Return a list of edges with weights.
This function will parse through the read-in input data between strings ''start_string'' and ''end_string''
to return the filtered text in-between... | e980e5462ac255f8899ca69ee087f575d7b5cdbf | 660,721 |
def _kappamstar(kappa, m, xi):
"""
Computes maximized cumulant of order m
Parameters
-----
kappa : list
The first two cumulants of the data
xi : int
The :math:`\\xi` for which is computed the p value of :math:`H_0`
m : float
The order of the cumulant
Returns
... | 756d42c3b45f02fd0850cf91ab33bae0e3c21994 | 660,722 |
def safe_get(dictionary, key):
"""
Safely get value from dictionary
"""
if key in dictionary:
return dictionary[key]
return None | af618b5a8d0fbcbf540b7b139dcef18203374077 | 660,723 |
def vectorfield(w, t, par):
"""
*Problem 8-05 Part (a)
{Elements of Chemical Reaction Engineering, Fogler (5th Ed.)}
Arguments:
w : vector of the state variables:
w = [Ca,Cb]
t : time
par : vector of the parameters:
par = [k1,k2]
... | 10eea5a1e63425cfcb579dc2aebb3b84326c5144 | 660,724 |
def degree_centrality(graph):
"""
Returns a dictionary with the degree centrality of all the nodes in a given graph network.
A node’s degree centrality is the number of links that lead into or out of the node.
"""
nodes = set(graph.nodes)
s = 1.0 / (len(nodes) - 1.0)
centrality = dict((n, d ... | fced226cd39ea9e186ad927852aaa42cec0525a2 | 660,725 |
def extract_task(spark):
"""Load data from csv file format.
#param spark: Spark session object.
#return: Spark Dataframe.
"""
market_df = spark.read.csv('/user/xxxx/userCryptoStorage/valid_market*', header=True)
return market_df | 67d2e93cf9d378070bda551806140ac93903e404 | 660,726 |
def Remove_Caps(sentence):
"""
Converts all capital letters in "data" into small caps
"""
return sentence.lower() | 9969947d5706c2bdf6e0175fc00993c837842d93 | 660,727 |
import os
def _get_directory_content(
directory_path: str,
allowed_dot: bool,
validation_method):
"""
:param directory_path: Directory path.
:param validation_method: Validation method.
:param allowed_dot: If True the list will contain dot files/directories.
:return: Lis... | 586e8f0947c841de29dec78290775ea07fa3bae3 | 660,728 |
import random
def random_symbol(num: int = 1, seed=None) -> list:
"""
Returns a list of random symbols from the following set:
['!', '@', '#', '$', '%', '^', '&, '*' ,'(', ')', '-', '_', '=', '+', '`', '~]
:param num: Number of symbols to return
:type num: int
:param seed: Random seed (Opti... | 1e6159fb8e15d974d9e97bddaa82e2bcef9e3b5e | 660,729 |
def W_to_MJ(W):
"""単位換算 W/m2 => MJ/m2・h
Args:
W(float):日射量等(W/m2)
Returns:
MJ(float):日射量等(MJ/m2・h)
"""
return W * 3600 * 10**-6 | 016105790c512162039c9edebae4ee4342c73973 | 660,730 |
def categorize_grades(grades):
"""
:type grades: iterable of librus_tricks.classes.SynergiaGrade
"""
grades_dict = dict()
for grade in grades:
if grade.subject not in grades_dict.keys():
grades_dict[grade.subject] = []
grades_dict[grade.subject].append(
grad... | 3d1aaadd9acd5aef73ae72ab83dce13f9f1d92e2 | 660,731 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.