text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def block_layer(inputs, filters, block_fn, blocks, strides, is_training, name, data_format="channels_first", use_td=False, targeting_rate=None, keep_prob=None):...
[ "def", "block_layer", "(", "inputs", ",", "filters", ",", "block_fn", ",", "blocks", ",", "strides", ",", "is_training", ",", "name", ",", "data_format", "=", "\"channels_first\"", ",", "use_td", "=", "False", ",", "targeting_rate", "=", "None", ",", "keep_p...
32.545455
19.805195
def qloguniform(low, high, q, random_state): ''' low: an float that represent an lower bound high: an float that represent an upper bound q: sample step random_state: an object of numpy.random.RandomState ''' return np.round(loguniform(low, high, random_state) / q) * q
[ "def", "qloguniform", "(", "low", ",", "high", ",", "q", ",", "random_state", ")", ":", "return", "np", ".", "round", "(", "loguniform", "(", "low", ",", "high", ",", "random_state", ")", "/", "q", ")", "*", "q" ]
36.25
18.25
def response(resp): '''post-response callback resp: requests response object ''' results = [] dom = html.fromstring(resp.text) try: number_of_results_string = re.sub('[^0-9]', '', dom.xpath( '//a[@class="active" and contains(@href,"/suchen/dudenonline")]/span/text()')[0] ...
[ "def", "response", "(", "resp", ")", ":", "results", "=", "[", "]", "dom", "=", "html", ".", "fromstring", "(", "resp", ".", "text", ")", "try", ":", "number_of_results_string", "=", "re", ".", "sub", "(", "'[^0-9]'", ",", "''", ",", "dom", ".", "x...
32.542857
25
def generate_help_text(): """Return a formatted string listing commands, HTTPie options, and HTTP actions. """ def generate_cmds_with_explanations(summary, cmds): text = '{0}:\n'.format(summary) for cmd, explanation in cmds: text += '\t{0:<10}\t{1:<20}\n'.format(cmd, explanat...
[ "def", "generate_help_text", "(", ")", ":", "def", "generate_cmds_with_explanations", "(", "summary", ",", "cmds", ")", ":", "text", "=", "'{0}:\\n'", ".", "format", "(", "summary", ")", "for", "cmd", ",", "explanation", "in", "cmds", ":", "text", "+=", "'...
43.866667
20.533333
def keyPressEvent(self, event): """ Listens for the left/right keys and the escape key to control the slides. :param event | <QtCore.Qt.QKeyEvent> """ if event.key() == QtCore.Qt.Key_Escape: self.cancel() elif event.key() == QtCo...
[ "def", "keyPressEvent", "(", "self", ",", "event", ")", ":", "if", "event", ".", "key", "(", ")", "==", "QtCore", ".", "Qt", ".", "Key_Escape", ":", "self", ".", "cancel", "(", ")", "elif", "event", ".", "key", "(", ")", "==", "QtCore", ".", "Qt"...
33.823529
13.823529
def copychildren(self, newdoc=None, idsuffix=""): """Generator creating a deep copy of the children of this element. Invokes :meth:`copy` on all children, parameters are the same. """ if idsuffix is True: idsuffix = ".copy." + "%08x" % random.getrandbits(32) #random 32-bit hash for each...
[ "def", "copychildren", "(", "self", ",", "newdoc", "=", "None", ",", "idsuffix", "=", "\"\"", ")", ":", "if", "idsuffix", "is", "True", ":", "idsuffix", "=", "\".copy.\"", "+", "\"%08x\"", "%", "random", ".", "getrandbits", "(", "32", ")", "#random 32-bi...
52.777778
25.111111
def ms_zoom(self, viewer, event, data_x, data_y, msg=True): """Zoom the image by dragging the cursor left or right. """ if not self.canzoom: return True msg = self.settings.get('msg_zoom', msg) x, y = self.get_win_xy(viewer) if event.state == 'move': ...
[ "def", "ms_zoom", "(", "self", ",", "viewer", ",", "event", ",", "data_x", ",", "data_y", ",", "msg", "=", "True", ")", ":", "if", "not", "self", ".", "canzoom", ":", "return", "True", "msg", "=", "self", ".", "settings", ".", "get", "(", "'msg_zoo...
30
16.285714
def onTWriteCallback__init(self, sim): """ Process for injecting of this callback loop into simulator """ yield from self.onTWriteCallback(sim) self.intf.t._sigInside.registerWriteCallback( self.onTWriteCallback, self.getEnable) self.intf.o._sigIns...
[ "def", "onTWriteCallback__init", "(", "self", ",", "sim", ")", ":", "yield", "from", "self", ".", "onTWriteCallback", "(", "sim", ")", "self", ".", "intf", ".", "t", ".", "_sigInside", ".", "registerWriteCallback", "(", "self", ".", "onTWriteCallback", ",", ...
36.272727
8.818182
def load_3MF(file_obj, postprocess=True, **kwargs): """ Load a 3MF formatted file into a Trimesh scene. Parameters ------------ file_obj: file object Returns ------------ kwargs: dict, with keys 'graph', 'geometry', 'base_frame' """ # dict, {name...
[ "def", "load_3MF", "(", "file_obj", ",", "postprocess", "=", "True", ",", "*", "*", "kwargs", ")", ":", "# dict, {name in archive: BytesIo}", "archive", "=", "util", ".", "decompress", "(", "file_obj", ",", "file_type", "=", "'zip'", ")", "# load the XML into an...
36.48538
15.526316
def compute_md5(self): """Compute and erturn MD5 hash value.""" import hashlib with open(self.path, "rt") as fh: text = fh.read() m = hashlib.md5(text.encode("utf-8")) return m.hexdigest()
[ "def", "compute_md5", "(", "self", ")", ":", "import", "hashlib", "with", "open", "(", "self", ".", "path", ",", "\"rt\"", ")", "as", "fh", ":", "text", "=", "fh", ".", "read", "(", ")", "m", "=", "hashlib", ".", "md5", "(", "text", ".", "encode"...
34.571429
9.428571
def set_param(self, param, value): '''Set a parameter in this configuration set.''' self.data[param] = value self._object.configuration_data = utils.dict_to_nvlist(self.data)
[ "def", "set_param", "(", "self", ",", "param", ",", "value", ")", ":", "self", ".", "data", "[", "param", "]", "=", "value", "self", ".", "_object", ".", "configuration_data", "=", "utils", ".", "dict_to_nvlist", "(", "self", ".", "data", ")" ]
48.75
15.75
def set_multi(self, mappings, time=0, compress_level=-1): """ Set multiple keys with it's values on server. :param mappings: A dict with keys/values :type mappings: dict :param time: Time in seconds that your key will expire. :type time: int :param compress_level...
[ "def", "set_multi", "(", "self", ",", "mappings", ",", "time", "=", "0", ",", "compress_level", "=", "-", "1", ")", ":", "returns", "=", "[", "]", "if", "not", "mappings", ":", "return", "False", "server_mappings", "=", "defaultdict", "(", "dict", ")",...
37.846154
15.538462
def data(self): """Return list of (dataframe, filestem) tuples.""" stemdict = { "ANIm": pyani_config.ANIM_FILESTEMS, "ANIb": pyani_config.ANIB_FILESTEMS, "ANIblastall": pyani_config.ANIBLASTALL_FILESTEMS, } return zip( ( sel...
[ "def", "data", "(", "self", ")", ":", "stemdict", "=", "{", "\"ANIm\"", ":", "pyani_config", ".", "ANIM_FILESTEMS", ",", "\"ANIb\"", ":", "pyani_config", ".", "ANIB_FILESTEMS", ",", "\"ANIblastall\"", ":", "pyani_config", ".", "ANIBLASTALL_FILESTEMS", ",", "}", ...
31.529412
14.117647
def check_token(request): """ Resource check is token valid. --- request_serializer: serializers.CheckToken type: username: required: true type: string description: token related user responseMessages: - code: 200 message: Token is v...
[ "def", "check_token", "(", "request", ")", ":", "serializer", "=", "serializers", ".", "CheckToken", "(", "data", "=", "request", ".", "data", ")", "serializer", ".", "is_valid", "(", "raise_exception", "=", "True", ")", "token", "=", "serializer", ".", "v...
27.576923
17.730769
def _data_flow_chain(self): """ Get a list of all elements in the data flow graph. The first element is the original source, the next one reads from the prior and so on and so forth. Returns ------- list: list of data sources """ if self.data_producer is...
[ "def", "_data_flow_chain", "(", "self", ")", ":", "if", "self", ".", "data_producer", "is", "None", ":", "return", "[", "]", "res", "=", "[", "]", "ds", "=", "self", ".", "data_producer", "while", "not", "ds", ".", "is_reader", ":", "res", ".", "appe...
25.571429
19.761905
def do_POST(self): """ This method will be called for each POST request to one of the listener ports. It parses the CIM-XML export message and delivers the contained CIM indication to the stored listener object. """ # Accept header check described in DSP0200 ...
[ "def", "do_POST", "(", "self", ")", ":", "# Accept header check described in DSP0200", "accept", "=", "self", ".", "headers", ".", "get", "(", "'Accept'", ",", "'text/xml'", ")", "if", "accept", "not", "in", "(", "'text/xml'", ",", "'application/xml'", ",", "'...
42.228395
19.364198
def to_representation(self, obj): """Convert given internal object instance into representation dict. Representation dict may be later serialized to the content-type of choice in the resource HTTP method handler. This loops over all fields and retrieves source keys/attributes as ...
[ "def", "to_representation", "(", "self", ",", "obj", ")", ":", "representation", "=", "{", "}", "for", "name", ",", "field", "in", "self", ".", "fields", ".", "items", "(", ")", ":", "if", "field", ".", "write_only", ":", "continue", "# note fields do no...
36.526316
24.315789
def add_splitrelation(self, splitrelation): """ Parameters ---------- splitrelation : etree.Element etree representation of a <splitRelation> element A <splitRelation> annotates its parent element (e.g. as an anaphora). Its parent can be either a <word...
[ "def", "add_splitrelation", "(", "self", ",", "splitrelation", ")", ":", "if", "self", ".", "ignore_relations", "is", "False", "and", "self", ".", "ignore_splitrelations", "is", "False", ":", "source_id", "=", "self", ".", "get_element_id", "(", "splitrelation",...
58.619048
32.52381
def search(description, all=False): """ Gets a list of :class:`language_tags.Subtag.Subtag` objects where the description matches. :param description: a string or compiled regular expression. For example: ``search(re.compile('\d{4}'))`` if the description of the returned subtag must...
[ "def", "search", "(", "description", ",", "all", "=", "False", ")", ":", "# If the input query is all lowercase, make a case-insensitive match.", "if", "isinstance", "(", "description", ",", "str", ")", ":", "list_to_string", "=", "lambda", "l", ":", "', '", ".", ...
54.939394
33.848485
def multicolumn_store_with_uncompressed_write(mongo_server): """ The database state created by this fixture is equivalent to the following operations using arctic 1.40 or previous: arctic.initialize_library('arctic_test.TEST', m.VERSION_STORE, segment='month') library = arctic.get_library('...
[ "def", "multicolumn_store_with_uncompressed_write", "(", "mongo_server", ")", ":", "mongo_server", ".", "api", ".", "drop_database", "(", "'arctic_test'", ")", "library_name", "=", "'arctic_test.TEST'", "arctic", "=", "m", ".", "Arctic", "(", "mongo_host", "=", "mon...
44.107143
26.988095
def print_row(*argv): """ Print one row of data """ #for i in range(0, len(argv)): # row += f"{argv[i]}" # columns row = "" # id row += f"{argv[0]:<3}" # name row += f" {argv[1]:<13}" # allocation row += f" {argv[2]:>5}" # level #row += f"{argv[3]}" print(row...
[ "def", "print_row", "(", "*", "argv", ")", ":", "#for i in range(0, len(argv)):", "# row += f\"{argv[i]}\"", "# columns", "row", "=", "\"\"", "# id", "row", "+=", "f\"{argv[0]:<3}\"", "# name", "row", "+=", "f\" {argv[1]:<13}\"", "# allocation", "row", "+=", "f\" {arg...
19.125
20.4375
def serverUrl(self, value): """gets/sets the server url""" if value.lower() != self._serverUrl.lower(): self._serverUrl = value
[ "def", "serverUrl", "(", "self", ",", "value", ")", ":", "if", "value", ".", "lower", "(", ")", "!=", "self", ".", "_serverUrl", ".", "lower", "(", ")", ":", "self", ".", "_serverUrl", "=", "value" ]
38
7.5
def compute_time_at_sun_angle(day, latitude, angle): """Compute the floating point time difference between mid-day and an angle. All the prayers are defined as certain angles from mid-day (Zuhr). This formula is taken from praytimes.org/calculation :param day: The day to which to compute for :para...
[ "def", "compute_time_at_sun_angle", "(", "day", ",", "latitude", ",", "angle", ")", ":", "positive_angle_rad", "=", "radians", "(", "abs", "(", "angle", ")", ")", "angle_sign", "=", "abs", "(", "angle", ")", "/", "angle", "latitude_rad", "=", "radians", "(...
36.307692
22.076923
def embedded_images(X, images, exclusion_radius=None, ax=None, cmap=None, zoom=1, seed=None, frameon=False): '''Plots a subset of images on an axis. Useful for visualizing image embeddings, especially when plotted over a scatterplot. Selects random points to annotate with their corresponding i...
[ "def", "embedded_images", "(", "X", ",", "images", ",", "exclusion_radius", "=", "None", ",", "ax", "=", "None", ",", "cmap", "=", "None", ",", "zoom", "=", "1", ",", "seed", "=", "None", ",", "frameon", "=", "False", ")", ":", "assert", "X", ".", ...
42.32
19.6
def _backtrack(ex): """ If this function is satisfiable, return a satisfying input upoint. Otherwise, return None. """ if ex is Zero: return None elif ex is One: return dict() else: v = ex.top points = {v: 0}, {v: 1} for point in points: so...
[ "def", "_backtrack", "(", "ex", ")", ":", "if", "ex", "is", "Zero", ":", "return", "None", "elif", "ex", "is", "One", ":", "return", "dict", "(", ")", "else", ":", "v", "=", "ex", ".", "top", "points", "=", "{", "v", ":", "0", "}", ",", "{", ...
25.222222
15.444444
def check_image_state(self, image_id, wait=True): ''' method for checking the state of an image on AWS EC2 :param image_id: string with AWS id of image :param wait: [optional] boolean to wait for image while pending :return: string reporting state of image ''' ...
[ "def", "check_image_state", "(", "self", ",", "image_id", ",", "wait", "=", "True", ")", ":", "title", "=", "'%s.check_image_state'", "%", "self", ".", "__class__", ".", "__name__", "# validate inputs", "input_fields", "=", "{", "'image_id'", ":", "image_id", ...
40.285714
21.285714
def catch_all(path): """Catch all path - return a JSON 404 """ return (dict(error='Invalid URL: /{}'.format(path), links=dict(root='{}{}'.format(request.url_root, PREFIX[1:]))), HTTPStatus.NOT_FOUND)
[ "def", "catch_all", "(", "path", ")", ":", "return", "(", "dict", "(", "error", "=", "'Invalid URL: /{}'", ".", "format", "(", "path", ")", ",", "links", "=", "dict", "(", "root", "=", "'{}{}'", ".", "format", "(", "request", ".", "url_root", ",", "P...
46.4
16.2
def _assert_in_buildroot(self, filepath): """Raises an error if the given filepath isn't in the buildroot. Returns the normalized, absolute form of the path. """ filepath = os.path.normpath(filepath) root = get_buildroot() if not os.path.abspath(filepath) == filepath: # If not absolute, a...
[ "def", "_assert_in_buildroot", "(", "self", ",", "filepath", ")", ":", "filepath", "=", "os", ".", "path", ".", "normpath", "(", "filepath", ")", "root", "=", "get_buildroot", "(", ")", "if", "not", "os", ".", "path", ".", "abspath", "(", "filepath", "...
45.421053
18.842105
def serve(): """main entry point""" logging.getLogger().setLevel(logging.DEBUG) logging.info('Python Tornado Crossdock Server Starting ...') tracer = Tracer( service_name='python', reporter=NullReporter(), sampler=ConstSampler(decision=True)) opentracing.tracer = tracer ...
[ "def", "serve", "(", ")", ":", "logging", ".", "getLogger", "(", ")", ".", "setLevel", "(", "logging", ".", "DEBUG", ")", "logging", ".", "info", "(", "'Python Tornado Crossdock Server Starting ...'", ")", "tracer", "=", "Tracer", "(", "service_name", "=", "...
30.52381
17.190476
def exciter(self, Xexc, Pexc, Vexc): """ Exciter model. Based on Exciter.m from MatDyn by Stijn Cole, developed at Katholieke Universiteit Leuven. See U{http://www.esat.kuleuven.be/electa/teaching/ matdyn/} for more information. """ exciters = self.exciters F = ...
[ "def", "exciter", "(", "self", ",", "Xexc", ",", "Pexc", ",", "Vexc", ")", ":", "exciters", "=", "self", ".", "exciters", "F", "=", "zeros", "(", "Xexc", ".", "shape", ")", "typ1", "=", "[", "e", ".", "generator", ".", "_i", "for", "e", "in", "...
26.660714
20.071429
def _load_class(class_path, default): """ Loads the class from the class_path string """ if class_path is None: return default component = class_path.rsplit('.', 1) result_processor = getattr( importlib.import_module(component[0]), component[1], default ) if len(comp...
[ "def", "_load_class", "(", "class_path", ",", "default", ")", ":", "if", "class_path", "is", "None", ":", "return", "default", "component", "=", "class_path", ".", "rsplit", "(", "'.'", ",", "1", ")", "result_processor", "=", "getattr", "(", "importlib", "...
27.692308
14.461538
def parse_spec(self, spec): """Parse the given spec into a `specs.Spec` object. :param spec: a single spec string. :return: a single specs.Specs object. :raises: CmdLineSpecParser.BadSpecError if the address selector could not be parsed. """ if spec.endswith('::'): spec_path = spec[:-len...
[ "def", "parse_spec", "(", "self", ",", "spec", ")", ":", "if", "spec", ".", "endswith", "(", "'::'", ")", ":", "spec_path", "=", "spec", "[", ":", "-", "len", "(", "'::'", ")", "]", "return", "DescendantAddresses", "(", "self", ".", "_normalize_spec_pa...
39.368421
17.578947
def set_edist_powerlaw(self, emin_mev, emax_mev, delta, ne_cc): """Set the energy distribution function to a power law. **Call signature** *emin_mev* The minimum energy of the distribution, in MeV *emax_mev* The maximum energy of the distribution, in MeV *de...
[ "def", "set_edist_powerlaw", "(", "self", ",", "emin_mev", ",", "emax_mev", ",", "delta", ",", "ne_cc", ")", ":", "if", "not", "(", "emin_mev", ">=", "0", ")", ":", "raise", "ValueError", "(", "'must have emin_mev >= 0; got %r'", "%", "(", "emin_mev", ",", ...
38.580645
18.774194
def ipv4_prefix_to_mask(prefix): """ ipv4 cidr prefix to net mask :param prefix: cidr prefix , rang in (0, 32) :type prefix: int :return: dot separated ipv4 net mask code, eg: 255.255.255.0 :rtype: str """ if prefix > 32 or prefix < 0: raise ValueError("invalid cidr prefix for i...
[ "def", "ipv4_prefix_to_mask", "(", "prefix", ")", ":", "if", "prefix", ">", "32", "or", "prefix", "<", "0", ":", "raise", "ValueError", "(", "\"invalid cidr prefix for ipv4\"", ")", "else", ":", "mask", "=", "(", "(", "1", "<<", "32", ")", "-", "1", ")...
30.52381
14.333333
def focus_left(pymux): " Move focus to the left. " _move_focus(pymux, lambda wp: wp.xpos - 2, # 2 in order to skip over the border. lambda wp: wp.ypos)
[ "def", "focus_left", "(", "pymux", ")", ":", "_move_focus", "(", "pymux", ",", "lambda", "wp", ":", "wp", ".", "xpos", "-", "2", ",", "# 2 in order to skip over the border.", "lambda", "wp", ":", "wp", ".", "ypos", ")" ]
37.6
17.6
def mdct(x, L): """Modified Discrete Cosine Transform (MDCT) Returns the Modified Discrete Cosine Transform with fixed window size L of the signal x. The window is based on a sine window. Parameters ---------- x : ndarray, shape (N,) The signal L : int The window lengt...
[ "def", "mdct", "(", "x", ",", "L", ")", ":", "x", "=", "np", ".", "asarray", "(", "x", ",", "dtype", "=", "np", ".", "float", ")", "N", "=", "x", ".", "size", "# Number of frequency channels", "K", "=", "L", "//", "2", "# Test length", "if", "N",...
20.948718
21.217949
def update_redirect_to_from_json(page, redirect_to_complete_slugs): """ The second pass of create_and_update_from_json_data used to update the redirect_to field. Returns a messages list to be appended to the messages from the first pass. """ messages = [] s = '' for lang, s in list(...
[ "def", "update_redirect_to_from_json", "(", "page", ",", "redirect_to_complete_slugs", ")", ":", "messages", "=", "[", "]", "s", "=", "''", "for", "lang", ",", "s", "in", "list", "(", "redirect_to_complete_slugs", ".", "items", "(", ")", ")", ":", "r", "="...
31.05
20.05
def reduce_prod(attrs, inputs, proto_obj): """Reduce the array along a given axis by product value""" new_attrs = translation_utils._fix_attribute_names(attrs, {'axes':'axis'}) return 'prod', new_attrs, inputs
[ "def", "reduce_prod", "(", "attrs", ",", "inputs", ",", "proto_obj", ")", ":", "new_attrs", "=", "translation_utils", ".", "_fix_attribute_names", "(", "attrs", ",", "{", "'axes'", ":", "'axis'", "}", ")", "return", "'prod'", ",", "new_attrs", ",", "inputs" ...
54.5
11
def led(host, seq, anim, f, d): """ Control the drones LED. Parameters: seq -- sequence number anim -- Integer: animation to play f -- Float: frequency in HZ of the animation d -- Integer: total duration in seconds of the animation """ at(host, 'LED', seq, [anim, float(f), d])
[ "def", "led", "(", "host", ",", "seq", ",", "anim", ",", "f", ",", "d", ")", ":", "at", "(", "host", ",", "'LED'", ",", "seq", ",", "[", "anim", ",", "float", "(", "f", ")", ",", "d", "]", ")" ]
27.636364
12.363636
def roll_qtrday(other, n, month, day_option, modby=3): """Possibly increment or decrement the number of periods to shift based on rollforward/rollbackward conventions. Parameters ---------- other : cftime.datetime n : number of periods to increment, before adjusting for rolling month : int ...
[ "def", "roll_qtrday", "(", "other", ",", "n", ",", "month", ",", "day_option", ",", "modby", "=", "3", ")", ":", "months_since", "=", "other", ".", "month", "%", "modby", "-", "month", "%", "modby", "if", "n", ">", "0", ":", "if", "months_since", "...
32.487179
20.692308
def by_category(self): """Returns every :class:`CategoryChannel` and their associated channels. These channels and categories are sorted in the official Discord UI order. If the channels do not have a category, then the first element of the tuple is ``None``. Returns -...
[ "def", "by_category", "(", "self", ")", ":", "grouped", "=", "defaultdict", "(", "list", ")", "for", "channel", "in", "self", ".", "_channels", ".", "values", "(", ")", ":", "if", "isinstance", "(", "channel", ",", "CategoryChannel", ")", ":", "continue"...
34.866667
23.366667
def parse_data(self, logfile): """Parse data from data stream and replace object lines. :param logfile: [required] Log file data stream. :type logfile: str """ for line in logfile: stripped_line = line.strip() parsed_line = Line(stripped_line) ...
[ "def", "parse_data", "(", "self", ",", "logfile", ")", ":", "for", "line", "in", "logfile", ":", "stripped_line", "=", "line", ".", "strip", "(", ")", "parsed_line", "=", "Line", "(", "stripped_line", ")", "if", "parsed_line", ".", "valid", ":", "self", ...
33.5
17.0625
def update_settings(self): """After changing the settings, we need to recreate the whole image.""" self.display() self.display_markers() if self.parent.notes.annot is not None: self.parent.notes.display_notes()
[ "def", "update_settings", "(", "self", ")", ":", "self", ".", "display", "(", ")", "self", ".", "display_markers", "(", ")", "if", "self", ".", "parent", ".", "notes", ".", "annot", "is", "not", "None", ":", "self", ".", "parent", ".", "notes", ".", ...
41.5
9
def imeicsum(text): ''' Calculate the imei check byte. ''' digs = [] for i in range(14): v = int(text[i]) if i % 2: v *= 2 [digs.append(int(x)) for x in str(v)] chek = 0 valu = sum(digs) remd = valu % 10 if remd != 0: chek = 10 - remd ...
[ "def", "imeicsum", "(", "text", ")", ":", "digs", "=", "[", "]", "for", "i", "in", "range", "(", "14", ")", ":", "v", "=", "int", "(", "text", "[", "i", "]", ")", "if", "i", "%", "2", ":", "v", "*=", "2", "[", "digs", ".", "append", "(", ...
16
24.5
def disconnect(self, driver): """Disconnect from the console.""" self.log("TELNETCONSOLE disconnect") try: while self.device.mode != 'global': self.device.send('exit', timeout=10) except OSError: self.log("TELNETCONSOLE already disconnected") ...
[ "def", "disconnect", "(", "self", ",", "driver", ")", ":", "self", ".", "log", "(", "\"TELNETCONSOLE disconnect\"", ")", "try", ":", "while", "self", ".", "device", ".", "mode", "!=", "'global'", ":", "self", ".", "device", ".", "send", "(", "'exit'", ...
35.933333
15.8
def newDocProp(self, name, value): """Create a new property carried by a document. """ ret = libxml2mod.xmlNewDocProp(self._o, name, value) if ret is None:raise treeError('xmlNewDocProp() failed') __tmp = xmlAttr(_obj=ret) return __tmp
[ "def", "newDocProp", "(", "self", ",", "name", ",", "value", ")", ":", "ret", "=", "libxml2mod", ".", "xmlNewDocProp", "(", "self", ".", "_o", ",", "name", ",", "value", ")", "if", "ret", "is", "None", ":", "raise", "treeError", "(", "'xmlNewDocProp() ...
45
12.833333
def statistical_distances(samples1, samples2, earth_mover_dist=True, energy_dist=True): """Compute measures of the statistical distance between samples. Parameters ---------- samples1: 1d array samples2: 1d array earth_mover_dist: bool, optional Whether or not ...
[ "def", "statistical_distances", "(", "samples1", ",", "samples2", ",", "earth_mover_dist", "=", "True", ",", "energy_dist", "=", "True", ")", ":", "out", "=", "[", "]", "temp", "=", "scipy", ".", "stats", ".", "ks_2samp", "(", "samples1", ",", "samples2", ...
31.481481
20.777778
def _embedding_dim(vocab_size): """Calculate a reasonable embedding size for a vocabulary. Rule of thumb is 6 * 4th root of vocab_size. Args: vocab_size: Size of the input vocabulary. Returns: The embedding size to use. Raises: ValueError: if `vocab_size` is invalid. """ if not vocab_size or...
[ "def", "_embedding_dim", "(", "vocab_size", ")", ":", "if", "not", "vocab_size", "or", "(", "vocab_size", "<=", "0", ")", ":", "raise", "ValueError", "(", "\"Invalid vocab_size %g.\"", "%", "vocab_size", ")", "return", "int", "(", "round", "(", "6.0", "*", ...
29.666667
16.4
def getMember(self, address, id, headers=None, query_params=None, content_type="application/json"): """ Get network member settings It is method for GET /network/{id}/member/{address} """ uri = self.client.base_url + "/network/"+id+"/member/"+address return self.client.ge...
[ "def", "getMember", "(", "self", ",", "address", ",", "id", ",", "headers", "=", "None", ",", "query_params", "=", "None", ",", "content_type", "=", "\"application/json\"", ")", ":", "uri", "=", "self", ".", "client", ".", "base_url", "+", "\"/network/\"",...
51.857143
21.571429
def _choose_read_fs(authority, cache, read_path, version_check, hasher): ''' Context manager returning the appropriate up-to-date readable filesystem Use ``cache`` if it is a valid filessystem and has a file at ``read_path``, otherwise use ``authority``. If the file at ``read_path`` is out of date,...
[ "def", "_choose_read_fs", "(", "authority", ",", "cache", ",", "read_path", ",", "version_check", ",", "hasher", ")", ":", "if", "cache", "and", "cache", ".", "fs", ".", "isfile", "(", "read_path", ")", ":", "if", "version_check", "(", "hasher", "(", "ca...
31.875
23.5625
def get_segment(sla,N,last=True,mid=None,first=None,remove_edges=True,truncate_if_continents=True): ''' Intelligent segmentation of data. :keyword remove_edges: discard data at track edges. :keyword truncate_if_continents: Force truncating data if a continent is found within a segment of data....
[ "def", "get_segment", "(", "sla", ",", "N", ",", "last", "=", "True", ",", "mid", "=", "None", ",", "first", "=", "None", ",", "remove_edges", "=", "True", ",", "truncate_if_continents", "=", "True", ")", ":", "#Set defaults\r", "if", "first", "is", "n...
31.791209
21.747253
def _to_diagonally_dominant_weighted(mat): """Make matrix weighted diagonally dominant using the Laplacian.""" mat += np.diag(np.sum(np.abs(mat), axis=1) + 0.01) return mat
[ "def", "_to_diagonally_dominant_weighted", "(", "mat", ")", ":", "mat", "+=", "np", ".", "diag", "(", "np", ".", "sum", "(", "np", ".", "abs", "(", "mat", ")", ",", "axis", "=", "1", ")", "+", "0.01", ")", "return", "mat" ]
45.25
10.5
def fcs(args): """ %prog fcs fcsfile Process the results from Genbank contaminant screen. An example of the file looks like: contig name, length, span(s), apparent source contig0746 11760 1..141 vector contig0751 14226 13476..14226 vector contig0800 124133 30512...
[ "def", "fcs", "(", "args", ")", ":", "p", "=", "OptionParser", "(", "fcs", ".", "__doc__", ")", "p", ".", "add_option", "(", "\"--cutoff\"", ",", "default", "=", "200", ",", "help", "=", "\"Skip small components less than [default: %default]\"", ")", "opts", ...
28.156863
16.823529
def remove_get_department_uids(portal): """Removes getDepartmentUIDs indexes and metadata """ logger.info("Removing filtering by department ...") del_index(portal, "bika_catalog", "getDepartmentUIDs") del_index(portal, "bika_setup_catalog", "getDepartmentUID") del_index(portal, CATALOG_ANALYSIS_...
[ "def", "remove_get_department_uids", "(", "portal", ")", ":", "logger", ".", "info", "(", "\"Removing filtering by department ...\"", ")", "del_index", "(", "portal", ",", "\"bika_catalog\"", ",", "\"getDepartmentUIDs\"", ")", "del_index", "(", "portal", ",", "\"bika_...
54.461538
22.307692
def has_no_flat_neurites(neuron, tol=0.1, method='ratio'): '''Check that a neuron has no flat neurites Arguments: neuron(Neuron): The neuron object to test tol(float): tolerance method(string): way of determining flatness, 'tolerance', 'ratio' \ as described in :meth:`neurom.che...
[ "def", "has_no_flat_neurites", "(", "neuron", ",", "tol", "=", "0.1", ",", "method", "=", "'ratio'", ")", ":", "return", "CheckResult", "(", "len", "(", "get_flat_neurites", "(", "neuron", ",", "tol", ",", "method", ")", ")", "==", "0", ")" ]
35.846154
24.615385
def move_to_step(self, step): """ Use in cases when you need to move in given step depending on input """ if step not in self._scenario_steps.keys(): raise UndefinedState("step {} not defined in scenario".format(step)) try: session_id = session.sessionId ...
[ "def", "move_to_step", "(", "self", ",", "step", ")", ":", "if", "step", "not", "in", "self", ".", "_scenario_steps", ".", "keys", "(", ")", ":", "raise", "UndefinedState", "(", "\"step {} not defined in scenario\"", ".", "format", "(", "step", ")", ")", "...
41.083333
14.583333
def getGeometry(self,ra=None,dec=None): """Return an array of rectangles that represent the 'ra,dec' corners of the FOV""" import math,ephem ccds=[] if ra is None: ra=self.ra if dec is None: dec=self.dec self.ra=ephem.hours(ra) self.dec=e...
[ "def", "getGeometry", "(", "self", ",", "ra", "=", "None", ",", "dec", "=", "None", ")", ":", "import", "math", ",", "ephem", "ccds", "=", "[", "]", "if", "ra", "is", "None", ":", "ra", "=", "self", ".", "ra", "if", "dec", "is", "None", ":", ...
33.1
17.1
def set_or_reset_runtime_param(self, key, value): """Maintains the context of the runtime settings for invoking a command. This should be called by a click.option callback, and only called once for each setting for each command invocation. If the setting exists, it follows that...
[ "def", "set_or_reset_runtime_param", "(", "self", ",", "key", ",", "value", ")", ":", "if", "self", ".", "_runtime", ".", "has_option", "(", "'general'", ",", "key", ")", ":", "self", ".", "_runtime", "=", "self", ".", "_new_parser", "(", ")", "if", "v...
39.058824
20.117647
def get_story(self, id): """Fetches a single story by id. get /v1/public/stories/{storyId} :param id: ID of Story :type params: int :returns: StoryDataWrapper >>> m = Marvel(public_key, private_key) >>> response = m.get_story(29) >>> p...
[ "def", "get_story", "(", "self", ",", "id", ")", ":", "url", "=", "\"%s/%s\"", "%", "(", "Story", ".", "resource_url", "(", ")", ",", "id", ")", "response", "=", "json", ".", "loads", "(", "self", ".", "_call", "(", "url", ")", ".", "text", ")", ...
31.736842
17.684211
def create_app(self, args): """创建应用 在指定区域创建一个新应用,所属应用为当前请求方。 Args: - args: 请求参数(json),参考 http://kirk-docs.qiniu.com/apidocs/ Returns: - result 成功返回所创建的应用信息,若失败则返回None - ResponseInfo 请求的Response信息 """ url = '{0}/v3/apps'.form...
[ "def", "create_app", "(", "self", ",", "args", ")", ":", "url", "=", "'{0}/v3/apps'", ".", "format", "(", "self", ".", "host", ")", "return", "http", ".", "_post_with_qiniu_mac", "(", "url", ",", "args", ",", "self", ".", "auth", ")" ]
25.466667
20
def change_active_pointer_grab(self, event_mask, cursor, time, onerror = None): """Change the dynamic parameters of a pointer grab. See XChangeActivePointerGrab(3X11).""" request.ChangeActivePointerGrab(display = self.display, onerror = onerror, ...
[ "def", "change_active_pointer_grab", "(", "self", ",", "event_mask", ",", "cursor", ",", "time", ",", "onerror", "=", "None", ")", ":", "request", ".", "ChangeActivePointerGrab", "(", "display", "=", "self", ".", "display", ",", "onerror", "=", "onerror", ",...
59.625
16.5
def fallbacks(enable=True): """ Temporarily switch all language fallbacks on or off. Example: with fallbacks(False): lang_has_slug = bool(self.slug) May be used to enable fallbacks just when they're needed saving on some processing or check if there is a value for the current ...
[ "def", "fallbacks", "(", "enable", "=", "True", ")", ":", "current_enable_fallbacks", "=", "settings", ".", "ENABLE_FALLBACKS", "settings", ".", "ENABLE_FALLBACKS", "=", "enable", "try", ":", "yield", "finally", ":", "settings", ".", "ENABLE_FALLBACKS", "=", "cu...
28.526316
20.947368
def name(self): """ Returns name of the node so if its path then only last part is returned. """ org = safe_unicode(self.path.rstrip('/').split('/')[-1]) return u'%s @ %s' % (org, self.changeset.short_id)
[ "def", "name", "(", "self", ")", ":", "org", "=", "safe_unicode", "(", "self", ".", "path", ".", "rstrip", "(", "'/'", ")", ".", "split", "(", "'/'", ")", "[", "-", "1", "]", ")", "return", "u'%s @ %s'", "%", "(", "org", ",", "self", ".", "chan...
35.142857
10.571429
def model(self, autoGenerate=False): """ Returns the default Table class that is associated with this \ schema instance. :param autoGenerate | <bool> :return <subclass of Table> """ if self.__model is None and autoGenerate: s...
[ "def", "model", "(", "self", ",", "autoGenerate", "=", "False", ")", ":", "if", "self", ".", "__model", "is", "None", "and", "autoGenerate", ":", "self", ".", "__model", "=", "orb", ".", "system", ".", "generateModel", "(", "self", ")", "self", ".", ...
32.307692
12
def daemon_run(no_error, restart, record_path, keep_json, check_duplicate, use_polling, log_level): """ Run RASH index daemon. This daemon watches the directory ``~/.config/rash/data/record`` and translate the JSON files dumped by ``record`` command into sqlite3 DB at ``~/.config/ras...
[ "def", "daemon_run", "(", "no_error", ",", "restart", ",", "record_path", ",", "keep_json", ",", "check_duplicate", ",", "use_polling", ",", "log_level", ")", ":", "# Probably it makes sense to use this daemon to provide search", "# API, so that this daemon is going to be the o...
38.181818
19.568182
def AddTrainingOperators(model, softmax, label): """Adds training operators to the model.""" xent = model.LabelCrossEntropy([softmax, label], 'xent') # compute the expected loss loss = model.AveragedLoss(xent, "loss") # track the accuracy of the model AddAccuracy(model, softmax, label) # use...
[ "def", "AddTrainingOperators", "(", "model", ",", "softmax", ",", "label", ")", ":", "xent", "=", "model", ".", "LabelCrossEntropy", "(", "[", "softmax", ",", "label", "]", ",", "'xent'", ")", "# compute the expected loss", "loss", "=", "model", ".", "Averag...
49.84
16.92
def get(self, tag, default=None): """Get a metadata value. Each metadata value is referenced by a ``tag`` -- a short string such as ``'xlen'`` or ``'audit'``. In the sidecar file these tag names are prepended with ``'Xmp.pyctools.'``, which corresponds to a custom namespace in t...
[ "def", "get", "(", "self", ",", "tag", ",", "default", "=", "None", ")", ":", "full_tag", "=", "'Xmp.pyctools.'", "+", "tag", "if", "full_tag", "in", "self", ".", "data", ":", "return", "self", ".", "data", "[", "full_tag", "]", "return", "default" ]
31.526316
19.368421
def menu(self, venue_id, date): """Get the menu for the venue corresponding to venue_id, on date. :param venue_id: A string representing the id of a venue, e.g. "abc". :param date: A string representing the date of a venue's menu, e.g. "2015-09-20". >>> com...
[ "def", "menu", "(", "self", ",", "venue_id", ",", "date", ")", ":", "query", "=", "\"&date=\"", "+", "date", "response", "=", "self", ".", "_request", "(", "V2_ENDPOINTS", "[", "'MENUS'", "]", "+", "venue_id", "+", "query", ")", "return", "response" ]
32.666667
21.666667
def request_info_of_jids(self, peer_jids: Union[str, List[str]]): """ Requests basic information (username, display name, picture) of some peer JIDs. When the information arrives, the callback on_peer_info_received() will fire. :param peer_jids: The JID(s) for which to request the infor...
[ "def", "request_info_of_jids", "(", "self", ",", "peer_jids", ":", "Union", "[", "str", ",", "List", "[", "str", "]", "]", ")", ":", "return", "self", ".", "_send_xmpp_element", "(", "roster", ".", "BatchPeerInfoRequest", "(", "peer_jids", ")", ")" ]
60.777778
36.111111
def read_proximity(self, timeout_sec=1): """Read the sensor proximity and return it as an unsigned 16-bit value. The larger the value the closer an object is to the sensor. """ # Ask for a proximity measurement and wait for the response. self._device.write8(VCNL40xx_COMMAND, VCNL...
[ "def", "read_proximity", "(", "self", ",", "timeout_sec", "=", "1", ")", ":", "# Ask for a proximity measurement and wait for the response.", "self", ".", "_device", ".", "write8", "(", "VCNL40xx_COMMAND", ",", "VCNL40xx_MEASUREPROXIMITY", ")", "self", ".", "_wait_respo...
55.888889
14.777778
async def statistics(self, tube_name=None): """ Returns queue statistics (coroutine) :param tube_name: If specified, statistics by a specific tube is returned, else statistics about all tubes is returned """ args = None if tube_nam...
[ "async", "def", "statistics", "(", "self", ",", "tube_name", "=", "None", ")", ":", "args", "=", "None", "if", "tube_name", "is", "not", "None", ":", "args", "=", "(", "tube_name", ",", ")", "res", "=", "await", "self", ".", "_conn", ".", "call", "...
34.6875
16.9375
async def main(): redis = await create_pool(RedisSettings()) job = await redis.enqueue_job('the_task') # get the job's id print(job.job_id) """ > 68362958a244465b9be909db4b7b5ab4 (or whatever) """ # get information about the job, will include results if the job has finished, but ...
[ "async", "def", "main", "(", ")", ":", "redis", "=", "await", "create_pool", "(", "RedisSettings", "(", ")", ")", "job", "=", "await", "redis", ".", "enqueue_job", "(", "'the_task'", ")", "# get the job's id", "print", "(", "job", ".", "job_id", ")", "# ...
24.538462
17.410256
def guess_content_type(self, pathname): """Guess the content type for the given path. :param path: The path of file for which to guess the content type. :return: Returns the content type or ``None`` if the content type could not be determined. Usage:...
[ "def", "guess_content_type", "(", "self", ",", "pathname", ")", ":", "file_basename", "=", "os", ".", "path", ".", "basename", "(", "pathname", ")", "content_type", "=", "None", "# Try to determine from the path.", "if", "not", "content_type", "and", "self", "."...
42.632353
18.161765
def ensure_local_image( local_image: str, parent_image: str = SC_PARENT_IMAGE, java_image: str = SC_JAVA_IMAGE, starcraft_base_dir: str = SCBW_BASE_DIR, starcraft_binary_link: str = SC_BINARY_LINK, ) -> None: """ Check if `local_image` is present locally. If it is not, pu...
[ "def", "ensure_local_image", "(", "local_image", ":", "str", ",", "parent_image", ":", "str", "=", "SC_PARENT_IMAGE", ",", "java_image", ":", "str", "=", "SC_JAVA_IMAGE", ",", "starcraft_base_dir", ":", "str", "=", "SCBW_BASE_DIR", ",", "starcraft_binary_link", ":...
44.421053
22.105263
def _proxy(self): """ Generate an instance context for the instance, the context is capable of performing various actions. All instance actions are proxied to the context :returns: ExecutionStepContextContext for this ExecutionStepContextInstance :rtype: twilio.rest.studio.v1.f...
[ "def", "_proxy", "(", "self", ")", ":", "if", "self", ".", "_context", "is", "None", ":", "self", ".", "_context", "=", "ExecutionStepContextContext", "(", "self", ".", "_version", ",", "flow_sid", "=", "self", ".", "_solution", "[", "'flow_sid'", "]", "...
45.625
24.125
def append_cell_value(self, column_family_id, column, value): """Appends a value to an existing cell. .. note:: This method adds a read-modify rule protobuf to the accumulated read-modify rules on this row, but does not make an API request. To actually send an API r...
[ "def", "append_cell_value", "(", "self", ",", "column_family_id", ",", "column", ",", "value", ")", ":", "column", "=", "_to_bytes", "(", "column", ")", "value", "=", "_to_bytes", "(", "value", ")", "rule_pb", "=", "data_v2_pb2", ".", "ReadModifyWriteRule", ...
40.083333
23.25
def timed_call(self, ms, callback, *args, **kwargs): """ Invoke a callable on the main event loop thread at a specified time in the future. Parameters ---------- ms : int The time to delay, in milliseconds, before executing the callable. callback...
[ "def", "timed_call", "(", "self", ",", "ms", ",", "callback", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "loop", ".", "timed_call", "(", "ms", ",", "callback", ",", "*", "args", ",", "*", "*", "kwargs", ")" ]
30.894737
22.210526
def update_x(self, x, indices=None): """ Update partial or entire x. Args: x (numpy.ndarray or list): to-be-updated x indices (numpy.ndarray or list or optional): to-be-updated qubit indices Returns: Pauli: self Raises: QiskitErr...
[ "def", "update_x", "(", "self", ",", "x", ",", "indices", "=", "None", ")", ":", "x", "=", "_make_np_bool", "(", "x", ")", "if", "indices", "is", "None", ":", "if", "len", "(", "self", ".", "_x", ")", "!=", "len", "(", "x", ")", ":", "raise", ...
32.222222
21.333333
def CQO(cpu): """ RDX:RAX = sign-extend of RAX. """ res = Operators.SEXTEND(cpu.RAX, 64, 128) cpu.RAX = Operators.EXTRACT(res, 0, 64) cpu.RDX = Operators.EXTRACT(res, 64, 64)
[ "def", "CQO", "(", "cpu", ")", ":", "res", "=", "Operators", ".", "SEXTEND", "(", "cpu", ".", "RAX", ",", "64", ",", "128", ")", "cpu", ".", "RAX", "=", "Operators", ".", "EXTRACT", "(", "res", ",", "0", ",", "64", ")", "cpu", ".", "RDX", "="...
30.857143
7.714286
def listen(self): """Starts the listen loop. If threading is enabled, then the loop will be started in its own thread. Args: None Returns: None """ self.listening = True if self.threading: from threading import Thread ...
[ "def", "listen", "(", "self", ")", ":", "self", ".", "listening", "=", "True", "if", "self", ".", "threading", ":", "from", "threading", "import", "Thread", "self", ".", "listen_thread", "=", "Thread", "(", "target", "=", "self", ".", "listen_loop", ")",...
25.48
19.76
def _separate_objects_by_boxes(self, objects: Set[Object]) -> Dict[Box, List[Object]]: """ Given a set of objects, separate them by the boxes they belong to and return a dict. """ objects_per_box: Dict[Box, List[Object]] = defaultdict(list) for box in self.boxes: for ...
[ "def", "_separate_objects_by_boxes", "(", "self", ",", "objects", ":", "Set", "[", "Object", "]", ")", "->", "Dict", "[", "Box", ",", "List", "[", "Object", "]", "]", ":", "objects_per_box", ":", "Dict", "[", "Box", ",", "List", "[", "Object", "]", "...
46.1
16.9
def init_logging(logfile=None, loglevel=logging.INFO, configfile=None): """ Configures the logging using either basic filename + loglevel or passed config file path. This is performed separately from L{init_config()} in order to support the case where logging should happen independent of (usu. *after*...
[ "def", "init_logging", "(", "logfile", "=", "None", ",", "loglevel", "=", "logging", ".", "INFO", ",", "configfile", "=", "None", ")", ":", "# If a config file was specified, we will use that in place of the", "# explicitly", "use_configfile", "=", "False", "if", "con...
47.642857
30.785714
def wrap(access_pyxb, read_only=False): """Work with the AccessPolicy in a SystemMetadata PyXB object. Args: access_pyxb : AccessPolicy PyXB object The AccessPolicy to modify. read_only: bool Do not update the wrapped AccessPolicy. When only a single AccessPolicy operation is ...
[ "def", "wrap", "(", "access_pyxb", ",", "read_only", "=", "False", ")", ":", "w", "=", "AccessPolicyWrapper", "(", "access_pyxb", ")", "yield", "w", "if", "not", "read_only", ":", "w", ".", "get_normalized_pyxb", "(", ")" ]
29.333333
20.055556
def initPos(self, startpos=0.0): """ initialize the elements position [m] in lattice, the starting point is 0 [m] for the first element by default. :param startpos: starting point, 0 [m] by default """ spos = startpos for ele in self._lattice_eleobjlist: ...
[ "def", "initPos", "(", "self", ",", "startpos", "=", "0.0", ")", ":", "spos", "=", "startpos", "for", "ele", "in", "self", ".", "_lattice_eleobjlist", ":", "# print(\"{name:<10s}: {pos:<10.3f}\".format(name=ele.name, pos=spos))", "ele", ".", "setPosition", "(", "spo...
41.090909
14.727273
def annotate_snv(adpter, variant): """Annotate an SNV/INDEL variant Args: adapter(loqusdb.plugin.adapter) variant(cyvcf2.Variant) """ variant_id = get_variant_id(variant) variant_obj = adapter.get_variant(variant={'_id':variant_id}) annotated_variant = annotated_variant...
[ "def", "annotate_snv", "(", "adpter", ",", "variant", ")", ":", "variant_id", "=", "get_variant_id", "(", "variant", ")", "variant_obj", "=", "adapter", ".", "get_variant", "(", "variant", "=", "{", "'_id'", ":", "variant_id", "}", ")", "annotated_variant", ...
30
14.916667
def check_experiment_id(args): '''check if the id is valid ''' update_experiment() experiment_config = Experiments() experiment_dict = experiment_config.get_all_experiments() if not experiment_dict: print_normal('There is no experiment running...') return None if not args.id:...
[ "def", "check_experiment_id", "(", "args", ")", ":", "update_experiment", "(", ")", "experiment_config", "=", "Experiments", "(", ")", "experiment_dict", "=", "experiment_config", ".", "get_all_experiments", "(", ")", "if", "not", "experiment_dict", ":", "print_norm...
45.583333
20.75
def data_filler_detailed_registration(self, number_of_rows, db): '''creates and fills the table with detailed regis. information ''' try: detailed_registration = db data_list = list() for i in range(0, number_of_rows): post_det_reg = { ...
[ "def", "data_filler_detailed_registration", "(", "self", ",", "number_of_rows", ",", "db", ")", ":", "try", ":", "detailed_registration", "=", "db", "data_list", "=", "list", "(", ")", "for", "i", "in", "range", "(", "0", ",", "number_of_rows", ")", ":", "...
38.12
19.16
def historicalData(self, reqId, date, open, high, low, close, volume, barCount, WAP, hasGaps): """historicalData(EWrapper self, TickerId reqId, IBString const & date, double open, double high, double low, double close, int volume, int barCount, double WAP, int hasGaps)""" return _swigibpy.EWrapper_histo...
[ "def", "historicalData", "(", "self", ",", "reqId", ",", "date", ",", "open", ",", "high", ",", "low", ",", "close", ",", "volume", ",", "barCount", ",", "WAP", ",", "hasGaps", ")", ":", "return", "_swigibpy", ".", "EWrapper_historicalData", "(", "self",...
134
45.666667
def p_list_andnot(self, p): 'list : list ANDNOT list' p[0] = p[1].loc[set(p[1].index) - set(p[3].index)]
[ "def", "p_list_andnot", "(", "self", ",", "p", ")", ":", "p", "[", "0", "]", "=", "p", "[", "1", "]", ".", "loc", "[", "set", "(", "p", "[", "1", "]", ".", "index", ")", "-", "set", "(", "p", "[", "3", "]", ".", "index", ")", "]" ]
39.333333
12.666667
def layer_norm_compute(x, epsilon, scale, bias, layer_collection=None): """Layer norm raw computation.""" # Save these before they get converted to tensors by the casting below params = (scale, bias) epsilon, scale, bias = [cast_like(t, x) for t in [epsilon, scale, bias]] mean = tf.reduce_mean(x, axis=[-1],...
[ "def", "layer_norm_compute", "(", "x", ",", "epsilon", ",", "scale", ",", "bias", ",", "layer_collection", "=", "None", ")", ":", "# Save these before they get converted to tensors by the casting below", "params", "=", "(", "scale", ",", "bias", ")", "epsilon", ",",...
32.375
25.3125
def _reset(self, **kwargs): """ Reset after repopulating from API (or when initializing). """ # set object attributes from params for key in kwargs: setattr(self, key, kwargs[key]) # set defaults (if need be) where the default is not None for attr in ...
[ "def", "_reset", "(", "self", ",", "*", "*", "kwargs", ")", ":", "# set object attributes from params", "for", "key", "in", "kwargs", ":", "setattr", "(", "self", ",", "key", ",", "kwargs", "[", "key", "]", ")", "# set defaults (if need be) where the default is ...
38.5
15.166667
def column_family_name(cls, include_keyspace=True): """ Returns the column family name if it's been defined otherwise, it creates it from the module and class name """ cf_name = '' if cls.__table_name__: cf_name = cls.__table_name__.lower() else: ...
[ "def", "column_family_name", "(", "cls", ",", "include_keyspace", "=", "True", ")", ":", "cf_name", "=", "''", "if", "cls", ".", "__table_name__", ":", "cf_name", "=", "cls", ".", "__table_name__", ".", "lower", "(", ")", "else", ":", "# get polymorphic base...
45.173913
20.304348
def WriteTo(self, values): """Writes values to a byte stream. Args: values (tuple[object, ...]): values to copy to the byte stream. Returns: bytes: byte stream. Raises: IOError: if byte stream cannot be written. OSError: if byte stream cannot be read. """ try: re...
[ "def", "WriteTo", "(", "self", ",", "values", ")", ":", "try", ":", "return", "self", ".", "_struct", ".", "pack", "(", "*", "values", ")", "except", "(", "TypeError", ",", "struct", ".", "error", ")", "as", "exception", ":", "raise", "IOError", "(",...
26.555556
20.611111
def receive_connection(): """Wait for and then return a connected socket.. Opens a TCP connection on port 8080, and waits for a single client. """ server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) server.bind(("localhost", 8...
[ "def", "receive_connection", "(", ")", ":", "server", "=", "socket", ".", "socket", "(", "socket", ".", "AF_INET", ",", "socket", ".", "SOCK_STREAM", ")", "server", ".", "setsockopt", "(", "socket", ".", "SOL_SOCKET", ",", "socket", ".", "SO_REUSEADDR", ",...
31
19.230769
def hash(self): """Return an hash string computed on the PSF data.""" hash_list = [] for key, value in sorted(self.__dict__.items()): if not callable(value): if isinstance(value, np.ndarray): hash_list.append(value.tostring()) else:...
[ "def", "hash", "(", "self", ")", ":", "hash_list", "=", "[", "]", "for", "key", ",", "value", "in", "sorted", "(", "self", ".", "__dict__", ".", "items", "(", ")", ")", ":", "if", "not", "callable", "(", "value", ")", ":", "if", "isinstance", "("...
42.5
13.8
def get_rows(self, infer_nrows, skiprows=None): """ Read rows from self.f, skipping as specified. We distinguish buffer_rows (the first <= infer_nrows lines) from the rows returned to detect_colspecs because it's simpler to leave the other locations with skiprows logic a...
[ "def", "get_rows", "(", "self", ",", "infer_nrows", ",", "skiprows", "=", "None", ")", ":", "if", "skiprows", "is", "None", ":", "skiprows", "=", "set", "(", ")", "buffer_rows", "=", "[", "]", "detect_rows", "=", "[", "]", "for", "i", ",", "row", "...
30.675676
15.216216
def get_homogenous_list_type(list_): """ Returns the best matching python type even if it is an ndarray assumes all items in the list are of the same type. does not check this """ # TODO Expand and make work correctly if HAVE_NUMPY and isinstance(list_, np.ndarray): item = list_ elif...
[ "def", "get_homogenous_list_type", "(", "list_", ")", ":", "# TODO Expand and make work correctly", "if", "HAVE_NUMPY", "and", "isinstance", "(", "list_", ",", "np", ".", "ndarray", ")", ":", "item", "=", "list_", "elif", "isinstance", "(", "list_", ",", "list",...
27.807692
16.269231
def locked_coroutine(f): """ Method decorator that replace asyncio.coroutine that warranty that this specific method of this class instance will not we executed twice at the same time """ @asyncio.coroutine def new_function(*args, **kwargs): # In the instance of the class we will st...
[ "def", "locked_coroutine", "(", "f", ")", ":", "@", "asyncio", ".", "coroutine", "def", "new_function", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# In the instance of the class we will store", "# a lock has an attribute.", "lock_var_name", "=", "\"__\"",...
33.473684
16.315789
def cmd(send, msg, args): """Reports the difference between now and some specified time. Syntax: {command} <time> """ parser = arguments.ArgParser(args['config']) parser.add_argument('date', nargs='*', action=arguments.DateParser) try: cmdargs = parser.parse_args(msg) except argume...
[ "def", "cmd", "(", "send", ",", "msg", ",", "args", ")", ":", "parser", "=", "arguments", ".", "ArgParser", "(", "args", "[", "'config'", "]", ")", "parser", ".", "add_argument", "(", "'date'", ",", "nargs", "=", "'*'", ",", "action", "=", "arguments...
31.03125
16.5625
def remove_team(name, profile="github"): ''' Remove a github team. name The name of the team to be removed. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.remove_team 'team_name' ...
[ "def", "remove_team", "(", "name", ",", "profile", "=", "\"github\"", ")", ":", "team_info", "=", "get_team", "(", "name", ",", "profile", "=", "profile", ")", "if", "not", "team_info", ":", "log", ".", "error", "(", "'Team %s to be removed does not exist.'", ...
27.181818
22.393939