content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
def normalize_nonzero_membership(u): """ Given a matrix, it returns the same matrix normalized by row. Parameters ---------- u: Numpy array Numpy Matrix. Returns ------- The matrix normalized by row. """ den1 = u.sum(axis = 1, keepdims = Tr...
5b12faadd671990decbf1e13843e6c47871e9795
672,951
import socket import struct def unpack_ip_addr(addr): """Given a six-octet BACnet address, return an IP address tuple.""" if isinstance(addr, bytearray): addr = bytes(addr) return (socket.inet_ntoa(addr[0:4]), struct.unpack('!H', addr[4:6])[0])
eb92776c1854782c2f7b6094627eab52148e5244
672,952
def __object_attr(obj, mode, keys_to_skip, attr_type): """list object attributes of a given type""" #print('keys_to_skip=%s' % keys_to_skip) keys_to_skip = [] if keys_to_skip is None else keys_to_skip test = { 'public': lambda k: (not k.startswith('_') and k not in keys_to_skip), 'priva...
d37bd47d76bd316bbbff6faf9c6f926ee8a3a955
672,953
def get_provenance( software_name="x", software_version="y", schema_version="1", environment=None, parameters=None): """ Utility function to return a provenance document for testing. """ document = { "schema_version": schema_version, "software": { "name": soft...
9883da0d6905c757c9a12531968255b8eafe9968
672,954
import re def str_to_int(int_str): """ A more relaxed version of int_or_none """ if int_str is None: return None int_str = re.sub(r'[,\.\+]', '', int_str) return int(int_str)
ed81f12fc4f17d20add780190ecc2ca14e8b924b
672,955
import pickle def load_metrics(filestr:str): """ Load metric dict from filestr Args: filestr (str): strig to save dict to Return: metrics (dict): loaded metrics """ # pickle load with open(filestr, 'rb') as f: metrics = pickle.load(f) return metrics
199a30d7391e81a78ba7f4567de35e8c4f0a13a5
672,956
def remove_before(args, lines): """Remove lines before the match.""" if not args.remove_before: return lines new_lines = [] found = False for ln in lines: if args.remove_before.search(ln): found = True if found: new_lines.append(ln) return new_l...
12237259ee56d742c10cfe1e5eac8939a9fef15c
672,957
def leap_year(year: int) -> bool: """Report if a year is leap. :param year: int - year. :return: bool """ return (year % 4 == 0 and not year % 100 == 0) or year % 400 == 0
6c4c63c92431e363b82f25df6d4c2910fe8ea6e4
672,958
def ping(): """ No argument, returns a boolean """ return True
3d4a81df429c41088ea97ac86e0e3b6db1b11447
672,959
def check_pkt_filter_report_hash(mode): """Check if Flow Director hash match reporting mode is valid There are three modes for the reporting mode. * none * match (default) * always """ if mode in ['none', 'match', 'always']: return True else: return False
c044df224e49ea5ac8ae77df91554aa64503dded
672,960
def get_node_value(json_object, parent_node_name, child_node_name=None): """Returns value of given child_node. If child_node is not given, then value of parent node is returned :returns: None If json_object or parent_node is not given, If child_node is not found under parent_node ""...
db50e228f440c604927d930459e2e5abdb6be20a
672,961
def causal_estimation(cpi, rate): """ Calculate all the data to make a causal estimation of the exchange rate, according to the PPP theory: ex_rate_USD_UYU ~= a * CPI_uy / CPI_us The constant "a" is calculated with the expanding mean of the previous values. The function makes no predictions into the...
3b98fb79e06995c1876183e5dbf6bdc151ca1e76
672,962
def parse_alpha(fname): """Helper function """ actions = [] alphas = [] next_nodes = [] with open(fname+'.alpha') as f: lines = f.readlines() for i in range(len(lines)//3): actions.append( int(lines[3*i]) ) alphas.append([float(a) for a in lines[3*i+1].split()]) ...
2fa41e606f741d2d109ee134edde09b07dd86186
672,963
def volume_prisma(area_dasar: float, tinggi: float) -> float: """ kalkulasi dari volume prisma referensi https://en.wikipedia.org/wiki/Prism_(geometry) >>> volume_prisma(10, 2) 20.0 >>> volume_prisma(11, 1) 11.0 """ return float(area_dasar * tinggi)
f792ca88398346d1e673a97c903421349cb7d889
672,964
import os def get_lowest_base(base): """Return the part of name closest to ROOT dir, which starts with capital letter.""" parts = os.path.normpath(base).split(os.sep) #import pdb; pdb.set_trace() x = [p for p in parts if p[0].isupper()] try: return x[0] except IndexError: retur...
b5cb4c7fcfced4493a69ef673c310d21ba07e244
672,965
def get_topics(bag, topic_filters=None): """Get the list of topics from a ROS bag. # Parameters bag: rosbag.Bag a target rosbag. topics_filter: list list of topics that is/are filtered. # Returns bag_topics : dictionary dictionary of topics in the...
cf5ec5f5746c57497581d46c49138381fa7d8c8f
672,966
def getSeqPos(ref_profile, seq): """ Get the start and end position when mapped to refSeq. Sequence to feed to the func should be afa format (e.x. one from mothurAligner). Parameters: ----------- ref_profile : list a gap profile, 0 is gap and 1 is real base pair. seq : str ...
5161a6a3eee701e4c299f3c0c50682282c8dafc3
672,967
import struct def parse_arrayindexandlength(number): """ Returns an array index and length tuple for the given number. """ # Could just use >> and & for this, but since we have to be more # careful with LinkIdAndLinkedBehavior anyway, since that one's # weirder, we may as well just use struct ...
47a30bec6f2cb934e0d5bc0abeab930d9cb504ff
672,968
def prepare_special_error_type(source, target, error_type, charset=None): """ Remove all non-matching words from both the source and the target string. Args: source (str): Source string. target (str): Target string. error_type (str): One of: 'copy_chars', 'uppercase', 'digits', ...
108f60e04d8044e7bc36708d78ef7301b680655b
672,970
def self(client): """Requests information on role of the current user.""" return client.get_role_self()
88342e26c847928467907440fb0f8e70ff93be90
672,972
def no_c(my_string): """ removes all instances of 'c' & 'C' from string """ new_str = "" for i in range(len(my_string)): if my_string[i] != 'c' and my_string[i] != 'C': new_str += my_string[i] return (new_str)
af49292fe65ae0e905e7d808ac9b7196dc5a0c8b
672,973
import math def abs(x): """Return the absolute value of x""" return math.fabs(x)
6dd0df1fc8e288245a520a39bcbe91096371c30b
672,975
def jupyter_get_variable(name, magic_command_instance): """ Retrieves the value of a local variable in a notebook. @param name variable name @param magic_command_instance instance of `Magics <http://ipython.readthedocs.io/en/stable/api/ ...
e8c717540c0100f4d1104decda7c3c39d91db09d
672,976
def get_tx_input_amount(tx): """Returns the the total input amount""" inp_amount = 0 for inp in tx.inputs: inp_amount += inp.witness_utxo.value return inp_amount
fc882f709e4f80caaa5d6d7cd01298eed277edf4
672,977
def append_to_dict_list(modified_dict, key, val): """ :return a list with an extra element The list is retrieved from the `modified_dict` at address `key` """ try: my_list = modified_dict[key] except IndexError: # there is no list at the specified key therefore init one ...
ce23df64b2cc5162800860113b5192b3d6cc8a23
672,978
def xor(string, byte): """Exclusive-ors each character in a string with the given byte.""" results = [] for ch in string: results.append(chr(ord(ch) ^ byte)) return ''.join(results)
b4d93995d64065e1752263f0e1600f97f0a4a3fd
672,979
def get_seccomp_bpf_filter(syscall, entry): """Returns a minijail seccomp-bpf filter expression for the syscall.""" arg_index = entry.arg_index arg_values = entry.value_set atoms = [] if syscall in ('mmap', 'mmap2', 'mprotect') and arg_index == 2: # See if there is at least one instance of a...
4c34adff119c223385a50479b9c5a491b90b0f08
672,980
def CheckChangeHasTestField(input_api, output_api): """Requires that the changelist have a TEST= field.""" if input_api.change.TEST: return [] else: return [output_api.PresubmitNotifyResult( 'Changelist should have a TEST= field. TEST=none is allowed.')]
451b10a4ad6cc61f03b253d8183f813386410828
672,981
def _shifty(offset): """ Move rotated figure along y access to line up the origin point """ def _innerf(tile): tile[1] -= offset return tile return _innerf
0be66a85d2f4b6088030a36cb34a5655f7e56a7b
672,982
def shorter_name(key): """Return a shorter name for an id. Does this by only taking the last part of the URI, after the last / and the last #. Also replaces - and . with _. Parameters ---------- key: str Some URI Returns ------- key_short: str A shortened, but more...
b185c52efb6642d5c691bf8947a4e0b210fb7be8
672,983
def _catmull_rom_weighting_function(x: float) -> float: """Catmull-Rom filter's weighting function. For more information about the Catmull-Rom filter, see `Cubic Filters <https://legacy.imagemagick.org/Usage/filter/#cubics>`_. Args: x (float): distance to source pixel. Returns: fl...
7b4213289af57a782962b437087dd094ff112890
672,984
def assign_item(obj, index, val, oper=None): """ does an augmented assignment to the indexed (keyed) item of obj. returns obj for chaining. does a simple replacement if no operator is specified usually used in combination with the operator module, though any appropriate binary function may be ...
9f72b4a7e0b8d43ecca228733267bfc40c7d76fb
672,985
def is_image(resp): """Returns true if html request response was an image""" try: return resp.headers['content-type'].split('/')[0] == 'image' except: return False
1a73df2ccbaf50a6424a5ba1ddcc952fd023cc9c
672,986
def normalize_frac(unnorm_power, dt, n_bin, mean_flux, background_flux=0): """Fractional rms normalization. ..math:: P = \frac{P_{Leahy}}{\mu} = \frac{2T}{N_{ph}^2}P_{unnorm} where :math:`\mu` is the mean count rate, :math:`T` is the length of the observation, and :math:`N_{ph}` the number of ...
e8ee8d187cc08fd05cb7ef2c63a59299374b6eff
672,989
def convert_neg(arr, size): """ Convert any negative indices into their positive equivalent. This only works for a 1D array. Parameters ---------- arr : ndarray Array having negative indices converted. size : int Dimension of the array. Returns ------- ndarray ...
9040cb636210071015449784ff7db20b3a53f849
672,990
def _format_dict(data): """Formats raw data. Args: data ([dict]): Raw data. Returns: [dict]: Formatted data. """ return {key:value['raw'] if type(value) == dict and value != {} else value for key, value in data.items()}
6d55c1cbba2fdbeb7e313303cb87eb97a3365a0c
672,993
import sys def getUserInput(): """ Get keyboard input from the user. """ if sys.version_info[0] < 3: # The Python version is smaller than 3 terminalEncoding = sys.stdin.encoding userInput = raw_input().decode(encoding=terminalEncoding,\ errors='strict') else...
8b6869b02ef8642a5fccc2d0517be3b0ec599399
672,994
import json import os def _read_configs_from_directory(default_config_path): """Creates a config file from a directory that has folders and json files""" run_config = {} temp_config_files = [] temp_config_folders = [] for each_entry in default_config_path.glob("*/"): # category j...
ff695a00ec964996ec83c6a4ef9033b4e42cda9a
672,996
def reflect_coords_thru_plane(atom, plane): """pysimm.apps.random_walk.reflect_coords_thru_plane This function reflects an atom through a plane, and is used for implementing syndiotactic insertions of monomers Args: atom: either an atom or an array containing x,y,z coordinates for an atom, to b...
c7f480635658b1e33f00196b758f34b108d81922
672,997
def gf_neg(f, p, K): """Negate a polynomial in `GF(p)[x]`. """ return [ -coeff % p for coeff in f ]
3a83fa82bf7fc12ec63bca3c7a45c958d0faed72
672,998
def convert_to_post(input_data): """ Api to get POST json data using PATCH/PUT json data Author: Ramprakash Reddy (ramprakash-reddy.kanala@broadcom.com) :param: input_data (PATCH/PUT data) :return: POST data """ post_data = dict() temp = list(input_data.keys())[0] if isinstance(input...
bf68b8a2f8b8b5368bcb6093858f3433b1da65a7
672,999
import subprocess def cmd(cmdline): """ Run a space-separated command and return its stdout/stderr. Uses shell, blocks until subprocess returns. """ proc = subprocess.Popen(cmdline, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE) # need shell else lnetctl not found stdout, stderr =...
c60c4a9faf42eec5c5a9b9d32b3c6f18dc2c2962
673,000
import sys def getsizeofLocal(l,exclude=[]): """[Returns size of the local variable excluding certain names] Args: l ([type]): [description] exclude ([type]): [description] """ sz = 0 for lk,lv in zip(l.keys(),l.values()): if(lk not in exclude): sz += sys.getsi...
e127536455b5c983e54d00600a92a12ce826e64c
673,001
import torch def tvr_loss(y): """Calculate Total Variation Regularization Loss of Generated Image""" loss = torch.sum(torch.abs(y[:, :, :, :-1] - y[:, :, :, 1:])) + torch.sum( torch.abs(y[:, :, :-1, :] - y[:, :, 1:, :]) ) return loss
44f2a577b5d8d9e4fa2d8f8ccbede8c28a276bb3
673,002
def transform_to_factory_kwargs(data, original_kwargs=None, prefix=""): """ Transforms factory data into the correct kwargs to pass to the factory Args: data (dict): dictionary of data from the factory_data file original_kwargs (dict): kwargs passed into the factory function from code ...
819be74ae16cf56e758e61834365295184fc98b8
673,003
def list_to_dict(seq): """ Take list and insert value in dict Using values from list as keys and index from list as values in BST. """ d = {} for v, k in enumerate(seq): d[k] = v return d
a97290cb7c64c8dda3955a7e7a8a89dc53cd5336
673,005
def can_user_perform(user, account_id, action): """ Utility method for checking arbitrary actions are applicable to a specific account for a user. :param user: A dict object representing user :param account: A string representing an AWS account to validate permission for. :param action: A string rep...
400c485a7040010a7b172e2229dde03ebccd0ef6
673,007
import os def get_config(): """Return configuration data for tests.""" return { 're_api_url': os.environ['RE_API_URL'], 'db_url': os.environ['DB_URL'], 'db_auth': (os.environ['DB_USER'], os.environ.get('DB_PASS', '')) }
9b3e022dda9b2f03277d3c1e4f085f1f4c927e1c
673,008
def run_single_identify(run_identify): # pylint: disable=redefined-outer-name """ Fixture to run the identification step for a given sample file which should contain only one cluster, and return the result for that cluster. """ def inner(sample_name): res = run_identify(sample_name) ...
fde8b415d48d6aa212e9e4b7f908c258c3c4a9a9
673,009
def generate_contain_word_features(df, word): """ 是否包含特定的单词, 如 not """ df[word + "_count_cq1"] = df['cleaned_question1'].apply(lambda x: str(x).strip().split().count(word)) df[word + "_count_cq2"] = df['cleaned_question2'].apply(lambda x: str(x).strip().split().count(word)) df[word + "_cq1_cq2_...
62330c3c4a90056593668de352330805d5424af5
673,011
import re def parseNeighbors(urls): """Parses a urls pair string into urls pair.""" parts = re.split(r'\s+', urls) return parts[0], parts[1]
17728ef54d10ebe4239661f26f30ed8fc10fde57
673,012
def join_lines(strings): """ Stack strings horizontally. This doesn't keep lines aligned unless the preceding lines have the same length. :param strings: Strings to stack :return: String consisting of the horizontally stacked input """ liness = [string.splitlines() for string in strings] ...
072b8cab3bc989053581c52d41b610f88ed8921d
673,013
import re def wrap_line(line, breakable_regex, line_cont, base_indent=0, max_width=80, rewrap=False): """Wrap the given line within the given width. This function is going to be exported to be used by template writers in Jinja as a filter. Parameters ---------- line Th...
70e076188dbea29b7d8e5e8dea7a31897ad3e9a6
673,014
def makehist(vals, incr=1, normalize=0): """Makes a histogram for the given vals and returns a dict. Incr is how much each item counts for If normalize is true, then the sum of return values is normalize. """ ret = {} sum = 0 for v in vals: if v not in ret: ret[v] = 0 ...
2501396bf9bdee4bc59f70411b961b75881b4a36
673,015
def remove_internal_fields(_, publication): """This publisher removes fields from DefaultPublisher that are only useful internally""" publication.pop('staged', None) publication.pop('publishers', None) publication.pop('outputs', None) return publication
34a534d165f836d7cfe7586471b133eb21be1eca
673,016
def gravity(z, g0, r0): """Relates Earth gravity field magnitude with the geometric height. Parameters ---------- z: ~astropy.units.Quantity Geometric height. g0: ~astropy.units.Quantity Gravity value at sea level. r0: ~astropy.units.Quantity Planet/Natural satellite rad...
3386b5be505fb3759c691c3ea8e166af41ecd151
673,017
def compare_versions(v1: str, v2: str) -> int: """Compare two semver-style version strings, returning -1 if v1 < v2; +1 if v1 > v2; or 0 if the two version strings are equal.""" parts1 = v1.split(".") parts2 = v2.split(".") # Zero-fill the parts to the same length length_difference = abs(len...
d66c525831bf1f7f71724613307e248782f37ed5
673,018
def EnableSensorCompensation(iMode): """ This function enables/disables the on camera sensor compensation. """ return None
a8cc23488d7f620f80976673988ba448caeaa231
673,019
def to_index(series): """ returns dataframe with index and the series.name """ df_obj = series.reset_index() return df_obj
5e4300be2ebec4f14f76c36bd89129b853e51a16
673,020
import re def extract_hyperlinks(content): """Returns a list of hyperlinks.""" #Regular expression, note that the group used to identify the hyperlink #uses the non-greedy version of the '*' (Repeat matching) special character. hyperlinks = re.findall(r'<a href="(.*?)".*>', content) return hyperli...
ac077ce6560b2f7a7e37c2a9b13db04ee32bfd54
673,021
def td_read_line(line): """Return x column""" return float(line.split(',')[0])
c08317bba960f3e889ffed7c8396d470c7c384f0
673,022
import numpy def PIL2array(img): """ Convert a PIL/Pillow image to a numpy array """ return numpy.array(img.getdata(), numpy.uint16).reshape(1, img.size_index[1], img.size_index[0], 1)
232b5d77219cbe76378d15115fe11acde270dc1a
673,024
def first(lst): """Return the first element of the given list - otherwise return None""" return lst[0] if lst else None
5e92dadbc0a0bf6a7cc390ca80b45e93d1e3c82c
673,025
def J(theta,X,y): """theta是n*1的矩阵,X是m*n的矩阵,y是m*1的矩阵""" m=len(X) return (X*theta-y).T*(X*theta-y)/(2*m)
da37cccb0727256ebae6049e6ba1b2d51817d2dd
673,026
import functools def single_or_multiple(f): """ Method wrapper, converts first positional argument to tuple: tuples/lists are passed on as tuples, other objects are turned into tuple singleton. Return values should match the length of the argument list, and are unpacked if the original argument was not a tu...
82313931130538ea1f78eb4caf14663cc6cb36eb
673,027
from typing import Union import requests def validate_request_success(resp: Union[requests.Response, str]): """ Validate the response from the webhook request """ return not isinstance(resp, str) and resp.status_code in [200, 201]
13fa27f2c71780f7f33a62ff767eccae45722b91
673,028
def format_action_as_text(field): """ Given an instance (ie from "numpy_to_instance") convert it into text :param field: :param object_id: which object :param convert_ids: Whether to convert numbers like "distance: 3" into the names :return: text representation """ txt = ['Action: {}'.fo...
e90b03e7eb73668d2859f83441e3310a0769198f
673,029
def soloList(data, index): """convert all values in a index in a list to a single list""" x = [] for i in data: x.append(i[index]) return x
273669767af9e485e9e4b2eed08372f384ff607b
673,030
def convert_SI(val, unit_in, unit_out): """Based on unitconverters.net.""" SI = {'Meter':1, 'Kilometer':1000, 'Centimeter':0.01, 'Millimeter':0.001, 'Micrometer':0.000001, 'Mile':1609.35, 'Yard':0.9144, 'Foot':0.3048, 'Inch':0.0254} return val*SI[unit_in]/SI[unit_out]
e7f3dd2e354312febb01102ce11888e68595b42a
673,031
def transform(im, pixel_means, need_mean=False): """ transform into mxnet tensor subtract pixel size and transform to correct format :param im: [height, width, channel] in BGR :param pixel_means: [[[R, G, B pixel means]]] :return: [batch, channel, height, width] """ assert False, "should...
860a916b30627713c84ab6f55c73f37ce3790fa3
673,032
from typing import List from typing import Optional import re def filter_list(arr: List[str], pattern: Optional[str] = None) -> List[str]: """Filter a list of strings with given pattern ```python >> arr = ['crossentropy', 'binarycrossentropy', 'softmax', 'mae',] >> filter_list(arr, ".*entropy*") >...
22b644fa7cd1c35151b4edfd3f196aa561434c5f
673,033
def pythonop_maybe_keep(**kwargs) -> str: """ accepts the following via the caller's op_kwargs: 'next_op': the operator to call on success 'bail_op': the operator to which to bail on failure (default 'no_keep') 'test_op': the operator providing the success code 'test_key': xcom key to test. Def...
4628b0fb459cd586b8dc0d3b5c702bb0cbc2cd40
673,034
import math import torch def get_efficient_ctilde_u_mtx(k): """ Constructs the efficient O(\log k)$ encoding """ embeddings = [] softmaxes = [] logk = int(math.log2(k)) for i in range(k): all_zeros_1 = torch.zeros(logk) bitlist = [int(x) for x in list(bin(i)[2:])] for j in range(len(bitlist)...
3aafcf14b362d7d70741f083b82959344178a250
673,035
def prepend_zeros(length, string): """ Prepend zeros to the string until the desired length is reached :param length: the length that the string should have :param string: the string that we should appends 0's to :return: A string with zeros appended """ return "{}{}".format("0" * (length - ...
f5c56fe7f1dc4c6a65f3c1f93b1257fbe57dea5a
673,036
def player_setup_size(): """ask and return the size of the grid wanted by the player""" size_number_horizontal = input("Rentrez la taille horizontale de la grille que vous souhaitez avoir") while size_number_horizontal.isdigit() == False: size_number_horizontal = input("Entrée invalide, réessayer s'...
998ce2005f08b4aa521c44844c780a0854e84fd2
673,037
def get_with_to_specify_outcome(name): """ Get if user does not wish to specify an outcome. :param str name: The name of the parameter which is allowed to not be set. :return: Allow none ot not :rtype: bool """ accepted_inputs = ["Y", "N"] item_input = input( f"Do you wi...
c966860ea96eb6ea6f8b3ebd73660a3df3f3a2dd
673,039
def plus_haut(points): """ Trouve le point (xb, yb) le plus en haut à droite, en temps linéaire.""" n = len(points) xb, yb = points[0] for j in range(1, n): xj, yj = points[j] if (yb < yj) or (yb == yj and xb < xj): xb, yb = xj, yj return xb, yb
4476f1a357c2296642f6a37c922c7f4e7b4c25ba
673,040
import string def build_link_exp_decay(adj, weight, words_map, words, from_index, to_index, max_dist, stopwords, links_to_stopwords=True, self_links=False): """ Builds a link from a given word in the graph to another word at a defined index. The farther the other word, the smaller the edge between them. ...
6a810ba96740987751b77cf61acc589e401fef60
673,041
def try_decode(obj: bytes, encoding="utf-8"): """ Try decode given bytes with encoding (default utf-8) :return: Decoded bytes to string if succeeded, else object itself """ try: rc = obj.decode(encoding=encoding) except AttributeError: rc = obj return rc.strip()
77919da9204f1574262a95df818c970102977489
673,042
import subprocess async def diffPeak(name1, name2, control1, control2, res_directory, scaling1, scaling2, size): """ calls MACS2 bdgdiff given some parameters Args: ----- name1: str bamfilepath name2: str bamfilepath control1: str control bam filepath (INPUT/IGG) control2: str control bam filepath (INPUT...
4dae89ba4af79875ad0f5a72a4672969361780d0
673,043
import re def files_deleted_match(output): """Retrieves files from output from subprocess i.e: wcase/templates/hello.html\n delete mode 100644 Throws away everything but path to file """ files = [] integers_match_pattern = '^[-+]?[0-9]+$' for line in output.split(): if ...
e7eb13448ca8c6dcd1311308977f61bd9de8fe81
673,044
import re def infer_team(score, current, home, guest): """ Count which team did the goal (home or guest), return a team and current score """ h, g = re.split("[\u2013–-]", score, maxsplit=1) if int(h) > current[0]: team = home elif int(g) > current[1]: team = guest else: #...
c7e30a900184df2f04ff89ef05cef3fbf6679787
673,045
def func_return_none_and_smth(): """function returning none and something else""" print('dougloup') if 2 or 3: return None return 3
fc67cd324d8f42148f25a60ca4107ccee9471637
673,046
def apply_parent_validation(clazz, error_prefix=None): """ Decorator to automatically invoke parent class validation before applying custom validation rules. Usage:: class Child(Parent): @apply_parent_validation(Child, error_prefix="From Child: ") def validate(data): ...
a8cec4db9bb826024726f8a98ee2ee84bdd28182
673,047
from typing import List def get_predicate_indices(tags: List[str]) -> List[int]: """ Return the word indices of a predicate in BIO tags. """ return [ind for ind, tag in enumerate(tags) if "V" in tag]
357c314e9ca581adc130972548f52da533dce45c
673,048
import os def get_img_paths(base_dir, ignore_filetypes=['.txt']): """ Inputs: base_dir (string/ os.path type) relative path to the directory with folders containing images *kwargs ignore_filetypes (list of strings) filetypes to exclude from output type_foldes (dictionary) folde...
2b441a268d90ec3a2ee58d48b9873f766f86f957
673,049
import threading def on_main_thread(): """Checks if we are on the main thread or not.""" return threading.current_thread() is threading.main_thread()
b3f263f0b82870590aef25f3e9af12064cd12ed2
673,050
from pathlib import Path from typing import Tuple import os def _create_output_fname( fname: Path, dir_in: Path, dir_out: Path ) -> Tuple[Path, Path, Path]: """Create the output file names. The output file names is based on the relative path between fname and input_dir_fif. """ # this will fa...
4809728aa2920585eb1767ab8385bb10f8d93f27
673,051
def mean(mylist): """ function to take the mean of a list Parameters ---------- mylist : list list of numbers to take a mean Returns ------- mean_list : float The mean of the list. Examples -------- >>> mean([1,2,3,4,5,6,7]) 4.0 """ ...
5b3c0796e752c2ac384ea00f97ff14ab7d3e7f2d
673,052
def least_squares_parameters(n): """ An order 1 least squared filter can be computed by a g-h filter by varying g and h over time according to the formulas below, where the first measurement is at n=0, the second is at n=1, and so on: .. math:: h_n = \\frac{6}{(n+2)(n+1)} g_n = \\frac...
a3bfa4e116c59ac5e4b289d6e35088c6fe29890f
673,054
def get_summary_line() -> str: """Prompt the user for the summary line for the function. :returns summary_line: {str} """ summary_line = None while summary_line is None or summary_line == "": summary_line = input("What is the summary line for the function? ") summary_line = summar...
73088a20e1d0b44207eef86e4e1d9934ec632ea4
673,055
from functools import reduce def reduce_get(cfg: dict, key: str): """ gets value from dictionary based on flat 'key' provided e.g. instead of dict1["alpha"]["beta"]["gamma"], we do: key = "alpha.beta.gamma" :param cfg: config dictionary :param key: flat key e.g. "alpha.beta.gamma" :return: val...
d2741121bb38abda70e2a733d2afc3d8906e268c
673,056
def func_module1(password): """func_module1 Docstring""" if password != "bicycle": return None else: return "42"
cd0e388c0b484da2cb28900f639fef317d013f82
673,057
def formata_valor(_valor: str) -> float: """ formata a string do valor para ser convertida para float :param _valor: str :return: float """ return float(f'{_valor[:-2]}.{_valor[-2:]}')
c23ae8c483815dd2210b179c3ee3ff91f0d8911c
673,058
def traverse(node, order="pre-order", include_terminal=True, acc=None): """ Parameters ---------- node: NonTerminal or Terminal order: str, default "pre-order" include_terminal: bool, default True acc: list[T] or None, default None T -> NonTerminal or Terminal Returns ------...
450865dc005be90b28f77378412e3515917077cf
673,059
def fatorial(n, mostrarConta): """ Funcao que calcula o valor do fatorial de um numero, onde: param: n = valor inicial param: show = valor logico que mostra ou nao o calculo do fatorial return: valor do fatorial = param : f """ f = 1 if mostrarConta == 'S': for c in range(n, ...
ad0cb45c92a8721af048556148c29f86429cf1a2
673,060
def add_cross_sentence(sentences, tokenizer, max_length=200): """add_cross_sentence add cross sentences with adding equal number of left and right context tokens. """ new_sents = [] all_tokens = [] sent_lens = [] last_id = sentences[0]['sentId'] - 1 article_id = sentences[0]['articleId'...
f673b69325ca33e6d3c4e1ee0b49aa8f33ab286b
673,061
def safe_open(path): """ If the file can be opened, returns a file handle; otherwise None.""" try: return open(path, 'rb') except (IOError, PermissionError, FileNotFoundError): return None
61d5439e438e38f87bfc3936b630d4883bad5454
673,062
def getAllReachable1Step(original_nodes): """ return all node, value pairs reachable from any of the pairs in the original nodes in a single step :param original_nodes: a set of node, value, complete_path pairs from which we check what they can reach in 1 step :return: a set of node, value pairs that ca...
6d6939efbf669b05470c2c27035c90e49650f149
673,064
import argparse def _parse_arguments(argv): """Parses command line arguments.""" parser = argparse.ArgumentParser(description="Runs training on THD data.") parser.add_argument( "--model_dir", required=True, help="The directory where model outputs will be written") parser.add_argument( ...
42691eaeb0815d49e862a0333a0415b9839ddcef
673,066