content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
def get_rb_data_attribute(xmldict, attr): """Get Attribute `attr` from dict `xmldict` Parameters ---------- xmldict : dict Blob Description Dictionary attr : str Attribute key Returns ------- sattr : int Attribute Values """ try: sattr = int(xmldict["@" + attr]) except KeyError: raise KeyError( f"Attribute @{attr} is missing from " "Blob Description. There may be some " "problems with your file" ) return sattr
dfc48ad47f67b2303874154ce4a164a176c1f4bf
707,786
def tls_params(mqtt_config): """Return the TLS configuration parameters from a :class:`.MQTTConfig` object. Args: mqtt_config (:class:`.MQTTConfig`): The MQTT connection settings. Returns: dict: A dict {'ca_certs': ca_certs, 'certfile': certfile, 'keyfile': keyfile} with the TLS configuration parameters, or None if no TLS connection is used. .. versionadded:: 0.6.0 """ # Set up a dict containing TLS configuration parameters for the MQTT # client. if mqtt_config.tls.hostname: return {'ca_certs': mqtt_config.tls.ca_file, 'certfile': mqtt_config.tls.client_cert, 'keyfile': mqtt_config.tls.client_key} # Or don't use TLS. else: return None
4b5d214a50fea60f5cb325fc7a0c93dfa9cb3c02
707,787
def segment_range_to_fragment_range(segment_start, segment_end, segment_size, fragment_size): """ Takes a byterange spanning some segments and converts that into a byterange spanning the corresponding fragments within their fragment archives. Handles prefix, suffix, and fully-specified byte ranges. :param segment_start: first byte of the first segment :param segment_end: last byte of the last segment :param segment_size: size of an EC segment, in bytes :param fragment_size: size of an EC fragment, in bytes :returns: a 2-tuple (frag_start, frag_end) where * frag_start is the first byte of the first fragment, or None if this is a suffix byte range * frag_end is the last byte of the last fragment, or None if this is a prefix byte range """ # Note: segment_start and (segment_end + 1) are # multiples of segment_size, so we don't have to worry # about integer math giving us rounding troubles. # # There's a whole bunch of +1 and -1 in here; that's because HTTP wants # byteranges to be inclusive of the start and end, so e.g. bytes 200-300 # is a range containing 101 bytes. Python has half-inclusive ranges, of # course, so we have to convert back and forth. We try to keep things in # HTTP-style byteranges for consistency. # the index of the first byte of the first fragment fragment_start = (( segment_start // segment_size * fragment_size) if segment_start is not None else None) # the index of the last byte of the last fragment fragment_end = ( # range unbounded on the right None if segment_end is None else # range unbounded on the left; no -1 since we're # asking for the last N bytes, not to have a # particular byte be the last one ((segment_end + 1) // segment_size * fragment_size) if segment_start is None else # range bounded on both sides; the -1 is because the # rest of the expression computes the length of the # fragment, and a range of N bytes starts at index M # and ends at M + N - 1. ((segment_end + 1) // segment_size * fragment_size) - 1) return (fragment_start, fragment_end)
e20c9bb55d9d3e90beb20bed7a170d1066611ba9
707,788
def test_function_decorators(): """Function Decorators.""" # Function decorators are simply wrappers to existing functions. Putting the ideas mentioned # above together, we can build a decorator. In this example let's consider a function that # wraps the string output of another function by p tags. # This is the function that we want to decorate. def greeting(name): return "Hello, {0}!".format(name) # This function decorates another functions output with <p> tag. def decorate_with_p(func): def function_wrapper(name): return "<p>{0}</p>".format(func(name)) return function_wrapper # Now, let's call our decorator and pass the function we want decorate to it. my_get_text = decorate_with_p(greeting) # Here we go, we've just decorated the function output without changing the function itself. assert my_get_text('John') == '<p>Hello, John!</p>' # With decorator. assert greeting('John') == 'Hello, John!' # Without decorator. # Now, Python makes creating and using decorators a bit cleaner and nicer for the programmer # through some syntactic sugar There is a neat shortcut for that, which is to mention the # name of the decorating function before the function to be decorated. The name of the # decorator should be prepended with an @ symbol. @decorate_with_p def greeting_with_p(name): return "Hello, {0}!".format(name) assert greeting_with_p('John') == '<p>Hello, John!</p>' # Now let's consider we wanted to decorate our greeting function by one more functions to wrap a # div the string output. # This will be our second decorator. def decorate_with_div(func): def function_wrapper(text): return "<div>{0}</div>".format(func(text)) return function_wrapper # With the basic approach, decorating get_text would be along the lines of # greeting_with_div_p = decorate_with_div(decorate_with_p(greeting_with_p)) # With Python's decorator syntax, same thing can be achieved with much more expressive power. @decorate_with_div @decorate_with_p def greeting_with_div_p(name): return "Hello, {0}!".format(name) assert greeting_with_div_p('John') == '<div><p>Hello, John!</p></div>' # One important thing to notice here is that the order of setting our decorators matters. # If the order was different in the example above, the output would have been different. # Passing arguments to decorators. # Looking back at the example before, you can notice how redundant the decorators in the # example are. 2 decorators(decorate_with_div, decorate_with_p) each with the same # functionality but wrapping the string with different tags. We can definitely do much better # than that. Why not have a more general implementation for one that takes the tag to wrap # with as a string? Yes please! def tags(tag_name): def tags_decorator(func): def func_wrapper(name): return "<{0}>{1}</{0}>".format(tag_name, func(name)) return func_wrapper return tags_decorator @tags('div') @tags('p') def greeting_with_tags(name): return "Hello, {0}!".format(name) assert greeting_with_tags('John') == '<div><p>Hello, John!</p></div>'
03b3ba299ceb7a75b0de1674fabe892243abd8b3
707,789
import os import sys def exists_case_sensitive(path: str) -> bool: """Returns if the given path exists and also matches the case on Windows. When finding files that can be imported, it is important for the cases to match because while file os.path.exists("module.py") and os.path.exists("MODULE.py") both return True on Windows, Python can only import using the case of the real file. """ result = os.path.exists(path) if ( sys.platform.startswith("win") or sys.platform == "darwin" ) and result: # pragma: no cover directory, basename = os.path.split(path) result = basename in os.listdir(directory) return result
a879f950bcfb6739db3bfe620a75591de92a7a35
707,790
def generate_parallelogrammatic_board(width=5, height=5): """ Creates a board with a shape of a parallelogram. Width and height specify the size (in fields) of the board. """ return [[1] * height for _ in range(width)]
1c9bd6e6e26f6693b434d44e6dbe4085ba9236b8
707,791
import torch def where(condition, x, y): """Wrapper of `torch.where`. Parameters ---------- condition : DTensor of bool Where True, yield x, otherwise yield y. x : DTensor The first tensor. y : DTensor The second tensor. """ return torch.where(condition, x, y)
0ec419e19ab24500f1be6c511eb472d1d929fe2c
707,792
def _xyz_atom_coords(atom_group): """Use this method if you need to identify if CB is present in atom_group and if not return CA""" tmp_dict = {} for atom in atom_group.atoms(): if atom.name.strip() in {"CA", "CB"}: tmp_dict[atom.name.strip()] = atom.xyz if 'CB' in tmp_dict: return tmp_dict['CB'] elif 'CA' in tmp_dict: return tmp_dict['CA'] else: return float('inf'), float('inf'), float('inf')
fd7ef43b1935f8722b692ad28a7e8b309033b720
707,793
from typing import get_origin from typing import Tuple def is_tuple(typ) -> bool: """ Test if the type is `typing.Tuple`. """ try: return issubclass(get_origin(typ), tuple) except TypeError: return typ in (Tuple, tuple)
c8c75f4b1523971b20bbe8c716ced53199150b95
707,794
import functools import unittest def _skip_if(cond, reason): """Skip test if cond(self) is True""" def decorator(impl): @functools.wraps(impl) def wrapper(self, *args, **kwargs): if cond(self): raise unittest.SkipTest(reason) else: impl(self, *args, **kwargs) return wrapper return decorator
4141cc1f99c84633bdf2e92941d9abf2010c11f6
707,795
import ctypes def destructor(cfunc): """ Make a C function a destructor. Destructors accept pointers to void pointers as argument. They are also wrapped as a staticmethod for usage in classes. :param cfunc: The C function as imported by ctypes. :return: The configured destructor. """ cfunc.argtypes = [ctypes.POINTER(ctypes.c_void_p)] cfunc.restype = None return staticmethod(cfunc)
05abd181649a2178d4dce704ef93f61eb5418092
707,796
def update_file_info_in_job(job, file_infos): """ Update the 'setup.package.fileInformations' data in the JSON to append new file information. """ for file_info in file_infos: try: job['setup']['package']['fileInformations'].append(file_info) except (KeyError, TypeError, AttributeError): # If we get here, 'setup.package.fileInformations' does not exist yet. print('Job file input is missing required setup.package.fileInformations data.') exit(1) return job
9902173548d72fcd35c8f80bb44b59aac27d9401
707,797
import math def distance(x1: float, y1: float, x2: float, y2: float) -> float: """ Finds distance between two given points Parameters: x1, y1 : The x and y coordinates of first point x2, y2 : The x and y coordinates of second point Returns: Distance upto two decimal places. """ distance = math.sqrt( ((x1-x2)**2)+((y1-y2)**2) ) return round(distance,2)
63f103f46b52aae146b52f385e15bc3441f042e5
707,798
def _str_trim_left(x): """ Remove leading whitespace. """ return x.str.replace(r"^\s*", "")
2718086073706411929b45edf80a1d464dfaeff6
707,799
def print_formula(elements): """ The input dictionary, atoms and their amount, is processed to produce the chemical formula as a string Parameters ---------- elements : dict The elements that form the metabolite and their corresponding amount Returns ------- formula : str The formula of the metabolite """ formula = "".join([f"{k}{int(v)}" for k, v in elements.items()]) return formula
a3c404ef0d18c417e44aee21106917f4ee203065
707,801
import unicodedata def is_chinese_char(cc): """ Check if the character is Chinese args: cc: char output: boolean """ return unicodedata.category(cc) == 'Lo'
d376e6097e628ac2f3a7934ba42ee2772177f857
707,802
def is_quant_contam(contam_model): """Get the flag for quantitative contamination""" # the list of quantitative models quant_models = ['GAUSS', 'FLUXCUBE'] # set the default value isquantcont = True # check whether the contamination is not quantitative if not contam_model.upper() in quant_models: # re-set the flag isquantcont = False # return the flag return isquantcont
8a88609857ac8eb61bfddfa8d8227ffa237d2641
707,803
def format_component_descriptor(name, version): """ Return a properly formatted component 'descriptor' in the format <name>-<version> """ return '{0}-{1}'.format(name, version)
2edb92f20179ae587614cc3c9ca8198c9a4c240e
707,804
import sqlite3 def dbconn(): """ Initializing db connection """ sqlite_db_file = '/tmp/test_qbo.db' return sqlite3.connect(sqlite_db_file, detect_types=sqlite3.PARSE_DECLTYPES|sqlite3.PARSE_COLNAMES)
b0c6dd235490cee93ada20f060d681a319b120f0
707,805
def get_r(x, y, x1, y1): """ Get r vector following Xu et al. (2006) Eq. 4.2 x, y = arrays; x1, y1 = single points; or vice-versa """ return ((x-x1)**2 + (y-y1)**2)**0.5
424408f86e6e3301ee6eca72e2da7da5bf1f8140
707,807
import re def replace_empty_bracket(tokens): """ Remove empty bracket :param tokens: List of tokens :return: Fixed sequence """ merged = "".join(tokens) find = re.search(r"\{\}", merged) while find: merged = re.sub(r"\{\}", "", merged) find = re.search(r"\{\}", merged) return list(merged)
fd2c9f2f1c2e199056e89dbdba65f92e4d5834eb
707,808
def extra_credit(grades,students,bonus): """ Returns a copy of grades with extra credit assigned The dictionary returned adds a bonus to the grade of every student whose netid is in the list students. Parameter grades: The dictionary of student grades Precondition: grades has netids as keys, ints as values. Parameter netids: The list of students to give extra credit Precondition: netids is a list of valid (string) netids Parameter bonus: The extra credit bonus to award Precondition: bonus is an int """ # DICTIONARY COMPREHENSION #return { k:(grades[k]+bonus if k in students else grades[k]) for k in grades } # ACCUMULATOR PATTERN result = {} for k in grades: if k in students: result[k] = grades[k]+bonus else: result[k] = grades[k] return result
334a9edb3d1d045832009e20c6cba7f24e5c181d
707,809
def get_rectangle(origin, end): """Return all points of rectangle contained by origin and end.""" size_x = abs(origin[0]-end[0])+1 size_y = abs(origin[1]-end[1])+1 rectangle = [] for x in range(size_x): for y in range(size_y): rectangle.append((origin[0]+x, origin[1]+y)) return rectangle
36badfd8aefaaeda806215b02ed6e92fce6509a3
707,810
def policy(Q): """Hard max over prescriptions Params: ------- * Q: dictionary of dictionaries Nested dictionary representing a table Returns: ------- * policy: dictonary of states to policies """ pol = {} for s in Q: pol[s] = max(Q[s].items(), key=lambda x: x[1])[0] return pol
e69f66fba94b025034e03428a5e93ba1b95918e8
707,811
def user_directory_path(instance, filename): """Sets path to user uploads to: MEDIA_ROOT/user_<id>/<filename>""" return f"user_{instance.user.id}/{filename}"
84be5fe74fa5059c023d746b2a0ff6e32c14c10d
707,812
def pa11y_counts(results): """ Given a list of pa11y results, return three integers: number of errors, number of warnings, and number of notices. """ num_error = 0 num_warning = 0 num_notice = 0 for result in results: if result['type'] == 'error': num_error += 1 elif result['type'] == 'warning': num_warning += 1 elif result['type'] == 'notice': num_notice += 1 return num_error, num_warning, num_notice
346c1efe0cae5934e623a8643b0f23f85300181d
707,813
import requests def http_request(method, url, headers, data=None): """ Request util :param method: GET or POST or PUT :param url: url :param headers: headers :param data: optional data (needed for POST) :return: response text """ response = requests.request(method, url, headers=headers, data=data) if response.status_code not in [200, 201, 204]: http_error_msg = u'%s HTTP request failed: %s for url: %s' % (response.status_code, response.text, url) #print ("utils.http_request ", http_error_msg) raise requests.exceptions.HTTPError(response.text) return response.text
6d0453be79b3ae0f7ed60b5a8759b9295365dd6c
707,814
def parse_title(line): """if this is title, return Tuple[level, content], @type line: str @return: Optional[Tuple[level, content]] """ line = line.strip() if not line.startswith('#'): return None sharp_count = 0 for c in line: if c == '#': sharp_count += 1 else: break if sharp_count == len(line): return None title = line[sharp_count:].strip() return sharp_count, title
7c170f417755c878d225b780b8475a379501c19f
707,815
def postprocess(backpointers, best_tag_id): """Do postprocess.""" best_tag_id = best_tag_id.asnumpy() batch_size = len(best_tag_id) best_path = [] for i in range(batch_size): best_path.append([]) best_local_id = best_tag_id[i] best_path[-1].append(best_local_id) for bptrs_t in reversed(backpointers): bptrs_t = bptrs_t[0].asnumpy() local_idx = bptrs_t[i] best_local_id = local_idx[best_local_id] best_path[-1].append(best_local_id) # Pop off the start tag (we dont want to return that to the caller) best_path[-1].pop() best_path[-1].reverse() return best_path
5be856610a3c81453c11c584507dcb4ad0e4cf61
707,816
def f(p, x): """ Parameters ---------- p : list A that has a length of at least 2. x : int or float Scaling factor for the first variable in p. Returns ------- int or float Returns the first value in p scaled by x, aded by the second value in p. Examples -------- >>> import numpy as np >>> from .pycgmKinetics import f >>> p = [1, 2] >>> x = 10 >>> f(p, x) 12 >>> p = np.array([5.16312215, 8.79307163]) >>> x = 2.0 >>> np.around(f(p, x),8) 19.11931593 """ return (p[0] * x) + p[1]
3a5e464e7599b6233086e3dddb623d88c6e5ccb6
707,817
import requests def pairs_of_response(request): """pairwise testing for content-type, headers in responses for all urls """ response = requests.get(request.param[0], headers=request.param[1]) print(request.param[0]) print(request.param[1]) return response
f3a67b1cbf41e2c2e2aa5edb441a449fdff0d8ae
707,818
import itertools import functools def next_count(start: int = 0, step: int = 1): """Return a callable returning descending ints. >>> nxt = next_count(1) >>> nxt() 1 >>> nxt() 2 """ count = itertools.count(start, step) return functools.partial(next, count)
299d457b2b449607ab02877eb108c076cb6c3e16
707,819
import json def make_img_id(label, name): """ Creates the image ID for an image. Args: label: The image label. name: The name of the image within the label. Returns: The image ID. """ return json.dumps([label, name])
4ddcbf9f29d8e50b0271c6ee6260036b8654b90f
707,820
def CalculatePercentIdentity(pair, gap_char="-"): """return number of idential and transitions/transversions substitutions in the alignment. """ transitions = ("AG", "GA", "CT", "TC") transversions = ("AT", "TA", "GT", "TG", "GC", "CG", "AC", "CA") nidentical = 0 naligned = 0 ndifferent = 0 ntransitions = 0 ntransversions = 0 nunaligned = 0 for x in range(min(len(pair.mAlignedSequence1), len(pair.mAlignedSequence2))): if pair.mAlignedSequence1[x] != gap_char and \ pair.mAlignedSequence2[x] != gap_char: naligned += 1 if pair.mAlignedSequence1[x] == pair.mAlignedSequence2[x]: nidentical += 1 else: ndifferent += 1 if (pair.mAlignedSequence1[x] + pair.mAlignedSequence2[x]) in transitions: ntransitions += 1 if (pair.mAlignedSequence1[x] + pair.mAlignedSequence2[x]) in transversions: ntransversions += 1 else: nunaligned += 1 return nidentical, ntransitions, ntransversions, naligned, nunaligned
84d67754d9f63eaee5a172425ffb8397c3b5a7ff
707,821
def scale(pix, pixMax, floatMin, floatMax): """ scale takes in pix, the CURRENT pixel column (or row) pixMax, the total # of pixel columns floatMin, the min floating-point value floatMax, the max floating-point value scale returns the floating-point value that corresponds to pix """ return (pix / pixMax) * (floatMax - floatMin) + floatMin
455d0233cbeeafd53c30baa4584dbdac8502ef94
707,822
def make_set(value): """ Takes a value and turns it into a set !!!! This is important because set(string) will parse a string to individual characters vs. adding the string as an element of the set i.e. x = 'setvalue' set(x) = {'t', 'a', 'e', 'v', 'u', 's', 'l'} make_set(x) = {'setvalue'} or use set([x,]) by adding string as first item in list. :param value: :return: """ if isinstance(value, list): value = set(value) elif not isinstance(value, set): value = set([value]) return value
c811729ea83dc1fbff7c76c8b596e26153aa68ee
707,823
def dt642epoch(dt64): """ Convert numpy.datetime64 array to epoch time (seconds since 1/1/1970 00:00:00) Parameters ---------- dt64 : numpy.datetime64 Single or array of datetime64 object(s) Returns ------- time : float Epoch time (seconds since 1/1/1970 00:00:00) """ return dt64.astype('datetime64[ns]').astype('float') / 1e9
f7cdaf44312cb0564bf57393a5fde727bc24e566
707,824
import math def calc_val_resize_value(input_image_size=(224, 224), resize_inv_factor=0.875): """ Calculate image resize value for validation subset. Parameters: ---------- input_image_size : tuple of 2 int Main script arguments. resize_inv_factor : float Resize inverted factor. Returns: ------- int Resize value. """ if isinstance(input_image_size, int): input_image_size = (input_image_size, input_image_size) resize_value = int(math.ceil(float(input_image_size[0]) / resize_inv_factor)) return resize_value
5a8bcb77d849e62ef5ecfad74f5a3470ab4cfe59
707,825
from typing import Optional def unformat_number(new_str: str, old_str: Optional[str], type_: str) -> str: """Undoes some of the locale formatting to ensure float(x) works.""" ret_ = new_str if old_str is not None: if type_ in ("int", "uint"): new_str = new_str.replace(",", "") new_str = new_str.replace(".", "") ret_ = new_str else: end_comma = False if new_str.endswith(",") or new_str.endswith("."): # Si acaba en coma, lo guardo end_comma = True ret_ = new_str.replace(",", "") ret_ = ret_.replace(".", "") if end_comma: ret_ = ret_ + "." # else: # comma_pos = old_str.find(".") # if comma_pos > -1: print("Desformateando", new_str, ret_) # else: # pos_comma = old_str.find(".") # if pos_comma > -1: # if pos_comma > new_str.find("."): # new_str = new_str.replace(".", "") # ret_ = new_str[0:pos_comma] + "." + new_str[pos_comma:] # print("l2", ret_) return ret_
419698cf46c1f6d3620dbb8c6178f0ba387ef360
707,826
import os def mkdirs(path, raise_path_exits=False): """Create a dir leaf""" if not os.path.exists(path): os.makedirs(path) else: if raise_path_exits: raise ValueError('Path %s has exitsted.' % path) return path
d2491589f2ee9d9aa9b9ceeb5ae8d0f678fc5473
707,827
def cli(ctx, comment, metadata=""): """Add a canned comment Output: A dictionnary containing canned comment description """ return ctx.gi.cannedcomments.add_comment(comment, metadata=metadata)
bacfab650aac1a1785a61756a7cbf84aab7df77a
707,828
def PyException_GetCause(space, w_exc): """Return the cause (another exception instance set by raise ... from ...) associated with the exception as a new reference, as accessible from Python through __cause__. If there is no cause associated, this returns NULL.""" w_cause = space.getattr(w_exc, space.wrap('__cause__')) if space.is_none(w_cause): return None return w_cause
dce5c1df12af7074ce25387e493ccac1aaac27ec
707,829
def splitclass(classofdevice): """ Splits the given class of device to return a 3-item tuple with the major service class, major device class and minor device class values. These values indicate the device's major services and the type of the device (e.g. mobile phone, laptop, etc.). If you google for "assigned numbers bluetooth baseband" you might find some documents that discuss how to extract this information from the class of device. Example: >>> splitclass(1057036) (129, 1, 3) >>> """ if not isinstance(classofdevice, int): try: classofdevice = int(classofdevice) except (TypeError, ValueError): raise TypeError("Given device class '%s' cannot be split" % \ str(classofdevice)) data = classofdevice >> 2 # skip over the 2 "format" bits service = data >> 11 major = (data >> 6) & 0x1F minor = data & 0x3F return (service, major, minor)
37c19ab17293b4fd0c46cff24c30e349459f7bd0
707,830
def get_positive(data_frame, column_name): """ Query given data frame for positive values, including zero :param data_frame: Pandas data frame to query :param column_name: column name to filter values by :return: DataFrame view """ return data_frame.query(f'{column_name} >= 0')
2aec7f611a1b181132f55f2f3ca73bf5025f2474
707,831
import argparse def _get_server_argparser(): """ Create a :class:`argparse.ArgumentParser` with standard configuration options that cli subcommands which communicate with a server require, e.g., hostname and credential information. :return: the argparser :rtype: argparse.ArgumentParser """ parser = argparse.ArgumentParser(add_help=False) parser.add_argument("host", metavar="HOST_NAME", help="hostname where the management service resides") parser.add_argument("-u", "--user", metavar="USERNAME", default=None, required=False, help="user registered at the management service") parser.add_argument("-p", "--password", metavar="PASSWORD", default=None, required=False, help="password for the management service user") parser.add_argument("-t", "--port", metavar="PORT", required=False, default=8443, help="port where the management service resides") parser.add_argument("-e", "--truststore", metavar="TRUSTSTORE_FILE", default=False, required=False, help="""name of file containing one or more CA pems to use in validating the management server""") return parser
0e9300600640e622cd26ba76145f33ca682e6e4c
707,832
def is_internet_file(url): """Return if url starts with http://, https://, or ftp://. Args: url (str): URL of the link """ return ( url.startswith("http://") or url.startswith("https://") or url.startswith("ftp://") )
00f9d90d580da3fe8f6cbc3604be61153b17a154
707,833
from typing import List def get_groups(records_data: dict, default_group: str) -> List: """ Returns the specified groups in the SQS Message """ groups = records_data["Groups"] try: if len(groups) > 0: return groups else: return [default_group] except IndexError as err: raise err
29ffe05da86816750b59bab03041d8bf43ca8961
707,834
import os import stat import pickle def dump_obj(obj, path): """Dump object to file.""" file_name = hex(id(obj)) file_path = path + file_name with open(file_path, 'wb') as f: os.chmod(file_path, stat.S_IWUSR | stat.S_IRUSR) pickle.dump(obj, f) return file_name
d392ffa14e5eb8965ba84e353427358219c9eacc
707,835
import time def count_time(start): """ :param start: :return: return the time in seconds """ end = time.time() return end-start
1945f6e6972b47d7bbdb6941ee7d80b8a6eedd9a
707,836
def split_by_state(xs, ys, states): """ Splits the results get_frame_per_second into a list of continuos line segments, divided by state. This is to plot multiple line segments with different color for each segment. """ res = [] last_state = None for x, y, s in zip(xs, ys, states): if s != last_state: res.append((s, [], [])) last_state = s res[-1][1].append(x) res[-1][2].append(y) return res
0a872617bd935f7c52ee0d10e759674969a19c4e
707,837
def pwr_y(x, a, b, e): """ Calculate the Power Law relation with a deviation term. Parameters ---------- x : numeric Input to Power Law relation. a : numeric Constant. b : numeric Exponent. e : numeric Deviation term. Returns ------- numeric Output of Power Law relation. Notes ----- Power Law relation: :math:`y = a x^b + e` """ return a*x**b+e
e736d9bb2e4305ef0dc0a360143a611b805f7612
707,838
def mimicry(span): """Enrich the match.""" data = {'mimicry': span.lower_} sexes = set() for token in span: if token.ent_type_ in {'female', 'male'}: if token.lower_ in sexes: return {} sexes.add(token.lower_) return data
724d09156e97961049cb29d9f3c1f02ab5af48b0
707,839
def LeftBinarySearch(nums, target): """ :type nums: List[int] :type target: int :rtype: int """ low = 0 high = len(nums) while low < high: mid = (low + high) // 2 if nums[mid] < target: low = mid + 1 else: high = mid assert low == high if low == len(nums) or nums[low] != target: return -1 return low
d08f72e1563ee91e9ca6c9cf95db4c794312aa59
707,840
def parse_char(char, invert=False): """Return symbols depending on the binary input Keyword arguments: char -- binary integer streamed into the function invert -- boolean to invert returned symbols """ if invert == False: if char == 0: return '.' elif char == 1: return '@' if char == 0: return '@' elif char == 1: return '.'
38c0d1c150a1c8e8f7d2f3d1bde08ec3e5ceb65b
707,841
def list_datasets(service, project_id): """Lists BigQuery datasets. Args: service: BigQuery service object that is authenticated. Example: service = build('bigquery','v2', http=http) project_id: string, Name of Google project Returns: List containing dataset names """ datasets = service.datasets() response = datasets.list(projectId=project_id).execute() dataset_list = [] for field in response['datasets']: dataset_list.append(field['datasetReference']['datasetId']) return dataset_list
2712e6a99427ce3b141e7948bba36e8e724f82bc
707,842
def make_postdict_to_fetch_token(token_endpoint: str, grant_type: str, code: str, client_id: str, client_secret: str, redirect_uri: str) -> dict: """POST dictionary is the API of the requests library""" return {'url': token_endpoint, 'data': { 'grant_type': grant_type, 'code': code, 'client_id': client_id, 'client_secret': client_secret, 'redirect_uri': redirect_uri, }, 'headers': { 'Content-Type': 'application/x-www-form-urlencoded', }}
f366fc140c70d094ff99b28a369ac96b4c2a8b49
707,844
def spread_match_network(expr_df_in, node_names_in): """ Matches S (spreadsheet of gene expressions) and N (network) The function returns expr_df_out which is formed by reshuffling columns of expr_df_in. Also, node_names_out is formed by reshuffling node_names_in. The intersection of node_names_out and column names of expr_df_out are placed at the beginning of both lists. Input: expr_df_in: A pandas dataframe corresponding to gene expression node_names_in: Name of the nodes in the network Output: expr_df_out: Reorganized dataframe of gene expressions nodes_names_out: Reordered node names nodes_genes_intersect: Sorted list of shared genes """ node_names_in_set = set(node_names_in) gene_names_in_set = set(expr_df_in.columns.values) nodes_genes_intersect = sorted(list(gene_names_in_set & node_names_in_set)) nodes_minus_genes = sorted(list(node_names_in_set - gene_names_in_set)) genes_minus_nodes = sorted(list(gene_names_in_set - node_names_in_set)) genes_names_out = nodes_genes_intersect + genes_minus_nodes nodes_names_out = nodes_genes_intersect + nodes_minus_genes expr_df_out = expr_df_in[genes_names_out] return(expr_df_out, nodes_names_out, nodes_genes_intersect)
c0b78263a341d3b7682922eb9a948c21ab2e7e45
707,845
from typing import List from typing import Tuple import bisect def line_col(lbreaks: List[int], pos: int) -> Tuple[int, int]: """ Returns the position within a text as (line, column)-tuple based on a list of all line breaks, including -1 and EOF. """ if not lbreaks and pos >= 0: return 0, pos if pos < 0 or pos > lbreaks[-1]: # one character behind EOF is still an allowed position! raise ValueError('Position %i outside text of length %s !' % (pos, lbreaks[-1])) line = bisect.bisect_left(lbreaks, pos) column = pos - lbreaks[line - 1] return line, column
6b99e3b19ed1a490e4a9cc284f99e875085f819a
707,846
import random def get_word(): """Returns random word.""" words = ['Charlie', 'Woodstock', 'Snoopy', 'Lucy', 'Linus', 'Schroeder', 'Patty', 'Sally', 'Marcie'] return random.choice(words).upper()
c4437edc3a1e91cd90c342eda40cfd779364d9c1
707,847
from datetime import datetime def parsed_json_to_dict(parsed): """ Convert parsed dict into dict with python built-in type param: parsed parsed dict by json decoder """ new_bangumi = {} new_bangumi['name'] = parsed['name'] new_bangumi['start_date'] = datetime.strptime( parsed['start_date'], '%Y-%m-%d').date() if 'translation_team' in parsed: new_bangumi['translation_team'] = parsed['translation_team'] else: new_bangumi['translation_team'] = [] if 'total_ep' in parsed: new_bangumi['total_ep'] = int(parsed['total_ep']) else: new_bangumi['total_ep'] = 99 if 'dled_ep' in parsed: new_bangumi['dled_ep'] = int(parsed['dled_ep']) else: new_bangumi['dled_ep'] = 0 if 'keyword' in parsed: new_bangumi['keyword'] = parsed['keyword'] else: new_bangumi['keyword'] = new_bangumi['name'] new_bangumi['folder'] = parsed['folder'] if 'folder' in parsed and parsed[ 'folder'] is not '' else new_bangumi['name'] new_bangumi['offset'] = int(parsed['offset']) if 'offset' in parsed else 0 return new_bangumi
e3bb8306e19a16c9e82d5f6e96c9b4a3707c0446
707,848
from datetime import datetime from shutil import copyfile def backup_file(file): """Create timestamp'd backup of a file Args: file (str): filepath Returns: backupfile(str) """ current_time = datetime.now() time_stamp = current_time.strftime("%b-%d-%y-%H.%M.%S") backupfile = file +'.bkp_'+ time_stamp copyfile(file, backupfile) return(backupfile)
1c1b33028aab01b4e41ed3ef944202ecc53415df
707,849
def _rle_decode(data): """ Decodes run-length-encoded `data`. """ if not data: return data new = b'' last = b'' for cur in data: if last == b'\0': new += last * cur last = b'' else: new += last last = bytes([cur]) return new + last
8463ff6a20b3a39df7b67013d47fe81ed6d53477
707,850
def scale_log2lin(value): """ Scale value from log10 to linear scale: 10**(value/10) Parameters ---------- value : float or array-like Value or array to be scaled Returns ------- float or array-like Scaled value """ return 10**(value/10)
04f15a8b5a86a6e94dd6a0f657d7311d38da5dc0
707,851
def _error_to_level(error): """Convert a boolean error field to 'Error' or 'Info' """ if error: return 'Error' else: return 'Info'
b43e029a4bb14b10de4056758acecebc85546a95
707,852
def add_review(status): """ Adds the flags on the tracker document. Input: tracker document. Output: sum of the switches. """ cluster = status['cluster_switch'] classify = status['classify_switch'] replace = status['replace_switch'] final = status['final_switch'] finished = status['finished_switch'] num = cluster + classify + replace + final + finished return num
8f2ba4cd8b6bd4e500e868f13733146579edd7ce
707,853
import math import operator from typing import Counter def vertical_log_binning(p, data): """Create vertical log_binning. Used for peak sale.""" index, value = zip(*sorted(data.items(), key=operator.itemgetter(1))) bin_result = [] value = list(value) bin_edge = [min(value)] i = 1 while len(value) > 0: num_to_bin = int(math.ceil(p * len(value))) # print num_to_bin edge_value = value[num_to_bin - 1] bin_edge.append(edge_value) to_bin = list(filter(lambda x: x <= edge_value, value)) bin_result += [i] * len(to_bin) value = list(filter(lambda x: x > edge_value, value)) # print len(bin_result) + len(value) i += 1 # print '\n' bin_result_dict = dict(zip(index, bin_result)) bin_distri = Counter(bin_result_dict.values()) # print len(index), len(bin_result) return bin_result_dict, bin_edge, bin_distri
bf536250bc32a9bda54c8359589b10aa5936e902
707,854
from datetime import datetime def generateDateTime(s): """生成时间""" dt = datetime.fromtimestamp(float(s)/1e3) time = dt.strftime("%H:%M:%S.%f") date = dt.strftime("%Y%m%d") return date, time
8d566412230b5bb779baa395670ba06457c2074f
707,855
def prep_ciphertext(ciphertext): """Remove whitespace.""" message = "".join(ciphertext.split()) print("\nciphertext = {}".format(ciphertext)) return message
a5cd130ed3296addf6a21460cc384d8a0582f862
707,856
from typing import List from typing import Tuple from typing import Union def normalize_boxes(boxes: List[Tuple], img_shape: Union[Tuple, List]) -> List[Tuple]: """ Transform bounding boxes back to yolo format """ img_height = img_shape[1] img_width = img_shape[2] boxes_ = [] for i in range(len(boxes)): x1, y1, x2, y2 = boxes[i] width = x2 - x1 height = y2 - y1 x_mid = x1 + 0.5 * width y_mid = y1 + 0.5 * height box = [ x_mid / img_width, y_mid / img_height, width / img_width, height / img_height, ] boxes_.append(box) return boxes_
086e0b069d06a4718e8ffd37189cf3d08c41d19f
707,857
import copy def _make_reference_filters(filters, ref_dimension, offset_func): """ Copies and replaces the reference dimension's definition in all of the filters applied to a dataset query. This is used to shift the dimension filters to fit the reference window. :param filters: :param ref_dimension: :param offset_func: :return: """ reference_filters = [] for ref_filter in filters: if ref_filter.field is ref_dimension: # NOTE: Important to apply the offset function to the start and stop properties because the date math can # become expensive over many rows ref_filter = copy.copy(ref_filter) ref_filter.start = offset_func(ref_filter.start) ref_filter.stop = offset_func(ref_filter.stop) reference_filters.append(ref_filter) return reference_filters
eeeeb74bb3618c87f3540de5b44970e197885dc6
707,858
import os def detect(): """ Detects the shell the user is currently using. The logic is picked from Docker Machine https://github.com/docker/machine/blob/master/libmachine/shell/shell.go#L13 """ shell = os.getenv("SHELL") if not shell: return None if os.getenv("__fish_bin_dir"): return "fish" return os.path.basename(shell)
4c6db387f21b1e4abef17efebbdc45b45c5b7fe7
707,859
def _destupidize_dict(mylist): """The opposite of _stupidize_dict()""" output = {} for item in mylist: output[item['key']] = item['value'] return output
f688e25a9d308e39f47390fef493ab80d303ea15
707,860
def filter_pdf_files(filepaths): """ Returns a filtered list with strings that end with '.pdf' Keyword arguments: filepaths -- List of filepath strings """ return [x for x in filepaths if x.endswith('.pdf')]
3f44b3af9859069de866cec3fac33a9e9de5439d
707,861
import os def alter_subprocess_kwargs_by_platform(**kwargs): """ Given a dict, populate kwargs to create a generally useful default setup for running subprocess processes on different platforms. For example, `close_fds` is set on posix and creation of a new console window is disabled on Windows. This function will alter the given kwargs and return the modified dict. """ kwargs.setdefault('close_fds', os.name == 'posix') if os.name == 'nt': CONSOLE_CREATION_FLAGS = 0 # Default value # See: https://msdn.microsoft.com/en-us/library/windows/desktop/ms684863%28v=vs.85%29.aspx CREATE_NO_WINDOW = 0x08000000 # We "or" them together CONSOLE_CREATION_FLAGS |= CREATE_NO_WINDOW kwargs.setdefault('creationflags', CONSOLE_CREATION_FLAGS) return kwargs
93ada5c681c535b45fc5c321ab4b27b49587a106
707,862
def _format_program_counter_relative(state): """Program Counter Relative""" program_counter = state.program_counter operand = state.current_operand if operand & 0x80 == 0x00: near_addr = (program_counter + operand) & 0xFFFF else: near_addr = (program_counter - (0x100 - operand)) & 0xFFFF return '${:04X}'.format(near_addr)
74f13e9230a6c116413b373b92e36bd884a906e7
707,863
def justify_to_box( boxstart: float, boxsize: float, itemsize: float, just: float = 0.0) -> float: """ Justifies, similarly, but within a box. """ return boxstart + (boxsize - itemsize) * just
a644d5a7a6ff88009e66ffa35498d9720b24222c
707,864
def istype(klass, object): """Return whether an object is a member of a given class.""" try: raise object except klass: return 1 except: return 0
bceb83914a9a346c59d90984730dddb808bf0e78
707,865
import numpy def scale_quadrature(quad_func, order, lower, upper, **kwargs): """ Scale quadrature rule designed for unit interval to an arbitrary interval. Args: quad_func (Callable): Function that creates quadrature abscissas and weights on the unit interval. order (int): The quadrature order passed to the quadrature function. lower (float): The new lower limit for the quadrature function. upper (float): The new upper limit for the quadrature function. kwargs (Any): Extra keyword arguments passed to `quad_func`. Returns: Same as ``quad_func(order, **kwargs)`` except scaled to a new interval. Examples: >>> def my_quad(order): ... return (numpy.linspace(0, 1, order+1)[numpy.newaxis], ... 1./numpy.full(order+1, order+2)) >>> my_quad(2) (array([[0. , 0.5, 1. ]]), array([0.25, 0.25, 0.25])) >>> scale_quadrature(my_quad, 2, lower=0, upper=2) (array([[0., 1., 2.]]), array([0.5, 0.5, 0.5])) >>> scale_quadrature(my_quad, 2, lower=-0.5, upper=0.5) (array([[-0.5, 0. , 0.5]]), array([0.25, 0.25, 0.25])) """ abscissas, weights = quad_func(order=order, **kwargs) assert numpy.all(abscissas >= 0) and numpy.all(abscissas <= 1) assert numpy.sum(weights) <= 1+1e-10 assert numpy.sum(weights > 0) weights = weights*(upper-lower) abscissas = (abscissas.T*(upper-lower)+lower).T return abscissas, weights
f3854cee12a482bc9c92fe2809a0388dddb422e0
707,866
import re def text_cleanup(text: str) -> str: """ A simple text cleanup function that strips all new line characters and substitutes consecutive white space characters by a single one. :param text: Input text to be cleaned. :return: The cleaned version of the text """ text.replace('\n', '') return re.sub(r'\s{2,}', ' ', text)
84b9752f261f94164e2e83b944a2c12cee2ae5d8
707,867
import os def get_files_under_dir(directory, ext='', case_sensitive=False): """ Perform recursive search in directory to match files with one of the extensions provided :param directory: path to directory you want to perform search in. :param ext: list of extensions of simple extension for files to match :param case_sensitive: is case of filename takes into consideration :return: list of files that matched query """ if isinstance(ext, (list, tuple)): allowed_exensions = ext else: allowed_exensions = [ext] if not case_sensitive: allowed_exensions = map(str.lower, allowed_exensions) result = [] for root, dirs, files in os.walk(directory): for filename in files: check_filename = filename if case_sensitive else filename.lower() if any(map(check_filename.endswith, allowed_exensions)): result.append(filename) return result
3ba3428d88c164fce850a29419b6eab46aa8b646
707,868
def boolean(func): """ Sets 'boolean' attribute (this attribute is used by list_display). """ func.boolean=True return func
9bbf731d72e53aa9814caacaa30446207af036bd
707,869
from typing import OrderedDict from typing import Counter def profile_nominal(pairs, **options): """Return stats for the nominal field Arguments: :param pairs: list with pairs (row, value) :return: dictionary with stats """ result = OrderedDict() values = [r[1] for r in pairs] c = Counter(values) result['top'], result['freq'] = c.most_common(1)[0] categories = list(c) categories.sort() result['categories'] = categories result['categories_num'] = len(categories) return result
00ef211e8f665a02f152e764c409668481c748cc
707,870
import os def getJsonPath(name, moduleFile): """ 获取JSON配置文件的路径: 1. 优先从当前工作目录查找JSON文件 2. 若无法找到则前往模块所在目录查找 """ currentFolder = os.getcwd() currentJsonPath = os.path.join(currentFolder, name) if os.path.isfile(currentJsonPath): return currentJsonPath else: moduleFolder = os.path.abspath(os.path.dirname(moduleFile)) moduleJsonPath = os.path.join(moduleFolder, '.', name) return moduleJsonPath
5f0dca485794dead91ecce70b4040809886186c3
707,871
def enable_pause_data_button(n, interval_disabled): """ Enable the play button when data has been loaded and data *is* currently streaming """ if n and n[0] < 1: return True if interval_disabled: return True return False
4257a2deb9b8be87fe64a54129ae869623c323e8
707,872
import sys def _score_match(matchinfo: bytes, form, query) -> float: """ Score how well the matches form matches the query 0.5: half of the terms match (using normalized forms) 1: all terms match (using normalized forms) 2: all terms are identical 3: all terms are identical, including case """ try: if form == query: return 3 if form.lower() == query.lower(): return 2 # Decode matchinfo blob according to https://www.sqlite.org/fts3.html#matchinfo offset = 0 num_cols = int.from_bytes(matchinfo[offset : offset + 4], sys.byteorder) offset += 4 tokens = int.from_bytes(matchinfo[offset : offset + 4], sys.byteorder) offset += num_cols * 4 matched_tokens = int.from_bytes(matchinfo[offset : offset + 4], sys.byteorder) # print(matchinfo, form, query, matched_tokens, tokens) return matched_tokens / tokens except Exception as e: print(e) raise
ef8c223b6c972f7b43fe46788ac894c5454e3f18
707,873
def thread_loop(run): """decorator to make the function run in a loop if it is a thread""" def fct(self, *args, **kwargs): if self.use_thread: while True: run(*args, **kwargs) else: run(*args, **kwargs) return fct
a68eee708bc0a1fe0a3da01e68ec84b6a43d9210
707,874
def get_price_for_market_stateless(result): """Returns the price for the symbols that the API doesnt follow the market state (ETF, Index)""" ## It seems that for ETF symbols it uses REGULAR market fields return { "current": result['regularMarketPrice']['fmt'], "previous": result['regularMarketPreviousClose']['fmt'], "change": result['regularMarketChange']['fmt'], "percent": result['regularMarketChangePercent']['fmt'] }
6afb9d443f246bd0db5c320a41c8341953f5dd7a
707,875
def jump(current_command): """Return Jump Mnemonic of current C-Command""" #jump exists after ; if ; in string. Always the last part of the command if ";" in current_command: command_list = current_command.split(";") return command_list[-1] else: return ""
2530ae99fcc4864c5e529d783b687bfc00d58156
707,877
def compute( op , x , y ): """Compute the value of expression 'x op y', where -x and y are two integers and op is an operator in '+','-','*','/'""" if (op=='+'): return x+y elif op=='-': return x-y elif op=='*': return x*y elif op=='/': return x/y else: return 0
dbdf73a91bdb7092d2a18b6245ce6b8d75b5ab33
707,878
def get_indentation(line_): """ returns the number of preceding spaces """ return len(line_) - len(line_.lstrip())
23a65ba620afa3268d4ab364f64713257824340d
707,880
import argparse def node_parameter_parser(s): """Expects arguments as (address,range,probability)""" try: vals = s.split(",") address = int(vals[0]) range = float(vals[1]) probability = float(vals[2]) return address, range, probability except: raise argparse.ArgumentTypeError("Node parameters must be address,range,probability")
a1d378d5f71b53fb187a920f71d7fc3373e775df
707,881
from typing import List from typing import Any from typing import Optional def jinja_calc_buffer(fields: List[Any], category: Optional[str] = None) -> int: """calculate buffer for list of fields based on their length""" if category: fields = [f for f in fields if f.category == category] return max(len(f.to_string()) for f in fields)
c1f619acd8f68a9485026b344ece0c162c6f0fb0
707,882
def get_delete_op(op_name): """ Determine if we are dealing with a deletion operation. Normally we just do the logic in the last return. However, we may want special behavior for some types. :param op_name: ctx.operation.name.split('.')[-1]. :return: bool """ return 'delete' == op_name
508a9aad3ac6f4d58f5890c1abc138326747ee51
707,883
def warmUp(): """ Warm up the machine in AppEngine a few minutes before the daily standup """ return "ok"
f7c83939d224b06db26570ab8ccc8f04bd69c1d6
707,884
def _mysql_int_length(subtype): """Determine smallest field that can hold data with given length.""" try: length = int(subtype) except ValueError: raise ValueError( 'Invalid subtype for Integer column: {}'.format(subtype) ) if length < 3: kind = 'TINYINT' elif length < 4: kind = 'SMALLINT' elif length < 7: kind = 'MEDIUMINT' elif length <= 10: kind = 'INT' else: kind = 'BIGINT' return '{}({})'.format(kind, length)
3a0e84a3ac602bb018ae7056f4ad06fe0dcab53b
707,885
def regularity(sequence): """ Compute the regularity of a sequence. The regularity basically measures what percentage of a user's visits are to a previously visited place. Parameters ---------- sequence : list A list of symbols. Returns ------- float 1 minus the ratio between unique and total symbols in the sequence. """ n = len(sequence) n_unique = len(set(sequence)) if n_unique <= 1: return 1.0 if n_unique == n: return .0 return 1 - (n_unique / n)
e03d38cc3882ea5d0828b1f8942039865a90d49d
707,886
def contains_whitespace(s : str): """ Returns True if any whitespace chars in input string. """ return " " in s or "\t" in s
c5dc974988efcfa4fe0ec83d115dfa7508cef798
707,887
import math def divide_list(l, n): """Divides list l into n successive chunks.""" length = len(l) chunk_size = int(math.ceil(length/n)) expected_length = n * chunk_size chunks = [] for i in range(0, expected_length, chunk_size): chunks.append(l[i:i+chunk_size]) for i in range(len(chunks), n): chunks.append([]) return chunks
bad7c118988baebd5712cd496bb087cd8788abb7
707,888
from typing import List import os def get_output_file_path(file_path: str) -> str: """ get the output file's path :param file_path: the file path :return: the output file's path """ split_file_path: List[str] = list(os.path.splitext(file_path)) return f'{split_file_path[0]}_sorted{split_file_path[1]}'
baf014ab2587c2b8b3248284e4993a76c502983a
707,890
def binarySearch(arr, val): """ array values must be sorted """ left = 0 right = len(arr) - 1 half = (left + right) // 2 while arr[half] != val: if val < arr[half]: right = half - 1 else: left = half + 1 half = (left + right) // 2 if arr[half] == val: return half return -1
2457e01dee0f3e3dd988471ca708883d2a612066
707,891