text
stringlengths
75
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
0.18
def _format_output(account, data): """Format data to get a readable output""" data['account'] = account output = ("""Ebox data for account: {d[account]} Balance ======= Balance: {d[balance]:.2f} $ Usage ===== Usage: {d[usage]:.2f} % Before offpeak ============== Download: {d[before_offpeak_down...
[ "def", "_format_output", "(", "account", ",", "data", ")", ":", "data", "[", "'account'", "]", "=", "account", "output", "=", "(", "\"\"\"Ebox data for account: {d[account]}\n\nBalance\n=======\nBalance: {d[balance]:.2f} $\n\nUsage\n=====\nUsage: {d[usage]:.2f} %\n\nBefor...
20.727273
0.001397
def _make_c_string(string): """Make a 'C' string.""" if isinstance(string, bytes): try: _utf_8_decode(string, None, True) return string + b"\x00" except UnicodeError: raise InvalidStringData("strings in documents must be valid " ...
[ "def", "_make_c_string", "(", "string", ")", ":", "if", "isinstance", "(", "string", ",", "bytes", ")", ":", "try", ":", "_utf_8_decode", "(", "string", ",", "None", ",", "True", ")", "return", "string", "+", "b\"\\x00\"", "except", "UnicodeError", ":", ...
36
0.002463
def applyVoucherCodesFinal(sender,**kwargs): ''' Once a registration has been completed, vouchers are used and referrers are awarded ''' logger.debug('Signal fired to mark voucher codes as applied.') finalReg = kwargs.pop('registration') tr = finalReg.temporaryRegistration tvus = ...
[ "def", "applyVoucherCodesFinal", "(", "sender", ",", "*", "*", "kwargs", ")", ":", "logger", ".", "debug", "(", "'Signal fired to mark voucher codes as applied.'", ")", "finalReg", "=", "kwargs", ".", "pop", "(", "'registration'", ")", "tr", "=", "finalReg", "."...
36.125
0.010118
def DumpAsCSV (self, separator=",", file=sys.stdout): """dump as a comma separated value file""" for row in range(1, self.maxRow + 1): sep = "" for column in range(1, self.maxColumn + 1): file.write("%s\...
[ "def", "DumpAsCSV", "(", "self", ",", "separator", "=", "\",\"", ",", "file", "=", "sys", ".", "stdout", ")", ":", "for", "row", "in", "range", "(", "1", ",", "self", ".", "maxRow", "+", "1", ")", ":", "sep", "=", "\"\"", "for", "column", "in", ...
56.875
0.012987
def cid(i): """ Input: { (repo_uoa) - repo UOA (module_uoa) - module UOA (data_uoa) - data UOA If above is empty, detect in current path ! } Output: { return - return code = 0, if successful ...
[ "def", "cid", "(", "i", ")", ":", "o", "=", "i", ".", "get", "(", "'out'", ",", "''", ")", "# Check which CID to detect", "ruoa", "=", "i", ".", "get", "(", "'repo_uoa'", ",", "''", ")", "muoa", "=", "i", ".", "get", "(", "'module_uoa'", ",", "''...
23.392157
0.025744
def r_sa_check(template, tag_type, is_standalone): """Do a final checkto see if a tag could be a standalone""" # Check right side if we might be a standalone if is_standalone and tag_type not in ['variable', 'no escape']: on_newline = template.split('\n', 1) # If the stuff to the right of ...
[ "def", "r_sa_check", "(", "template", ",", "tag_type", ",", "is_standalone", ")", ":", "# Check right side if we might be a standalone", "if", "is_standalone", "and", "tag_type", "not", "in", "[", "'variable'", ",", "'no escape'", "]", ":", "on_newline", "=", "templ...
33.25
0.001828
def hostname(hn, ft, si): """Check hostname, facter and systemid to get the fqdn, hostname and domain. Prefer hostname to facter and systemid. Returns: insights.combiners.hostname.Hostname: A named tuple with `fqdn`, `hostname` and `domain` components. Raises: Exception: If no...
[ "def", "hostname", "(", "hn", ",", "ft", ",", "si", ")", ":", "if", "not", "hn", "or", "not", "hn", ".", "fqdn", ":", "hn", "=", "ft", "if", "hn", "and", "hn", ".", "fqdn", ":", "fqdn", "=", "hn", ".", "fqdn", "hostname", "=", "hn", ".", "h...
31.448276
0.002128
def start_monitoring(self): """ Monitor IP addresses and send notifications if one of them has failed. This function will continuously monitor q_monitor_ips for new lists of IP addresses to monitor. Each message received there is the full state (the complete lists of addresses t...
[ "def", "start_monitoring", "(", "self", ")", ":", "time", ".", "sleep", "(", "1", ")", "# This is our working set. This list may be updated occasionally when", "# we receive messages on the q_monitor_ips queue. But irrespective of", "# any received updates, the list of IPs in here is reg...
48.115385
0.001566
def tremolo(self, speed=6.0, depth=40.0): '''Apply a tremolo (low frequency amplitude modulation) effect to the audio. The tremolo frequency in Hz is giv en by speed, and the depth as a percentage by depth (default 40). Parameters ---------- speed : float Tre...
[ "def", "tremolo", "(", "self", ",", "speed", "=", "6.0", ",", "depth", "=", "40.0", ")", ":", "if", "not", "is_number", "(", "speed", ")", "or", "speed", "<=", "0", ":", "raise", "ValueError", "(", "\"speed must be a positive number.\"", ")", "if", "not"...
27.589744
0.001795
def get_methods(self): """ Returns a list of `MethodClassAnalysis` objects """ for c in self.classes.values(): for m in c.get_methods(): yield m
[ "def", "get_methods", "(", "self", ")", ":", "for", "c", "in", "self", ".", "classes", ".", "values", "(", ")", ":", "for", "m", "in", "c", ".", "get_methods", "(", ")", ":", "yield", "m" ]
24.75
0.009756
def set_proto_message_event( pb_message_event, span_data_message_event): """Sets properties on the protobuf message event. :type pb_message_event: :class: `~opencensus.proto.trace.Span.TimeEvent.MessageEvent` :param pb_message_event: protobuf message event :type span_data_messa...
[ "def", "set_proto_message_event", "(", "pb_message_event", ",", "span_data_message_event", ")", ":", "pb_message_event", ".", "type", "=", "span_data_message_event", ".", "type", "pb_message_event", ".", "id", "=", "span_data_message_event", ".", "id", "pb_message_event",...
37.2
0.001311
def _get_env_bin_path(env_path): """Return the bin path for a virtualenv This provides a fallback for a situation in which you're trying to use the script and create a virtualenv from within a virtualenv in which virtualenv isn't installed and so is not importable. """ if IS_VIRTUALENV_INST...
[ "def", "_get_env_bin_path", "(", "env_path", ")", ":", "if", "IS_VIRTUALENV_INSTALLED", ":", "path", "=", "virtualenv", ".", "path_locations", "(", "env_path", ")", "[", "3", "]", "else", ":", "path", "=", "os", ".", "path", ".", "join", "(", "env_path", ...
36.846154
0.002037
def dump(obj, file, protocol=None, dump_code=False): """Serialize obj as bytes streamed into file protocol defaults to cloudpickle.DEFAULT_PROTOCOL which is an alias to pickle.HIGHEST_PROTOCOL. This setting favors maximum communication speed between processes running the same Python version. Set p...
[ "def", "dump", "(", "obj", ",", "file", ",", "protocol", "=", "None", ",", "dump_code", "=", "False", ")", ":", "CloudPickler", "(", "file", ",", "protocol", "=", "protocol", ",", "dump_code", "=", "dump_code", ")", ".", "dump", "(", "obj", ")" ]
45.545455
0.001957
def avail_images(call=None): ''' Return available Linode images. CLI Example: .. code-block:: bash salt-cloud --list-images my-linode-config salt-cloud -f avail_images my-linode-config ''' if call == 'action': raise SaltCloudException( 'The avail_images fun...
[ "def", "avail_images", "(", "call", "=", "None", ")", ":", "if", "call", "==", "'action'", ":", "raise", "SaltCloudException", "(", "'The avail_images function must be called with -f or --function.'", ")", "response", "=", "_query", "(", "'avail'", ",", "'distribution...
21.583333
0.001848
async def close(self): """ Closes connection and resets pool """ if self._pool is not None and not isinstance(self.connection, aioredis.Redis): self._pool.close() await self._pool.wait_closed() self._pool = None
[ "async", "def", "close", "(", "self", ")", ":", "if", "self", ".", "_pool", "is", "not", "None", "and", "not", "isinstance", "(", "self", ".", "connection", ",", "aioredis", ".", "Redis", ")", ":", "self", ".", "_pool", ".", "close", "(", ")", "awa...
33.5
0.010909
def capability_functions(self, fn): """This generator yields functions that match the requested capability sorted by z-index.""" if _debug: Collector._debug("capability_functions %r", fn) # build a list of functions to call fns = [] for cls in self.capabilities: ...
[ "def", "capability_functions", "(", "self", ",", "fn", ")", ":", "if", "_debug", ":", "Collector", ".", "_debug", "(", "\"capability_functions %r\"", ",", "fn", ")", "# build a list of functions to call", "fns", "=", "[", "]", "for", "cls", "in", "self", ".", ...
37.047619
0.010025
def renames(old, new): # type: (str, str) -> None """Like os.renames(), but handles renaming across devices.""" # Implementation borrowed from os.renames(). head, tail = os.path.split(new) if head and tail and not os.path.exists(head): os.makedirs(head) shutil.move(old, new) head, ...
[ "def", "renames", "(", "old", ",", "new", ")", ":", "# type: (str, str) -> None", "# Implementation borrowed from os.renames().", "head", ",", "tail", "=", "os", ".", "path", ".", "split", "(", "new", ")", "if", "head", "and", "tail", "and", "not", "os", "."...
27.375
0.002208
def run_example(): r""" Runs the example. """ weather = mc_e.get_weather_data('weather.csv') my_turbine, e126, dummy_turbine = mc_e.initialize_wind_turbines() example_farm, example_farm_2 = initialize_wind_farms(my_turbine, e126) example_cluster = initialize_wind_turbine_cluster(example_far...
[ "def", "run_example", "(", ")", ":", "weather", "=", "mc_e", ".", "get_weather_data", "(", "'weather.csv'", ")", "my_turbine", ",", "e126", ",", "dummy_turbine", "=", "mc_e", ".", "initialize_wind_turbines", "(", ")", "example_farm", ",", "example_farm_2", "=", ...
41.416667
0.001969
def write_screen(self, font, color, screen_pos, text, align="left", valign="top"): """Write to the screen in font.size relative coordinates.""" pos = point.Point(*screen_pos) * point.Point(0.75, 1) * font.get_linesize() text_surf = font.render(str(text), True, color) rect = text_surf....
[ "def", "write_screen", "(", "self", ",", "font", ",", "color", ",", "screen_pos", ",", "text", ",", "align", "=", "\"left\"", ",", "valign", "=", "\"top\"", ")", ":", "pos", "=", "point", ".", "Point", "(", "*", "screen_pos", ")", "*", "point", ".", ...
39.8
0.00982
def parse_net32string(self): """ >>> next(InBuffer(b"\\0\\0\\0\\x03eggs").parse_net32string()) == b'egg' True """ return parse_map(operator.itemgetter(1), parse_chain(self.parse_net32int, self.parse_fixedbuffer))
[ "def", "parse_net32string", "(", "self", ")", ":", "return", "parse_map", "(", "operator", ".", "itemgetter", "(", "1", ")", ",", "parse_chain", "(", "self", ".", "parse_net32int", ",", "self", ".", "parse_fixedbuffer", ")", ")" ]
36.166667
0.036036
def _add_timeout_handler(self, handler): """Add a TimeoutHandler to the pool. """ self.timeout_handlers.append(handler) if self.event_thread is None: return self._run_timeout_threads(handler)
[ "def", "_add_timeout_handler", "(", "self", ",", "handler", ")", ":", "self", ".", "timeout_handlers", ".", "append", "(", "handler", ")", "if", "self", ".", "event_thread", "is", "None", ":", "return", "self", ".", "_run_timeout_threads", "(", "handler", ")...
33.857143
0.00823
def get_pattern_step_time(self, patternnumber, stepnumber): """Get the step time. Args: * patternnumber (integer): 0-7 * stepnumber (integer): 0-7 Returns: The step time (int??). """ _checkPatternNumber(pa...
[ "def", "get_pattern_step_time", "(", "self", ",", "patternnumber", ",", "stepnumber", ")", ":", "_checkPatternNumber", "(", "patternnumber", ")", "_checkStepNumber", "(", "stepnumber", ")", "address", "=", "_calculateRegisterAddress", "(", "'time'", ",", "patternnumbe...
30.5
0.011928
def activations(self): """Loads sampled activations, which requires network access.""" if self._activations is None: self._activations = _get_aligned_activations(self) return self._activations
[ "def", "activations", "(", "self", ")", ":", "if", "self", ".", "_activations", "is", "None", ":", "self", ".", "_activations", "=", "_get_aligned_activations", "(", "self", ")", "return", "self", ".", "_activations" ]
41.2
0.009524
def _term_query(self, term, field_name, field_type, stemmed=True): """ Constructs a query of a single term. If `field_name` is not `None`, the term is search on that field only. If exact is `True`, the search is restricted to boolean matches. """ constructor = '{prefix}{...
[ "def", "_term_query", "(", "self", ",", "term", ",", "field_name", ",", "field_type", ",", "stemmed", "=", "True", ")", ":", "constructor", "=", "'{prefix}{term}'", "# construct the prefix to be used.", "prefix", "=", "''", "if", "field_name", ":", "prefix", "="...
40.6
0.001603
def max_sum(a): """ For an input array a, output the range that gives the largest sum >>> max_sum([4, 4, 9, -5, -6, -1, 5, -6, -8, 9]) (17, 0, 2) >>> max_sum([8, -10, 10, -9, -6, 9, -7, -4, -10, -8]) (10, 2, 2) >>> max_sum([10, 1, -10, -8, 6, 10, -10, 6, -3, 10]) (19, 4, 9) """ ...
[ "def", "max_sum", "(", "a", ")", ":", "max_sum", ",", "max_start_index", ",", "max_end_index", "=", "-", "Infinity", ",", "0", ",", "0", "current_max_sum", "=", "0", "current_start_index", "=", "0", "for", "current_end_index", ",", "x", "in", "enumerate", ...
32.76
0.001186
def message_with_options(self, *, args=None, kwargs=None, **options): """Build a message with an arbitray set of processing options. This method is useful if you want to compose actors. See the actor composition documentation for details. Parameters: args(tuple): Positional a...
[ "def", "message_with_options", "(", "self", ",", "*", ",", "args", "=", "None", ",", "kwargs", "=", "None", ",", "*", "*", "options", ")", ":", "for", "name", "in", "[", "\"on_failure\"", ",", "\"on_success\"", "]", ":", "callback", "=", "options", "."...
40.142857
0.001738
def build(self): """Build the full HTML source.""" if self.is_built(): # pragma: no cover return with _wait_signal(self.loadFinished, 20): self.rebuild() self._built = True
[ "def", "build", "(", "self", ")", ":", "if", "self", ".", "is_built", "(", ")", ":", "# pragma: no cover", "return", "with", "_wait_signal", "(", "self", ".", "loadFinished", ",", "20", ")", ":", "self", ".", "rebuild", "(", ")", "self", ".", "_built",...
31.857143
0.008734
def mapper(module, entry_point, modpath='pkg_resources', globber='root', modname='es6', fext=JS_EXT, registry=_utils): """ General mapper Loads components from the micro registry. """ modname_f = modname if callable(modname) else _utils['modname'][modname] return { ...
[ "def", "mapper", "(", "module", ",", "entry_point", ",", "modpath", "=", "'pkg_resources'", ",", "globber", "=", "'root'", ",", "modname", "=", "'es6'", ",", "fext", "=", "JS_EXT", ",", "registry", "=", "_utils", ")", ":", "modname_f", "=", "modname", "i...
30.444444
0.00177
def refresh(self): """Obtain a new personal-use script type access token.""" self._request_token( grant_type="password", username=self._username, password=self._password, )
[ "def", "refresh", "(", "self", ")", ":", "self", ".", "_request_token", "(", "grant_type", "=", "\"password\"", ",", "username", "=", "self", ".", "_username", ",", "password", "=", "self", ".", "_password", ",", ")" ]
32.285714
0.008621
def unformat_rule(celf, rule) : "converts a match rule string from the standard syntax to a dict of {key : value} entries." if isinstance(rule, dict) : pass elif isinstance(rule, str) : PARSE = celf.PARSE parsed = {} chars = iter(rule) ...
[ "def", "unformat_rule", "(", "celf", ",", "rule", ")", ":", "if", "isinstance", "(", "rule", ",", "dict", ")", ":", "pass", "elif", "isinstance", "(", "rule", ",", "str", ")", ":", "PARSE", "=", "celf", ".", "PARSE", "parsed", "=", "{", "}", "chars...
44.486726
0.01654
def export_private_key(self, password=None): """ Export a private key in PEM-format :param password: If it is not None, then result will be encrypt with given password :return: bytes """ if self.__private_key is None: raise ValueError('Unable to call this method. Private key must be set') if password ...
[ "def", "export_private_key", "(", "self", ",", "password", "=", "None", ")", ":", "if", "self", ".", "__private_key", "is", "None", ":", "raise", "ValueError", "(", "'Unable to call this method. Private key must be set'", ")", "if", "password", "is", "not", "None"...
34.391304
0.02706
def loadModelData(self,name): """ Loads the model data of the given name. The model file must always be a .json file. """ path = self.resourceNameToPath(name,".json") try: data = json.load(open(path,"r")) except Exception: # Tempor...
[ "def", "loadModelData", "(", "self", ",", "name", ")", ":", "path", "=", "self", ".", "resourceNameToPath", "(", "name", ",", "\".json\"", ")", "try", ":", "data", "=", "json", ".", "load", "(", "open", "(", "path", ",", "\"r\"", ")", ")", "except", ...
43.416667
0.027778
def isosurface(image, smoothing=0, threshold=None, connectivity=False): """Return a ``vtkActor`` isosurface extracted from a ``vtkImageData`` object. :param float smoothing: gaussian filter to smooth vtkImageData, in units of sigmas :param threshold: value or list of values to draw the isosurface(s) ...
[ "def", "isosurface", "(", "image", ",", "smoothing", "=", "0", ",", "threshold", "=", "None", ",", "connectivity", "=", "False", ")", ":", "if", "smoothing", ":", "smImg", "=", "vtk", ".", "vtkImageGaussianSmooth", "(", ")", "smImg", ".", "SetDimensionalit...
31.943396
0.002292
def setBackoffTiming(self, srcBaseReconnectTimeSecond, srcMaximumReconnectTimeSecond, srcMinimumConnectTimeSecond): """ Make custom settings for backoff timing for reconnect logic srcBaseReconnectTimeSecond - The base reconnection time in seconds srcMaximumReconnectTimeSecond - The maxim...
[ "def", "setBackoffTiming", "(", "self", ",", "srcBaseReconnectTimeSecond", ",", "srcMaximumReconnectTimeSecond", ",", "srcMinimumConnectTimeSecond", ")", ":", "self", ".", "_backoffCore", ".", "configTime", "(", "srcBaseReconnectTimeSecond", ",", "srcMaximumReconnectTimeSecon...
74.777778
0.008811
def get_format_spec(self): ''' The format specification according to the values of `align` and `width` ''' return u"{{:{align}{width}}}".format(align=self.align, width=self.width)
[ "def", "get_format_spec", "(", "self", ")", ":", "return", "u\"{{:{align}{width}}}\"", ".", "format", "(", "align", "=", "self", ".", "align", ",", "width", "=", "self", ".", "width", ")" ]
41.4
0.014218
def prompt_for_password(url, user=None, default_user=None): """Prompt for username and password. If a user name is passed, only prompt for a password. Args: url (str): hostname user (str, optional): Pass a valid name to skip prompting for a user name default_user (str, o...
[ "def", "prompt_for_password", "(", "url", ",", "user", "=", "None", ",", "default_user", "=", "None", ")", ":", "if", "user", "is", "None", ":", "default_user", "=", "default_user", "or", "getpass", ".", "getuser", "(", ")", "while", "user", "is", "None"...
33.451613
0.000937
def merge(cls, components): """Merges components into a single component, applying their actions appropriately. This operation is associative: M(M(a, b), c) == M(a, M(b, c)) == M(a, b, c). :param list components: an iterable of instances of DictValueComponent. :return: An instance representing the re...
[ "def", "merge", "(", "cls", ",", "components", ")", ":", "# Note that action of the merged component is EXTEND until the first REPLACE is encountered.", "# This guarantees associativity.", "action", "=", "cls", ".", "EXTEND", "val", "=", "{", "}", "for", "component", "in", ...
39.909091
0.008899
def join(self, join_streamlet, window_config, join_function): """Return a new Streamlet by joining join_streamlet with this streamlet """ from heronpy.streamlet.impl.joinbolt import JoinStreamlet, JoinBolt join_streamlet_result = JoinStreamlet(JoinBolt.INNER, window_config, ...
[ "def", "join", "(", "self", ",", "join_streamlet", ",", "window_config", ",", "join_function", ")", ":", "from", "heronpy", ".", "streamlet", ".", "impl", ".", "joinbolt", "import", "JoinStreamlet", ",", "JoinBolt", "join_streamlet_result", "=", "JoinStreamlet", ...
54.444444
0.002008
def replace(name, pattern, repl, count=0, flags=8, bufsize=1, append_if_not_found=False, prepend_if_not_found=False, not_found_content=None, backup='.bak', show_changes=True, ignore_if_mis...
[ "def", "replace", "(", "name", ",", "pattern", ",", "repl", ",", "count", "=", "0", ",", "flags", "=", "8", ",", "bufsize", "=", "1", ",", "append_if_not_found", "=", "False", ",", "prepend_if_not_found", "=", "False", ",", "not_found_content", "=", "Non...
36.316583
0.000269
def _recursive_remove_blank_dirs(self, path): """ Make sure, that blank directories are removed from the storage. Args: path (str): Path which you suspect that is blank. """ path = os.path.abspath(path) # never delete root of the storage or smaller paths ...
[ "def", "_recursive_remove_blank_dirs", "(", "self", ",", "path", ")", ":", "path", "=", "os", ".", "path", ".", "abspath", "(", "path", ")", "# never delete root of the storage or smaller paths", "if", "path", "==", "self", ".", "path", "or", "len", "(", "path...
30.266667
0.002134
def is_horz_aligned(c): """Return True if all the components of c are horizontally aligned. Horizontal alignment means that the bounding boxes of each Mention of c shares a similar y-axis value in the visual rendering of the document. :param c: The candidate to evaluate :rtype: boolean """ ...
[ "def", "is_horz_aligned", "(", "c", ")", ":", "return", "all", "(", "[", "_to_span", "(", "c", "[", "i", "]", ")", ".", "sentence", ".", "is_visual", "(", ")", "and", "bbox_horz_aligned", "(", "bbox_from_span", "(", "_to_span", "(", "c", "[", "i", "]...
30.666667
0.001757
def get(self): """Gets the next item from the queue. Returns a Future that resolves to the next item once it is available. """ io_loop = IOLoop.current() new_get = Future() with self._lock: get, self._get = self._get, new_get answer = Future() ...
[ "def", "get", "(", "self", ")", ":", "io_loop", "=", "IOLoop", ".", "current", "(", ")", "new_get", "=", "Future", "(", ")", "with", "self", ".", "_lock", ":", "get", ",", "self", ".", "_get", "=", "self", ".", "_get", ",", "new_get", "answer", "...
29.75
0.002035
def add_event(self, event): """ Add a new event and notify subscribers. event -- the event that occurred """ self.events.append(event) self.event_notify(event)
[ "def", "add_event", "(", "self", ",", "event", ")", ":", "self", ".", "events", ".", "append", "(", "event", ")", "self", ".", "event_notify", "(", "event", ")" ]
25.125
0.009615
def get_reward_and_done(board): """Given a representation of the board, returns reward and done.""" # Returns (reward, done) where: # reward: -1 means lost, +1 means win, 0 means draw or continuing. # done: True if the game is over, i.e. someone won or it is a draw. # Sum all rows ... all_sums = [np.sum(bo...
[ "def", "get_reward_and_done", "(", "board", ")", ":", "# Returns (reward, done) where:", "# reward: -1 means lost, +1 means win, 0 means draw or continuing.", "# done: True if the game is over, i.e. someone won or it is a draw.", "# Sum all rows ...", "all_sums", "=", "[", "np", ".", "...
28.44
0.023129
def create_table( data, meta=None, fields=None, skip_header=True, import_fields=None, samples=None, force_types=None, max_rows=None, *args, **kwargs ): """Create a rows.Table object based on data rows and some configurations - `skip_header` is only used if `fields` is se...
[ "def", "create_table", "(", "data", ",", "meta", "=", "None", ",", "fields", "=", "None", ",", "skip_header", "=", "True", ",", "import_fields", "=", "None", ",", "samples", "=", "None", ",", "force_types", "=", "None", ",", "max_rows", "=", "None", ",...
34.008696
0.000745
def average_price(quantity_1, price_1, quantity_2, price_2): """Calculates the average price between two asset states.""" return (quantity_1 * price_1 + quantity_2 * price_2) / \ (quantity_1 + quantity_2)
[ "def", "average_price", "(", "quantity_1", ",", "price_1", ",", "quantity_2", ",", "price_2", ")", ":", "return", "(", "quantity_1", "*", "price_1", "+", "quantity_2", "*", "price_2", ")", "/", "(", "quantity_1", "+", "quantity_2", ")" ]
55.25
0.008929
def _precision_recall_multi(y_true, y_score, ax=None): """ Plot precision-recall curve. Parameters ---------- y_true : array-like, shape = [n_samples, n_classes] Correct target values (ground truth). y_score : array-like, shape = [n_samples, n_classes] Target scores (estimator p...
[ "def", "_precision_recall_multi", "(", "y_true", ",", "y_score", ",", "ax", "=", "None", ")", ":", "# Compute micro-average ROC curve and ROC area", "precision", ",", "recall", ",", "_", "=", "precision_recall_curve", "(", "y_true", ".", "ravel", "(", ")", ",", ...
29.515152
0.000994
def find_best_string(query, corpus, step=4, flex=3, case_sensitive=False): """Return best matching substring of corpus. Parameters ---------- query : str corpus : str step : int Step size of first match-...
[ "def", "find_best_string", "(", "query", ",", "corpus", ",", "step", "=", "4", ",", "flex", "=", "3", ",", "case_sensitive", "=", "False", ")", ":", "def", "ratio", "(", "a", ",", "b", ")", ":", "\"\"\"Compact alias for SequenceMatcher.\"\"\"", "return", "...
29.042553
0.001063
def sanitize_http_wsgi_env(client, event): """ Sanitizes WSGI environment variables :param client: an ElasticAPM client :param event: a transaction or error event :return: The modified event """ try: env = event["context"]["request"]["env"] event["context"]["request"]["env"]...
[ "def", "sanitize_http_wsgi_env", "(", "client", ",", "event", ")", ":", "try", ":", "env", "=", "event", "[", "\"context\"", "]", "[", "\"request\"", "]", "[", "\"env\"", "]", "event", "[", "\"context\"", "]", "[", "\"request\"", "]", "[", "\"env\"", "]"...
28.285714
0.002445
def wait_ssh_open(server, port, keep_waiting=None, timeout=None): """ Wait for network service to appear @param server: host to connect to (str) @param port: port (int) @param timeout: in seconds, if None or 0 wait forever @return: True of False, if timeout is None may return only Tr...
[ "def", "wait_ssh_open", "(", "server", ",", "port", ",", "keep_waiting", "=", "None", ",", "timeout", "=", "None", ")", ":", "import", "socket", "import", "errno", "import", "time", "log", "=", "logging", ".", "getLogger", "(", "'wait_ssh_open'", ")", "sle...
33.850746
0.001285
def serialtoflat(self, bytes, width=None): """Convert serial format (byte stream) pixel data to flat row flat pixel. """ if self.bitdepth == 8: return bytes if self.bitdepth == 16: bytes = tostring(bytes) return array('H', struct...
[ "def", "serialtoflat", "(", "self", ",", "bytes", ",", "width", "=", "None", ")", ":", "if", "self", ".", "bitdepth", "==", "8", ":", "return", "bytes", "if", "self", ".", "bitdepth", "==", "16", ":", "bytes", "=", "tostring", "(", "bytes", ")", "r...
30.846154
0.010883
def render_template(template_name, context, format='png', output=None, using=None, **options): """ Render a template from django project, and return the file object of the result. """ # output stream, as required by casperjs_capture stream = BytesIO() out_f = None # t...
[ "def", "render_template", "(", "template_name", ",", "context", ",", "format", "=", "'png'", ",", "output", "=", "None", ",", "using", "=", "None", ",", "*", "*", "options", ")", ":", "# output stream, as required by casperjs_capture", "stream", "=", "BytesIO", ...
35.877193
0.000476
def make(parser): """ Ceph MON Daemon management """ parser.formatter_class = ToggleRawTextHelpFormatter mon_parser = parser.add_subparsers(dest='subcommand') mon_parser.required = True mon_add = mon_parser.add_parser( 'add', help=('R|Add a monitor to an existing cluster:\n...
[ "def", "make", "(", "parser", ")", ":", "parser", ".", "formatter_class", "=", "ToggleRawTextHelpFormatter", "mon_parser", "=", "parser", ".", "add_subparsers", "(", "dest", "=", "'subcommand'", ")", "mon_parser", ".", "required", "=", "True", "mon_add", "=", ...
30.2
0.001374
def get_all_current_trains(self, train_type=None, direction=None): """Returns all trains that are due to start in the next 10 minutes @param train_type: ['mainline', 'suburban', 'dart'] """ params = None if train_type: url = self.api_base_url + 'getCurrentTrainsXML_Wi...
[ "def", "get_all_current_trains", "(", "self", ",", "train_type", "=", "None", ",", "direction", "=", "None", ")", ":", "params", "=", "None", "if", "train_type", ":", "url", "=", "self", ".", "api_base_url", "+", "'getCurrentTrainsXML_WithTrainType'", "params", ...
32.6
0.002384
def spectral_centroid_and_spread(data, fs): """Computes spectral centroid of frame (given abs(FFT))""" data = np.mean(data, axis=1) nFFT = len(data) // 2 X = FFT(data, nFFT) ind = (np.arange(1, len(X) + 1)) * (fs / (2.0 * len(X))) Xt = X.copy() Xt = Xt / Xt.max() NUM = np.sum(ind * Xt...
[ "def", "spectral_centroid_and_spread", "(", "data", ",", "fs", ")", ":", "data", "=", "np", ".", "mean", "(", "data", ",", "axis", "=", "1", ")", "nFFT", "=", "len", "(", "data", ")", "//", "2", "X", "=", "FFT", "(", "data", ",", "nFFT", ")", "...
20.64
0.001852
def summarize_subgraph_edge_overlap(graph: BELGraph, annotation: str = 'Subgraph') -> Mapping[str, Mapping[str, float]]: """Return a similarity matrix between all subgraphs (or other given annotation). :param annotation: The annotation to group by and compare. Defaults to :code:`"Subgraph"` :return: A simi...
[ "def", "summarize_subgraph_edge_overlap", "(", "graph", ":", "BELGraph", ",", "annotation", ":", "str", "=", "'Subgraph'", ")", "->", "Mapping", "[", "str", ",", "Mapping", "[", "str", ",", "float", "]", "]", ":", "_", ",", "_", ",", "_", ",", "subgrap...
53.333333
0.010246
def collect_episodes(local_evaluator=None, remote_evaluators=[], timeout_seconds=180): """Gathers new episodes metrics tuples from the given evaluators.""" pending = [ a.apply.remote(lambda ev: ev.get_metrics()) for a in remote_evaluators ] collected, _...
[ "def", "collect_episodes", "(", "local_evaluator", "=", "None", ",", "remote_evaluators", "=", "[", "]", ",", "timeout_seconds", "=", "180", ")", ":", "pending", "=", "[", "a", ".", "apply", ".", "remote", "(", "lambda", "ev", ":", "ev", ".", "get_metric...
39.695652
0.00107
def cublasSsymm(handle, side, uplo, m, n, alpha, A, lda, B, ldb, beta, C, ldc): """ Matrix-matrix product for symmetric matrix. """ status = _libcublas.cublasSsymm_v2(handle, _CUBLAS_SIDE_MODE[side], _CUBLAS_FILL_MODE[u...
[ "def", "cublasSsymm", "(", "handle", ",", "side", ",", "uplo", ",", "m", ",", "n", ",", "alpha", ",", "A", ",", "lda", ",", "B", ",", "ldb", ",", "beta", ",", "C", ",", "ldc", ")", ":", "status", "=", "_libcublas", ".", "cublasSsymm_v2", "(", "...
44.214286
0.011076
def _VarintBytes(value): """Encode the given integer as a varint and return the bytes. This is only called at startup time so it doesn't need to be fast.""" pieces = [] _EncodeVarint(pieces.append, value) return b"".join(pieces)
[ "def", "_VarintBytes", "(", "value", ")", ":", "pieces", "=", "[", "]", "_EncodeVarint", "(", "pieces", ".", "append", ",", "value", ")", "return", "b\"\"", ".", "join", "(", "pieces", ")" ]
33.428571
0.020833
def to_genshi(walker): """Convert a tree to a genshi tree :arg walker: the treewalker to use to walk the tree to convert it :returns: generator of genshi nodes """ text = [] for token in walker: type = token["type"] if type in ("Characters", "SpaceCharacters"): tex...
[ "def", "to_genshi", "(", "walker", ")", ":", "text", "=", "[", "]", "for", "token", "in", "walker", ":", "type", "=", "token", "[", "\"type\"", "]", "if", "type", "in", "(", "\"Characters\"", ",", "\"SpaceCharacters\"", ")", ":", "text", ".", "append",...
31.270833
0.001292
def _table_attrs(table): ''' Helper function to find valid table attributes ''' cmd = ['osqueryi'] + ['--json'] + ['pragma table_info({0})'.format(table)] res = __salt__['cmd.run_all'](cmd) if res['retcode'] == 0: attrs = [] text = salt.utils.json.loads(res['stdout']) for...
[ "def", "_table_attrs", "(", "table", ")", ":", "cmd", "=", "[", "'osqueryi'", "]", "+", "[", "'--json'", "]", "+", "[", "'pragma table_info({0})'", ".", "format", "(", "table", ")", "]", "res", "=", "__salt__", "[", "'cmd.run_all'", "]", "(", "cmd", ")...
30.692308
0.002433
def batch_filter(x, P, zs, Fs, Qs, Hs, Rs, Bs=None, us=None, update_first=False, saver=None): """ Batch processes a sequences of measurements. Parameters ---------- zs : list-like list of measurements at each time step. Missing measurements must be represented by N...
[ "def", "batch_filter", "(", "x", ",", "P", ",", "zs", ",", "Fs", ",", "Qs", ",", "Hs", ",", "Rs", ",", "Bs", "=", "None", ",", "us", "=", "None", ",", "update_first", "=", "False", ",", "saver", "=", "None", ")", ":", "n", "=", "np", ".", "...
30.824
0.000754
def _parse_version(self, value): """Parses `version` option value. :param value: :rtype: str """ version = self._parse_file(value) if version != value: version = version.strip() # Be strict about versions loaded from file because it's easy to ...
[ "def", "_parse_version", "(", "self", ",", "value", ")", ":", "version", "=", "self", ".", "_parse_file", "(", "value", ")", "if", "version", "!=", "value", ":", "version", "=", "version", ".", "strip", "(", ")", "# Be strict about versions loaded from file be...
30.117647
0.001892
def association_rules(self): """ Returns association rules that were generated. Only if implements AssociationRulesProducer. :return: the association rules that were generated :rtype: AssociationRules """ if not self.check_type(self.jobject, "weka.associations.Associatio...
[ "def", "association_rules", "(", "self", ")", ":", "if", "not", "self", ".", "check_type", "(", "self", ".", "jobject", ",", "\"weka.associations.AssociationRulesProducer\"", ")", ":", "return", "None", "return", "AssociationRules", "(", "javabridge", ".", "call",...
44.727273
0.00996
def _add_edges(self, ast_node, trunk=None): """"Add all bonds in the SMARTS string as edges in the graph.""" atom_indices = self._atom_indices for atom in ast_node.tail: if atom.head == 'atom': atom_idx = atom_indices[id(atom)] if atom.is_first_kid and...
[ "def", "_add_edges", "(", "self", ",", "ast_node", ",", "trunk", "=", "None", ")", ":", "atom_indices", "=", "self", ".", "_atom_indices", "for", "atom", "in", "ast_node", ".", "tail", ":", "if", "atom", ".", "head", "==", "'atom'", ":", "atom_idx", "=...
49.105263
0.002103
def start_mon_service(distro, cluster, hostname): """ start mon service depending on distro init """ if distro.init == 'sysvinit': service = distro.conn.remote_module.which_service() remoto.process.run( distro.conn, [ service, 'ceph...
[ "def", "start_mon_service", "(", "distro", ",", "cluster", ",", "hostname", ")", ":", "if", "distro", ".", "init", "==", "'sysvinit'", ":", "service", "=", "distro", ".", "conn", ".", "remote_module", ".", "which_service", "(", ")", "remoto", ".", "process...
26.75
0.001127
def compute_fitness_cdf(chromosomes, ga): """ Return a list of fitness-weighted cumulative probabilities for a set of chromosomes. chromosomes: chromosomes to use for fitness-based calculations ga: ``algorithms.BaseGeneticAlgorithm`` used to obtain fitness values using its ``eval_fitness`` method...
[ "def", "compute_fitness_cdf", "(", "chromosomes", ",", "ga", ")", ":", "ga", ".", "sort", "(", "chromosomes", ")", "fitness", "=", "[", "ga", ".", "eval_fitness", "(", "c", ")", "for", "c", "in", "chromosomes", "]", "min_fit", "=", "min", "(", "fitness...
36.761905
0.010101
def ensure_float(arr): """ Ensure that an array object has a float dtype if possible. Parameters ---------- arr : array-like The array whose data type we want to enforce as float. Returns ------- float_arr : The original array cast to the float dtype if possible...
[ "def", "ensure_float", "(", "arr", ")", ":", "if", "issubclass", "(", "arr", ".", "dtype", ".", "type", ",", "(", "np", ".", "integer", ",", "np", ".", "bool_", ")", ")", ":", "arr", "=", "arr", ".", "astype", "(", "float", ")", "return", "arr" ]
25.666667
0.002088
def precision_at_k( model, test_interactions, train_interactions=None, k=10, user_features=None, item_features=None, preserve_rows=False, num_threads=1, check_intersections=True, ): """ Measure the precision at k metric for a model: the fraction of known positives in the ...
[ "def", "precision_at_k", "(", "model", ",", "test_interactions", ",", "train_interactions", "=", "None", ",", "k", "=", "10", ",", "user_features", "=", "None", ",", "item_features", "=", "None", ",", "preserve_rows", "=", "False", ",", "num_threads", "=", "...
37.378378
0.002113
def toSet(self, flags): """ Generates a flag value based on the given set of values. :param values: <set> :return: <int> """ return {key for key, value in self.items() if value & flags}
[ "def", "toSet", "(", "self", ",", "flags", ")", ":", "return", "{", "key", "for", "key", ",", "value", "in", "self", ".", "items", "(", ")", "if", "value", "&", "flags", "}" ]
25.222222
0.008511
def json2table(json): """This does format a dictionary into a table. Note this expects a dictionary (not a json string!) :param json: :return: """ filter_terms = ['ResponseMetadata'] table = [] try: for k in filter(lambda k: k not in filter_terms, json.keys()): table...
[ "def", "json2table", "(", "json", ")", ":", "filter_terms", "=", "[", "'ResponseMetadata'", "]", "table", "=", "[", "]", "try", ":", "for", "k", "in", "filter", "(", "lambda", "k", ":", "k", "not", "in", "filter_terms", ",", "json", ".", "keys", "(",...
29.789474
0.001712
def _ostaunicode(src): # type: (str) -> bytes ''' Internal function to create an OSTA byte string from a source string. ''' if have_py_3: bytename = src else: bytename = src.decode('utf-8') # type: ignore try: enc = bytename.encode('latin-1') encbyte = b'\x0...
[ "def", "_ostaunicode", "(", "src", ")", ":", "# type: (str) -> bytes", "if", "have_py_3", ":", "bytename", "=", "src", "else", ":", "bytename", "=", "src", ".", "decode", "(", "'utf-8'", ")", "# type: ignore", "try", ":", "enc", "=", "bytename", ".", "enco...
26.647059
0.002132
def drip(): """Drips data over a duration after an optional initial delay. --- tags: - Dynamic data parameters: - in: query name: duration type: number description: The amount of time (in seconds) over which to drip each byte default: 2 required: false...
[ "def", "drip", "(", ")", ":", "args", "=", "CaseInsensitiveDict", "(", "request", ".", "args", ".", "items", "(", ")", ")", "duration", "=", "float", "(", "args", ".", "get", "(", "\"duration\"", ",", "2", ")", ")", "numbytes", "=", "min", "(", "in...
25.522388
0.001689
def _get_roots(self): """ Return URL roots for this storage. Returns: tuple of str or re.Pattern: URL roots """ region = self._get_session().region_name or r'[\w-]+' return ( # S3 scheme # - s3://<bucket>/<key> ...
[ "def", "_get_roots", "(", "self", ")", ":", "region", "=", "self", ".", "_get_session", "(", ")", ".", "region_name", "or", "r'[\\w-]+'", "return", "(", "# S3 scheme", "# - s3://<bucket>/<key>", "'s3://'", ",", "# Virtual-hosted–style URL", "# - http://<bucket>.s3.ama...
43.875
0.001115
def dedent(string, indent_str=' ', max_levels=None): """Revert the effect of indentation. Examples -------- Remove a simple one-level indentation: >>> text = '''<->This is line 1. ... <->Next line. ... <->And another one.''' >>> print(text) <->This is line 1. <->Next line. ...
[ "def", "dedent", "(", "string", ",", "indent_str", "=", "' '", ",", "max_levels", "=", "None", ")", ":", "if", "len", "(", "indent_str", ")", "==", "0", ":", "return", "string", "lines", "=", "string", ".", "splitlines", "(", ")", "# Determine common (...
23.357143
0.000587
def get_distance_coefficients(self, C, imt): """ Returns the c3 term """ c3 = self.c3[imt]["c3"] if self.c3 else C["c3"] return c3
[ "def", "get_distance_coefficients", "(", "self", ",", "C", ",", "imt", ")", ":", "c3", "=", "self", ".", "c3", "[", "imt", "]", "[", "\"c3\"", "]", "if", "self", ".", "c3", "else", "C", "[", "\"c3\"", "]", "return", "c3" ]
27.5
0.011765
def transfer(self, data, assert_ss=True, deassert_ss=True): """Full-duplex SPI read and write. If assert_ss is true, the SS line will be asserted low, the specified bytes will be clocked out the MOSI line while bytes will also be read from the MISO line, and if deassert_ss is true the S...
[ "def", "transfer", "(", "self", ",", "data", ",", "assert_ss", "=", "True", ",", "deassert_ss", "=", "True", ")", ":", "if", "self", ".", "_mosi", "is", "None", ":", "raise", "RuntimeError", "(", "'Write attempted with no MOSI pin specified.'", ")", "if", "s...
50.840909
0.000877
def patched_function(self, *args, **kwargs): """ Step 3. Wrapped function calling. """ self.validate(*args, **kwargs) return self.function(*args, **kwargs)
[ "def", "patched_function", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "self", ".", "validate", "(", "*", "args", ",", "*", "*", "kwargs", ")", "return", "self", ".", "function", "(", "*", "args", ",", "*", "*", "kwargs", ")...
31.666667
0.010256
def lemmatise_multiple(self, string, pos=False, get_lemma_object=False, as_list=True): """ Lemmatise une liste complète :param string: Chaîne à lemmatiser :param pos: Récupère la POS :param get_lemma_object: Retrieve Lemma object instead of string representation of lemma :param ...
[ "def", "lemmatise_multiple", "(", "self", ",", "string", ",", "pos", "=", "False", ",", "get_lemma_object", "=", "False", ",", "as_list", "=", "True", ")", ":", "mots", "=", "SPACES", ".", "split", "(", "string", ")", "resultats", "=", "[", "self", "."...
48.846154
0.009274
def subscribe_to_candles(self, pair, timeframe=None, **kwargs): """Subscribe to the passed pair's OHLC data channel. :param pair: str, Symbol pair to request data for :param timeframe: str, {1m, 5m, 15m, 30m, 1h, 3h, 6h, 12h, 1D, 7D, 14D, 1M} :param kwarg...
[ "def", "subscribe_to_candles", "(", "self", ",", "pair", ",", "timeframe", "=", "None", ",", "*", "*", "kwargs", ")", ":", "valid_tfs", "=", "[", "'1m'", ",", "'5m'", ",", "'15m'", ",", "'30m'", ",", "'1h'", ",", "'3h'", ",", "'6h'", ",", "'12h'", ...
41.047619
0.002268
def connection_made(self, transport): """ On socket creation """ self.transport = transport sock = transport.get_extra_info("socket") self.port = sock.getsockname()[1]
[ "def", "connection_made", "(", "self", ",", "transport", ")", ":", "self", ".", "transport", "=", "transport", "sock", "=", "transport", ".", "get_extra_info", "(", "\"socket\"", ")", "self", ".", "port", "=", "sock", ".", "getsockname", "(", ")", "[", "...
32.5
0.01
def inference(self, kern, X, likelihood, Y, Y_metadata=None): """ Returns a GridPosterior class containing essential quantities of the posterior """ N = X.shape[0] #number of training points D = X.shape[1] #number of dimensions Kds = np.zeros(D, dtype=object) #vector fo...
[ "def", "inference", "(", "self", ",", "kern", ",", "X", ",", "likelihood", ",", "Y", ",", "Y_metadata", "=", "None", ")", ":", "N", "=", "X", ".", "shape", "[", "0", "]", "#number of training points", "D", "=", "X", ".", "shape", "[", "1", "]", "...
43.8
0.014428
def from_dict(name, values): ''' Convert a dictionary of configuration values into a sequence of BlockadeContainerConfig instances ''' # determine the number of instances of this container count = 1 count_value = values.get('count', 1) if isinstance(count...
[ "def", "from_dict", "(", "name", ",", "values", ")", ":", "# determine the number of instances of this container", "count", "=", "1", "count_value", "=", "values", ".", "get", "(", "'count'", ",", "1", ")", "if", "isinstance", "(", "count_value", ",", "int", "...
36.707317
0.001294
def check_version_info(conn, version_table, expected_version): """ Checks for a version value in the version table. Parameters ---------- conn : sa.Connection The connection to use to perform the check. version_table : sa.Table The version table of the asset database expecte...
[ "def", "check_version_info", "(", "conn", ",", "version_table", ",", "expected_version", ")", ":", "# Read the version out of the table", "version_from_table", "=", "conn", ".", "execute", "(", "sa", ".", "select", "(", "(", "version_table", ".", "c", ".", "versio...
30.40625
0.000996
def organize_objects(self): """Organize objects and namespaces""" def _render_children(obj): for child in obj.children_strings: child_object = self.objects.get(child) if child_object: obj.item_map[child_object.plural].append(child_object) ...
[ "def", "organize_objects", "(", "self", ")", ":", "def", "_render_children", "(", "obj", ")", ":", "for", "child", "in", "obj", ".", "children_strings", ":", "child_object", "=", "self", ".", "objects", ".", "get", "(", "child", ")", "if", "child_object", ...
36.769231
0.001359
def run_migration(data, version_start, version_end): """Runs migration against a data set.""" items = [] if version_start == 1 and version_end == 2: for item in data['accounts']: items.append(v2.upgrade(item)) if version_start == 2 and version_end == 1: for item in data: ...
[ "def", "run_migration", "(", "data", ",", "version_start", ",", "version_end", ")", ":", "items", "=", "[", "]", "if", "version_start", "==", "1", "and", "version_end", "==", "2", ":", "for", "item", "in", "data", "[", "'accounts'", "]", ":", "items", ...
33.583333
0.002415
async def create_websocket(url: str, ssl: Optional[SSLContext] = None, headers: Optional[list] = None, subprotocols: Optional[list] = None): """ A more low-level form of open_websocket. You are responsible for closing this webs...
[ "async", "def", "create_websocket", "(", "url", ":", "str", ",", "ssl", ":", "Optional", "[", "SSLContext", "]", "=", "None", ",", "headers", ":", "Optional", "[", "list", "]", "=", "None", ",", "subprotocols", ":", "Optional", "[", "list", "]", "=", ...
30.642857
0.00113
def run(file_path,include_dirs=[],dlems=False,nogui=False): """ Function for running from a script or shell. """ import argparse args = argparse.Namespace() args.lems_file = file_path args.I = include_dirs args.dlems = dlems args.nogui = nogui main(args=args)
[ "def", "run", "(", "file_path", ",", "include_dirs", "=", "[", "]", ",", "dlems", "=", "False", ",", "nogui", "=", "False", ")", ":", "import", "argparse", "args", "=", "argparse", ".", "Namespace", "(", ")", "args", ".", "lems_file", "=", "file_path",...
26.272727
0.016722
def tasks(self, path, postmap=None, **params): """ Return the task status. This delves into the operating structures and picks out information about tasks that is useful for status monitoring. For each task, the response includes: control - The active task control ...
[ "def", "tasks", "(", "self", ",", "path", ",", "postmap", "=", "None", ",", "*", "*", "params", ")", ":", "q", "=", "httpd", ".", "merge_query", "(", "path", ",", "postmap", ")", "ans", "=", "{", "}", "for", "name", ",", "tinfo", "in", "self", ...
44.661538
0.001348
def siret_validator(): """Validate a SIRET: check its length (14), its final code, and pass it through the Luhn algorithm.""" def _validate_siret(form, field, siret=""): """SIRET validator. A WTForm validator wants a form and a field as parameters. We also want to give directly a s...
[ "def", "siret_validator", "(", ")", ":", "def", "_validate_siret", "(", "form", ",", "field", ",", "siret", "=", "\"\"", ")", ":", "\"\"\"SIRET validator.\n\n A WTForm validator wants a form and a field as parameters. We\n also want to give directly a siret, for a scr...
35
0.000842
def _with_ast_loc(f): """Wrap a generator function in a decorator to supply line and column information to the returned Python AST node. Dependency nodes will not be hydrated, functions whose returns need dependency nodes to be hydrated should use `_with_ast_loc_deps` below.""" @wraps(f) def wi...
[ "def", "_with_ast_loc", "(", "f", ")", ":", "@", "wraps", "(", "f", ")", "def", "with_lineno_and_col", "(", "ctx", ":", "GeneratorContext", ",", "node", ":", "Node", ",", "*", "args", ",", "*", "*", "kwargs", ")", "->", "GeneratedPyAST", ":", "py_ast",...
38.214286
0.001825
def _get_size_recursive(self, dat): """ recursively walk through a data set or json file to get the total number of nodes """ self.total_records += 1 #self.total_nodes += 1 for rec in dat: if hasattr(rec, '__iter__') and type(rec) is not str: ...
[ "def", "_get_size_recursive", "(", "self", ",", "dat", ")", ":", "self", ".", "total_records", "+=", "1", "#self.total_nodes += 1", "for", "rec", "in", "dat", ":", "if", "hasattr", "(", "rec", ",", "'__iter__'", ")", "and", "type", "(", "rec", ")", "is",...
34.769231
0.008621
def feed_data(self, data_loader, training=True): """ Runs training or validation on batches from data_loader. :param data_loader: data loader :param training: if True runs training else runs validation """ if training: assert self.optimizer is not None ...
[ "def", "feed_data", "(", "self", ",", "data_loader", ",", "training", "=", "True", ")", ":", "if", "training", ":", "assert", "self", ".", "optimizer", "is", "not", "None", "eval_fractions", "=", "np", ".", "linspace", "(", "0", ",", "1", ",", "self", ...
41.584158
0.00186
def deploy_sandbox_shared_setup(log, verbose=True, app=None, exp_config=None): """Set up Git, push to Heroku, and launch the app.""" if verbose: out = None else: out = open(os.devnull, "w") config = get_config() if not config.ready: config.load() heroku.sanity_check(conf...
[ "def", "deploy_sandbox_shared_setup", "(", "log", ",", "verbose", "=", "True", ",", "app", "=", "None", ",", "exp_config", "=", "None", ")", ":", "if", "verbose", ":", "out", "=", "None", "else", ":", "out", "=", "open", "(", "os", ".", "devnull", ",...
31.88
0.001217
def issues_closed_since(period=timedelta(days=365), project="arokem/python-matlab-bridge", pulls=False): """Get all issues closed since a particular point in time. period can either be a datetime object, or a timedelta object. In the latter case, it is used as a time before the present. """ which =...
[ "def", "issues_closed_since", "(", "period", "=", "timedelta", "(", "days", "=", "365", ")", ",", "project", "=", "\"arokem/python-matlab-bridge\"", ",", "pulls", "=", "False", ")", ":", "which", "=", "'pulls'", "if", "pulls", "else", "'issues'", "if", "isin...
45.541667
0.013441
def DeleteAllItems(self): "Remove all the item from the list and unset the related data" self._py_data_map.clear() self._wx_data_map.clear() wx.ListCtrl.DeleteAllItems(self)
[ "def", "DeleteAllItems", "(", "self", ")", ":", "self", ".", "_py_data_map", ".", "clear", "(", ")", "self", ".", "_wx_data_map", ".", "clear", "(", ")", "wx", ".", "ListCtrl", ".", "DeleteAllItems", "(", "self", ")" ]
41
0.009569
def setShowLanguage(self, state): """ Sets the display mode for this widget to the inputed mode. :param state | <bool> """ if state == self._showLanguage: return self._showLanguage = state self.setDirty()
[ "def", "setShowLanguage", "(", "self", ",", "state", ")", ":", "if", "state", "==", "self", ".", "_showLanguage", ":", "return", "self", ".", "_showLanguage", "=", "state", "self", ".", "setDirty", "(", ")" ]
26.818182
0.013115
def multi_template_gen(catalog, st, length, swin='all', prepick=0.05, all_horiz=False, delayed=True, plot=False, debug=0, return_event=False, min_snr=None): """ Generate multiple templates from one stream of data. Thin wrapper around _template_gen to generate m...
[ "def", "multi_template_gen", "(", "catalog", ",", "st", ",", "length", ",", "swin", "=", "'all'", ",", "prepick", "=", "0.05", ",", "all_horiz", "=", "False", ",", "delayed", "=", "True", ",", "plot", "=", "False", ",", "debug", "=", "0", ",", "retur...
44.289474
0.000291
def count(self, value): """ Setter for **self.__count** attribute. :param value: Attribute value. :type value: int """ if value is not None: assert type(value) is int, "'{0}' attribute: '{1}' type is not 'int'!".format( "count", value) ...
[ "def", "count", "(", "self", ",", "value", ")", ":", "if", "value", "is", "not", "None", ":", "assert", "type", "(", "value", ")", "is", "int", ",", "\"'{0}' attribute: '{1}' type is not 'int'!\"", ".", "format", "(", "\"count\"", ",", "value", ")", "asser...
33.615385
0.008909
def principal_angle(A,B): """ Find the principal angle between two subspaces spanned by columns of A and B """ from numpy.linalg import qr, svd qA, _ = qr(A) qB, _ = qr(B) U,S,V = svd(qA.T.dot(qB)) return np.arccos(min(S.min(), 1.0))
[ "def", "principal_angle", "(", "A", ",", "B", ")", ":", "from", "numpy", ".", "linalg", "import", "qr", ",", "svd", "qA", ",", "_", "=", "qr", "(", "A", ")", "qB", ",", "_", "=", "qr", "(", "B", ")", "U", ",", "S", ",", "V", "=", "svd", "...
26
0.01487