text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def apply(self, ax): """ Apply this theme, then apply additional modifications in order. Subclasses that override this method should make sure that the base class method is called. """ for th in self.themeables.values(): th.apply(ax)
[ "def", "apply", "(", "self", ",", "ax", ")", ":", "for", "th", "in", "self", ".", "themeables", ".", "values", "(", ")", ":", "th", ".", "apply", "(", "ax", ")" ]
31.777778
15.111111
def authenticate(self, request): """ Returns two-tuple of (user, token) if authentication succeeds, or None otherwise. """ auth = get_authorization_header(request).split() if len(auth) == 1: msg = 'Invalid bearer header. No credentials provided.' ...
[ "def", "authenticate", "(", "self", ",", "request", ")", ":", "auth", "=", "get_authorization_header", "(", "request", ")", ".", "split", "(", ")", "if", "len", "(", "auth", ")", "==", "1", ":", "msg", "=", "'Invalid bearer header. No credentials provided.'", ...
37.28
20.32
def to_text(self, omit_final_dot = False): """Convert name to text format. @param omit_final_dot: If True, don't emit the final dot (denoting the root label) for absolute names. The default is False. @rtype: string """ if len(self.labels) == 0: return '@' ...
[ "def", "to_text", "(", "self", ",", "omit_final_dot", "=", "False", ")", ":", "if", "len", "(", "self", ".", "labels", ")", "==", "0", ":", "return", "'@'", "if", "len", "(", "self", ".", "labels", ")", "==", "1", "and", "self", ".", "labels", "[...
33.235294
15.470588
def isSAFESEHEnabled(self): """ Determines if the current L{PE} instance has the SAFESEH (Image has Safe Exception Handlers) flag enabled. @see: U{http://msdn.microsoft.com/en-us/library/9a89h429.aspx} @rtype: bool @return: Returns C{True} if the current L{PE} instance has the S...
[ "def", "isSAFESEHEnabled", "(", "self", ")", ":", "NOSEH", "=", "-", "1", "SAFESEH_OFF", "=", "0", "SAFESEH_ON", "=", "1", "if", "self", ".", "ntHeaders", ".", "optionalHeader", ".", "dllCharacteristics", ".", "value", "&", "consts", ".", "IMAGE_DLL_CHARACTE...
42.45
31.05
def label_for_waypoint(self, wp_num): '''return the label the waypoint which should appear on the map''' wp = self.module('wp').wploader.wp(wp_num) command = wp.command if command not in self._label_suffix_for_wp_command: return str(wp_num) return str(wp_num) + "(" + ...
[ "def", "label_for_waypoint", "(", "self", ",", "wp_num", ")", ":", "wp", "=", "self", ".", "module", "(", "'wp'", ")", ".", "wploader", ".", "wp", "(", "wp_num", ")", "command", "=", "wp", ".", "command", "if", "command", "not", "in", "self", ".", ...
51.714286
18.857143
def if_then(self, pred, likely=None): """ A context manager which sets up a conditional basic block based on the given predicate (a i1 value). If the conditional block is not explicitly terminated, a branch will be added to the next block. If *likely* is given, its boole...
[ "def", "if_then", "(", "self", ",", "pred", ",", "likely", "=", "None", ")", ":", "bb", "=", "self", ".", "basic_block", "bbif", "=", "self", ".", "append_basic_block", "(", "name", "=", "_label_suffix", "(", "bb", ".", "name", ",", "'.if'", ")", ")"...
42.428571
19.666667
def _init_default_values(self): """Set default initial values The default values are hard-coded for backwards compatibility and for several functionalities in dclab. """ # Do not filter out invalid event values self["filtering"]["remove invalid events"] = False #...
[ "def", "_init_default_values", "(", "self", ")", ":", "# Do not filter out invalid event values", "self", "[", "\"filtering\"", "]", "[", "\"remove invalid events\"", "]", "=", "False", "# Enable filters switch is mandatory", "self", "[", "\"filtering\"", "]", "[", "\"ena...
42.52381
11
def _graph_reduction(adj, x, g, f): """we can go ahead and remove any simplicial or almost-simplicial vertices from adj. """ as_list = set() as_nodes = {v for v in adj if len(adj[v]) <= f and is_almost_simplicial(adj, v)} while as_nodes: as_list.union(as_nodes) for n in as_nodes: ...
[ "def", "_graph_reduction", "(", "adj", ",", "x", ",", "g", ",", "f", ")", ":", "as_list", "=", "set", "(", ")", "as_nodes", "=", "{", "v", "for", "v", "in", "adj", "if", "len", "(", "adj", "[", "v", "]", ")", "<=", "f", "and", "is_almost_simpli...
28.75
20.375
def encrypt(self, data, pad=True): """ DES encrypts the data based on the key it was initialised with. :param data: The bytes string to encrypt :param pad: Whether to right pad data with \x00 to a multiple of 8 :return: The encrypted bytes string """ encrypted_da...
[ "def", "encrypt", "(", "self", ",", "data", ",", "pad", "=", "True", ")", ":", "encrypted_data", "=", "b\"\"", "for", "i", "in", "range", "(", "0", ",", "len", "(", "data", ")", ",", "8", ")", ":", "block", "=", "data", "[", "i", ":", "i", "+...
37.9
13.2
def _wrap_row(cls, row): """Wrap ViewField or ViewDefinition Rows.""" doc = row.get('doc') if doc is not None: return cls.wrap(doc) data = row['value'] data['_id'] = row['id'] return cls.wrap(data)
[ "def", "_wrap_row", "(", "cls", ",", "row", ")", ":", "doc", "=", "row", ".", "get", "(", "'doc'", ")", "if", "doc", "is", "not", "None", ":", "return", "cls", ".", "wrap", "(", "doc", ")", "data", "=", "row", "[", "'value'", "]", "data", "[", ...
31.25
10.25
def env_check(self, *args, **kwargs): """ This method provides a common entry for any checks on the environment (input / output dirs, etc) """ b_status = True str_error = '' if not len(self.str_outputDir): b_status = False str_error ...
[ "def", "env_check", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "b_status", "=", "True", "str_error", "=", "''", "if", "not", "len", "(", "self", ".", "str_outputDir", ")", ":", "b_status", "=", "False", "str_error", "=", "'outp...
35.125
12
def class_get_trait_help(cls, trait, inst=None): """Get the help string for a single trait. If `inst` is given, it's current trait values will be used in place of the class default. """ assert inst is None or isinstance(inst, cls) lines = [] header = "--%...
[ "def", "class_get_trait_help", "(", "cls", ",", "trait", ",", "inst", "=", "None", ")", ":", "assert", "inst", "is", "None", "or", "isinstance", "(", "inst", ",", "cls", ")", "lines", "=", "[", "]", "header", "=", "\"--%s.%s=<%s>\"", "%", "(", "cls", ...
39.666667
16.1
def update_room(self, stream_id, room_definition): ''' update a room definition ''' req_hook = 'pod/v2/room/' + str(stream_id) + '/update' req_args = json.dumps(room_definition) status_code, response = self.__rest__.POST_query(req_hook, req_args) self.logger.debug('%s: %s' % (sta...
[ "def", "update_room", "(", "self", ",", "stream_id", ",", "room_definition", ")", ":", "req_hook", "=", "'pod/v2/room/'", "+", "str", "(", "stream_id", ")", "+", "'/update'", "req_args", "=", "json", ".", "dumps", "(", "room_definition", ")", "status_code", ...
53
14.142857
def _http_call(the_url, method, authorization, **kw): ''' send an http request and return a json object if no error occurred. ''' params = None boundary = None if method == _HTTP_UPLOAD: # fix sina upload url: the_url = the_url.replace('https://api.', 'https://upload.api.') ...
[ "def", "_http_call", "(", "the_url", ",", "method", ",", "authorization", ",", "*", "*", "kw", ")", ":", "params", "=", "None", "boundary", "=", "None", "if", "method", "==", "_HTTP_UPLOAD", ":", "# fix sina upload url:", "the_url", "=", "the_url", ".", "r...
38.526316
20
def DiscreteUniform(n=10,LB=1,UB=99,B=100): """DiscreteUniform: create random, uniform instance for the bin packing problem.""" B = 100 s = [0]*n for i in range(n): s[i] = random.randint(LB,UB) return s,B
[ "def", "DiscreteUniform", "(", "n", "=", "10", ",", "LB", "=", "1", ",", "UB", "=", "99", ",", "B", "=", "100", ")", ":", "B", "=", "100", "s", "=", "[", "0", "]", "*", "n", "for", "i", "in", "range", "(", "n", ")", ":", "s", "[", "i", ...
32.285714
15.285714
def _hasCredentials(self): """ Return True, if credentials is given """ cred = self.options.get('credentials') return ( cred and 'clientId' in cred and 'accessToken' in cred and cred['clientId'] and cred['accessToken'] )
[ "def", "_hasCredentials", "(", "self", ")", ":", "cred", "=", "self", ".", "options", ".", "get", "(", "'credentials'", ")", "return", "(", "cred", "and", "'clientId'", "in", "cred", "and", "'accessToken'", "in", "cred", "and", "cred", "[", "'clientId'", ...
30.3
12.1
def upgrade(): """Upgrade database.""" # table ObjectVersion: modify primary_key if op.get_context().dialect.name == 'mysql': Fk = 'fk_files_object_bucket_id_files_bucket' op.execute( 'ALTER TABLE files_object ' 'DROP FOREIGN KEY {0}, DROP PRIMARY KEY, ' '...
[ "def", "upgrade", "(", ")", ":", "# table ObjectVersion: modify primary_key", "if", "op", ".", "get_context", "(", ")", ".", "dialect", ".", "name", "==", "'mysql'", ":", "Fk", "=", "'fk_files_object_bucket_id_files_bucket'", "op", ".", "execute", "(", "'ALTER TAB...
34.414634
15.268293
def offTagAdd(self, name, func): ''' Unregister a callback for tag addition. Args: name (str): The name of the tag or tag glob. func (function): The callback func(node, tagname, tagval). ''' if '*' in name: self.ontagaddglobs.rem(name, func) ...
[ "def", "offTagAdd", "(", "self", ",", "name", ",", "func", ")", ":", "if", "'*'", "in", "name", ":", "self", ".", "ontagaddglobs", ".", "rem", "(", "name", ",", "func", ")", "return", "cblist", "=", "self", ".", "ontagadds", ".", "get", "(", "name"...
24.85
21.15
def getAssociations( self, request=None, featureSets=[]): """ This query is the main search mechanism. It queries the graph for annotations that match the AND of [feature,environment,phenotype]. """ if len(featureSets) == 0: featureSets = self.getP...
[ "def", "getAssociations", "(", "self", ",", "request", "=", "None", ",", "featureSets", "=", "[", "]", ")", ":", "if", "len", "(", "featureSets", ")", "==", "0", ":", "featureSets", "=", "self", ".", "getParentContainer", "(", ")", ".", "getFeatureSets",...
44.117647
16.196078
def put_multiple(self, task_args_kwargs_list): """put a list of tasks and their arguments This method can be used to put multiple tasks at once. Calling this method once with multiple tasks can be much faster than calling `put()` multiple times. Parameters ---------- ...
[ "def", "put_multiple", "(", "self", ",", "task_args_kwargs_list", ")", ":", "if", "not", "self", ".", "isopen", ":", "logger", "=", "logging", ".", "getLogger", "(", "__name__", ")", "logger", ".", "warning", "(", "'the drop box is not open'", ")", "return", ...
31.805556
18.833333
def _process_directory(files, user_conf, error_protocol): """ Look at items in given directory, try to match them for same names and pair them. If the items can't be paired, add their representation. Note: All successfully processed files are removed. Returns: list: of items. ...
[ "def", "_process_directory", "(", "files", ",", "user_conf", ",", "error_protocol", ")", ":", "items", "=", "[", "]", "banned", "=", "[", "settings", ".", "USER_IMPORT_LOG", ",", "settings", ".", "USER_ERROR_LOG", "]", "files", "=", "filter", "(", "lambda", ...
36.234375
24.390625
def get_class_traits(klass): """ Yield all of the documentation for trait definitions on a class object. """ # FIXME: gracefully handle errors here or in the caller? source = inspect.getsource(klass) cb = CommentBlocker() cb.process_file(StringIO(source)) mod_ast = compiler.parse(source) ...
[ "def", "get_class_traits", "(", "klass", ")", ":", "# FIXME: gracefully handle errors here or in the caller?", "source", "=", "inspect", ".", "getsource", "(", "klass", ")", "cb", "=", "CommentBlocker", "(", ")", "cb", ".", "process_file", "(", "StringIO", "(", "s...
42.625
9
def copy_database_structure(self, source, destination, tables=None): """Copy multiple tables from one database to another.""" # Change database to source self.change_db(source) if tables is None: tables = self.tables # Change database to destination self.cha...
[ "def", "copy_database_structure", "(", "self", ",", "source", ",", "destination", ",", "tables", "=", "None", ")", ":", "# Change database to source", "self", ".", "change_db", "(", "source", ")", "if", "tables", "is", "None", ":", "tables", "=", "self", "."...
40.916667
19.25
def device_characteristics_str(self, indent): """Convenience to string method. """ s = "{}\n".format(self.label) s += indent + "MAC Address: {}\n".format(self.mac_addr) s += indent + "IP Address: {}\n".format(self.ip_addr) s += indent + "Port: {}\n".format(self.port) ...
[ "def", "device_characteristics_str", "(", "self", ",", "indent", ")", ":", "s", "=", "\"{}\\n\"", ".", "format", "(", "self", ".", "label", ")", "s", "+=", "indent", "+", "\"MAC Address: {}\\n\"", ".", "format", "(", "self", ".", "mac_addr", ")", "s", "+...
46.181818
13.727273
def get_prep_value(self, value): """Convert our JSON object to a string before we save""" if value == "": return None if isinstance(value, dict): value = json.dumps(value, cls=DjangoJSONEncoder) return value
[ "def", "get_prep_value", "(", "self", ",", "value", ")", ":", "if", "value", "==", "\"\"", ":", "return", "None", "if", "isinstance", "(", "value", ",", "dict", ")", ":", "value", "=", "json", ".", "dumps", "(", "value", ",", "cls", "=", "DjangoJSONE...
25.7
20.7
def delete_attachment(self, id): """Delete attachment by id. :param id: ID of the attachment to delete :type id: str """ url = self._get_url('attachment/' + str(id)) return self._session.delete(url)
[ "def", "delete_attachment", "(", "self", ",", "id", ")", ":", "url", "=", "self", ".", "_get_url", "(", "'attachment/'", "+", "str", "(", "id", ")", ")", "return", "self", ".", "_session", ".", "delete", "(", "url", ")" ]
30
11
def update_ikepolicy(self, ikepolicy, body=None): """Updates an IKEPolicy.""" return self.put(self.ikepolicy_path % (ikepolicy), body=body)
[ "def", "update_ikepolicy", "(", "self", ",", "ikepolicy", ",", "body", "=", "None", ")", ":", "return", "self", ".", "put", "(", "self", ".", "ikepolicy_path", "%", "(", "ikepolicy", ")", ",", "body", "=", "body", ")" ]
51
12.666667
def describe_api_deployments(restApiId, region=None, key=None, keyid=None, profile=None): ''' Gets information about the defined API Deployments. Return list of api deployments. CLI Example: .. code-block:: bash salt myminion boto_apigateway.describe_api_deployments restApiId ''' tr...
[ "def", "describe_api_deployments", "(", "restApiId", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "try", ":", "conn", "=", "_get_conn", "(", "region", "=", "region", ",", "key", ...
36.653846
31.576923
def VarCircle(XY, Par): # must have at least 4 sets of xy points or else division by zero occurs """ computing the sample variance of distances from data points (XY) to the circle Par = [a b R] """ if type(XY) != numpy.ndarray: XY = numpy.array(XY) n = len(XY) if n < 4: raise Wa...
[ "def", "VarCircle", "(", "XY", ",", "Par", ")", ":", "# must have at least 4 sets of xy points or else division by zero occurs", "if", "type", "(", "XY", ")", "!=", "numpy", ".", "ndarray", ":", "XY", "=", "numpy", ".", "array", "(", "XY", ")", "n", "=", "le...
40
22.428571
def figure(self): """ The [`matplotlib.pyplot.figure`][1] instance. [1]: http://matplotlib.org/api/figure_api.html#matplotlib.figure.Figure """ if not hasattr(self, '_figure'): self._figure = matplotlib.pyplot.figure() return self._figure
[ "def", "figure", "(", "self", ")", ":", "if", "not", "hasattr", "(", "self", ",", "'_figure'", ")", ":", "self", ".", "_figure", "=", "matplotlib", ".", "pyplot", ".", "figure", "(", ")", "return", "self", ".", "_figure" ]
35
21.25
def can_start_on_cluster(nodes_status, nodes, start, walltime): """Check if #nodes can be started on a given cluster. This is intended to give a good enough approximation. This can be use to prefiltered possible reservation dates be...
[ "def", "can_start_on_cluster", "(", "nodes_status", ",", "nodes", ",", "start", ",", "walltime", ")", ":", "candidates", "=", "[", "]", "for", "node", ",", "status", "in", "nodes_status", ".", "items", "(", ")", ":", "reservations", "=", "status", ".", "...
40.083333
13.527778
def link_parameter(self, param, index=None): """ :param parameters: the parameters to add :type parameters: list of or one :py:class:`paramz.param.Param` :param [index]: index of where to put parameters Add all parameters to this param class, you can insert parameters ...
[ "def", "link_parameter", "(", "self", ",", "param", ",", "index", "=", "None", ")", ":", "if", "param", "in", "self", ".", "parameters", "and", "index", "is", "not", "None", ":", "self", ".", "unlink_parameter", "(", "param", ")", "return", "self", "."...
47.915254
18.881356
def rtt_get_num_up_buffers(self): """After starting RTT, get the current number of up buffers. Args: self (JLink): the ``JLink`` instance Returns: The number of configured up buffers on the target. Raises: JLinkRTTException if the underlying JLINK_RTTERMIN...
[ "def", "rtt_get_num_up_buffers", "(", "self", ")", ":", "cmd", "=", "enums", ".", "JLinkRTTCommand", ".", "GETNUMBUF", "dir", "=", "ctypes", ".", "c_int", "(", "enums", ".", "JLinkRTTDirection", ".", "UP", ")", "return", "self", ".", "rtt_control", "(", "c...
34.571429
17.928571
def getRootNodes(self): ''' getRootNodes - Gets all objects at the "root" (first level; no parent). Use this if you may have multiple roots (not children of <html>) Use this method to get objects, for example, in an AJAX request where <html> may not be your root. Not...
[ "def", "getRootNodes", "(", "self", ")", ":", "root", "=", "self", ".", "root", "if", "not", "root", ":", "return", "[", "]", "if", "root", ".", "tagName", "==", "INVISIBLE_ROOT_TAG", ":", "return", "list", "(", "root", ".", "children", ")", "return", ...
49.3125
38.1875
def get_ball_by_ball(self, match_key, over_key=None): """ match_key: key of the match over_key : key of the over Return: json data: """ if over_key: ball_by_ball_url = "{base_path}match/{match_key}/balls/{over_key}/".format(base_path=self....
[ "def", "get_ball_by_ball", "(", "self", ",", "match_key", ",", "over_key", "=", "None", ")", ":", "if", "over_key", ":", "ball_by_ball_url", "=", "\"{base_path}match/{match_key}/balls/{over_key}/\"", ".", "format", "(", "base_path", "=", "self", ".", "api_path", "...
38
27.333333
def parse(self, name): """Parse distribution string :param name: distribution string, e.g. "Fedora 23" :type name: string """ name = name.strip() groups = self._parseFedora(name) if groups: self._signature = DistributionNameSignature("Fedora", groups.group(1)) return self raise ValueError("Dist...
[ "def", "parse", "(", "self", ",", "name", ")", ":", "name", "=", "name", ".", "strip", "(", ")", "groups", "=", "self", ".", "_parseFedora", "(", "name", ")", "if", "groups", ":", "self", ".", "_signature", "=", "DistributionNameSignature", "(", "\"Fed...
26.923077
20.538462
def _init_ui(self): """Initial the first UI page. - load html from '/' endpoint - if <title> is defined, use as windows title """ (content, mimetype) = make_response(self._url_map_to_function('/')) try: beautifulsoup = BeautifulSoup(content) self.w...
[ "def", "_init_ui", "(", "self", ")", ":", "(", "content", ",", "mimetype", ")", "=", "make_response", "(", "self", ".", "_url_map_to_function", "(", "'/'", ")", ")", "try", ":", "beautifulsoup", "=", "BeautifulSoup", "(", "content", ")", "self", ".", "wi...
30.909091
18.454545
def read_kepler_pklc(picklefile): '''This turns the pickled lightcurve file back into an `lcdict`. Parameters ---------- picklefile : str The path to a previously written Kepler LC picklefile generated by `kepler_lcdict_to_pkl` above. Returns ------- lcdict Return...
[ "def", "read_kepler_pklc", "(", "picklefile", ")", ":", "if", "picklefile", ".", "endswith", "(", "'.gz'", ")", ":", "infd", "=", "gzip", ".", "open", "(", "picklefile", ",", "'rb'", ")", "else", ":", "infd", "=", "open", "(", "picklefile", ",", "'rb'"...
25.25641
25.871795
def module(self): """The module in which the Rule is defined. Python equivalent of the CLIPS defrule-module command. """ modname = ffi.string(lib.EnvDefruleModule(self._env, self._rule)) defmodule = lib.EnvFindDefmodule(self._env, modname) return Module(self._env, defm...
[ "def", "module", "(", "self", ")", ":", "modname", "=", "ffi", ".", "string", "(", "lib", ".", "EnvDefruleModule", "(", "self", ".", "_env", ",", "self", ".", "_rule", ")", ")", "defmodule", "=", "lib", ".", "EnvFindDefmodule", "(", "self", ".", "_en...
31.7
22.1
def interaction(self, factors, pairwise, max_factors, min_occurrence, destination_frame=None): """ Categorical Interaction Feature Creation in H2O. Creates a frame in H2O with n-th order interaction features between categorical columns, as specified by the user. :param factors:...
[ "def", "interaction", "(", "self", ",", "factors", ",", "pairwise", ",", "max_factors", ",", "min_occurrence", ",", "destination_frame", "=", "None", ")", ":", "return", "h2o", ".", "interaction", "(", "data", "=", "self", ",", "factors", "=", "factors", "...
61.473684
40.736842
def next_task(self, item, **kwargs): """Calls import_batch for the next filename in the queue and "archives" the file. The archive folder is typically the folder for the deserializer queue. """ filename = os.path.basename(item) try: self.tx_importer.import_ba...
[ "def", "next_task", "(", "self", ",", "item", ",", "*", "*", "kwargs", ")", ":", "filename", "=", "os", ".", "path", ".", "basename", "(", "item", ")", "try", ":", "self", ".", "tx_importer", ".", "import_batch", "(", "filename", "=", "filename", ")"...
36.923077
14.692308
def from_call(cls, call_node): """Get a CallSite object from the given Call node.""" callcontext = contextmod.CallContext(call_node.args, call_node.keywords) return cls(callcontext)
[ "def", "from_call", "(", "cls", ",", "call_node", ")", ":", "callcontext", "=", "contextmod", ".", "CallContext", "(", "call_node", ".", "args", ",", "call_node", ".", "keywords", ")", "return", "cls", "(", "callcontext", ")" ]
50.5
14.75
def _handle_linux(self, keycode, character, press): """Linux key event handler.""" if character is None: return key = self._keyname(character, keycode) if key in self.MODIFIERNAMES: self._modifiers[self.MODIFIERNAMES[key]] = press self._realmodifiers[key] = ...
[ "def", "_handle_linux", "(", "self", ",", "keycode", ",", "character", ",", "press", ")", ":", "if", "character", "is", "None", ":", "return", "key", "=", "self", ".", "_keyname", "(", "character", ",", "keycode", ")", "if", "key", "in", "self", ".", ...
56.944444
20
def __split_name_unit(self, line): """ Split a string that has value and unit as one. :param str line: :return str str: """ vals = [] unit = '' if line != '' or line != ' ': # If there are parenthesis, remove them line = line.replac...
[ "def", "__split_name_unit", "(", "self", ",", "line", ")", ":", "vals", "=", "[", "]", "unit", "=", "''", "if", "line", "!=", "''", "or", "line", "!=", "' '", ":", "# If there are parenthesis, remove them", "line", "=", "line", ".", "replace", "(", "'('"...
38.290323
11.903226
def discard(self, *args): ''' cplan.discard(...) yields a new calculation plan identical to cplan except without any of the calculation steps listed in the arguments. ''' return Plan(reduce(lambda m,k: m.discard(k), args, self.nodes))
[ "def", "discard", "(", "self", ",", "*", "args", ")", ":", "return", "Plan", "(", "reduce", "(", "lambda", "m", ",", "k", ":", "m", ".", "discard", "(", "k", ")", ",", "args", ",", "self", ".", "nodes", ")", ")" ]
44.833333
29.166667
def datasets_create_version_by_id(self, id, dataset_new_version_request, **kwargs): # noqa: E501 """Create a new dataset version by id # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = ap...
[ "def", "datasets_create_version_by_id", "(", "self", ",", "id", ",", "dataset_new_version_request", ",", "*", "*", "kwargs", ")", ":", "# noqa: E501", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'async_req'", ")...
53.857143
29.952381
def run_script(self, filename, start_opts=None, globals_=None, locals_=None): """ Run debugger on Python script `filename'. The script may inspect sys.argv for command arguments. `globals_' and `locals_' are the dictionaries to use for local and global variables. If `g...
[ "def", "run_script", "(", "self", ",", "filename", ",", "start_opts", "=", "None", ",", "globals_", "=", "None", ",", "locals_", "=", "None", ")", ":", "self", ".", "mainpyfile", "=", "self", ".", "core", ".", "canonic", "(", "filename", ")", "# Start ...
40.207547
17.358491
def _marker(self, lat, long, text, xmap, color=None, icon=None, text_mark=False, style=None): """ Adds a marker to the default map """ kwargs = {} if icon is not None: kwargs["icon"] = icon if color is not None: kwargs["color"] = co...
[ "def", "_marker", "(", "self", ",", "lat", ",", "long", ",", "text", ",", "xmap", ",", "color", "=", "None", ",", "icon", "=", "None", ",", "text_mark", "=", "False", ",", "style", "=", "None", ")", ":", "kwargs", "=", "{", "}", "if", "icon", "...
37.607143
11.464286
def cast_str(s, encoding='utf8', errors='strict'): """cast bytes or str to str""" if isinstance(s, bytes): return s.decode(encoding, errors) elif isinstance(s, str): return s else: raise TypeError("Expected unicode or bytes, got %r" % s)
[ "def", "cast_str", "(", "s", ",", "encoding", "=", "'utf8'", ",", "errors", "=", "'strict'", ")", ":", "if", "isinstance", "(", "s", ",", "bytes", ")", ":", "return", "s", ".", "decode", "(", "encoding", ",", "errors", ")", "elif", "isinstance", "(",...
33.75
14.25
def weld_invert(array): """Inverts a bool array. Parameters ---------- array : numpy.ndarray or WeldObject Input data. Assumed to be bool data. Returns ------- WeldObject Representation of this computation. """ obj_id, weld_obj = create_weld_object(array) weld...
[ "def", "weld_invert", "(", "array", ")", ":", "obj_id", ",", "weld_obj", "=", "create_weld_object", "(", "array", ")", "weld_template", "=", "\"\"\"result(\n for({array},\n appender[bool],\n |b: appender[bool], i: i64, e: bool|\n if(e, merge(b, false), mer...
20.222222
19.962963
def delete_s3_bucket(client, resource): """Delete an S3 bucket This function will try to delete an S3 bucket Args: client (:obj:`boto3.session.Session.client`): A boto3 client object resource (:obj:`Resource`): The resource object to terminate Returns: `ActionStatus` """ ...
[ "def", "delete_s3_bucket", "(", "client", ",", "resource", ")", ":", "if", "dbconfig", ".", "get", "(", "'enable_delete_s3_buckets'", ",", "NS_AUDITOR_REQUIRED_TAGS", ",", "False", ")", ":", "client", ".", "delete_bucket", "(", "Bucket", "=", "resource", ".", ...
30.4375
23.125
def _apply_to_instance(self, project_id, instance_id, configuration_name, node_count, display_name, func): """ Invokes a method on a given instance by applying a specified Callable. :param project_id: The ID of the GCP project that owns the Cloud Spanner ...
[ "def", "_apply_to_instance", "(", "self", ",", "project_id", ",", "instance_id", ",", "configuration_name", ",", "node_count", ",", "display_name", ",", "func", ")", ":", "# noinspection PyUnresolvedReferences", "instance", "=", "self", ".", "_get_client", "(", "pro...
47.314286
22.228571
def task_add(self, t, periodic=None): """ Register a task in this legion. "periodic" should be None, or a callback function which will be called periodically when the legion is otherwise idle. """ name = t.get_name() if name in self._tasknames: raise Task...
[ "def", "task_add", "(", "self", ",", "t", ",", "periodic", "=", "None", ")", ":", "name", "=", "t", ".", "get_name", "(", ")", "if", "name", "in", "self", ".", "_tasknames", ":", "raise", "TaskError", "(", "name", ",", "'Task already exists with %d daemo...
43.333333
15.5
def mousePressEvent(self, event): """Override Qt method""" if self.slider and event.button() == Qt.LeftButton: vsb = self.editor.verticalScrollBar() value = self.position_to_value(event.pos().y()) vsb.setValue(value-vsb.pageStep()/2)
[ "def", "mousePressEvent", "(", "self", ",", "event", ")", ":", "if", "self", ".", "slider", "and", "event", ".", "button", "(", ")", "==", "Qt", ".", "LeftButton", ":", "vsb", "=", "self", ".", "editor", ".", "verticalScrollBar", "(", ")", "value", "...
46.666667
10.333333
def resolve_expression(self, *args, **kwargs): """Resolves expressions inside the dictionary.""" result = dict() for key, value in self.value.items(): if hasattr(value, 'resolve_expression'): result[key] = value.resolve_expression( *args, **kwargs...
[ "def", "resolve_expression", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "result", "=", "dict", "(", ")", "for", "key", ",", "value", "in", "self", ".", "value", ".", "items", "(", ")", ":", "if", "hasattr", "(", "value", ",...
33.333333
14.416667
def analog_units(self): """ Shortcut to retrieve all analog points units [Used by Bokeh trending feature] """ au = [] us = [] for each in self.points: if isinstance(each, NumericPoint): au.append(each.properties.name) u...
[ "def", "analog_units", "(", "self", ")", ":", "au", "=", "[", "]", "us", "=", "[", "]", "for", "each", "in", "self", ".", "points", ":", "if", "isinstance", "(", "each", ",", "NumericPoint", ")", ":", "au", ".", "append", "(", "each", ".", "prope...
34.636364
14.090909
def producer_consumer(producer, consumer, addr='tcp://127.0.0.1', port=None, context=None): """A producer-consumer pattern. Parameters ---------- producer : callable Callable that takes a single argument, a handle for a ZeroMQ PUSH socket. Must be picklable. co...
[ "def", "producer_consumer", "(", "producer", ",", "consumer", ",", "addr", "=", "'tcp://127.0.0.1'", ",", "port", "=", "None", ",", "context", "=", "None", ")", ":", "context_created", "=", "False", "if", "context", "is", "None", ":", "context_created", "=",...
31.927273
19.454545
def check_command(self, name): """ Checks whether the given Django management command exists, excluding this command from the search. """ if not check_command( name, exclude_packages=self.get_exclude_packages(), exclude_command_class=...
[ "def", "check_command", "(", "self", ",", "name", ")", ":", "if", "not", "check_command", "(", "name", ",", "exclude_packages", "=", "self", ".", "get_exclude_packages", "(", ")", ",", "exclude_command_class", "=", "self", ".", "__class__", ")", ":", "raise"...
40.125
15.5
def modpath_to_modname(modpath, hide_init=True, hide_main=False, check=True, relativeto=None): """ Determines importable name from file path Converts the path to a module (__file__) to the importable python name (__name__) without importing the module. The filename is conver...
[ "def", "modpath_to_modname", "(", "modpath", ",", "hide_init", "=", "True", ",", "hide_main", "=", "False", ",", "check", "=", "True", ",", "relativeto", "=", "None", ")", ":", "if", "check", "and", "relativeto", "is", "None", ":", "if", "not", "exists",...
37.151515
22.545455
def __message(expected_row_count, actual_row_count, query): """ Composes the exception message. :param str expected_row_count: The expected row count. :param int actual_row_count: The actual row count. :param str query: The query. :rtype: str """ query =...
[ "def", "__message", "(", "expected_row_count", ",", "actual_row_count", ",", "query", ")", ":", "query", "=", "query", ".", "strip", "(", ")", "message", "=", "'Wrong number of rows selected'", "message", "+=", "os", ".", "linesep", "message", "+=", "'Expected n...
32.173913
18.782609
def sample_folder(prj, sample): """ Get the path to this Project's root folder for the given Sample. :param attmap.PathExAttMap | Project prj: project with which sample is associated :param Mapping sample: Sample or sample data for which to get root output folder path. :return str: this Pro...
[ "def", "sample_folder", "(", "prj", ",", "sample", ")", ":", "return", "os", ".", "path", ".", "join", "(", "prj", ".", "metadata", ".", "results_subdir", ",", "sample", "[", "\"sample_name\"", "]", ")" ]
41.545455
20.090909
def on_plot_select(self,event): """ Select data point if cursor is in range of a data point @param: event -> the wx Mouseevent for that click """ if not self.xdata or not self.ydata: return pos=event.GetPosition() width, height = self.canvas.get_width_height() ...
[ "def", "on_plot_select", "(", "self", ",", "event", ")", ":", "if", "not", "self", ".", "xdata", "or", "not", "self", ".", "ydata", ":", "return", "pos", "=", "event", ".", "GetPosition", "(", ")", "width", ",", "height", "=", "self", ".", "canvas", ...
36.846154
16.076923
def update_image_properties(auth=None, **kwargs): ''' Update properties for an image CLI Example: .. code-block:: bash salt '*' glanceng.update_image_properties name=image1 hw_scsi_model=virtio-scsi hw_disk_bus=scsi salt '*' glanceng.update_image_properties name=0e4febc2a5ab4f2c8f374b...
[ "def", "update_image_properties", "(", "auth", "=", "None", ",", "*", "*", "kwargs", ")", ":", "cloud", "=", "get_operator_cloud", "(", "auth", ")", "kwargs", "=", "_clean_kwargs", "(", "*", "*", "kwargs", ")", "return", "cloud", ".", "update_image_propertie...
33.071429
27.357143
def run_application( application, patch_stdout=False, return_asyncio_coroutine=False, true_color=False, refresh_interval=0, eventloop=None): """ Run a prompt toolkit application. :param patch_stdout: Replace ``sys.stdout`` by a proxy that ensures that print statements from other...
[ "def", "run_application", "(", "application", ",", "patch_stdout", "=", "False", ",", "return_asyncio_coroutine", "=", "False", ",", "true_color", "=", "False", ",", "refresh_interval", "=", "0", ",", "eventloop", "=", "None", ")", ":", "assert", "isinstance", ...
33.296296
18.925926
def Statistics(season=None, clobber=False, model='nPLD', injection=False, compare_to='kepler', plot=True, cadence='lc', planets=False, **kwargs): ''' Computes and plots the CDPP statistics comparison between `model` and `compare_to` for all long cadence light curves in a given ...
[ "def", "Statistics", "(", "season", "=", "None", ",", "clobber", "=", "False", ",", "model", "=", "'nPLD'", ",", "injection", "=", "False", ",", "compare_to", "=", "'kepler'", ",", "plot", "=", "True", ",", "cadence", "=", "'lc'", ",", "planets", "=", ...
46.883077
19.203077
def find_node(self, name, create=False): """Find a node in the zone, possibly creating it. @param name: the name of the node to find @type name: dns.name.Name object or string @param create: should the node be created if it doesn't exist? @type create: bool @raises KeyEr...
[ "def", "find_node", "(", "self", ",", "name", ",", "create", "=", "False", ")", ":", "name", "=", "self", ".", "_validate_name", "(", "name", ")", "node", "=", "self", ".", "nodes", ".", "get", "(", "name", ")", "if", "node", "is", "None", ":", "...
34.894737
13.526316
def minmax_candidates(self): '''Get points where derivative is zero. Useful for computing the extrema of the polynomial over an interval if the polynomial has real roots. In this case, the maximum is attained for one of the interval endpoints or a point from the result of this f...
[ "def", "minmax_candidates", "(", "self", ")", ":", "from", "numpy", ".", "polynomial", "import", "Polynomial", "as", "P", "p", "=", "P", ".", "fromroots", "(", "self", ".", "roots", ")", "return", "p", ".", "deriv", "(", "1", ")", ".", "roots", "(", ...
44.272727
21.181818
def admin_authenticate(self, password): """ Authenticate the user using admin super privileges :param password: User's password :return: """ auth_params = { 'USERNAME': self.username, 'PASSWORD': password } self._add_sec...
[ "def", "admin_authenticate", "(", "self", ",", "password", ")", ":", "auth_params", "=", "{", "'USERNAME'", ":", "self", ".", "username", ",", "'PASSWORD'", ":", "password", "}", "self", ".", "_add_secret_hash", "(", "auth_params", ",", "'SECRET_HASH'", ")", ...
43.347826
18.826087
def event_channels_happened(self, eventcode): """ Params: VideoMotion: motion detection event VideoLoss: video loss detection event VideoBlind: video blind detection event AlarmLocal: alarm detection event StorageNotExist: storage not exist event StorageF...
[ "def", "event_channels_happened", "(", "self", ",", "eventcode", ")", ":", "ret", "=", "self", ".", "command", "(", "'eventManager.cgi?action=getEventIndexes&code={0}'", ".", "format", "(", "eventcode", ")", ")", "return", "ret", ".", "content", ".", "decode", "...
34
11
def compute_search_volume_in_bins(found, total, ndbins, sim_to_bins_function): """ Calculate search sensitive volume by integrating efficiency in distance bins No cosmological corrections are applied: flat space is assumed. The first dimension of ndbins must be bins over injected distance. sim_to_b...
[ "def", "compute_search_volume_in_bins", "(", "found", ",", "total", ",", "ndbins", ",", "sim_to_bins_function", ")", ":", "eff", ",", "err", "=", "compute_search_efficiency_in_bins", "(", "found", ",", "total", ",", "ndbins", ",", "sim_to_bins_function", ")", "dx"...
40.807692
24.576923
def add_edge_lengths(G): """ Add length (meters) attribute to each edge by great circle distance between nodes u and v. Parameters ---------- G : networkx multidigraph Returns ------- G : networkx multidigraph """ start_time = time.time() # first load all the edges' o...
[ "def", "add_edge_lengths", "(", "G", ")", ":", "start_time", "=", "time", ".", "time", "(", ")", "# first load all the edges' origin and destination coordinates as a", "# dataframe indexed by u, v, key", "coords", "=", "np", ".", "array", "(", "[", "[", "u", ",", "v...
37.828571
27.942857
def safe_cast_to_index(array: Any) -> pd.Index: """Given an array, safely cast it to a pandas.Index. If it is already a pandas.Index, return it unchanged. Unlike pandas.Index, if the array has dtype=object or dtype=timedelta64, this function will not attempt to do automatic type conversion but will ...
[ "def", "safe_cast_to_index", "(", "array", ":", "Any", ")", "->", "pd", ".", "Index", ":", "if", "isinstance", "(", "array", ",", "pd", ".", "Index", ")", ":", "index", "=", "array", "elif", "hasattr", "(", "array", ",", "'to_index'", ")", ":", "inde...
37.421053
16.421053
def check_platform_variable_attributes(self, ds): ''' Platform variables must contain the following attributes: ioos_code long_name short_name type :param netCDF4.Dataset ds: An open netCDF dataset ''' results = [] platform...
[ "def", "check_platform_variable_attributes", "(", "self", ",", "ds", ")", ":", "results", "=", "[", "]", "platform_name", "=", "getattr", "(", "ds", ",", "'platform'", ",", "''", ")", "# There can be multiple platforms defined here (space separated)", "for", "platform...
41.590909
24.409091
def confounds_correlation_plot(confounds_file, output_file=None, figure=None, reference='global_signal', max_dim=70): """ Parameters ---------- confounds_file: str File containing all confound regressors to be included in the correlation plot. output_fi...
[ "def", "confounds_correlation_plot", "(", "confounds_file", ",", "output_file", "=", "None", ",", "figure", "=", "None", ",", "reference", "=", "'global_signal'", ",", "max_dim", "=", "70", ")", ":", "confounds_data", "=", "pd", ".", "read_table", "(", "confou...
36.98
17.48
def _walk_directories(self, vd, extent_to_ptr, extent_to_inode, path_table_records): # type: (headervd.PrimaryOrSupplementaryVD, Dict[int, path_table_record.PathTableRecord], Dict[int, inode.Inode], List[path_table_record.PathTableRecord]) -> Tuple[int, int] ''' An internal method to walk the di...
[ "def", "_walk_directories", "(", "self", ",", "vd", ",", "extent_to_ptr", ",", "extent_to_inode", ",", "path_table_records", ")", ":", "# type: (headervd.PrimaryOrSupplementaryVD, Dict[int, path_table_record.PathTableRecord], Dict[int, inode.Inode], List[path_table_record.PathTableRecord...
53.390244
27.341463
def get_scales(scale=None, n=None): """ Returns a color scale Parameters: ----------- scale : str Color scale name If the color name is preceded by a minus (-) then the scale is inversed n : int Nu...
[ "def", "get_scales", "(", "scale", "=", "None", ",", "n", "=", "None", ")", ":", "if", "scale", ":", "is_reverse", "=", "False", "if", "scale", "[", "0", "]", "==", "'-'", ":", "scale", "=", "scale", "[", "1", ":", "]", "is_reverse", "=", "True",...
30.083333
16.583333
def write(self, outfile): """Write this shape list to a region file. Parameters ---------- outfile : str File name """ if len(self) < 1: print("WARNING: The region list is empty. The region file " "'{:s}' will be empty.".format(o...
[ "def", "write", "(", "self", ",", "outfile", ")", ":", "if", "len", "(", "self", ")", "<", "1", ":", "print", "(", "\"WARNING: The region list is empty. The region file \"", "\"'{:s}' will be empty.\"", ".", "format", "(", "outfile", ")", ")", "try", ":", "out...
34.721311
21.163934
def render(cls, obj): """ Using any display hooks that have been registered, render the object to a dictionary of MIME types and metadata information. """ class_hierarchy = inspect.getmro(type(obj)) hooks = [] for _, type_hooks in cls._display_hooks.items(): ...
[ "def", "render", "(", "cls", ",", "obj", ")", ":", "class_hierarchy", "=", "inspect", ".", "getmro", "(", "type", "(", "obj", ")", ")", "hooks", "=", "[", "]", "for", "_", ",", "type_hooks", "in", "cls", ".", "_display_hooks", ".", "items", "(", ")...
31.863636
14.136364
def silent_parse_args(self, command, args): """ Silently attempt to parse args. If there is a failure then we ignore the effects. Using an in-place namespace object ensures we capture as many of the valid arguments as possible when the argparse system would otherwise throw away the res...
[ "def", "silent_parse_args", "(", "self", ",", "command", ",", "args", ")", ":", "args_ns", "=", "argparse", ".", "Namespace", "(", ")", "stderr_save", "=", "argparse", ".", "_sys", ".", "stderr", "stdout_save", "=", "argparse", ".", "_sys", ".", "stdout", ...
43.166667
12.166667
def delete(self, fnames=None): """Delete files""" if fnames is None: fnames = self.get_selected_filenames() multiple = len(fnames) > 1 yes_to_all = None for fname in fnames: if fname == self.proxymodel.path_list[0]: self.sig_delete_...
[ "def", "delete", "(", "self", ",", "fnames", "=", "None", ")", ":", "if", "fnames", "is", "None", ":", "fnames", "=", "self", ".", "get_selected_filenames", "(", ")", "multiple", "=", "len", "(", "fnames", ")", ">", "1", "yes_to_all", "=", "None", "f...
38.428571
13.357143
def parse_instance_count(instance_count, speaker_total_count): """This parses the instance count dictionary (that may contain floats from 0.0 to 1.0 representing a percentage) and converts it to actual instance count. """ # Use all the instances of a speaker unless specified result = copy.copy(...
[ "def", "parse_instance_count", "(", "instance_count", ",", "speaker_total_count", ")", ":", "# Use all the instances of a speaker unless specified", "result", "=", "copy", ".", "copy", "(", "speaker_total_count", ")", "for", "speaker_id", ",", "count", "in", "instance_cou...
35.315789
19.157895
def date_this_decade(self, before_today=True, after_today=False): """ Gets a Date object for the decade year. :param before_today: include days in current decade before today :param after_today: include days in current decade after today :example Date('2012-04-04') :retu...
[ "def", "date_this_decade", "(", "self", ",", "before_today", "=", "True", ",", "after_today", "=", "False", ")", ":", "today", "=", "date", ".", "today", "(", ")", "this_decade_start", "=", "date", "(", "today", ".", "year", "-", "(", "today", ".", "ye...
41.952381
19.952381
def spop(self, name, count=None): "Remove and return a random member of set ``name``" args = (count is not None) and [count] or [] return self.execute_command('SPOP', name, *args)
[ "def", "spop", "(", "self", ",", "name", ",", "count", "=", "None", ")", ":", "args", "=", "(", "count", "is", "not", "None", ")", "and", "[", "count", "]", "or", "[", "]", "return", "self", ".", "execute_command", "(", "'SPOP'", ",", "name", ","...
50
13.5
def get_remote_addr(self, forwarded_for): """Selects the new remote addr from the given list of ips in X-Forwarded-For. By default it picks the one that the `num_proxies` proxy server provides. Before 0.9 it would always pick the first. .. versionadded:: 0.8 """ if len...
[ "def", "get_remote_addr", "(", "self", ",", "forwarded_for", ")", ":", "if", "len", "(", "forwarded_for", ")", ">=", "self", ".", "num_proxies", ":", "return", "forwarded_for", "[", "-", "1", "*", "self", ".", "num_proxies", "]" ]
44.888889
16.333333
def _git_dir(repo, path): """ Find the git dir that's appropriate for the path""" name = "%s" % (path,) if name in ['HEAD', 'ORIG_HEAD', 'FETCH_HEAD', 'index', 'logs']: return repo.git_dir return repo.common_dir
[ "def", "_git_dir", "(", "repo", ",", "path", ")", ":", "name", "=", "\"%s\"", "%", "(", "path", ",", ")", "if", "name", "in", "[", "'HEAD'", ",", "'ORIG_HEAD'", ",", "'FETCH_HEAD'", ",", "'index'", ",", "'logs'", "]", ":", "return", "repo", ".", "g...
38.333333
14.166667
def get_hexdigest(algorithm, salt, raw_password): """ Returns a string of the hexdigest of the given plaintext password and salt using the given algorithm ('md5', 'sha1' or 'crypt'). """ if isinstance(salt, unicode): salt = salt.encode('utf8') if algorithm == 'crypt': try...
[ "def", "get_hexdigest", "(", "algorithm", ",", "salt", ",", "raw_password", ")", ":", "if", "isinstance", "(", "salt", ",", "unicode", ")", ":", "salt", "=", "salt", ".", "encode", "(", "'utf8'", ")", "if", "algorithm", "==", "'crypt'", ":", "try", ":"...
39.666667
17.4
def process_string_tensor_event(event): """Convert a TensorEvent into a JSON-compatible response.""" string_arr = tensor_util.make_ndarray(event.tensor_proto) html = text_array_to_html(string_arr) return { 'wall_time': event.wall_time, 'step': event.step, 'text': html, }
[ "def", "process_string_tensor_event", "(", "event", ")", ":", "string_arr", "=", "tensor_util", ".", "make_ndarray", "(", "event", ".", "tensor_proto", ")", "html", "=", "text_array_to_html", "(", "string_arr", ")", "return", "{", "'wall_time'", ":", "event", "....
32.333333
14.333333
def _opcode_set(*names): """Return a set of opcodes by the names in `names`.""" s = set() for name in names: try: s.add(_opcode(name)) except KeyError: pass return s
[ "def", "_opcode_set", "(", "*", "names", ")", ":", "s", "=", "set", "(", ")", "for", "name", "in", "names", ":", "try", ":", "s", ".", "add", "(", "_opcode", "(", "name", ")", ")", "except", "KeyError", ":", "pass", "return", "s" ]
23.666667
18.333333
def changeRequestPosition(self, request_position, **kwargs): """Change the position of the thing. :param request_position: The new position for the slide (0-100) :param thing: a string with the name of the thing, which is then checked using getThings. :param thingUri: Uri (string) of th...
[ "def", "changeRequestPosition", "(", "self", ",", "request_position", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "'key'", "]", "=", "\"requestPosition\"", "kwargs", "[", "'value'", "]", "=", "request_position", "return", "self", ".", "changeKey", "(", ...
59.384615
27.769231
def combine_first(self, other): """Combine two Datasets, default to data_vars of self. The new coordinates follow the normal broadcasting and alignment rules of ``join='outer'``. Vacant cells in the expanded coordinates are filled with np.nan. Parameters ---------- ...
[ "def", "combine_first", "(", "self", ",", "other", ")", ":", "out", "=", "ops", ".", "fillna", "(", "self", ",", "other", ",", "join", "=", "\"outer\"", ",", "dataset_join", "=", "\"outer\"", ")", "return", "out" ]
30.5
23.777778
def load(cls, query_name): """Load a pre-made query. These queries are distributed with lsstprojectmeta. See :file:`lsstrojectmeta/data/githubv4/README.rst` inside the package repository for details on available queries. Parameters ---------- query_name : `str` ...
[ "def", "load", "(", "cls", ",", "query_name", ")", ":", "template_path", "=", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "__file__", ")", ",", "'../data/githubv4'", ",", "query_name", "+", "'.graphql'", ")", "with", "o...
30.740741
18.296296
def _load_data(self, band): """From the WISE All-Sky Explanatory Supplement, IV.4.h.i.1, and Jarrett+ 2011. These are relative response per erg and so can be integrated directly against F_nu spectra. Wavelengths are in micron, uncertainties are in parts per thousand. """ ...
[ "def", "_load_data", "(", "self", ",", "band", ")", ":", "# `band` should be 1, 2, 3, or 4.", "df", "=", "bandpass_data_frame", "(", "'filter_wise_'", "+", "str", "(", "band", ")", "+", "'.dat'", ",", "'wlen resp uncert'", ")", "df", ".", "wlen", "*=", "1e4", ...
47.571429
17.571429
def validate_owner_repo(ctx, param, value): """Ensure that owner/repo is formatted correctly.""" # pylint: disable=unused-argument form = "OWNER/REPO" return validate_slashes(param, value, minimum=2, maximum=2, form=form)
[ "def", "validate_owner_repo", "(", "ctx", ",", "param", ",", "value", ")", ":", "# pylint: disable=unused-argument", "form", "=", "\"OWNER/REPO\"", "return", "validate_slashes", "(", "param", ",", "value", ",", "minimum", "=", "2", ",", "maximum", "=", "2", ",...
46.6
11.4
def find_out_pattern(self, pattern): """ This function will read the standard error of the program and return a matching pattern if found. EG. prog_obj.FindErrPattern("Update of mySQL failed") """ if self.wdir != '': stdout = "%s/%s"%(self.wdir, self.stdout) else: ...
[ "def", "find_out_pattern", "(", "self", ",", "pattern", ")", ":", "if", "self", ".", "wdir", "!=", "''", ":", "stdout", "=", "\"%s/%s\"", "%", "(", "self", ".", "wdir", ",", "self", ".", "stdout", ")", "else", ":", "stdout", "=", "self", ".", "stdo...
36.15
13.7
def handle_update(self, action, params): """Handle the specified action on this component.""" _LOGGER.debug('Keypad: "%s" %s Action: %s Params: %s"' % ( self._keypad.name, self, action, params)) if action != Led._ACTION_LED_STATE: _LOGGER.debug("Unknown action %d for led %d in keypad...
[ "def", "handle_update", "(", "self", ",", "action", ",", "params", ")", ":", "_LOGGER", ".", "debug", "(", "'Keypad: \"%s\" %s Action: %s Params: %s\"'", "%", "(", "self", ".", "_keypad", ".", "name", ",", "self", ",", "action", ",", "params", ")", ")", "i...
45.0625
16.5625
def index(request, obj_id): """Handles a request based on method and calls the appropriate function""" if request.method == 'GET': return get(request, obj_id) elif request.method == 'PUT': getPutData(request) return put(request, obj_id)
[ "def", "index", "(", "request", ",", "obj_id", ")", ":", "if", "request", ".", "method", "==", "'GET'", ":", "return", "get", "(", "request", ",", "obj_id", ")", "elif", "request", ".", "method", "==", "'PUT'", ":", "getPutData", "(", "request", ")", ...
38
7.428571
def setup(app): """Allow this package to be used as Sphinx extension. This is also called from the top-level ``__init__.py``. :type app: sphinx.application.Sphinx """ from .patches import patch_django_for_autodoc # When running, make sure Django doesn't execute querysets patch_django_for_a...
[ "def", "setup", "(", "app", ")", ":", "from", ".", "patches", "import", "patch_django_for_autodoc", "# When running, make sure Django doesn't execute querysets", "patch_django_for_autodoc", "(", ")", "# Generate docstrings for Django model fields", "# Register the docstring processor...
33.235294
18.764706
def from_api(cls, api): """ create an application description for the todo app, that based on the api can use either tha api or the ux for interaction """ ux = TodoUX(api) from .pseudorpc import PseudoRpc rpc = PseudoRpc(api) return cls({ViaAPI: api, Via...
[ "def", "from_api", "(", "cls", ",", "api", ")", ":", "ux", "=", "TodoUX", "(", "api", ")", "from", ".", "pseudorpc", "import", "PseudoRpc", "rpc", "=", "PseudoRpc", "(", "api", ")", "return", "cls", "(", "{", "ViaAPI", ":", "api", ",", "ViaUX", ":"...
30.090909
18.090909
def get_header(self, request): """ Extracts the header containing the JSON web token from the given request. """ header = request.META.get('HTTP_AUTHORIZATION') if isinstance(header, str): # Work around django test client oddness header = header.e...
[ "def", "get_header", "(", "self", ",", "request", ")", ":", "header", "=", "request", ".", "META", ".", "get", "(", "'HTTP_AUTHORIZATION'", ")", "if", "isinstance", "(", "header", ",", "str", ")", ":", "# Work around django test client oddness", "header", "=",...
29.916667
17.75
def _set_wait_for_bgp(self, v, load=False): """ Setter method for wait_for_bgp, mapped from YANG variable /routing_system/router/isis/router_isis_cmds_holder/router_isis_attributes/set_overload_bit/on_startup/wait_for_bgp (container) If this variable is read-only (config: false) in the source YANG file,...
[ "def", "_set_wait_for_bgp", "(", "self", ",", "v", ",", "load", "=", "False", ")", ":", "if", "hasattr", "(", "v", ",", "\"_utype\"", ")", ":", "v", "=", "v", ".", "_utype", "(", "v", ")", "try", ":", "t", "=", "YANGDynClass", "(", "v", ",", "b...
77.272727
37.772727