text
stringlengths
75
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
0.18
def department_create(self, data, **kwargs): "https://developer.zendesk.com/rest_api/docs/chat/departments#create-department" api_path = "/api/v2/departments" return self.call(api_path, method="POST", data=data, **kwargs)
[ "def", "department_create", "(", "self", ",", "data", ",", "*", "*", "kwargs", ")", ":", "api_path", "=", "\"/api/v2/departments\"", "return", "self", ".", "call", "(", "api_path", ",", "method", "=", "\"POST\"", ",", "data", "=", "data", ",", "*", "*", ...
60.5
0.012245
def suffix(filename,suffix): ''' returns a filenames with ``suffix`` inserted before the dataset suffix ''' return os.path.split(re.sub(_afni_suffix_regex,"%s\g<1>" % suffix,str(filename)))[1]
[ "def", "suffix", "(", "filename", ",", "suffix", ")", ":", "return", "os", ".", "path", ".", "split", "(", "re", ".", "sub", "(", "_afni_suffix_regex", ",", "\"%s\\g<1>\"", "%", "suffix", ",", "str", "(", "filename", ")", ")", ")", "[", "1", "]" ]
66
0.035
def is_period(arr): """ Check whether an array-like is a periodical index. .. deprecated:: 0.24.0 Parameters ---------- arr : array-like The array-like to check. Returns ------- boolean Whether or not the array-like is a periodical index. Examples --------...
[ "def", "is_period", "(", "arr", ")", ":", "warnings", ".", "warn", "(", "\"'is_period' is deprecated and will be removed in a future \"", "\"version. Use 'is_period_dtype' or is_period_arraylike' \"", "\"instead.\"", ",", "FutureWarning", ",", "stacklevel", "=", "2", ")", "r...
23.967742
0.001294
def get(self, *args, **kwargs): """Get an item from the cache for this combination of args and kwargs. Args: *args: any arguments. **kwargs: any keyword arguments. Returns: object: The object which has been found in the cache, or `None` if no une...
[ "def", "get", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "not", "self", ".", "enabled", ":", "return", "None", "# Look in the cache to see if there is an unexpired item. If there is", "# we can just return the cached result.", "cache_key", ...
34.866667
0.00186
def x_y_by_col_lbl(df, y_col_lbl): """Returns an X dataframe and a y series by the given column name. Parameters ---------- df : pandas.DataFrame The dataframe to split. y_col_lbl : object The label of the y column. Returns ------- X, y : pandas.DataFrame, pandas.Series...
[ "def", "x_y_by_col_lbl", "(", "df", ",", "y_col_lbl", ")", ":", "x_cols", "=", "[", "col", "for", "col", "in", "df", ".", "columns", "if", "col", "!=", "y_col_lbl", "]", "return", "df", "[", "x_cols", "]", ",", "df", "[", "y_col_lbl", "]" ]
25.818182
0.001131
def research(self, upgrade, *args, **kwargs): """ Requires UpgradeId to be passed instead of AbilityId """ return self(self._game_data.upgrades[upgrade.value].research_ability.id, *args, **kwargs)
[ "def", "research", "(", "self", ",", "upgrade", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "self", "(", "self", ".", "_game_data", ".", "upgrades", "[", "upgrade", ".", "value", "]", ".", "research_ability", ".", "id", ",", "*", ...
70
0.014151
def insert(self, key, minhash, check_duplication=True): ''' Insert a key to the index, together with a MinHash (or weighted MinHash) of the set referenced by the key. :param str key: The identifier of the set. :param datasketch.MinHash minhash: The MinHash of the set. ...
[ "def", "insert", "(", "self", ",", "key", ",", "minhash", ",", "check_duplication", "=", "True", ")", ":", "self", ".", "_insert", "(", "key", ",", "minhash", ",", "check_duplication", "=", "check_duplication", ",", "buffer", "=", "False", ")" ]
53.785714
0.009138
def get_events_by_date_range(days_out, days_hold, max_num=5, featured=False): """ Get upcoming events for a given number of days (days out) Allows specifying number of days to hold events after they've started The max number to show (defaults to 5) and whether they should be featured or not. Usa...
[ "def", "get_events_by_date_range", "(", "days_out", ",", "days_hold", ",", "max_num", "=", "5", ",", "featured", "=", "False", ")", ":", "from", "happenings", ".", "models", "import", "Event", "range_start", "=", "today", "-", "datetime", ".", "timedelta", "...
39.043478
0.001087
def _handle_configspec(self, configspec): """Parse the configspec.""" # FIXME: Should we check that the configspec was created with the # correct settings ? (i.e. ``list_values=False``) if not isinstance(configspec, ConfigObj): try: configspec = ConfigO...
[ "def", "_handle_configspec", "(", "self", ",", "configspec", ")", ":", "# FIXME: Should we check that the configspec was created with the", "# correct settings ? (i.e. ``list_values=False``)", "if", "not", "isinstance", "(", "configspec", ",", "ConfigObj", ")", ":", "try...
47.666667
0.002286
def request( self, url, method='get', decode=None, encode=None, data=None, headers=None, raise_for=dict(), queue_lines=None ): '''Make HTTP(S) request. headers can be either dict or callable(url, method, body, mimetype or None). decode (response body) = None | json. encode (data) = None | json | form |...
[ "def", "request", "(", "self", ",", "url", ",", "method", "=", "'get'", ",", "decode", "=", "None", ",", "encode", "=", "None", ",", "data", "=", "None", ",", "headers", "=", "None", ",", "raise_for", "=", "dict", "(", ")", ",", "queue_lines", "=",...
40.525773
0.030544
def formatException(self, exc_info, record=None): """Format exception output with CONF.logging_exception_prefix.""" if not record: return logging.Formatter.formatException(self, exc_info) stringbuffer = cStringIO.StringIO() traceback.print_exception(exc_info[0], exc_info[1],...
[ "def", "formatException", "(", "self", ",", "exc_info", ",", "record", "=", "None", ")", ":", "if", "not", "record", ":", "return", "logging", ".", "Formatter", ".", "formatException", "(", "self", ",", "exc_info", ")", "stringbuffer", "=", "cStringIO", "....
41.2
0.002372
def _njobs(self): """%(InteractiveBase._njobs)s""" ret = super(self.__class__, self)._njobs or [0] ret[0] += 1 return ret
[ "def", "_njobs", "(", "self", ")", ":", "ret", "=", "super", "(", "self", ".", "__class__", ",", "self", ")", ".", "_njobs", "or", "[", "0", "]", "ret", "[", "0", "]", "+=", "1", "return", "ret" ]
29.8
0.013072
def salt_api_acl_tool(username, request): ''' ..versionadded:: 2016.3.0 Verifies user requests against the API whitelist. (User/IP pair) in order to provide whitelisting for the API similar to the master, but over the API. ..code-block:: yaml rest_cherrypy: api_acl: ...
[ "def", "salt_api_acl_tool", "(", "username", ",", "request", ")", ":", "failure_str", "=", "(", "\"[api_acl] Authentication failed for \"", "\"user %s from IP %s\"", ")", "success_str", "=", "(", "\"[api_acl] Authentication sucessful for \"", "\"user %s from IP %s\"", ")", "p...
32.447761
0.000446
def UpdateValues(self, grid): "Update all displayed values" # This sends an event to the grid table to update all of the values msg = gridlib.GridTableMessage(self, gridlib.GRIDTABLE_REQUEST_VIEW_GET_VALUES) grid.ProcessTableMessage(msg)
[ "def", "UpdateValues", "(", "self", ",", "grid", ")", ":", "# This sends an event to the grid table to update all of the values\r", "msg", "=", "gridlib", ".", "GridTableMessage", "(", "self", ",", "gridlib", ".", "GRIDTABLE_REQUEST_VIEW_GET_VALUES", ")", "grid", ".", "...
51
0.012862
def ids_and_clean_visible_from_streamcorpus_chunk_path(corpus_path): '''converts a streamcorpus.Chunk file into the structure that is passed by the search engine to find_soft_selectors ''' ch = clean_html(clean_html.default_config) cv = clean_visible(clean_visible.default_config) ids_and_clean_...
[ "def", "ids_and_clean_visible_from_streamcorpus_chunk_path", "(", "corpus_path", ")", ":", "ch", "=", "clean_html", "(", "clean_html", ".", "default_config", ")", "cv", "=", "clean_visible", "(", "clean_visible", ".", "default_config", ")", "ids_and_clean_visible", "=",...
41.25
0.001692
def detect_format(filename): """Detect file format of the channels based on extension. Parameters ---------- filename : Path name of the filename Returns ------- str file format """ filename = Path(filename) if filename.suffix == '.csv': recformat = 'cs...
[ "def", "detect_format", "(", "filename", ")", ":", "filename", "=", "Path", "(", "filename", ")", "if", "filename", ".", "suffix", "==", "'.csv'", ":", "recformat", "=", "'csv'", "elif", "filename", ".", "suffix", "==", "'.sfp'", ":", "recformat", "=", "...
17.666667
0.002237
def _disambiguate_sid_ksid( words_layer, text, scope=CLAUSES ): ''' Disambiguates verb forms based on existence of 2nd person pronoun ('sina') in given scope. The scope could be either CLAUSES or SENTENCES. ''' assert scope in [CLAUSES, SENTENCES], '(!) The scope should be either "clauses" or "sente...
[ "def", "_disambiguate_sid_ksid", "(", "words_layer", ",", "text", ",", "scope", "=", "CLAUSES", ")", ":", "assert", "scope", "in", "[", "CLAUSES", ",", "SENTENCES", "]", ",", "'(!) The scope should be either \"clauses\" or \"sentences\".'", "group_indices", "=", "get_...
64.069767
0.025384
def inrypl(vertex, direct, plane): """ Find the intersection of a ray and a plane. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/inrypl_c.html :param vertex: Vertex vector of ray. :type vertex: 3-Element Array of floats :param direct: Direction vector of ray. :type direct: 3-Elem...
[ "def", "inrypl", "(", "vertex", ",", "direct", ",", "plane", ")", ":", "assert", "(", "isinstance", "(", "plane", ",", "stypes", ".", "Plane", ")", ")", "vertex", "=", "stypes", ".", "toDoubleVector", "(", "vertex", ")", "direct", "=", "stypes", ".", ...
35.076923
0.001067
def add_xlabel(self, text=None): """ Add a label to the x-axis. """ x = self.fit.meta['independent'] if not text: text = '$' + x['tex_symbol'] + r'$ $(\si{' + x['siunitx'] + r'})$' self.plt.set_xlabel(text)
[ "def", "add_xlabel", "(", "self", ",", "text", "=", "None", ")", ":", "x", "=", "self", ".", "fit", ".", "meta", "[", "'independent'", "]", "if", "not", "text", ":", "text", "=", "'$'", "+", "x", "[", "'tex_symbol'", "]", "+", "r'$ $(\\si{'", "+", ...
32.5
0.011236
def miniaturize(self): ''' Tries to scrape the miniaturized version from vandale.nl. ''' element = self._first('NN') if element: if re.search('verkleinwoord: (\w+)', element, re.U): return re.findall('verkleinwoord: (\w+)', element, re.U) else: return [''] return [None]
[ "def", "miniaturize", "(", "self", ")", ":", "element", "=", "self", ".", "_first", "(", "'NN'", ")", "if", "element", ":", "if", "re", ".", "search", "(", "'verkleinwoord: (\\w+)'", ",", "element", ",", "re", ".", "U", ")", ":", "return", "re", ".",...
28.4
0.040956
def _switch(name, # pylint: disable=C0103 on, # pylint: disable=C0103 **kwargs): ''' Switch on/off service start at boot. .. versionchanged:: 2016.3.4 Support for jail (representing jid or jail name) and chroot keyword argument in kwarg...
[ "def", "_switch", "(", "name", ",", "# pylint: disable=C0103", "on", ",", "# pylint: disable=C0103", "*", "*", "kwargs", ")", ":", "jail", "=", "kwargs", ".", "get", "(", "'jail'", ",", "''", ")", "chroot", "=", "kwargs", ".", "get", "(", "'chroot'", ","...
35.285714
0.001969
def get_file(self, file_path): """ There are many types of execptions which can get raised from this method. We want to make sure we only return None when the file doesn't exist. """ try: resp = self._conn.get_object( Bucket=self._path.bucket, Key=self.get_path_to_fi...
[ "def", "get_file", "(", "self", ",", "file_path", ")", ":", "try", ":", "resp", "=", "self", ".", "_conn", ".", "get_object", "(", "Bucket", "=", "self", ".", "_path", ".", "bucket", ",", "Key", "=", "self", ".", "get_path_to_file", "(", "file_path", ...
27.086957
0.012403
def sample_batch_transitions(self, batch_size, forward_steps=1): """ Return indexes of next sample""" results = [] for i in range(self.num_envs): results.append(self.sample_frame_single_env(batch_size, forward_steps=forward_steps)) return np.stack(results, axis=-1)
[ "def", "sample_batch_transitions", "(", "self", ",", "batch_size", ",", "forward_steps", "=", "1", ")", ":", "results", "=", "[", "]", "for", "i", "in", "range", "(", "self", ".", "num_envs", ")", ":", "results", ".", "append", "(", "self", ".", "sampl...
38
0.009646
def get_translation_obj(self, lang, field, create=False): """ Return the translation object of an specific field in a Translatable istance @type lang: string @param lang: a string with the name of the language @type field: string @param field: a string with the ...
[ "def", "get_translation_obj", "(", "self", ",", "lang", ",", "field", ",", "create", "=", "False", ")", ":", "trans", "=", "None", "try", ":", "trans", "=", "Translation", ".", "objects", ".", "get", "(", "object_id", "=", "self", ".", "id", ",", "co...
31.806452
0.001969
def fsplit(file_to_split): """ Split the file and return the list of filenames. """ dirname = file_to_split + '_splitted' if not os.path.exists(dirname): os.mkdir(dirname) part_file_size = os.path.getsize(file_to_split) / number_of_files + 1 splitted_files = [] with open(file...
[ "def", "fsplit", "(", "file_to_split", ")", ":", "dirname", "=", "file_to_split", "+", "'_splitted'", "if", "not", "os", ".", "path", ".", "exists", "(", "dirname", ")", ":", "os", ".", "mkdir", "(", "dirname", ")", "part_file_size", "=", "os", ".", "p...
31.452381
0.000734
def path_to_resource(project, path, type=None): """Get the resource at path You only need to specify `type` if `path` does not exist. It can be either 'file' or 'folder'. If the type is `None` it is assumed that the resource already exists. Note that this function uses `Project.get_resource()`, ...
[ "def", "path_to_resource", "(", "project", ",", "path", ",", "type", "=", "None", ")", ":", "project_path", "=", "path_relative_to_project_root", "(", "project", ",", "path", ")", "if", "project_path", "is", "None", ":", "project_path", "=", "rope", ".", "ba...
36.409091
0.001217
def flux_minimization(model, fixed, solver, weights={}): """Minimize flux of all reactions while keeping certain fluxes fixed. The fixed reactions are given in a dictionary as reaction id to value mapping. The weighted L1-norm of the fluxes is minimized. Args: model: MetabolicModel to solve. ...
[ "def", "flux_minimization", "(", "model", ",", "fixed", ",", "solver", ",", "weights", "=", "{", "}", ")", ":", "fba", "=", "FluxBalanceProblem", "(", "model", ",", "solver", ")", "for", "reaction_id", ",", "value", "in", "iteritems", "(", "fixed", ")", ...
33.038462
0.001131
def commit_manually(using=None): """ Decorator that activates manual transaction control. It just disables automatic transaction control and doesn't do any commit/rollback of its own -- it's up to the user to call the commit and rollback functions themselves. """ def entering(using): ...
[ "def", "commit_manually", "(", "using", "=", "None", ")", ":", "def", "entering", "(", "using", ")", ":", "enter_transaction_management", "(", "using", "=", "using", ")", "def", "exiting", "(", "exc_value", ",", "using", ")", ":", "leave_transaction_management...
35.071429
0.001984
def get_poll_options(tweet): """ Get the text in the options of a poll as a list - If there is no poll in the Tweet, return an empty list - If the Tweet is in activity-streams format, raise 'NotAvailableError' Args: tweet (Tweet or dict): A Tweet object or dictionary Returns: l...
[ "def", "get_poll_options", "(", "tweet", ")", ":", "if", "is_original_format", "(", "tweet", ")", ":", "try", ":", "poll_options_text", "=", "[", "]", "for", "p", "in", "tweet", "[", "\"entities\"", "]", "[", "\"polls\"", "]", ":", "for", "o", "in", "p...
35.9375
0.001129
def pileup_reads_at_position(samfile, chromosome, base0_position): """ Returns a pileup column at the specified position. Unclear if a function like this is hiding somewhere in pysam API. """ # TODO: I want to pass truncate=True, stepper="all" # but for some reason I get this error: # ...
[ "def", "pileup_reads_at_position", "(", "samfile", ",", "chromosome", ",", "base0_position", ")", ":", "# TODO: I want to pass truncate=True, stepper=\"all\"", "# but for some reason I get this error:", "# pileup() got an unexpected keyword argument 'truncate'", "# ...even though thes...
33.038462
0.001131
def upcoming(cls, api_key=None, stripe_account=None, **params): """Return a deferred.""" url = cls.class_url() + '/upcoming' return cls.request('get', url, params)
[ "def", "upcoming", "(", "cls", ",", "api_key", "=", "None", ",", "stripe_account", "=", "None", ",", "*", "*", "params", ")", ":", "url", "=", "cls", ".", "class_url", "(", ")", "+", "'/upcoming'", "return", "cls", ".", "request", "(", "'get'", ",", ...
46
0.010695
def update_offer(self, offer_id, offer_dict): """ Updates an offer :param offer_id: the offer id :param offer_dict: dict :return: dict """ return self._create_put_request(resource=OFFERS, billomat_id=offer_id, send_data=offer_dict)
[ "def", "update_offer", "(", "self", ",", "offer_id", ",", "offer_dict", ")", ":", "return", "self", ".", "_create_put_request", "(", "resource", "=", "OFFERS", ",", "billomat_id", "=", "offer_id", ",", "send_data", "=", "offer_dict", ")" ]
31.111111
0.010417
def setRect(self, *args): """ Sets the rect of the region. Accepts the following arguments: setRect(rect_tuple) setRect(x, y, w, h) setRect(rect_region) """ if len(args) == 1: if isinstance(args[0], tuple): x, y, w, h = args[0] eli...
[ "def", "setRect", "(", "self", ",", "*", "args", ")", ":", "if", "len", "(", "args", ")", "==", "1", ":", "if", "isinstance", "(", "args", "[", "0", "]", ",", "tuple", ")", ":", "x", ",", "y", ",", "w", ",", "h", "=", "args", "[", "0", "]...
30.461538
0.002448
def main(argv=sys.argv[1:]): global main_thread global vaex global app global kernel global ipython_console global current vaex.set_log_level_warning() if app is None: app = QtGui.QApplication(argv) if not (frozen and darwin): # osx app has its own icon file ...
[ "def", "main", "(", "argv", "=", "sys", ".", "argv", "[", "1", ":", "]", ")", ":", "global", "main_thread", "global", "vaex", "global", "app", "global", "kernel", "global", "ipython_console", "global", "current", "vaex", ".", "set_log_level_warning", "(", ...
32.632911
0.00113
def mremove(self, class_name, names): """ Removes multiple components from the network. Removes them from component DataFrames. Parameters ---------- class_name : string Component class name name : list-like Component names Examp...
[ "def", "mremove", "(", "self", ",", "class_name", ",", "names", ")", ":", "if", "class_name", "not", "in", "self", ".", "components", ":", "logger", ".", "error", "(", "\"Component class {} not found\"", ".", "format", "(", "class_name", ")", ")", "return", ...
24.470588
0.002312
def set_label(self, value,callb=None): """Convenience method to set the label of the device This method will send a SetLabel message to the device, and request callb be executed when an ACK is received. The default callback will simply cache the value. :param value: The new label ...
[ "def", "set_label", "(", "self", ",", "value", ",", "callb", "=", "None", ")", ":", "if", "len", "(", "value", ")", ">", "32", ":", "value", "=", "value", "[", ":", "32", "]", "mypartial", "=", "partial", "(", "self", ".", "resp_set_label", ",", ...
42.904762
0.021716
def glance(self, user, **kwargs): """Send a glance to the user. The default property is ``text``, as this is used on most glances, however a valid glance does not need to require text and can be constructed using any combination of valid keyword properties. The list of valid keywords is ...
[ "def", "glance", "(", "self", ",", "user", ",", "*", "*", "kwargs", ")", ":", "payload", "=", "{", "\"user\"", ":", "user", ",", "\"token\"", ":", "self", ".", "token", "}", "for", "key", ",", "value", "in", "kwargs", ".", "iteritems", "(", ")", ...
44.473684
0.002317
def clustering_coef_wu_sign(W, coef_type='default'): ''' Returns the weighted clustering coefficient generalized or separated for positive and negative weights. Three Algorithms are supported; herefore referred to as default, zhang, and constantini. 1. Default (Onnela et al.), as in the trad...
[ "def", "clustering_coef_wu_sign", "(", "W", ",", "coef_type", "=", "'default'", ")", ":", "n", "=", "len", "(", "W", ")", "np", ".", "fill_diagonal", "(", "W", ",", "0", ")", "if", "coef_type", "==", "'default'", ":", "W_pos", "=", "W", "*", "(", "...
34.980198
0.000551
def get_hyperedge_id_mapping(H): """Generates mappings between the set of hyperedge IDs and integer indices (where every hyperedge ID corresponds to exactly 1 integer index). :param H: the hypergraph to find the hyperedge ID mapping on. :returns: dict -- for each integer index, maps the index to the hy...
[ "def", "get_hyperedge_id_mapping", "(", "H", ")", ":", "if", "not", "isinstance", "(", "H", ",", "UndirectedHypergraph", ")", ":", "raise", "TypeError", "(", "\"Algorithm only applicable to undirected hypergraphs\"", ")", "indices_to_hyperedge_ids", ",", "hyperedge_ids_to...
44.434783
0.000958
def data(self): """Get the data from the current state of widgets. :returns: Profile data in dictionary. :rtype: dict """ if len(self.widget_items) == 0: return data = {} for hazard_item in self.widget_items: hazard = hazard_item.data(0, Q...
[ "def", "data", "(", "self", ")", ":", "if", "len", "(", "self", ".", "widget_items", ")", "==", "0", ":", "return", "data", "=", "{", "}", "for", "hazard_item", "in", "self", ".", "widget_items", ":", "hazard", "=", "hazard_item", ".", "data", "(", ...
42.606061
0.001391
def Jpjmcoeff(ls, m, shift=False) -> sympy.Expr: r'''Eigenvalue of the $\Op{J}_{+}$ (:class:`Jplus`) operator .. math:: \Op{J}_{+} \ket{s, m} = \sqrt{s (s+1) - m (m+1)} \ket{s, m} where the multiplicity $s$ is implied by the size of the Hilbert space `ls`: there are $2s+1$ eigenstates with $m...
[ "def", "Jpjmcoeff", "(", "ls", ",", "m", ",", "shift", "=", "False", ")", "->", "sympy", ".", "Expr", ":", "assert", "isinstance", "(", "ls", ",", "SpinSpace", ")", "n", "=", "ls", ".", "dimension", "s", "=", "sympify", "(", "n", "-", "1", ")", ...
38.90625
0.000784
def format_field_names(obj, format_type=None): """ Takes a dict and returns it with formatted keys as set in `format_type` or `JSON_API_FORMAT_FIELD_NAMES` :format_type: Either 'dasherize', 'camelize', 'capitalize' or 'underscore' """ if format_type is None: format_type = json_api_setti...
[ "def", "format_field_names", "(", "obj", ",", "format_type", "=", "None", ")", ":", "if", "format_type", "is", "None", ":", "format_type", "=", "json_api_settings", ".", "FORMAT_FIELD_NAMES", "if", "isinstance", "(", "obj", ",", "dict", ")", ":", "formatted", ...
30.777778
0.001751
def _get_pos(self): """ Get current position for scroll bar. """ if self._canvas.height >= self._max_height: return 0 else: return self._canvas.start_line / (self._max_height - self._canvas.height + 1)
[ "def", "_get_pos", "(", "self", ")", ":", "if", "self", ".", "_canvas", ".", "height", ">=", "self", ".", "_max_height", ":", "return", "0", "else", ":", "return", "self", ".", "_canvas", ".", "start_line", "/", "(", "self", ".", "_max_height", "-", ...
32.25
0.011321
def update_params_for_auth(self, headers, querys, auth_settings): """ Updates header and query params based on authentication setting. :param headers: Header parameters dict to be updated. :param querys: Query parameters tuple list to be updated. :param auth_settings: Authentica...
[ "def", "update_params_for_auth", "(", "self", ",", "headers", ",", "querys", ",", "auth_settings", ")", ":", "config", "=", "Configuration", "(", ")", "if", "not", "auth_settings", ":", "return", "for", "auth", "in", "auth_settings", ":", "auth_setting", "=", ...
39.923077
0.001881
def send_chat_action(self, *args, **kwargs): """See :func:`send_chat_action`""" return send_chat_action(*args, **self._merge_overrides(**kwargs)).run()
[ "def", "send_chat_action", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "send_chat_action", "(", "*", "args", ",", "*", "*", "self", ".", "_merge_overrides", "(", "*", "*", "kwargs", ")", ")", ".", "run", "(", ")" ]
55
0.011976
def on_service_modify(self, svc_ref, old_properties): """ Called when a service has been modified in the framework :param svc_ref: A service reference :param old_properties: Previous properties values :return: A tuple (added, (service, reference)) if the dependency has ...
[ "def", "on_service_modify", "(", "self", ",", "svc_ref", ",", "old_properties", ")", ":", "with", "self", ".", "_lock", ":", "if", "svc_ref", "not", "in", "self", ".", "services", ":", "# A previously registered service now matches our filter", "return", "self", "...
42.909091
0.001036
def _do_multipart_upload(self, stream, metadata, size, num_retries): """Perform a multipart upload. :type stream: IO[bytes] :param stream: A bytes IO object open for reading. :type metadata: dict :param metadata: The metadata associated with the upload. :type size: int...
[ "def", "_do_multipart_upload", "(", "self", ",", "stream", ",", "metadata", ",", "size", ",", "num_retries", ")", ":", "data", "=", "stream", ".", "read", "(", "size", ")", "if", "len", "(", "data", ")", "<", "size", ":", "msg", "=", "_READ_LESS_THAN_S...
38.119048
0.001827
def _guess_apiserver(apiserver_url=None): '''Try to guees the kubemaster url from environ, then from `/etc/kubernetes/config` file ''' default_config = "/etc/kubernetes/config" if apiserver_url is not None: return apiserver_url if "KUBERNETES_MASTER" in os.environ: apiserver_url ...
[ "def", "_guess_apiserver", "(", "apiserver_url", "=", "None", ")", ":", "default_config", "=", "\"/etc/kubernetes/config\"", "if", "apiserver_url", "is", "not", "None", ":", "return", "apiserver_url", "if", "\"KUBERNETES_MASTER\"", "in", "os", ".", "environ", ":", ...
46.72
0.001678
def parse_argument(self, arg): """Parse a single argument. Lookup arg in self.specials, or call .to_python() if absent. Raise BadArgument on errors. """ lookup = self.casesensitive and arg or arg.lower() if lookup in self.special: return self.special...
[ "def", "parse_argument", "(", "self", ",", "arg", ")", ":", "lookup", "=", "self", ".", "casesensitive", "and", "arg", "or", "arg", ".", "lower", "(", ")", "if", "lookup", "in", "self", ".", "special", ":", "return", "self", ".", "special", "[", "loo...
35.615385
0.008421
def valid_mitemp_mac(mac, pat=re.compile(r"4C:65:A8:[0-9A-F]{2}:[0-9A-F]{2}:[0-9A-F]{2}")): """Check for valid mac adresses.""" if not pat.match(mac.upper()): raise argparse.ArgumentTypeError('The MAC address "{}" seems to be in the wrong format'.format(mac)) return mac
[ "def", "valid_mitemp_mac", "(", "mac", ",", "pat", "=", "re", ".", "compile", "(", "r\"4C:65:A8:[0-9A-F]{2}:[0-9A-F]{2}:[0-9A-F]{2}\"", ")", ")", ":", "if", "not", "pat", ".", "match", "(", "mac", ".", "upper", "(", ")", ")", ":", "raise", "argparse", ".",...
57.2
0.010345
def handle_simple_responses( self, timeout_ms=None, info_cb=DEFAULT_MESSAGE_CALLBACK): """Accepts normal responses from the device. Args: timeout_ms: Timeout in milliseconds to wait for each response. info_cb: Optional callback for text sent from the bootloader. Returns: OKAY packe...
[ "def", "handle_simple_responses", "(", "self", ",", "timeout_ms", "=", "None", ",", "info_cb", "=", "DEFAULT_MESSAGE_CALLBACK", ")", ":", "return", "self", ".", "_accept_responses", "(", "'OKAY'", ",", "info_cb", ",", "timeout_ms", "=", "timeout_ms", ")" ]
33.583333
0.002415
def _get_upstream(self): """Return the remote and remote merge branch for the current branch""" if not self._remote or not self._branch: branch = self.branch_name if not branch: raise Scm.LocalException('Failed to determine local branch') def get_local_config(key): value = sel...
[ "def", "_get_upstream", "(", "self", ")", ":", "if", "not", "self", ".", "_remote", "or", "not", "self", ".", "_branch", ":", "branch", "=", "self", ".", "branch_name", "if", "not", "branch", ":", "raise", "Scm", ".", "LocalException", "(", "'Failed to d...
44.6
0.011713
def merge(self, layers): """Flattens the given layers on the canvas. Merges the given layers with the indices in the list on the bottom layer in the list. The other layers are discarded. """ layers.sort() if layers[0] == 0: del ...
[ "def", "merge", "(", "self", ",", "layers", ")", ":", "layers", ".", "sort", "(", ")", "if", "layers", "[", "0", "]", "==", "0", ":", "del", "layers", "[", "0", "]", "self", ".", "flatten", "(", "layers", ")" ]
26.615385
0.019553
def __exec_python_cmd(cmd): """ Executes an externally spawned Python interpreter and returns anything that was emitted in the standard output as a single string. """ # Prepend PYTHONPATH with pathex pp = os.pathsep.join(PyInstaller.__pathex__) old_pp = compat.getenv('PYTHONPATH') if...
[ "def", "__exec_python_cmd", "(", "cmd", ")", ":", "# Prepend PYTHONPATH with pathex", "pp", "=", "os", ".", "pathsep", ".", "join", "(", "PyInstaller", ".", "__pathex__", ")", "old_pp", "=", "compat", ".", "getenv", "(", "'PYTHONPATH'", ")", "if", "old_pp", ...
30.652174
0.001376
def get_lb_nat_rule(access_token, subscription_id, resource_group, lb_name, rule_name): '''Get details about a load balancer inbound NAT rule. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. resource_group (str): Azure resource...
[ "def", "get_lb_nat_rule", "(", "access_token", ",", "subscription_id", ",", "resource_group", ",", "lb_name", ",", "rule_name", ")", ":", "endpoint", "=", "''", ".", "join", "(", "[", "get_rm_endpoint", "(", ")", ",", "'/subscriptions/'", ",", "subscription_id",...
43.5
0.00225
def distance_sphere(self, other, radius = 6371.0): ''' -- Deprecated in v0.70. Use distance(other, ellipse = 'sphere') instead -- Returns great circle distance between two lat/lon coordinates on a sphere using the Haversine formula. The default radius corresponds to the FAI sphere ...
[ "def", "distance_sphere", "(", "self", ",", "other", ",", "radius", "=", "6371.0", ")", ":", "warnings", ".", "warn", "(", "\"Deprecated in v0.70. Use distance(other, ellipse = 'sphere') instead\"", ",", "DeprecationWarning", ")", "lat1", ",", "lon1", "=", "self", "...
42.652174
0.008973
def _spectrum(self, photon_energy): """ Compute differential spectrum from pp interactions using the parametrization of Kafexhiu, E., Aharonian, F., Taylor, A.~M., and Vila, G.~S.\ 2014, `arXiv:1406.7369 <http://www.arxiv.org/abs/1406.7369>`_. Parameters --------...
[ "def", "_spectrum", "(", "self", ",", "photon_energy", ")", ":", "# Load LUT if available, otherwise use self._diffsigma", "if", "self", ".", "useLUT", ":", "LUT_base", "=", "\"PionDecayKafexhiu14_LUT_\"", "if", "self", ".", "nuclear_enhancement", ":", "LUT_base", "+=",...
34.619048
0.002007
def _sqlfile_to_statements(sql): """ Takes a SQL string containing 0 or more statements and returns a list of individual statements as strings. Comments and empty statements are ignored. """ statements = (sqlparse.format(stmt, strip_comments=True).strip() for stmt in sqlparse.split(sql)) re...
[ "def", "_sqlfile_to_statements", "(", "sql", ")", ":", "statements", "=", "(", "sqlparse", ".", "format", "(", "stmt", ",", "strip_comments", "=", "True", ")", ".", "strip", "(", ")", "for", "stmt", "in", "sqlparse", ".", "split", "(", "sql", ")", ")",...
44.375
0.008287
def checkUserManage(self): """ Checks if the current user has granted access to this worksheet and if has also privileges for managing it. """ granted = False can_access = self.checkUserAccess() if can_access is True: pm = getToolByName(self, 'portal_memb...
[ "def", "checkUserManage", "(", "self", ")", ":", "granted", "=", "False", "can_access", "=", "self", ".", "checkUserAccess", "(", ")", "if", "can_access", "is", "True", ":", "pm", "=", "getToolByName", "(", "self", ",", "'portal_membership'", ")", "edit_allo...
39.363636
0.002255
def cla_adder(a, b, cin=0, la_unit_len=4): """ Carry Lookahead Adder :param int la_unit_len: the length of input that every unit processes A Carry LookAhead Adder is an adder that is faster than a ripple carry adder, as it calculates the carry bits faster. It is not as fast as a Kogge-Stone add...
[ "def", "cla_adder", "(", "a", ",", "b", ",", "cin", "=", "0", ",", "la_unit_len", "=", "4", ")", ":", "a", ",", "b", "=", "pyrtl", ".", "match_bitwidth", "(", "a", ",", "b", ")", "if", "len", "(", "a", ")", "<=", "la_unit_len", ":", "sum", ",...
41
0.001403
def ordered_cols(self, columns, section): """Return ordered list of columns, from given columns and the name of the section """ columns = list(columns) # might be a tuple fixed_cols = [self.key] if section.lower() == "different": fixed_cols.extend([Differ.CHANGED_MAT...
[ "def", "ordered_cols", "(", "self", ",", "columns", ",", "section", ")", ":", "columns", "=", "list", "(", "columns", ")", "# might be a tuple", "fixed_cols", "=", "[", "self", ".", "key", "]", "if", "section", ".", "lower", "(", ")", "==", "\"different\...
45.8
0.008565
def language_contents(instance): """Ensure keys in Language Content's 'contents' dictionary are valid language codes, and that the keys in the sub-dictionaries match the rules for object property names. """ if instance['type'] != 'language-content' or 'contents' not in instance: return ...
[ "def", "language_contents", "(", "instance", ")", ":", "if", "instance", "[", "'type'", "]", "!=", "'language-content'", "or", "'contents'", "not", "in", "instance", ":", "return", "for", "key", ",", "value", "in", "instance", "[", "'contents'", "]", ".", ...
52.470588
0.002203
def run(self): """ The entry point of this script to generate change log 'ChangelogGeneratorError' Is thrown when one of the specified tags was not found in list of tags. """ if not self.options.project or not self.options.user: print("Project and/or user miss...
[ "def", "run", "(", "self", ")", ":", "if", "not", "self", ".", "options", ".", "project", "or", "not", "self", ".", "options", ".", "user", ":", "print", "(", "\"Project and/or user missing. \"", "\"For help run:\\n pygcgen --help\"", ")", "return", "if", "no...
32.210526
0.001586
def __gen_random_values(self): '''Generate random values based on supplied value ranges Returns: list: random values, one per tunable variable ''' values = [] if self._value_ranges is None: self._logger.log( 'crit', 'Must ...
[ "def", "__gen_random_values", "(", "self", ")", ":", "values", "=", "[", "]", "if", "self", ".", "_value_ranges", "is", "None", ":", "self", ".", "_logger", ".", "log", "(", "'crit'", ",", "'Must set the type/range of possible values'", ")", "raise", "RuntimeE...
35.37931
0.001898
def health_checks(consul_url=None, token=None, service=None, **kwargs): ''' Health information about the registered service. :param consul_url: The Consul server URL. :param service: The service to request health information about. :param dc: By default, the datacenter of the agent is queried; ...
[ "def", "health_checks", "(", "consul_url", "=", "None", ",", "token", "=", "None", ",", "service", "=", "None", ",", "*", "*", "kwargs", ")", ":", "ret", "=", "{", "}", "query_params", "=", "{", "}", "if", "not", "consul_url", ":", "consul_url", "=",...
30
0.000828
def pitch_contour(annotation, **kwargs): '''Plotting wrapper for pitch contours''' ax = kwargs.pop('ax', None) # If the annotation is empty, we need to construct a new axes ax = mir_eval.display.__get_axes(ax=ax)[0] times, values = annotation.to_interval_values() indices = np.unique([v['index...
[ "def", "pitch_contour", "(", "annotation", ",", "*", "*", "kwargs", ")", ":", "ax", "=", "kwargs", ".", "pop", "(", "'ax'", ",", "None", ")", "# If the annotation is empty, we need to construct a new axes", "ax", "=", "mir_eval", ".", "display", ".", "__get_axes...
36.190476
0.001282
def _exec_cmd(self, command, **kwargs): """Create a new method as command has specific requirements. There is a handful of the TMSH global commands supported, so this method requires them as a parameter. :raises: InvalidCommand """ kwargs['command'] = command s...
[ "def", "_exec_cmd", "(", "self", ",", "command", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "'command'", "]", "=", "command", "self", ".", "_check_exclusive_parameters", "(", "*", "*", "kwargs", ")", "requests_params", "=", "self", ".", "_handle_req...
38.238095
0.00243
def preparse(output_format): """ Do any special processing of a template, and return the result. """ try: return templating.preparse(output_format, lambda path: os.path.join(config.config_dir, "templates", path)) except ImportError as exc: if "tempita" in str(exc): raise erro...
[ "def", "preparse", "(", "output_format", ")", ":", "try", ":", "return", "templating", ".", "preparse", "(", "output_format", ",", "lambda", "path", ":", "os", ".", "path", ".", "join", "(", "config", ".", "config_dir", ",", "\"templates\"", ",", "path", ...
51.076923
0.008876
def parse_end_date(self, request, start_date): """ Return period in days after the start date to show event occurrences, which is one of the following in order of priority: - `end_date` GET parameter value, if given and valid. The filtering will be *inclusive* of the end date...
[ "def", "parse_end_date", "(", "self", ",", "request", ",", "start_date", ")", ":", "if", "request", ".", "GET", ".", "get", "(", "'end_date'", ")", ":", "try", ":", "return", "djtz", ".", "parse", "(", "'%s 00:00'", "%", "request", ".", "GET", ".", "...
45.130435
0.001887
def compute_node_colors(self): """Compute the node colors. Also computes the colorbar.""" data = [self.graph.node[n][self.node_color] for n in self.nodes] if self.group_order == "alphabetically": data_reduced = sorted(list(set(data))) elif self.group_order == "default": ...
[ "def", "compute_node_colors", "(", "self", ")", ":", "data", "=", "[", "self", ".", "graph", ".", "node", "[", "n", "]", "[", "self", ".", "node_color", "]", "for", "n", "in", "self", ".", "nodes", "]", "if", "self", ".", "group_order", "==", "\"al...
39.375
0.001239
def updateType(self, dataset, dataset_access_type): """ Used to change the status of a dataset type (production/etc.) """ if( dataset == "" ): dbsExceptionHandler("dbsException-invalid-input", "DBSDataset/updateType. dataset is required.") conn = self.dbi.connection(...
[ "def", "updateType", "(", "self", ",", "dataset", ",", "dataset_access_type", ")", ":", "if", "(", "dataset", "==", "\"\"", ")", ":", "dbsExceptionHandler", "(", "\"dbsException-invalid-input\"", ",", "\"DBSDataset/updateType. dataset is required.\"", ")", "conn", "="...
38.909091
0.009122
def set_style(self, input_feeds): """Set target style variables. Expected usage: style_loss = StyleLoss(style_layers) ... init_op = tf.global_variables_initializer() init_op.run() feeds = {... session.run() 'feeds' argument that will make 'style_layers' ...
[ "def", "set_style", "(", "self", ",", "input_feeds", ")", ":", "sess", "=", "tf", ".", "get_default_session", "(", ")", "computed", "=", "sess", ".", "run", "(", "self", ".", "input_grams", ",", "input_feeds", ")", "for", "v", ",", "g", "in", "zip", ...
35.470588
0.008078
def phase_shifted_coefficients(amplitude_coefficients, form='cos', shift=0.0): r""" Converts Fourier coefficients from the amplitude form to the phase-shifted form, as either a sine or cosine series. Amplitude form: .. math:: m(t) ...
[ "def", "phase_shifted_coefficients", "(", "amplitude_coefficients", ",", "form", "=", "'cos'", ",", "shift", "=", "0.0", ")", ":", "if", "form", "!=", "'sin'", "and", "form", "!=", "'cos'", ":", "raise", "NotImplementedError", "(", "'Fourier series must have form ...
36.058824
0.001588
def _record_field_to_json(fields, row_value): """Convert a record/struct field to its JSON representation. Args: fields ( \ Sequence[:class:`~google.cloud.bigquery.schema.SchemaField`], \ ): The :class:`~google.cloud.bigquery.schema.SchemaField`s of the recor...
[ "def", "_record_field_to_json", "(", "fields", ",", "row_value", ")", ":", "record", "=", "{", "}", "isdict", "=", "isinstance", "(", "row_value", ",", "dict", ")", "for", "subindex", ",", "subfield", "in", "enumerate", "(", "fields", ")", ":", "subname", ...
33.888889
0.001063
def now_millis(absolute=False) -> int: """Return current millis since epoch as integer.""" millis = int(time.time() * 1e3) if absolute: return millis return millis - EPOCH_MICROS // 1000
[ "def", "now_millis", "(", "absolute", "=", "False", ")", "->", "int", ":", "millis", "=", "int", "(", "time", ".", "time", "(", ")", "*", "1e3", ")", "if", "absolute", ":", "return", "millis", "return", "millis", "-", "EPOCH_MICROS", "//", "1000" ]
32.166667
0.025253
def main(): """ NAME plot_2cdfs.py DESCRIPTION makes plots of cdfs of data in input file SYNTAX plot_2cdfs.py [-h][command line options] OPTIONS -h prints help message and quits -f FILE1 FILE2 -t TITLE -fmt [svg,eps,png,pdf,jpg..] specify f...
[ "def", "main", "(", ")", ":", "fmt", "=", "'svg'", "title", "=", "\"\"", "if", "'-h'", "in", "sys", ".", "argv", ":", "print", "(", "main", ".", "__doc__", ")", "sys", ".", "exit", "(", ")", "if", "'-f'", "in", "sys", ".", "argv", ":", "ind", ...
25.272727
0.038781
def __initialize(self, sample): """! @brief Initializes internal states and resets clustering results in line with input sample. """ self.__processed = [False] * len(sample) self.__optics_objects = [optics_descriptor(i) for i in range(len(sample))] #...
[ "def", "__initialize", "(", "self", ",", "sample", ")", ":", "self", ".", "__processed", "=", "[", "False", "]", "*", "len", "(", "sample", ")", "self", ".", "__optics_objects", "=", "[", "optics_descriptor", "(", "i", ")", "for", "i", "in", "range", ...
54.166667
0.013616
def unlock(self): "Unlock the key" if self.lockroutine: self.lockroutine.close() self.lockroutine = None if self.locked: self.locked = False self.scheduler.ignore(LockEvent.createMatcher(self.context, self.key, self))
[ "def", "unlock", "(", "self", ")", ":", "if", "self", ".", "lockroutine", ":", "self", ".", "lockroutine", ".", "close", "(", ")", "self", ".", "lockroutine", "=", "None", "if", "self", ".", "locked", ":", "self", ".", "locked", "=", "False", "self",...
35.25
0.010381
def make_network( allele_encoding_dims, kmer_size, peptide_amino_acid_encoding, embedding_input_dim, embedding_output_dim, allele_dense_layer_sizes, peptide_dense_layer_sizes, peptide_allele_merge_method, peptide...
[ "def", "make_network", "(", "allele_encoding_dims", ",", "kmer_size", ",", "peptide_amino_acid_encoding", ",", "embedding_input_dim", ",", "embedding_output_dim", ",", "allele_dense_layer_sizes", ",", "peptide_dense_layer_sizes", ",", "peptide_allele_merge_method", ",", "peptid...
37.85
0.000919
def in_simo_and_inner(self): """ Test if a node is simo: single input and multiple output """ return len(self.successor) > 1 and self.successor[0] is not None and not self.successor[0].in_or_out and \ len(self.precedence) == 1 and self.precedence[0] is not None and not sel...
[ "def", "in_simo_and_inner", "(", "self", ")", ":", "return", "len", "(", "self", ".", "successor", ")", ">", "1", "and", "self", ".", "successor", "[", "0", "]", "is", "not", "None", "and", "not", "self", ".", "successor", "[", "0", "]", ".", "in_o...
56.5
0.014535
def conv_cond_concat(x, y): """Concatenate conditioning vector on feature map axis.""" x_shapes = x.get_shape() y_shapes = y.get_shape() return tf.concat(3, [x, y*tf.ones([x_shapes[0], x_shapes[1], x_shapes[2], y_shapes[3]])])
[ "def", "conv_cond_concat", "(", "x", ",", "y", ")", ":", "x_shapes", "=", "x", ".", "get_shape", "(", ")", "y_shapes", "=", "y", ".", "get_shape", "(", ")", "return", "tf", ".", "concat", "(", "3", ",", "[", "x", ",", "y", "*", "tf", ".", "ones...
47.6
0.008264
def infer_transportation_mode(self, clf, min_time): """In-place transportation mode inferring See infer_transportation_mode function Args: Returns: :obj:`Segment`: self """ self.transportation_modes = speed_clustering(clf, self.points, min_time) retu...
[ "def", "infer_transportation_mode", "(", "self", ",", "clf", ",", "min_time", ")", ":", "self", ".", "transportation_modes", "=", "speed_clustering", "(", "clf", ",", "self", ".", "points", ",", "min_time", ")", "return", "self" ]
28.818182
0.009174
def write_table(table, path, column_styles=None, cell_styles=None): """ Exporta una tabla en el formato deseado (CSV o XLSX). La extensión del archivo debe ser ".csv" o ".xlsx", y en función de ella se decidirá qué método usar para escribirlo. Args: table (list of dicts): Tabla a ser exportada...
[ "def", "write_table", "(", "table", ",", "path", ",", "column_styles", "=", "None", ",", "cell_styles", "=", "None", ")", ":", "assert", "isinstance", "(", "path", ",", "string_types", ")", ",", "\"`path` debe ser un string\"", "assert", "isinstance", "(", "ta...
40.21875
0.000759
def IterEnumerateInstancePaths(self, ClassName, namespace=None, FilterQueryLanguage=None, FilterQuery=None, OperationTimeout=None, ContinueOnError=None, MaxObjectCount=DEFAULT_ITER_MAXOBJECTCOUNT, ...
[ "def", "IterEnumerateInstancePaths", "(", "self", ",", "ClassName", ",", "namespace", "=", "None", ",", "FilterQueryLanguage", "=", "None", ",", "FilterQuery", "=", "None", ",", "OperationTimeout", "=", "None", ",", "ContinueOnError", "=", "None", ",", "MaxObjec...
47.866171
0.000609
def config_from_prefix(prefix): """Get config from zmq prefix""" settings = {} if prefix.lower() in ('default', 'auto', ''): settings['zmq_prefix'] = '' settings['libzmq_extension'] = False settings['no_libzmq_extension'] = False elif prefix.lower() in ('bundled', 'extension'): ...
[ "def", "config_from_prefix", "(", "prefix", ")", ":", "settings", "=", "{", "}", "if", "prefix", ".", "lower", "(", ")", "in", "(", "'default'", ",", "'auto'", ",", "''", ")", ":", "settings", "[", "'zmq_prefix'", "]", "=", "''", "settings", "[", "'l...
37.0625
0.001645
def destroy(self): """Delete the MUMPS context and release all array references.""" if self.id is not None and self._mumps_c is not None: self.id.job = -2 # JOB_END self._mumps_c(self.id) self.id = None self._refs = None
[ "def", "destroy", "(", "self", ")", ":", "if", "self", ".", "id", "is", "not", "None", "and", "self", ".", "_mumps_c", "is", "not", "None", ":", "self", ".", "id", ".", "job", "=", "-", "2", "# JOB_END", "self", ".", "_mumps_c", "(", "self", ".",...
38.571429
0.01087
def parse_color(src=None): # type: (Optional[str]) -> Optional[Union[Tuple[int, ...], int]] """Parse a string representing a color value. Color is either a fixed color (when coloring something from the UI, see the GLYPHS_COLORS constant) or a list of the format [u8, u8, u8, u8], Glyphs does not su...
[ "def", "parse_color", "(", "src", "=", "None", ")", ":", "# type: (Optional[str]) -> Optional[Union[Tuple[int, ...], int]]", "if", "src", "is", "None", ":", "return", "None", "# Tuple.", "if", "src", "[", "0", "]", "==", "\"(\"", ":", "rgba", "=", "tuple", "("...
32.833333
0.001972
def drop_matching_records(self, check): """Remove a record from the DB.""" matches = self._match(check) for m in matches: del self._records[m['msg_id']]
[ "def", "drop_matching_records", "(", "self", ",", "check", ")", ":", "matches", "=", "self", ".", "_match", "(", "check", ")", "for", "m", "in", "matches", ":", "del", "self", ".", "_records", "[", "m", "[", "'msg_id'", "]", "]" ]
36.8
0.010638
def _FormatServiceText(self, service): """Produces a human readable multi-line string representing the service. Args: service (WindowsService): service to format. Returns: str: human readable representation of a Windows Service. """ string_segments = [ service.name, '\...
[ "def", "_FormatServiceText", "(", "self", ",", "service", ")", ":", "string_segments", "=", "[", "service", ".", "name", ",", "'\\tImage Path = {0:s}'", ".", "format", "(", "service", ".", "image_path", ")", ",", "'\\tService Type = {0:s}'", ".", "format", "...
37.952381
0.002448
def run(self, port): # pragma: no coverage """ Run on given port. Parse standard options and start the http server. """ tornado.options.parse_command_line() http_server = tornado.httpserver.HTTPServer(self) http_server.listen(port) tornado.ioloop.IOLoop.instance()...
[ "def", "run", "(", "self", ",", "port", ")", ":", "# pragma: no coverage", "tornado", ".", "options", ".", "parse_command_line", "(", ")", "http_server", "=", "tornado", ".", "httpserver", ".", "HTTPServer", "(", "self", ")", "http_server", ".", "listen", "(...
40.125
0.009146
def intertwine(*iterables): """Constructs an iterable which intertwines given iterables. The resulting iterable will return an item from first sequence, then from second, etc. until the last one - and then another item from first, then from second, etc. - up until all iterables are exhausted. """ ...
[ "def", "intertwine", "(", "*", "iterables", ")", ":", "iterables", "=", "tuple", "(", "imap", "(", "ensure_iterable", ",", "iterables", ")", ")", "empty", "=", "object", "(", ")", "return", "(", "item", "for", "iterable", "in", "izip_longest", "(", "*", ...
40.461538
0.001859
def get_compositions_by_asset(self, asset_id): """Gets a list of compositions including the given asset. arg: asset_id (osid.id.Id): ``Id`` of the ``Asset`` return: (osid.repository.CompositionList) - the returned ``Composition list`` raise: NotFound - ``asset_id`` i...
[ "def", "get_compositions_by_asset", "(", "self", ",", "asset_id", ")", ":", "# Implemented from template for", "# osid.repository.AssetCompositionSession.get_compositions_by_asset", "collection", "=", "JSONClientValidated", "(", "'repository'", ",", "collection", "=", "'Compositi...
49.681818
0.001795
def process_rawq(self): """Transfer from raw queue to cooked queue. Set self.eof when connection is closed. """ buf = [b'', b''] try: while self.rawq: c = yield from self.rawq_getchar() if not self.iacseq: if self.s...
[ "def", "process_rawq", "(", "self", ")", ":", "buf", "=", "[", "b''", ",", "b''", "]", "try", ":", "while", "self", ".", "rawq", ":", "c", "=", "yield", "from", "self", ".", "rawq_getchar", "(", ")", "if", "not", "self", ".", "iacseq", ":", "if",...
39.673077
0.000946
def get_coeffs(expr, expand=False, epsilon=0.): """Create a dictionary with all Operator terms of the expression (understood as a sum) as keys and their coefficients as values. The returned object is a defaultdict that return 0. if a term/key doesn't exist. Args: expr: The operator express...
[ "def", "get_coeffs", "(", "expr", ",", "expand", "=", "False", ",", "epsilon", "=", "0.", ")", ":", "if", "expand", ":", "expr", "=", "expr", ".", "expand", "(", ")", "ret", "=", "defaultdict", "(", "int", ")", "operands", "=", "expr", ".", "operan...
32.931034
0.001017
def send_response(self, code, message=None, size='-'): """ Send the response header and log the response code. Also send two standard headers with the server software version and the current date. """ # pylint: disable-msg=W0221 if self._to_log or LOG.isEnabledFo...
[ "def", "send_response", "(", "self", ",", "code", ",", "message", "=", "None", ",", "size", "=", "'-'", ")", ":", "# pylint: disable-msg=W0221", "if", "self", ".", "_to_log", "or", "LOG", ".", "isEnabledFor", "(", "logging", ".", "DEBUG", ")", ":", "self...
35.909091
0.002466
def showPanelMenu(self, panel, point=None): """ Creates the panel menu for this view widget. If no point is supplied,\ then the current cursor position will be used. :param panel | <XViewPanel> point | <QPoint> || None """ if not sel...
[ "def", "showPanelMenu", "(", "self", ",", "panel", ",", "point", "=", "None", ")", ":", "if", "not", "self", ".", "_panelMenu", ":", "self", ".", "_panelMenu", "=", "XViewPanelMenu", "(", "self", ")", "if", "point", "is", "None", ":", "point", "=", "...
33.5625
0.009058
def get_hgnc_entry(hgnc_id): """Return the HGNC entry for the given HGNC ID from the web service. Parameters ---------- hgnc_id : str The HGNC ID to be converted. Returns ------- xml_tree : ElementTree The XML ElementTree corresponding to the entry for the given HGN...
[ "def", "get_hgnc_entry", "(", "hgnc_id", ")", ":", "url", "=", "hgnc_url", "+", "'hgnc_id/%s'", "%", "hgnc_id", "headers", "=", "{", "'Accept'", ":", "'*/*'", "}", "res", "=", "requests", ".", "get", "(", "url", ",", "headers", "=", "headers", ")", "if...
26.571429
0.00173
def gen_random_name(family_name=None, gender=None, length=None): """ 指定姓氏、性别、长度,返回随机人名,也可不指定生成随机人名 :param: * family_name: (string) 姓 * gender: (string) 性别 "01" 男性, "00" 女性, 默认 None: 随机 * length: (int) 大于等于 2 小于等于 10 的整数, 默认 None: 随机 2 或者 3 :return: * full_name: (string)...
[ "def", "gen_random_name", "(", "family_name", "=", "None", ",", "gender", "=", "None", ",", "length", "=", "None", ")", ":", "family_word", "=", "(", "\"赵钱孙李周吴郑王冯陈褚卫蒋沈韩杨朱秦尤许何吕施张孔曹严华金魏陶姜戚谢邹喻柏水窦章云苏潘葛\"", "\"奚范彭郎鲁韦昌马苗凤花方俞任袁柳酆鲍史唐费廉岑薛雷贺倪汤滕殷罗毕郝邬安常乐于时傅皮卞齐康\"", "\"伍余元卜顾孟平黄和穆萧尹姚邵湛汪祁...
39.79661
0.001247
def do_updateaccess(self, line): """updateaccess <identifier> [identifier ...] Update the Access Policy on one or more existing Science Data Objects.""" pids = self._split_args(line, 1, -1) self._command_processor.update_access_policy(pids) self._print_info_if_verbose( ...
[ "def", "do_updateaccess", "(", "self", ",", "line", ")", ":", "pids", "=", "self", ".", "_split_args", "(", "line", ",", "1", ",", "-", "1", ")", "self", ".", "_command_processor", ".", "update_access_policy", "(", "pids", ")", "self", ".", "_print_info_...
44.9
0.008734
def search(self, index, query, **kwargs): """ Perform full-text searches .. versionadded:: 2.0.9 .. warning:: The full-text search API is experimental and subject to change :param str index: Name of the index to query :param couchbase.fulltext.SearchQuery ...
[ "def", "search", "(", "self", ",", "index", ",", "query", ",", "*", "*", "kwargs", ")", ":", "itercls", "=", "kwargs", ".", "pop", "(", "'itercls'", ",", "_FTS", ".", "SearchRequest", ")", "iterargs", "=", "itercls", ".", "mk_kwargs", "(", "kwargs", ...
34.133333
0.001899