text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def insert(self, item, low_value): """ Create a new node and insert it into a sorted list. Calls the item duplicator, if any, on the item. If low_value is true, starts searching from the start of the list, otherwise searches from the end. Use the item comparator, if any, to find where to place the new n...
[ "def", "insert", "(", "self", ",", "item", ",", "low_value", ")", ":", "return", "c_void_p", "(", "lib", ".", "zlistx_insert", "(", "self", ".", "_as_parameter_", ",", "item", ",", "low_value", ")", ")" ]
51.1
24.1
def createissue(self, project_id, title, **kwargs): """ Create a new issue :param project_id: project id :param title: title of the issue :return: dict with the issue created """ data = {'id': id, 'title': title} if kwargs: data.update(kwargs)...
[ "def", "createissue", "(", "self", ",", "project_id", ",", "title", ",", "*", "*", "kwargs", ")", ":", "data", "=", "{", "'id'", ":", "id", ",", "'title'", ":", "title", "}", "if", "kwargs", ":", "data", ".", "update", "(", "kwargs", ")", "request"...
32.789474
15.631579
def init_config(app): """Initialize configuration. .. note:: If CairoSVG is installed then the configuration ``FORMATTER_BADGES_ENABLE`` is ``True``. :param app: The Flask application. """ try: get_distribution('CairoSVG') has_cairo = True ...
[ "def", "init_config", "(", "app", ")", ":", "try", ":", "get_distribution", "(", "'CairoSVG'", ")", "has_cairo", "=", "True", "except", "DistributionNotFound", ":", "has_cairo", "=", "False", "app", ".", "config", ".", "setdefault", "(", "'FORMATTER_BADGES_ENABL...
30.631579
17.842105
def resize_image(image, height, width, channels=None, resize_mode=None ): """ Resizes an image and returns it as a np.array Arguments: image -- a PIL.Image or numpy.ndarray height -- height of new image width -- width of new image Keyword Ar...
[ "def", "resize_image", "(", "image", ",", "height", ",", "width", ",", "channels", "=", "None", ",", "resize_mode", "=", "None", ")", ":", "if", "resize_mode", "is", "None", ":", "resize_mode", "=", "'squash'", "if", "resize_mode", "not", "in", "[", "'cr...
41.878378
17.567568
def on_treeview_delete_selection(self, event=None): """Removes selected items from treeview""" tv = self.treeview selection = tv.selection() # Need to remove filter self.filter_remove(remember=True) toplevel_items = tv.get_children() parents_to_redraw = set() ...
[ "def", "on_treeview_delete_selection", "(", "self", ",", "event", "=", "None", ")", ":", "tv", "=", "self", ".", "treeview", "selection", "=", "tv", ".", "selection", "(", ")", "# Need to remove filter", "self", ".", "filter_remove", "(", "remember", "=", "T...
33.382353
12.382353
def list_resources(self, session, query='?*::INSTR'): """Returns a tuple of all connected devices matching query. :param query: regular expression used to match devices. """ # For each session type, ask for the list of connected resources and # merge them into a single list. ...
[ "def", "list_resources", "(", "self", ",", "session", ",", "query", "=", "'?*::INSTR'", ")", ":", "# For each session type, ask for the list of connected resources and", "# merge them into a single list.", "resources", "=", "sum", "(", "[", "st", ".", "list_resources", "(...
34.6
23.533333
def qtemporal(dt, **meta): '''Converts a `numpy.datetime64` or `numpy.timedelta64` to :class:`.QTemporal` and enriches object instance with given meta data. Examples: >>> qtemporal(numpy.datetime64('2001-01-01', 'D'), qtype=QDATE) 2001-01-01 [metadata(qtype=-14)] >>> qtempora...
[ "def", "qtemporal", "(", "dt", ",", "*", "*", "meta", ")", ":", "result", "=", "QTemporal", "(", "dt", ")", "result", ".", "_meta_init", "(", "*", "*", "meta", ")", "return", "result" ]
34
22.434783
def config(self, handle, attributes=None, **kwattrs): """Sets or modifies one or more object attributes or relations. Arguments can be supplied either as a dictionary or as keyword arguments. Examples: stc.config('port1', location='//10.1.2.3/1/1') stc.config('port2', {...
[ "def", "config", "(", "self", ",", "handle", ",", "attributes", "=", "None", ",", "*", "*", "kwattrs", ")", ":", "self", ".", "_check_session", "(", ")", "if", "kwattrs", ":", "if", "attributes", ":", "attributes", ".", "update", "(", "kwattrs", ")", ...
37.714286
19.142857
def execute_code(self, lines, current_client=True, clear_variables=False): """Execute code instructions.""" sw = self.get_current_shellwidget() if sw is not None: if sw._reading: pass else: if not current_client: ...
[ "def", "execute_code", "(", "self", ",", "lines", ",", "current_client", "=", "True", ",", "clear_variables", "=", "False", ")", ":", "sw", "=", "self", ".", "get_current_shellwidget", "(", ")", "if", "sw", "is", "not", "None", ":", "if", "sw", ".", "_...
41.653846
12.846154
def get_objective_admin_session(self, proxy, *args, **kwargs): """Gets the ``OsidSession`` associated with the objective administration service. :param proxy: a proxy :type proxy: ``osid.proxy.Proxy`` :return: an ``ObjectiveAdminSession`` :rtype: ``osid.learning.ObjectiveAdminSe...
[ "def", "get_objective_admin_session", "(", "self", ",", "proxy", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "not", "self", ".", "supports_objective_admin", "(", ")", ":", "raise", "Unimplemented", "(", ")", "try", ":", "from", ".", "impor...
40.884615
19.423077
def row_to_dict(self, row): ''' translate a row of the current table to dictionary :param row: a row of the current table (selected with \\*) :return: dictionary of all fields ''' res = {} for i in range(len(self._fields)): res[self._fields[i][0]] = r...
[ "def", "row_to_dict", "(", "self", ",", "row", ")", ":", "res", "=", "{", "}", "for", "i", "in", "range", "(", "len", "(", "self", ".", "_fields", ")", ")", ":", "res", "[", "self", ".", "_fields", "[", "i", "]", "[", "0", "]", "]", "=", "r...
30.363636
18.909091
def sn(self): """Read the Serial Number string. This method is only available on OPC-N2 firmware versions 18+. :rtype: string :Example: >>> alpha.sn() 'OPC-N2 123456789' """ string = [] # Send the command byte and sleep for 9 ms self.cn...
[ "def", "sn", "(", "self", ")", ":", "string", "=", "[", "]", "# Send the command byte and sleep for 9 ms", "self", ".", "cnxn", ".", "xfer", "(", "[", "0x10", "]", ")", "sleep", "(", "9e-3", ")", "# Read the info string by sending 60 empty bytes", "for", "i", ...
22.04
20.84
def move(self, from_path, to_path, **kwargs): """移动单个文件或目录. :param from_path: 源文件/目录在网盘中的路径(包括文件名)。 .. warning:: * 路径长度限制为1000; * 径中不能包含以下字符:``\\\\ ? | " > < : *``; * 文件名或路径名开头结尾不能是 ``.`...
[ "def", "move", "(", "self", ",", "from_path", ",", "to_path", ",", "*", "*", "kwargs", ")", ":", "data", "=", "{", "'from'", ":", "from_path", ",", "'to'", ":", "to_path", ",", "}", "return", "self", ".", "_request", "(", "'file'", ",", "'move'", "...
35.407407
16.222222
def get_error(exc): """ Return the appropriate HTTP status code according to the Exception/Error. """ if isinstance(exc, HTTPError): # Returning the HTTP Error code coming from requests module return exc.response.status_code, text(exc.response.content) if isinstance(exc, Timeout): ...
[ "def", "get_error", "(", "exc", ")", ":", "if", "isinstance", "(", "exc", ",", "HTTPError", ")", ":", "# Returning the HTTP Error code coming from requests module", "return", "exc", ".", "response", ".", "status_code", ",", "text", "(", "exc", ".", "response", "...
27.444444
19.740741
def add_namespace_statistics(self, namespace, offset, data_points, byte_count): """Update namespace statistics for the period identified by offset""" query = 'UPDATE gauged_statistics ' \ 'SET data_points = data_points + %s,' \ 'byte_count...
[ "def", "add_namespace_statistics", "(", "self", ",", "namespace", ",", "offset", ",", "data_points", ",", "byte_count", ")", ":", "query", "=", "'UPDATE gauged_statistics '", "'SET data_points = data_points + %s,'", "'byte_count = byte_count + %s WHERE namespace = %s '", "'AND ...
56.5
17.357143
def _validate_edata(self, edata): """Validate edata argument of raise_exception_if method.""" # pylint: disable=R0916 if edata is None: return True if not (isinstance(edata, dict) or _isiterable(edata)): return False edata = [edata] if isinstance(edata, di...
[ "def", "_validate_edata", "(", "self", ",", "edata", ")", ":", "# pylint: disable=R0916", "if", "edata", "is", "None", ":", "return", "True", "if", "not", "(", "isinstance", "(", "edata", ",", "dict", ")", "or", "_isiterable", "(", "edata", ")", ")", ":"...
37.421053
14.842105
def list_topic_rules(topic=None, ruleDisabled=None, region=None, key=None, keyid=None, profile=None): ''' List all rules (for a given topic, if specified) Returns list of rules CLI Example: .. code-block:: bash salt myminion boto_iot.list_topic_rules Example Return: ...
[ "def", "list_topic_rules", "(", "topic", "=", "None", ",", "ruleDisabled", "=", "None", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "try", ":", "conn", "=", "_get_conn", "(", ...
27.55
21.6
def n_frames_total(self, stride=1, skip=0): r"""Returns total number of frames. Parameters ---------- stride : int return value is the number of frames in trajectories when running through them with a step size of `stride`. skip : int, default=0 ...
[ "def", "n_frames_total", "(", "self", ",", "stride", "=", "1", ",", "skip", "=", "0", ")", ":", "if", "not", "IteratorState", ".", "is_uniform_stride", "(", "stride", ")", ":", "return", "len", "(", "stride", ")", "return", "sum", "(", "self", ".", "...
32.578947
18.368421
def add_partitioning_indexes(portal): """Adds the indexes for partitioning """ logger.info("Adding partitioning indexes") add_index(portal, catalog_id=CATALOG_ANALYSIS_LISTING, index_name="getAncestorsUIDs", index_attribute="getAncestorsUIDs", index_metatype="K...
[ "def", "add_partitioning_indexes", "(", "portal", ")", ":", "logger", ".", "info", "(", "\"Adding partitioning indexes\"", ")", "add_index", "(", "portal", ",", "catalog_id", "=", "CATALOG_ANALYSIS_LISTING", ",", "index_name", "=", "\"getAncestorsUIDs\"", ",", "index_...
37.428571
11.642857
def strip_cdata(text): """Removes all CDATA blocks from `text` if it contains them. Note: If the function contains escaped XML characters outside of a CDATA block, they will be unescaped. Args: A string containing one or more CDATA blocks. Returns: An XML unescaped str...
[ "def", "strip_cdata", "(", "text", ")", ":", "if", "not", "is_cdata", "(", "text", ")", ":", "return", "text", "xml", "=", "\"<e>{0}</e>\"", ".", "format", "(", "text", ")", "node", "=", "etree", ".", "fromstring", "(", "xml", ")", "return", "node", ...
24.4
22.45
def SCAS(cpu, dest, src): """ Scans String. Compares the byte, word, or double word specified with the memory operand with the value in the AL, AX, EAX, or RAX register, and sets the status flags according to the results. The memory operand address is read from either th...
[ "def", "SCAS", "(", "cpu", ",", "dest", ",", "src", ")", ":", "dest_reg", "=", "dest", ".", "reg", "mem_reg", "=", "src", ".", "mem", ".", "base", "# , src.type, src.read()", "size", "=", "dest", ".", "size", "arg0", "=", "dest", ".", "read", "(", ...
40.076923
15.769231
def Nu_plate_Kumar(Re, Pr, chevron_angle, mu=None, mu_wall=None): r'''Calculates Nusselt number for single-phase flow in a **well-designed** Chevron-style plate heat exchanger according to [1]_. The data is believed to have been developed by APV International Limited, since acquired by SPX Corporation....
[ "def", "Nu_plate_Kumar", "(", "Re", ",", "Pr", ",", "chevron_angle", ",", "mu", "=", "None", ",", "mu_wall", "=", "None", ")", ":", "# Uses the standard diameter as characteristic diameter", "beta_list_len", "=", "len", "(", "Kumar_beta_list", ")", "for", "i", "...
38.505155
25.783505
def new_histogram(name, reservoir=None): """ Build a new histogram metric with a given reservoir object If the reservoir is not provided, a uniform reservoir with the default size is used """ if reservoir is None: reservoir = histogram.UniformReservoir(histogram.DEFAULT_UNIFORM_RESERVOIR_SI...
[ "def", "new_histogram", "(", "name", ",", "reservoir", "=", "None", ")", ":", "if", "reservoir", "is", "None", ":", "reservoir", "=", "histogram", ".", "UniformReservoir", "(", "histogram", ".", "DEFAULT_UNIFORM_RESERVOIR_SIZE", ")", "return", "new_metric", "(",...
37.5
23.1
def mark_meas_good(self, g_index): """ Marks the g_index'th measuremnt of current specimen good Parameters ---------- g_index : int that gives the index of the measurement to mark good, indexed from 0 """ meas_index, ind_data = 0, [] for i, me...
[ "def", "mark_meas_good", "(", "self", ",", "g_index", ")", ":", "meas_index", ",", "ind_data", "=", "0", ",", "[", "]", "for", "i", ",", "meas_data", "in", "enumerate", "(", "self", ".", "mag_meas_data", ")", ":", "if", "meas_data", "[", "'er_specimen_na...
53.297297
25.891892
def materials(self): """ Property for accessing :class:`MaterialManager` instance, which is used to manage materials. :rtype: yagocd.resources.material.MaterialManager """ if self._material_manager is None: self._material_manager = MaterialManager(session=self._sessi...
[ "def", "materials", "(", "self", ")", ":", "if", "self", ".", "_material_manager", "is", "None", ":", "self", ".", "_material_manager", "=", "MaterialManager", "(", "session", "=", "self", ".", "_session", ")", "return", "self", ".", "_material_manager" ]
39.222222
19.666667
def get_scopes_for(self, user_provided_scopes): """ Returns a list of scopes needed for each of the scope_helpers provided, by adding the prefix to them if required :param user_provided_scopes: a list of scopes or scope helpers :type user_provided_scopes: list or tuple or str :r...
[ "def", "get_scopes_for", "(", "self", ",", "user_provided_scopes", ")", ":", "if", "user_provided_scopes", "is", "None", ":", "# return all available scopes", "user_provided_scopes", "=", "[", "app_part", "for", "app_part", "in", "self", ".", "_oauth_scopes", "]", "...
42.692308
20.153846
def remove_rich_rule(zone, rule, permanent=True): ''' Add a rich rule to a zone .. versionadded:: 2016.11.0 CLI Example: .. code-block:: bash salt '*' firewalld.remove_rich_rule zone 'rule' ''' cmd = "--zone={0} --remove-rich-rule='{1}'".format(zone, rule) if permanent: ...
[ "def", "remove_rich_rule", "(", "zone", ",", "rule", ",", "permanent", "=", "True", ")", ":", "cmd", "=", "\"--zone={0} --remove-rich-rule='{1}'\"", ".", "format", "(", "zone", ",", "rule", ")", "if", "permanent", ":", "cmd", "+=", "' --permanent'", "return", ...
20
25.555556
def counter(path, delta, create_parents=False, **kwargs): """ Increment or decrement a counter in a document. :param path: Path to the counter :param delta: Amount by which to modify the value. The delta can be negative but not 0. It must be an integer (not a float) as well. :param ...
[ "def", "counter", "(", "path", ",", "delta", ",", "create_parents", "=", "False", ",", "*", "*", "kwargs", ")", ":", "if", "not", "delta", ":", "raise", "ValueError", "(", "\"Delta must be positive or negative!\"", ")", "return", "_gen_4spec", "(", "LCB_SDCMD_...
38.576923
23.884615
def _copy_vm(template=None, name=None, session=None, sr=None): ''' Create VM by copy This is slower and should be used if source and target are NOT in the same storage repository template = object reference name = string name of new VM session = object reference sr = object reference ...
[ "def", "_copy_vm", "(", "template", "=", "None", ",", "name", "=", "None", ",", "session", "=", "None", ",", "sr", "=", "None", ")", ":", "if", "session", "is", "None", ":", "session", "=", "_get_session", "(", ")", "log", ".", "debug", "(", "'Crea...
31.166667
17.944444
def arglist(self, args, call): """arglist: (argument ',')* (argument [','] | '*' test (',' argument)* [',' '**' test] | '**' test)""" for arg in args: if isinstance(arg, ast.keyword): call.keywords.appe...
[ "def", "arglist", "(", "self", ",", "args", ",", "call", ")", ":", "for", "arg", "in", "args", ":", "if", "isinstance", "(", "arg", ",", "ast", ".", "keyword", ")", ":", "call", ".", "keywords", ".", "append", "(", "arg", ")", "elif", "len", "(",...
43.666667
11.866667
def _updateVariantAnnotationSets(self, variantFile, dataUrl): """ Updates the variant annotation set associated with this variant using information in the specified pysam variantFile. """ # TODO check the consistency of this between VCF files. if not self.isAnnotated(): ...
[ "def", "_updateVariantAnnotationSets", "(", "self", ",", "variantFile", ",", "dataUrl", ")", ":", "# TODO check the consistency of this between VCF files.", "if", "not", "self", ".", "isAnnotated", "(", ")", ":", "annotationType", "=", "None", "for", "record", "in", ...
53.282051
16.307692
def run(self, creds, override_etype = [23]): """ Requests TGT tickets for all users specified in the targets list creds: list : the users to request the TGT tickets for override_etype: list : list of supported encryption types """ tgts = [] for cred in creds: try: kcomm = KerbrosComm(cred, self....
[ "def", "run", "(", "self", ",", "creds", ",", "override_etype", "=", "[", "23", "]", ")", ":", "tgts", "=", "[", "]", "for", "cred", "in", "creds", ":", "try", ":", "kcomm", "=", "KerbrosComm", "(", "cred", ",", "self", ".", "ksoc", ")", "kcomm",...
29.590909
21.909091
def p_queue(p): """ queue : QUEUE COLON LIFO | QUEUE COLON FIFO """ if p[3] == "LIFO": p[0] = {"queue": LIFO()} elif p[3] == "FIFO": p[0] = {"queue": FIFO()} else: raise RuntimeError("Queue discipline '%s' is not supported!" % p[1])
[ "def", "p_queue", "(", "p", ")", ":", "if", "p", "[", "3", "]", "==", "\"LIFO\"", ":", "p", "[", "0", "]", "=", "{", "\"queue\"", ":", "LIFO", "(", ")", "}", "elif", "p", "[", "3", "]", "==", "\"FIFO\"", ":", "p", "[", "0", "]", "=", "{",...
21.538462
18.923077
async def make_response(self, request, response, **response_kwargs): """Convert a handler result to web response.""" while iscoroutine(response): response = await response if isinstance(response, StreamResponse): return response response_kwargs.setdefault('conte...
[ "async", "def", "make_response", "(", "self", ",", "request", ",", "response", ",", "*", "*", "response_kwargs", ")", ":", "while", "iscoroutine", "(", "response", ")", ":", "response", "=", "await", "response", "if", "isinstance", "(", "response", ",", "S...
36.818182
20.909091
def _calc_damping_min(self): """minimum damping [decimal]""" return ((0.8005 + 0.0129 * self._plas_index * self._ocr ** -0.1069) * (self._stress_mean * KPA_TO_ATM) ** -0.2889 * (1 + 0.2919 * np.log(self._freq))) / 100
[ "def", "_calc_damping_min", "(", "self", ")", ":", "return", "(", "(", "0.8005", "+", "0.0129", "*", "self", ".", "_plas_index", "*", "self", ".", "_ocr", "**", "-", "0.1069", ")", "*", "(", "self", ".", "_stress_mean", "*", "KPA_TO_ATM", ")", "**", ...
52.2
17.2
def splitArgs(self, args): """Returns list of arguments parsed by shlex.split() or raise UsageError if failed""" try: return shlex.split(args) except ValueError as e: raise UsageError(e)
[ "def", "splitArgs", "(", "self", ",", "args", ")", ":", "try", ":", "return", "shlex", ".", "split", "(", "args", ")", "except", "ValueError", "as", "e", ":", "raise", "UsageError", "(", "e", ")" ]
33.714286
9.142857
def compute_num_true_positives(ref_freqs, est_freqs, window=0.5, chroma=False): """Compute the number of true positives in an estimate given a reference. A frequency is correct if it is within a quartertone of the correct frequency. Parameters ---------- ref_freqs : list of np.ndarray r...
[ "def", "compute_num_true_positives", "(", "ref_freqs", ",", "est_freqs", ",", "window", "=", "0.5", ",", "chroma", "=", "False", ")", ":", "n_frames", "=", "len", "(", "ref_freqs", ")", "true_positives", "=", "np", ".", "zeros", "(", "(", "n_frames", ",", ...
33.075
20.275
def setParams(self,params): """ set params """ start = 0 for i in range(self.n_terms): n_effects = self.B[i].size self.B[i] = np.reshape(params[start:start+n_effects],self.B[i].shape, order='F') start += n_effects
[ "def", "setParams", "(", "self", ",", "params", ")", ":", "start", "=", "0", "for", "i", "in", "range", "(", "self", ".", "n_terms", ")", ":", "n_effects", "=", "self", ".", "B", "[", "i", "]", ".", "size", "self", ".", "B", "[", "i", "]", "=...
38.142857
14.714286
def present(self, value): """Return a user-friendly representation of a value. Lookup value in self.specials, or call .to_literal() if absent. """ for k, v in self.special.items(): if v == value: return k return self.to_literal(value, *self.ar...
[ "def", "present", "(", "self", ",", "value", ")", ":", "for", "k", ",", "v", "in", "self", ".", "special", ".", "items", "(", ")", ":", "if", "v", "==", "value", ":", "return", "k", "return", "self", ".", "to_literal", "(", "value", ",", "*", "...
36.222222
14.333333
def hex(x): ''' x-->bytes | bytearray Returns-->bytes: hex-encoded ''' if isinstance(x, bytearray): x = bytes(x) return encode(x, 'hex')
[ "def", "hex", "(", "x", ")", ":", "if", "isinstance", "(", "x", ",", "bytearray", ")", ":", "x", "=", "bytes", "(", "x", ")", "return", "encode", "(", "x", ",", "'hex'", ")" ]
20.125
19.875
def _load_data(self, resource, default=DEFAULT_VALUE_SAFEGUARD, **kwargs): """ Load data from API client. Arguments: resource(string): type of resource to load default(any): value to return if API query returned empty result. Sensible values: [], {}, None etc. R...
[ "def", "_load_data", "(", "self", ",", "resource", ",", "default", "=", "DEFAULT_VALUE_SAFEGUARD", ",", "*", "*", "kwargs", ")", ":", "default_val", "=", "default", "if", "default", "!=", "self", ".", "DEFAULT_VALUE_SAFEGUARD", "else", "{", "}", "try", ":", ...
37.192308
22.038462
def clear_dtreat(self, force=False): """ Clear all treatment parameters in self.dtreat Subsequently also clear the working copy of data The working copy of data is thus reset to the reference data """ lC = [self._dtreat[k] is not None for k in self._dtreat.keys() i...
[ "def", "clear_dtreat", "(", "self", ",", "force", "=", "False", ")", ":", "lC", "=", "[", "self", ".", "_dtreat", "[", "k", "]", "is", "not", "None", "for", "k", "in", "self", ".", "_dtreat", ".", "keys", "(", ")", "if", "k", "!=", "'order'", "...
47.294118
13.882353
def inline_link( self, text, url): """*generate a MMD sytle link* **Key Arguments:** - ``text`` -- the text to link from - ``url`` -- the url to link to **Return:** - ``text`` -- the linked text **Usage:** ...
[ "def", "inline_link", "(", "self", ",", "text", ",", "url", ")", ":", "m", "=", "self", ".", "reWS", ".", "match", "(", "text", ")", "prefix", "=", "m", ".", "group", "(", "1", ")", "text", "=", "m", ".", "group", "(", "2", ")", "suffix", "="...
24.323529
21.117647
def _listen_for_dweets_from_response(response): """Yields dweets as received from dweet.io's streaming API """ streambuffer = '' for byte in response.iter_content(): if byte: streambuffer += byte.decode('ascii') try: dweet = json.loads(streambuffer.splitli...
[ "def", "_listen_for_dweets_from_response", "(", "response", ")", ":", "streambuffer", "=", "''", "for", "byte", "in", "response", ".", "iter_content", "(", ")", ":", "if", "byte", ":", "streambuffer", "+=", "byte", ".", "decode", "(", "'ascii'", ")", "try", ...
34.642857
10.714286
def normalize(data): """ Function to normalize data to have mean 0 and unity standard deviation (also called z-transform) Parameters ---------- data : numpy.ndarray Returns ------- numpy.ndarray z-transform of input array """ data = data.astyp...
[ "def", "normalize", "(", "data", ")", ":", "data", "=", "data", ".", "astype", "(", "float", ")", "data", "-=", "data", ".", "mean", "(", ")", "return", "data", "/", "data", ".", "std", "(", ")" ]
17.428571
22.666667
def extract_response(raw_response): """Extract requests response object. only extract those status_code in [200, 300). :param raw_response: a requests.Resposne object. :return: content of response. """ data = urlread(raw_response) if is_success_response(raw_response): return data ...
[ "def", "extract_response", "(", "raw_response", ")", ":", "data", "=", "urlread", "(", "raw_response", ")", "if", "is_success_response", "(", "raw_response", ")", ":", "return", "data", "elif", "is_failure_response", "(", "raw_response", ")", ":", "raise", "Remo...
28.833333
12.444444
def toProtocolElement(self): """ Returns the GA4GH protocol representation of this ReadGroup. """ # TODO this is very incomplete, but we don't have the # implementation to fill out the rest of the fields currently readGroup = protocol.ReadGroup() readGroup.id = se...
[ "def", "toProtocolElement", "(", "self", ")", ":", "# TODO this is very incomplete, but we don't have the", "# implementation to fill out the rest of the fields currently", "readGroup", "=", "protocol", ".", "ReadGroup", "(", ")", "readGroup", ".", "id", "=", "self", ".", "...
48.92
14.2
def parse_proposal_data(self, proposal_data, dossier_pk): """Get or Create a proposal model from raw data""" proposal_display = '{} ({})'.format(proposal_data['title'].encode( 'utf-8'), proposal_data.get('report', '').encode('utf-8')) if 'issue_type' not in proposal_data.keys(): ...
[ "def", "parse_proposal_data", "(", "self", ",", "proposal_data", ",", "dossier_pk", ")", ":", "proposal_display", "=", "'{} ({})'", ".", "format", "(", "proposal_data", "[", "'title'", "]", ".", "encode", "(", "'utf-8'", ")", ",", "proposal_data", ".", "get", ...
38.686869
21.272727
def verifyEmails(emails=[], regExpPattern="^.+$"): """ Method to perform the mail verification process. Arguments --------- emails: List of emails to verify. regExpPattern: Pattern that should match. Returns ------- list: A list containing the results that match. ""...
[ "def", "verifyEmails", "(", "emails", "=", "[", "]", ",", "regExpPattern", "=", "\"^.+$\"", ")", ":", "emailsMatched", "=", "set", "(", ")", "for", "i", ",", "e", "in", "enumerate", "(", "emails", ")", ":", "if", "re", ".", "match", "(", "regExpPatte...
22.363636
18.909091
def plotPointing(self, maptype=None, colour='b', mod3='r', showOuts=True, **kwargs): """Plot the FOV """ if maptype is None: maptype=self.defaultMap radec = self.currentRaDec for ch in radec[:,2][::4]: idx = np.where(radec[:,2].astype(np.int) == ch)[0] ...
[ "def", "plotPointing", "(", "self", ",", "maptype", "=", "None", ",", "colour", "=", "'b'", ",", "mod3", "=", "'r'", ",", "showOuts", "=", "True", ",", "*", "*", "kwargs", ")", ":", "if", "maptype", "is", "None", ":", "maptype", "=", "self", ".", ...
35.3
21.7
def create_archive( source: Path, target: Path, interpreter: str, main: str, compressed: bool = True ) -> None: """Create an application archive from SOURCE. A slightly modified version of stdlib's `zipapp.create_archive <https://docs.python.org/3/library/zipapp.html#zipapp.create_archi...
[ "def", "create_archive", "(", "source", ":", "Path", ",", "target", ":", "Path", ",", "interpreter", ":", "str", ",", "main", ":", "str", ",", "compressed", ":", "bool", "=", "True", ")", "->", "None", ":", "# Check that main has the right format.", "mod", ...
32.043478
21.043478
def save(self, *args, **kwargs): """ Override save() method to make sure that standard_name and systematic_name won't be null or empty, or consist of only space characters (such as space, tab, new line, etc). """ empty_std_name = False if not self.standard_name or...
[ "def", "save", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "empty_std_name", "=", "False", "if", "not", "self", ".", "standard_name", "or", "self", ".", "standard_name", ".", "isspace", "(", ")", ":", "empty_std_name", "=", "True"...
36.684211
17.947368
def generateLowerBoundList(confidence, numUniqueFeatures, numLocationsPerObject, maxNumObjects): """ Metric: How unique is each object's most unique feature? Calculate the probabilistic lower bound for the number of occurrences of an object's most unique feature. For example, if confi...
[ "def", "generateLowerBoundList", "(", "confidence", ",", "numUniqueFeatures", ",", "numLocationsPerObject", ",", "maxNumObjects", ")", ":", "# We're choosing a location, checking its feature, and checking how many", "# *other* occurrences there are of this feature. So we check n - 1 locati...
48.541667
24.791667
def export(app, local): """Export the data.""" print_header() log("Preparing to export the data...") id = str(app) subdata_path = os.path.join("data", id, "data") # Create the data package os.makedirs(subdata_path) # Copy the experiment code into a code/ subdirectory try: ...
[ "def", "export", "(", "app", ",", "local", ")", ":", "print_header", "(", ")", "log", "(", "\"Preparing to export the data...\"", ")", "id", "=", "str", "(", "app", ")", "subdata_path", "=", "os", ".", "path", ".", "join", "(", "\"data\"", ",", "id", "...
23.592105
22.75
def create(self, data, fields=[], models={}): ''' Create model attributes ''' if not fields: fields = self.fields if not models and hasattr(self, 'models'): models = self.models for field in fields: setattr(self,field,None) if not data: return None ...
[ "def", "create", "(", "self", ",", "data", ",", "fields", "=", "[", "]", ",", "models", "=", "{", "}", ")", ":", "if", "not", "fields", ":", "fields", "=", "self", ".", "fields", "if", "not", "models", "and", "hasattr", "(", "self", ",", "'models...
36.2
9.8
def atc(jobid): ''' Print the at(1) script that will run for the passed job id. This is mostly for debugging so the output will just be text. CLI Example: .. code-block:: bash salt '*' at.atc <jobid> ''' # Shim to produce output similar to what __virtual__() should do # bu...
[ "def", "atc", "(", "jobid", ")", ":", "# Shim to produce output similar to what __virtual__() should do", "# but __salt__ isn't available in __virtual__()", "output", "=", "_cmd", "(", "'at'", ",", "'-c'", ",", "six", ".", "text_type", "(", "jobid", ")", ")", "if", "o...
25.954545
24.318182
def Bezier(points, at): """Build Bézier curve from points. Deprecated. CatmulClark builds nicer splines """ at = np.asarray(at) at_flat = at.ravel() N = len(points) curve = np.zeros((at_flat.shape[0], 2)) for ii in range(N): curve += np.outer(Bernstein(N - 1, ii)(at_flat), points...
[ "def", "Bezier", "(", "points", ",", "at", ")", ":", "at", "=", "np", ".", "asarray", "(", "at", ")", "at_flat", "=", "at", ".", "ravel", "(", ")", "N", "=", "len", "(", "points", ")", "curve", "=", "np", ".", "zeros", "(", "(", "at_flat", "....
32.454545
11.636364
def repack_archive (archive, archive_new, verbosity=0, interactive=True): """Repack archive to different file and/or format.""" util.check_existing_filename(archive) util.check_new_filename(archive_new) if verbosity >= 0: util.log_info("Repacking %s to %s ..." % (archive, archive_new)) res =...
[ "def", "repack_archive", "(", "archive", ",", "archive_new", ",", "verbosity", "=", "0", ",", "interactive", "=", "True", ")", ":", "util", ".", "check_existing_filename", "(", "archive", ")", "util", ".", "check_new_filename", "(", "archive_new", ")", "if", ...
48.4
19.1
def sort(self): """Consolidate adjacent lines, if same commit ID. Will modify line number to be a range, when two or more lines with the same commit ID. """ self.sorted_commits = [] if not self.commits: return self.sorted_commits prev_commit = self.co...
[ "def", "sort", "(", "self", ")", ":", "self", ".", "sorted_commits", "=", "[", "]", "if", "not", "self", ".", "commits", ":", "return", "self", ".", "sorted_commits", "prev_commit", "=", "self", ".", "commits", ".", "pop", "(", "0", ")", "prev_line", ...
41.56
12.76
def _travis(self): """ Logic behind autosave under Travis CI. """ if PyFunceble.CONFIGURATION["travis"]: try: _ = PyFunceble.environ["TRAVIS_BUILD_DIR"] time_autorisation = False try: time_autorisation = in...
[ "def", "_travis", "(", "self", ")", ":", "if", "PyFunceble", ".", "CONFIGURATION", "[", "\"travis\"", "]", ":", "try", ":", "_", "=", "PyFunceble", ".", "environ", "[", "\"TRAVIS_BUILD_DIR\"", "]", "time_autorisation", "=", "False", "try", ":", "time_autoris...
38.063492
20.507937
def format_dirname(series_name, season_number): """Generates a directory name based on metadata using configured format. :param str series_name: name of TV series :param int season_number: the numeric season of series :returns: formatted directory name using input values and configured format :rtyp...
[ "def", "format_dirname", "(", "series_name", ",", "season_number", ")", ":", "data", "=", "{", "'seriesname'", ":", "_replace_series_name", "(", "series_name", ",", "cfg", ".", "CONF", ".", "output_series_replacements", ")", ",", "'seasonnumber'", ":", "season_num...
34.3125
20.375
def arxiv_eprints2marc(self, key, values): """Populate the ``037`` MARC field. Also populates the ``035`` and the ``65017`` MARC fields through side effects. """ result_037 = self.get('037', []) result_035 = self.get('035', []) result_65017 = self.get('65017', []) for value in values: ...
[ "def", "arxiv_eprints2marc", "(", "self", ",", "key", ",", "values", ")", ":", "result_037", "=", "self", ".", "get", "(", "'037'", ",", "[", "]", ")", "result_035", "=", "self", ".", "get", "(", "'035'", ",", "[", "]", ")", "result_65017", "=", "s...
29.484848
18.090909
def find_class_files(self): """Find compiled class files recursively in the root path :return: list of absolute file paths """ files = self._find_files() self.announce( "found '{}' compiled class files in '{}'".format( len(files), self.root ...
[ "def", "find_class_files", "(", "self", ")", ":", "files", "=", "self", ".", "_find_files", "(", ")", "self", ".", "announce", "(", "\"found '{}' compiled class files in '{}'\"", ".", "format", "(", "len", "(", "files", ")", ",", "self", ".", "root", ")", ...
28.583333
15.25
def render_page(page, page_args): """ Renders the template at page.template """ print(page_args) template_name = page.template if page.template else page.name template = "signage/pages/{}.html".format(template_name) if page.function: context_method = getattr(pages, page.function) els...
[ "def", "render_page", "(", "page", ",", "page_args", ")", ":", "print", "(", "page_args", ")", "template_name", "=", "page", ".", "template", "if", "page", ".", "template", "else", "page", ".", "name", "template", "=", "\"signage/pages/{}.html\"", ".", "form...
37.538462
13.230769
def dump(cls, data, encoding="ascii"): """ Convert str to appropriate format for "UserComment". :param data: Like u"foobar" :param str encoding: "ascii", "jis", or "unicode" :return: b"ASCII\x00\x00\x00foobar" :rtype: bytes :raises: ValueError if the encoding is ...
[ "def", "dump", "(", "cls", ",", "data", ",", "encoding", "=", "\"ascii\"", ")", ":", "if", "encoding", "not", "in", "cls", ".", "ENCODINGS", ":", "raise", "ValueError", "(", "'encoding {!r} must be one of {!r}'", ".", "format", "(", "encoding", ",", "cls", ...
50.666667
23.333333
def get_thellier_gui_meas_mapping(input_df, output=2): """ Get the appropriate mapping for translating measurements in Thellier GUI. This requires special handling for treat_step_num/measurement/measurement_number. Parameters ---------- input_df : pandas DataFrame MagIC records outp...
[ "def", "get_thellier_gui_meas_mapping", "(", "input_df", ",", "output", "=", "2", ")", ":", "if", "int", "(", "output", ")", "==", "2", ":", "thellier_gui_meas3_2_meas2_map", "=", "meas_magic3_2_magic2_map", ".", "copy", "(", ")", "if", "'treat_step_num'", "in",...
37.714286
21.028571
def start_session(self): """ Start Session """ response = self.request("hello") bits = response.split(" ") self.server_info.update({ "server_version": bits[2], "protocol_version": bits[4], "screen_width": int(bits[7]), "screen_height": int...
[ "def", "start_session", "(", "self", ")", ":", "response", "=", "self", ".", "request", "(", "\"hello\"", ")", "bits", "=", "response", ".", "split", "(", "\" \"", ")", "self", ".", "server_info", ".", "update", "(", "{", "\"server_version\"", ":", "bits...
31
8.642857
def handle_data(self, data): ''' Method called for each event by zipline. In intuition this is the place to factorize algorithms and then call event() ''' self.days += 1 signals = {} self.orderbook = {} # Everytime but the first tick if self.initialized and self....
[ "def", "handle_data", "(", "self", ",", "data", ")", ":", "self", ".", "days", "+=", "1", "signals", "=", "{", "}", "self", ".", "orderbook", "=", "{", "}", "# Everytime but the first tick", "if", "self", ".", "initialized", "and", "self", ".", "manager"...
39.075
18.475
def create(self, group_type, config_file, group_name=None, region=None, profile_name=None): """ Create a Greengrass group in the given region. :param group_type: the type of group to create. Must match a `key` in the `group_types` dict :param config_file: conf...
[ "def", "create", "(", "self", ",", "group_type", ",", "config_file", ",", "group_name", "=", "None", ",", "region", "=", "None", ",", "profile_name", "=", "None", ")", ":", "logging", ".", "info", "(", "\"[begin] create command using group_types:{0}\"", ".", "...
36.444444
20.074074
def pad_to_same(self): """Pad shorter pianorolls with zeros at the end along the time axis to make the resulting pianoroll lengths the same as the maximum pianoroll length among all the tracks.""" max_length = self.get_max_length() for track in self.tracks: if track.p...
[ "def", "pad_to_same", "(", "self", ")", ":", "max_length", "=", "self", ".", "get_max_length", "(", ")", "for", "track", "in", "self", ".", "tracks", ":", "if", "track", ".", "pianoroll", ".", "shape", "[", "0", "]", "<", "max_length", ":", "track", ...
51.125
12.75
def rosmsg(self): """:obj:`sensor_msgs.Image` : ROS Image """ from cv_bridge import CvBridge, CvBridgeError cv_bridge = CvBridge() try: return cv_bridge.cv2_to_imgmsg(self._data, encoding=self._encoding) except CvBridgeError as cv_bridge_exception: ...
[ "def", "rosmsg", "(", "self", ")", ":", "from", "cv_bridge", "import", "CvBridge", ",", "CvBridgeError", "cv_bridge", "=", "CvBridge", "(", ")", "try", ":", "return", "cv_bridge", ".", "cv2_to_imgmsg", "(", "self", ".", "_data", ",", "encoding", "=", "self...
40.111111
16.111111
def get_lib2to3_fixers(): '''returns a list of all fixers found in the lib2to3 library''' fixers = [] fixer_dirname = fixer_dir.__path__[0] for name in sorted(os.listdir(fixer_dirname)): if name.startswith("fix_") and name.endswith(".py"): fixers.append("lib2to3.fixes." + name[:-3]) ...
[ "def", "get_lib2to3_fixers", "(", ")", ":", "fixers", "=", "[", "]", "fixer_dirname", "=", "fixer_dir", ".", "__path__", "[", "0", "]", "for", "name", "in", "sorted", "(", "os", ".", "listdir", "(", "fixer_dirname", ")", ")", ":", "if", "name", ".", ...
41.25
17
async def Actions(self, entities): ''' entities : typing.Sequence[~Entity] Returns -> typing.Sequence[~ActionResult] ''' # map input types to rpc msg _params = dict() msg = dict(type='Action', request='Actions', version=2, ...
[ "async", "def", "Actions", "(", "self", ",", "entities", ")", ":", "# map input types to rpc msg", "_params", "=", "dict", "(", ")", "msg", "=", "dict", "(", "type", "=", "'Action'", ",", "request", "=", "'Actions'", ",", "version", "=", "2", ",", "param...
31
10.714286
def del_Unnamed(df): """ Deletes all the unnamed columns :param df: pandas dataframe """ cols_del=[c for c in df.columns if 'Unnamed' in c] return df.drop(cols_del,axis=1)
[ "def", "del_Unnamed", "(", "df", ")", ":", "cols_del", "=", "[", "c", "for", "c", "in", "df", ".", "columns", "if", "'Unnamed'", "in", "c", "]", "return", "df", ".", "drop", "(", "cols_del", ",", "axis", "=", "1", ")" ]
23.625
11.625
def register_on_extra_data_changed(self, callback): """Set the callback function to consume on extra data changed events. Callback receives a IExtraDataChangedEvent object. Returns the callback_id """ event_type = library.VBoxEventType.on_extra_data_changed retu...
[ "def", "register_on_extra_data_changed", "(", "self", ",", "callback", ")", ":", "event_type", "=", "library", ".", "VBoxEventType", ".", "on_extra_data_changed", "return", "self", ".", "event_source", ".", "register_callback", "(", "callback", ",", "event_type", ")...
37.1
19.9
def public_ip_prefixes(self): """Instance depends on the API version: * 2018-07-01: :class:`PublicIPPrefixesOperations<azure.mgmt.network.v2018_07_01.operations.PublicIPPrefixesOperations>` * 2018-08-01: :class:`PublicIPPrefixesOperations<azure.mgmt.network.v2018_08_01.operations.PublicIP...
[ "def", "public_ip_prefixes", "(", "self", ")", ":", "api_version", "=", "self", ".", "_get_api_version", "(", "'public_ip_prefixes'", ")", "if", "api_version", "==", "'2018-07-01'", ":", "from", ".", "v2018_07_01", ".", "operations", "import", "PublicIPPrefixesOpera...
66.142857
39
def create_fourier_design_matrix(t, nmodes, freq=False, Tspan=None, logf=False, fmin=None, fmax=None): """ Construct fourier design matrix from eq 11 of Lentati et al, 2013 :param t: vector of time series in seconds :param nmodes: number of fourier coefficients to use ...
[ "def", "create_fourier_design_matrix", "(", "t", ",", "nmodes", ",", "freq", "=", "False", ",", "Tspan", "=", "None", ",", "logf", "=", "False", ",", "fmin", "=", "None", ",", "fmax", "=", "None", ")", ":", "N", "=", "len", "(", "t", ")", "F", "=...
28.272727
19.227273
def wrap_search(cls, response): """Wrap the response from a stream search into instances and return them :param response: The response from searching a stream :type response: :class:`requests.Response` :returns: the new stream instances :rtype: :class:`list` of :class:`s...
[ "def", "wrap_search", "(", "cls", ",", "response", ")", ":", "streams", "=", "[", "]", "json", "=", "response", ".", "json", "(", ")", "streamjsons", "=", "json", "[", "'streams'", "]", "for", "j", "in", "streamjsons", ":", "s", "=", "cls", ".", "w...
32.352941
12.176471
def deploy_lambda(collector): """Deploy a lambda function""" amazon = collector.configuration['amazon'] aws_syncr = collector.configuration['aws_syncr'] find_lambda_function(aws_syncr, collector.configuration).deploy(aws_syncr, amazon)
[ "def", "deploy_lambda", "(", "collector", ")", ":", "amazon", "=", "collector", ".", "configuration", "[", "'amazon'", "]", "aws_syncr", "=", "collector", ".", "configuration", "[", "'aws_syncr'", "]", "find_lambda_function", "(", "aws_syncr", ",", "collector", ...
49.4
15
def run(self, **kwargs): """ Drive servo to the position set in the `position_sp` attribute. """ for key in kwargs: setattr(self, key, kwargs[key]) self.command = self.COMMAND_RUN
[ "def", "run", "(", "self", ",", "*", "*", "kwargs", ")", ":", "for", "key", "in", "kwargs", ":", "setattr", "(", "self", ",", "key", ",", "kwargs", "[", "key", "]", ")", "self", ".", "command", "=", "self", ".", "COMMAND_RUN" ]
32.142857
9.285714
def load_tool_info(tool_name): """ Load the tool-info class. @param tool_name: The name of the tool-info module. Either a full Python package name or a name within the benchexec.tools package. @return: A tuple of the full name of the used tool-info module and an instance of the tool-info class. ...
[ "def", "load_tool_info", "(", "tool_name", ")", ":", "tool_module", "=", "tool_name", "if", "'.'", "in", "tool_name", "else", "(", "\"benchexec.tools.\"", "+", "tool_name", ")", "try", ":", "tool", "=", "__import__", "(", "tool_module", ",", "fromlist", "=", ...
51
26.125
def toggle_view(self, checked): """Toggle view""" if not self.dockwidget: return if checked: self.dockwidget.show() self.dockwidget.raise_() else: self.dockwidget.hide()
[ "def", "toggle_view", "(", "self", ",", "checked", ")", ":", "if", "not", "self", ".", "dockwidget", ":", "return", "if", "checked", ":", "self", ".", "dockwidget", ".", "show", "(", ")", "self", ".", "dockwidget", ".", "raise_", "(", ")", "else", ":...
26.777778
11.555556
def from_points(cls, iterable_of_points): """ Creates a MultiPoint from an iterable collection of `pyowm.utils.geo.Point` instances :param iterable_of_points: iterable whose items are `pyowm.utils.geo.Point` instances :type iterable_of_points: iterable :return: a *MultiPoint* ins...
[ "def", "from_points", "(", "cls", ",", "iterable_of_points", ")", ":", "return", "MultiPoint", "(", "[", "(", "p", ".", "lon", ",", "p", ".", "lat", ")", "for", "p", "in", "iterable_of_points", "]", ")" ]
50.25
17.5
def open(self, session_file=None,session_url=None, verbose=False): """ Opens a session from a local file or URL. :param session_file: The path to the session file (.cys) to be loaded. :param session_url: A URL that provides a session file. :param verbose: print more """ ...
[ "def", "open", "(", "self", ",", "session_file", "=", "None", ",", "session_url", "=", "None", ",", "verbose", "=", "False", ")", ":", "PARAMS", "=", "set_param", "(", "[", "\"file\"", ",", "\"url\"", "]", ",", "[", "session_file", ",", "session_url", ...
40
22
def _gt_from_ge(self, other): """Return a > b. Computed by @total_ordering from (a >= b) and (a != b).""" op_result = self.__ge__(other) if op_result is NotImplemented: return NotImplemented return op_result and self != other
[ "def", "_gt_from_ge", "(", "self", ",", "other", ")", ":", "op_result", "=", "self", ".", "__ge__", "(", "other", ")", "if", "op_result", "is", "NotImplemented", ":", "return", "NotImplemented", "return", "op_result", "and", "self", "!=", "other" ]
40.833333
5.833333
def _find_substitutions(cls, item): """Convert HOCON input into a JSON output :return: JSON string representation :type return: basestring """ if isinstance(item, ConfigValues): return item.get_substitutions() substitutions = [] elements = [] ...
[ "def", "_find_substitutions", "(", "cls", ",", "item", ")", ":", "if", "isinstance", "(", "item", ",", "ConfigValues", ")", ":", "return", "item", ".", "get_substitutions", "(", ")", "substitutions", "=", "[", "]", "elements", "=", "[", "]", "if", "isins...
29.368421
12.421053
def delete(self, *keys): """Removes the specified keys. A key is ignored if it does not exist. Returns :data:`True` if all keys are removed. .. note:: **Time complexity**: ``O(N)`` where ``N`` is the number of keys that will be removed. When a key to remove holds a value ...
[ "def", "delete", "(", "self", ",", "*", "keys", ")", ":", "return", "self", ".", "_execute", "(", "[", "b'DEL'", "]", "+", "list", "(", "keys", ")", ",", "len", "(", "keys", ")", ")" ]
41.684211
24.315789
def displayEmptyInputWarningBox(display=True, parent=None): """ Displays a warning box for the 'input' parameter. """ if sys.version_info[0] >= 3: from tkinter.messagebox import showwarning else: from tkMessageBox import showwarning if display: msg = 'No valid input files fo...
[ "def", "displayEmptyInputWarningBox", "(", "display", "=", "True", ",", "parent", "=", "None", ")", ":", "if", "sys", ".", "version_info", "[", "0", "]", ">=", "3", ":", "from", "tkinter", ".", "messagebox", "import", "showwarning", "else", ":", "from", ...
35.846154
16.769231
def login_checking_email(pending_id, ticket, response, detail_url='https://pswdless.appspot.com/rest/detail'): """ Log user in using Passwordless service :param pending_id: PendingExternalToMainUser's id :param ticket: ticket returned from Passwordless :param response: Response object from webapp2 ...
[ "def", "login_checking_email", "(", "pending_id", ",", "ticket", ",", "response", ",", "detail_url", "=", "'https://pswdless.appspot.com/rest/detail'", ")", ":", "return", "LoginCheckingEmail", "(", "pending_id", ",", "ticket", ",", "response", ",", "USER_COOKIE_NAME", ...
51.8
18.4
def translate(self, tx, ty): """Modifies the current transformation matrix (CTM) by translating the user-space origin by ``(tx, ty)``. This offset is interpreted as a user-space coordinate according to the CTM in place before the new call to :meth:`translate`. In other words, the...
[ "def", "translate", "(", "self", ",", "tx", ",", "ty", ")", ":", "cairo", ".", "cairo_translate", "(", "self", ".", "_pointer", ",", "tx", ",", "ty", ")", "self", ".", "_check_status", "(", ")" ]
41.0625
18.9375
def _pseudoinverse(self, A, tol=1.0e-10): """Compute the Moore-Penrose pseudoinverse, wraps np.linalg.pinv REQUIRED ARGUMENTS A (np KxK matrix) - the square matrix whose pseudoinverse is to be computed RETURN VALUES Ainv (np KxK matrix) - the pseudoinverse OPTIONAL...
[ "def", "_pseudoinverse", "(", "self", ",", "A", ",", "tol", "=", "1.0e-10", ")", ":", "return", "np", ".", "linalg", ".", "pinv", "(", "A", ",", "rcond", "=", "tol", ")" ]
35.368421
29
def get_composite_field_value(self, name): """ Return the form/formset instance for the given field name. """ field = self.composite_fields[name] if hasattr(field, 'get_form'): return self.forms[name] if hasattr(field, 'get_formset'): return self.f...
[ "def", "get_composite_field_value", "(", "self", ",", "name", ")", ":", "field", "=", "self", ".", "composite_fields", "[", "name", "]", "if", "hasattr", "(", "field", ",", "'get_form'", ")", ":", "return", "self", ".", "forms", "[", "name", "]", "if", ...
36.111111
4.555556
def Random(self): """Chooses a random element from this PMF. Returns: float value from the Pmf """ if len(self.d) == 0: raise ValueError('Pmf contains no values.') target = random.random() total = 0.0 for x, p in self.d.iteritems(): ...
[ "def", "Random", "(", "self", ")", ":", "if", "len", "(", "self", ".", "d", ")", "==", "0", ":", "raise", "ValueError", "(", "'Pmf contains no values.'", ")", "target", "=", "random", ".", "random", "(", ")", "total", "=", "0.0", "for", "x", ",", "...
23.944444
16.666667
def return_env(self, exists=True): """ Return environment dict. Parameters ---------- exists: bool It True, only return existing paths. """ env = dict( include=self._build_paths('include', [self.VCIncl...
[ "def", "return_env", "(", "self", ",", "exists", "=", "True", ")", ":", "env", "=", "dict", "(", "include", "=", "self", ".", "_build_paths", "(", "'include'", ",", "[", "self", ".", "VCIncludes", ",", "self", ".", "OSIncludes", ",", "self", ".", "UC...
42.886364
12.931818
def _set_preferences(self, node): ''' Set preferences. :return: ''' pref = etree.SubElement(node, 'preferences') pacman = etree.SubElement(pref, 'packagemanager') pacman.text = self._get_package_manager() p_version = etree.SubElement(pref, 'version') ...
[ "def", "_set_preferences", "(", "self", ",", "node", ")", ":", "pref", "=", "etree", ".", "SubElement", "(", "node", ",", "'preferences'", ")", "pacman", "=", "etree", ".", "SubElement", "(", "pref", ",", "'packagemanager'", ")", "pacman", ".", "text", "...
35.259259
18.888889
def _findSwiplFromExec(): """ This function tries to use an executable on the path to find SWI-Prolog SO/DLL and the resource file. :returns: A tuple of (path to the swipl DLL, path to the resource file) :returns type: ({str, None}, {str, None}) """ platform = sys.platform...
[ "def", "_findSwiplFromExec", "(", ")", ":", "platform", "=", "sys", ".", "platform", "[", ":", "3", "]", "fullName", "=", "None", "swiHome", "=", "None", "try", ":", "# try to get library path from swipl executable.", "# We may have pl or swipl as the executable", "tr...
37.365591
20.526882
def split_before(iterable, pred): """Yield lists of items from *iterable*, where each list starts with an item where callable *pred* returns ``True``: >>> list(split_before('OneTwo', lambda s: s.isupper())) [['O', 'n', 'e'], ['T', 'w', 'o']] >>> list(split_before(range(10), lambda n: n...
[ "def", "split_before", "(", "iterable", ",", "pred", ")", ":", "buf", "=", "[", "]", "for", "item", "in", "iterable", ":", "if", "pred", "(", "item", ")", "and", "buf", ":", "yield", "buf", "buf", "=", "[", "]", "buf", ".", "append", "(", "item",...
29
18
def main(): """Command line entry point.""" def help_exit(): raise SystemExit("usage: ddate [day] [month] [year]") if "--help" in sys.argv or "-h" in sys.argv: help_exit() if len(sys.argv) == 2: # allow for 23-2-2014 style, be lazy/sloppy with it for split_char in ".-/`,:;": ...
[ "def", "main", "(", ")", ":", "def", "help_exit", "(", ")", ":", "raise", "SystemExit", "(", "\"usage: ddate [day] [month] [year]\"", ")", "if", "\"--help\"", "in", "sys", ".", "argv", "or", "\"-h\"", "in", "sys", ".", "argv", ":", "help_exit", "(", ")", ...
27.565217
22.478261
def remove_vg(self, vg): """ Removes a volume group:: from lvm2py import * lvm = LVM() vg = lvm.get_vg("myvg", "w") lvm.remove_vg(vg) *Args:* * vg (obj): A VolumeGroup instance. *Raises:* * HandleErro...
[ "def", "remove_vg", "(", "self", ",", "vg", ")", ":", "vg", ".", "open", "(", ")", "rm", "=", "lvm_vg_remove", "(", "vg", ".", "handle", ")", "if", "rm", "!=", "0", ":", "vg", ".", "close", "(", ")", "raise", "CommitError", "(", "\"Failed to remove...
23.060606
21
def header_string_from_file(filename='feff.inp'): """ Reads Header string from either a HEADER file or feff.inp file Will also read a header from a non-pymatgen generated feff.inp file Args: filename: File name containing the Header data. Returns: Reads ...
[ "def", "header_string_from_file", "(", "filename", "=", "'feff.inp'", ")", ":", "with", "zopen", "(", "filename", ",", "\"r\"", ")", "as", "fobject", ":", "f", "=", "fobject", ".", "readlines", "(", ")", "feff_header_str", "=", "[", "]", "ln", "=", "0", ...
33.125
17.975