text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def _shuffle_tfrecord(path, random_gen): """Shuffle a single record file in memory.""" # Read all records record_iter = tf.compat.v1.io.tf_record_iterator(path) all_records = [ r for r in utils.tqdm( record_iter, desc="Reading...", unit=" examples", leave=False) ] # Shuffling in memory ran...
[ "def", "_shuffle_tfrecord", "(", "path", ",", "random_gen", ")", ":", "# Read all records", "record_iter", "=", "tf", ".", "compat", ".", "v1", ".", "io", ".", "tf_record_iterator", "(", "path", ")", "all_records", "=", "[", "r", "for", "r", "in", "utils",...
35.6
15.933333
def _setup_source_and_destination(self): """use the base class to setup the source and destinations but add to that setup the instantiation of the "new_crash_source" """ super(FetchTransformSaveWithSeparateNewCrashSourceApp, self) \ ._setup_source_and_destination() if self.co...
[ "def", "_setup_source_and_destination", "(", "self", ")", ":", "super", "(", "FetchTransformSaveWithSeparateNewCrashSourceApp", ",", "self", ")", ".", "_setup_source_and_destination", "(", ")", "if", "self", ".", "config", ".", "new_crash_source", ".", "new_crash_source...
52.3125
15
def xover_gen(self, range=None): """Generator for the XOVER command. The XOVER command returns information from the overview database for the article(s) specified. <http://tools.ietf.org/html/rfc2980#section-2.8> Args: range: An article number as an integer, or a t...
[ "def", "xover_gen", "(", "self", ",", "range", "=", "None", ")", ":", "args", "=", "None", "if", "range", "is", "not", "None", ":", "args", "=", "utils", ".", "unparse_range", "(", "range", ")", "code", ",", "message", "=", "self", ".", "command", ...
37.323529
23.264706
def get_var_primal(self, name): """Get the primal value of a variable. Returns None if the problem has not bee optimized.""" if self._var_primals is None: return None else: index = self._get_var_index(name) return self._var_primals[index]
[ "def", "get_var_primal", "(", "self", ",", "name", ")", ":", "if", "self", ".", "_var_primals", "is", "None", ":", "return", "None", "else", ":", "index", "=", "self", ".", "_get_var_index", "(", "name", ")", "return", "self", ".", "_var_primals", "[", ...
41.714286
9.142857
async def _observe(self, api_command): """Observe an endpoint.""" duration = api_command.observe_duration url = api_command.url(self._host) err_callback = api_command.err_callback msg = Message(code=Code.GET, uri=url, observe=duration) # Note that this is necessary to s...
[ "async", "def", "_observe", "(", "self", ",", "api_command", ")", ":", "duration", "=", "api_command", ".", "observe_duration", "url", "=", "api_command", ".", "url", "(", "self", ".", "_host", ")", "err_callback", "=", "api_command", ".", "err_callback", "m...
32.043478
16.826087
def _pwm_to_str(self, precision=4): """Return string representation of pwm. Parameters ---------- precision : int, optional, default 4 Floating-point precision. Returns ------- pwm_string : str """ if not self.pwm: return ...
[ "def", "_pwm_to_str", "(", "self", ",", "precision", "=", "4", ")", ":", "if", "not", "self", ".", "pwm", ":", "return", "\"\"", "fmt", "=", "\"{{:.{:d}f}}\"", ".", "format", "(", "precision", ")", "return", "\"\\n\"", ".", "join", "(", "[", "\"\\t\"",...
24.8
16.6
def choices(cls, order='natural'): """ Generate the choices as required by Django models. Parameters ---------- order : str in which the elements should be returned. Possible values are: * 'sorted', the elements will be sorted by `value` * 're...
[ "def", "choices", "(", "cls", ",", "order", "=", "'natural'", ")", ":", "INC", ",", "DEC", ",", "NAT", "=", "'sorted'", ",", "'reverse'", ",", "'natural'", "options", "=", "[", "INC", ",", "DEC", ",", "NAT", "]", "assert", "order", "in", "options", ...
38.5625
22.25
async def run_script(self, script): """Execute the script and save results.""" # Create a Bash command to add all the tools to PATH. tools_paths = ':'.join([map_["dest"] for map_ in self.tools_volumes]) add_tools_path = 'export PATH=$PATH:{}'.format(tools_paths) # Spawn another c...
[ "async", "def", "run_script", "(", "self", ",", "script", ")", ":", "# Create a Bash command to add all the tools to PATH.", "tools_paths", "=", "':'", ".", "join", "(", "[", "map_", "[", "\"dest\"", "]", "for", "map_", "in", "self", ".", "tools_volumes", "]", ...
58.266667
20.266667
def get_interface_name(): """ Returns the interface name of the first not link_local and not loopback interface. """ interface_name = '' interfaces = psutil.net_if_addrs() for name, details in interfaces.items(): for detail in details: if detail.family == socket.AF_INET: ...
[ "def", "get_interface_name", "(", ")", ":", "interface_name", "=", "''", "interfaces", "=", "psutil", ".", "net_if_addrs", "(", ")", "for", "name", ",", "details", "in", "interfaces", ".", "items", "(", ")", ":", "for", "detail", "in", "details", ":", "i...
38.785714
14.071429
def draw_text(self, content): """Draws text cell content to context""" wx2pango_alignment = { "left": pango.ALIGN_LEFT, "center": pango.ALIGN_CENTER, "right": pango.ALIGN_RIGHT, } cell_attributes = self.code_array.cell_attributes[self.key] a...
[ "def", "draw_text", "(", "self", ",", "content", ")", ":", "wx2pango_alignment", "=", "{", "\"left\"", ":", "pango", ".", "ALIGN_LEFT", ",", "\"center\"", ":", "pango", ".", "ALIGN_CENTER", ",", "\"right\"", ":", "pango", ".", "ALIGN_RIGHT", ",", "}", "cel...
31.615385
20.769231
def itermonthdates(cls, year, month): """ Returns an iterator for the month in a year This iterator will return all days (as NepDate objects) for the month and all days before the start of the month or after the end of the month that are required to get a complete week. "...
[ "def", "itermonthdates", "(", "cls", ",", "year", ",", "month", ")", ":", "curday", "=", "NepDate", ".", "from_bs_date", "(", "year", ",", "month", ",", "1", ")", "start_weekday", "=", "curday", ".", "weekday", "(", ")", "# Start_weekday represents the numbe...
44.142857
16
def get_rna(self) -> Rna: """Get the corresponding RNA or raise an exception if it's not the reference node. :raises: InferCentralDogmaException """ if self.variants: raise InferCentralDogmaException('can not get rna for variant') return Rna( namespace=s...
[ "def", "get_rna", "(", "self", ")", "->", "Rna", ":", "if", "self", ".", "variants", ":", "raise", "InferCentralDogmaException", "(", "'can not get rna for variant'", ")", "return", "Rna", "(", "namespace", "=", "self", ".", "namespace", ",", "name", "=", "s...
30.692308
16.769231
def no_intersections(nodes1, degree1, nodes2, degree2): r"""Determine if one surface is in the other. Helper for :func:`combine_intersections` that handles the case of no points of intersection. In this case, either the surfaces are disjoint or one is fully contained in the other. To check contain...
[ "def", "no_intersections", "(", "nodes1", ",", "degree1", ",", "nodes2", ",", "degree2", ")", ":", "# NOTE: This is a circular import.", "from", "bezier", "import", "_surface_intersection", "located", "=", "_surface_intersection", ".", "locate_point", "(", "nodes2", "...
36.341463
22.731707
def save(self, filepath = None, password = None, keyfile = None): """This method saves the database. It's possible to parse a data path to an alternative file. """ if (password is None and keyfile is not None and keyfile != "" and type(keyfile) is str): ...
[ "def", "save", "(", "self", ",", "filepath", "=", "None", ",", "password", "=", "None", ",", "keyfile", "=", "None", ")", ":", "if", "(", "password", "is", "None", "and", "keyfile", "is", "not", "None", "and", "keyfile", "!=", "\"\"", "and", "type", ...
40.102941
16.757353
def display_graphic(self, flag_curves, ui): """ This function plots results of a file into the canvas. Inputs : flag_curves : A boolean to know with we have to plot all curves or not. ui : The main_Window. """ ui.graphic_widget.canvas.picture.clear() x =...
[ "def", "display_graphic", "(", "self", ",", "flag_curves", ",", "ui", ")", ":", "ui", ".", "graphic_widget", ".", "canvas", ".", "picture", ".", "clear", "(", ")", "x", "=", "scipy", ".", "linspace", "(", "self", ".", "x_data", "[", "0", "]", ",", ...
55.941176
31.529412
def flatten(list_of_lists): """Flatten a list of lists but maintain strings and ints as entries.""" flat_list = [] for sublist in list_of_lists: if isinstance(sublist, string_types) or isinstance(sublist, int): flat_list.append(sublist) elif sublist is None: continue ...
[ "def", "flatten", "(", "list_of_lists", ")", ":", "flat_list", "=", "[", "]", "for", "sublist", "in", "list_of_lists", ":", "if", "isinstance", "(", "sublist", ",", "string_types", ")", "or", "isinstance", "(", "sublist", ",", "int", ")", ":", "flat_list",...
38.615385
14.846154
def FDMT(data, f_min, f_max, maxDT, dataType): """ This function implements the FDMT algorithm. Input: Input visibility array (nints, nbl, nchan, npol) f_min,f_max are the base-band begin and end frequencies. The frequencies should be entered in MHz maxDT - the max...
[ "def", "FDMT", "(", "data", ",", "f_min", ",", "f_max", ",", "maxDT", ",", "dataType", ")", ":", "nint", ",", "nbl", ",", "nchan", ",", "npol", "=", "data", ".", "shape", "niters", "=", "int", "(", "np", ".", "log2", "(", "nchan", ")", ")", "as...
43.676471
22.735294
def get_revision_history(brain_or_object): """Get the revision history for the given brain or context. :param brain_or_object: A single catalog brain or content object :type brain_or_object: ATContentType/DexterityContentType/CatalogBrain :returns: Workflow history :rtype: obj """ obj = get...
[ "def", "get_revision_history", "(", "brain_or_object", ")", ":", "obj", "=", "get_object", "(", "brain_or_object", ")", "chv", "=", "ContentHistoryView", "(", "obj", ",", "safe_getattr", "(", "obj", ",", "\"REQUEST\"", ",", "None", ")", ")", "return", "chv", ...
39.363636
16.636364
def fit_transform(self, col): """Prepare the transformer and return processed data. Args: col(pandas.DataFrame): Data to transform. Returns: pandas.DataFrame """ if self.anonymize: col = self.anonymize_column(col) self._fit(col) ...
[ "def", "fit_transform", "(", "self", ",", "col", ")", ":", "if", "self", ".", "anonymize", ":", "col", "=", "self", ".", "anonymize_column", "(", "col", ")", "self", ".", "_fit", "(", "col", ")", "return", "self", ".", "transform", "(", "col", ")" ]
22.466667
19.266667
def get(self, *args, **kwargs): """Get the next waiting message from the queue. :returns: A :class:`Message` instance, or ``None`` if there is no messages waiting. """ if not mqueue.qsize(): return None message_data, content_type, content_encoding = mque...
[ "def", "get", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "not", "mqueue", ".", "qsize", "(", ")", ":", "return", "None", "message_data", ",", "content_type", ",", "content_encoding", "=", "mqueue", ".", "get", "(", ")", ...
37.307692
17.461538
def to_import_properties(properties): # type: (dict) -> dict """ Returns a dictionary where export properties have been replaced by import ones :param properties: A dictionary of service properties (with export keys) :return: A dictionary with import properties """ # Copy the given dict...
[ "def", "to_import_properties", "(", "properties", ")", ":", "# type: (dict) -> dict", "# Copy the given dictionary", "props", "=", "properties", ".", "copy", "(", ")", "# Add the \"imported\" property", "props", "[", "pelix", ".", "remote", ".", "PROP_IMPORTED", "]", ...
26.5
20.119048
def safe_open(filename, *args, **kwargs): """Open a file safely, ensuring that its directory exists. :API: public """ safe_mkdir_for(filename) return open(filename, *args, **kwargs)
[ "def", "safe_open", "(", "filename", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "safe_mkdir_for", "(", "filename", ")", "return", "open", "(", "filename", ",", "*", "args", ",", "*", "*", "kwargs", ")" ]
26.571429
11.571429
def import_name(self, import_loc, names): """import_name: 'import' dotted_as_names""" return ast.Import(names=names, keyword_loc=import_loc, loc=import_loc.join(names[-1].loc))
[ "def", "import_name", "(", "self", ",", "import_loc", ",", "names", ")", ":", "return", "ast", ".", "Import", "(", "names", "=", "names", ",", "keyword_loc", "=", "import_loc", ",", "loc", "=", "import_loc", ".", "join", "(", "names", "[", "-", "1", ...
53.75
12
def _nac(self, q_direction): """nac_term = (A1 (x) A2) / B * coef. """ num_atom = self._pcell.get_number_of_atoms() nac_q = np.zeros((num_atom, num_atom, 3, 3), dtype='double') if (np.abs(q_direction) < 1e-5).all(): return nac_q rec_lat = np.linalg.inv(self._...
[ "def", "_nac", "(", "self", ",", "q_direction", ")", ":", "num_atom", "=", "self", ".", "_pcell", ".", "get_number_of_atoms", "(", ")", "nac_q", "=", "np", ".", "zeros", "(", "(", "num_atom", ",", "num_atom", ",", "3", ",", "3", ")", ",", "dtype", ...
34.56
14
def make_scale(ae, series, *args, **kwargs): """ Return a proper scale object for the series The scale is for the aesthetic ae, and args & kwargs are passed on to the scale creating class """ stype = scale_type(series) # filter parameters by scale type if stype == 'discrete': w...
[ "def", "make_scale", "(", "ae", ",", "series", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "stype", "=", "scale_type", "(", "series", ")", "# filter parameters by scale type", "if", "stype", "==", "'discrete'", ":", "with", "suppress", "(", "KeyEr...
28.705882
12.117647
def data(self): """returns the reference to the data functions as a class""" if self._resources is None: self.__init() if "data" in self._resources: url = self._url + "/data" return _data.Data(url=url, securityHandler=self._securi...
[ "def", "data", "(", "self", ")", ":", "if", "self", ".", "_resources", "is", "None", ":", "self", ".", "__init", "(", ")", "if", "\"data\"", "in", "self", ".", "_resources", ":", "url", "=", "self", ".", "_url", "+", "\"/data\"", "return", "_data", ...
39.923077
12.692308
def iterate_with_name(cls): """Iterate over fields, but also give `structure_name`. Format is `(attribute_name, structue_name, field_instance)`. Structure name is name under which value is seen in structure and schema (in primitives) and only there. """ for attr_name, fi...
[ "def", "iterate_with_name", "(", "cls", ")", ":", "for", "attr_name", ",", "field", "in", "cls", ".", "iterate_over_fields", "(", ")", ":", "structure_name", "=", "field", ".", "structue_name", "(", "attr_name", ")", "yield", "attr_name", ",", "structure_name"...
45.5
16.7
def walk(self, dag, walk_func): """ Walks each node of the graph, in parallel if it can. The walk_func is only called when the nodes dependencies have been satisfied """ # First, we'll topologically sort all of the nodes, with nodes that # have no dependencies first. We ...
[ "def", "walk", "(", "self", ",", "dag", ",", "walk_func", ")", ":", "# First, we'll topologically sort all of the nodes, with nodes that", "# have no dependencies first. We do this to ensure that we don't call", "# .join on a thread that hasn't yet been started.", "#", "# TODO(ejholmes):...
35.754386
19.561404
def first_invoke(func1, func2): """ Return a function that when invoked will invoke func1 without any parameters (for its side-effect) and then invoke func2 with whatever parameters were passed, returning its result. """ def wrapper(*args, **kwargs): func1() return func2(*args, **kwargs) return wrapper
[ "def", "first_invoke", "(", "func1", ",", "func2", ")", ":", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "func1", "(", ")", "return", "func2", "(", "*", "args", ",", "*", "*", "kwargs", ")", "return", "wrapper" ]
30.5
14.5
def from_file_obj(cls, fp): """ Init a new object from a file-like object. Not for Outlook msg. Args: fp (file-like object): file-like object of raw email Returns: Instance of MailParser """ log.debug("Parsing email from file object") ...
[ "def", "from_file_obj", "(", "cls", ",", "fp", ")", ":", "log", ".", "debug", "(", "\"Parsing email from file object\"", ")", "try", ":", "fp", ".", "seek", "(", "0", ")", "except", "IOError", ":", "# When stdout is a TTY it's a character device", "# and it's not ...
26
19.090909
def timestamp(self, timestamp): """ Allows for custom timestamps to be saved with the record. """ clone = copy.deepcopy(self) clone._timestamp = timestamp return clone
[ "def", "timestamp", "(", "self", ",", "timestamp", ")", ":", "clone", "=", "copy", ".", "deepcopy", "(", "self", ")", "clone", ".", "_timestamp", "=", "timestamp", "return", "clone" ]
29.857143
9
def is_not_empty(self, value, strict=False): """if value is not empty""" value = stringify(value) if value is not None: return self.shout('Value %r is empty', strict, value)
[ "def", "is_not_empty", "(", "self", ",", "value", ",", "strict", "=", "False", ")", ":", "value", "=", "stringify", "(", "value", ")", "if", "value", "is", "not", "None", ":", "return", "self", ".", "shout", "(", "'Value %r is empty'", ",", "strict", "...
35.333333
9.833333
def mapTrace(trace, net, delta, verbose=False): """ matching a list of 2D positions to consecutive edges in a network """ result = [] paths = {} if verbose: print("mapping trace with %s points" % len(trace)) for pos in trace: newPaths = {} candidates = net.getNeighbor...
[ "def", "mapTrace", "(", "trace", ",", "net", ",", "delta", ",", "verbose", "=", "False", ")", ":", "result", "=", "[", "]", "paths", "=", "{", "}", "if", "verbose", ":", "print", "(", "\"mapping trace with %s points\"", "%", "len", "(", "trace", ")", ...
38.121951
14.756098
def log_exception(func, handler, args, kwargs): """ Wrap the handler ``log_exception`` method to finish the Span for the given request, if available. This method is called when an Exception is not handled in the user code. """ # safe-guard: expected arguments -> log_exception(self, typ, value, t...
[ "def", "log_exception", "(", "func", ",", "handler", ",", "args", ",", "kwargs", ")", ":", "# safe-guard: expected arguments -> log_exception(self, typ, value, tb)", "value", "=", "args", "[", "1", "]", "if", "len", "(", "args", ")", "==", "3", "else", "None", ...
39.8125
18.3125
def install_mesos_single_box_mode(distribution): """ install mesos (all of it) on a single node""" if 'ubuntu' in distribution: log_green('adding mesosphere apt-key') apt_add_key(keyid='E56151BF') os = lsb_release() apt_string = 'deb http://repos.mesosphere.io/%s %s main' % ( ...
[ "def", "install_mesos_single_box_mode", "(", "distribution", ")", ":", "if", "'ubuntu'", "in", "distribution", ":", "log_green", "(", "'adding mesosphere apt-key'", ")", "apt_add_key", "(", "keyid", "=", "'E56151BF'", ")", "os", "=", "lsb_release", "(", ")", "apt_...
38.12963
19.62963
def stats(self): """ Returns a data frame with Sample data and state. """ nameordered = self.samples.keys() nameordered.sort() ## Set pandas to display all samples instead of truncating pd.options.display.max_rows = len(self.samples) statdat = pd.DataFrame([self.samples[...
[ "def", "stats", "(", "self", ")", ":", "nameordered", "=", "self", ".", "samples", ".", "keys", "(", ")", "nameordered", ".", "sort", "(", ")", "## Set pandas to display all samples instead of truncating", "pd", ".", "options", ".", "display", ".", "max_rows", ...
45.785714
19.214286
def apply(self, **kwexpr): """ Specify one or more projection expressions to add to each result ### Parameters - **kwexpr**: One or more key-value pairs for a projection. The key is the alias for the projection, and the value is the projection expression itself,...
[ "def", "apply", "(", "self", ",", "*", "*", "kwexpr", ")", ":", "for", "alias", ",", "expr", "in", "kwexpr", ".", "items", "(", ")", ":", "self", ".", "_projections", ".", "append", "(", "[", "alias", ",", "expr", "]", ")", "return", "self" ]
34.357143
23.214286
def pivot(self, pivot_col, values=None): """ Pivots a column of the current :class:`DataFrame` and perform the specified aggregation. There are two versions of pivot function: one that requires the caller to specify the list of distinct values to pivot on, and one that does not. The latt...
[ "def", "pivot", "(", "self", ",", "pivot_col", ",", "values", "=", "None", ")", ":", "if", "values", "is", "None", ":", "jgd", "=", "self", ".", "_jgd", ".", "pivot", "(", "pivot_col", ")", "else", ":", "jgd", "=", "self", ".", "_jgd", ".", "pivo...
54.444444
34.444444
def request_acquisition(self, acquisition_request): """RequestAcquisition. [Preview API] :param :class:`<ExtensionAcquisitionRequest> <azure.devops.v5_1.gallery.models.ExtensionAcquisitionRequest>` acquisition_request: :rtype: :class:`<ExtensionAcquisitionRequest> <azure.devops.v5_1.gall...
[ "def", "request_acquisition", "(", "self", ",", "acquisition_request", ")", ":", "content", "=", "self", ".", "_serialize", ".", "body", "(", "acquisition_request", ",", "'ExtensionAcquisitionRequest'", ")", "response", "=", "self", ".", "_send", "(", "http_method...
63.333333
29.75
def verify_signature_unicode(self, address, signature, message): """Verify <signature> of <unicode> by <address>.""" hexdata = binascii.hexlify(message.encode("utf-8")) return self.verify_signature(address, signature, hexdata)
[ "def", "verify_signature_unicode", "(", "self", ",", "address", ",", "signature", ",", "message", ")", ":", "hexdata", "=", "binascii", ".", "hexlify", "(", "message", ".", "encode", "(", "\"utf-8\"", ")", ")", "return", "self", ".", "verify_signature", "(",...
61.75
17
def create(context, job_id, name, type, url, data): """create(context, job_id, name, type, url, data) Create an analytic. >>> dcictl analytic-create [OPTIONS] :param string job-id: The job on which to attach the analytic :param string name: Name of the analytic [required] :param string type: ...
[ "def", "create", "(", "context", ",", "job_id", ",", "name", ",", "type", ",", "url", ",", "data", ")", ":", "result", "=", "analytic", ".", "create", "(", "context", ",", "job_id", "=", "job_id", ",", "name", "=", "name", ",", "type", "=", "type",...
36.176471
18.176471
def _request(self, text, properties, retries=0): """Send a request to the CoreNLP server. :param (str | unicode) text: raw text for the CoreNLPServer to parse :param (dict) properties: properties that the server expects :return: request result """ text = to_unicode(text)...
[ "def", "_request", "(", "self", ",", "text", ",", "properties", ",", "retries", "=", "0", ")", ":", "text", "=", "to_unicode", "(", "text", ")", "# ensures unicode", "try", ":", "r", "=", "requests", ".", "post", "(", "self", ".", "server", ",", "par...
44.555556
19.925926
def call(name, function, *args, **kwargs): ''' Executes a Salt function inside a chroot environment. The chroot does not need to have Salt installed, but Python is required. name Path to the chroot environment function Salt execution module function CLI Example: .. c...
[ "def", "call", "(", "name", ",", "function", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "not", "function", ":", "raise", "CommandExecutionError", "(", "'Missing function parameter'", ")", "if", "not", "exist", "(", "name", ")", ":", "rais...
32.418919
21.824324
def create_checkered_image(width, height, c1=(154, 154, 154, 255), c2=(100, 100, 100, 255), s=6): """ Return a checkered image of size width x height. Arguments: * width: image width * height: image height * c1: first color (RGBA) * c2: second colo...
[ "def", "create_checkered_image", "(", "width", ",", "height", ",", "c1", "=", "(", "154", ",", "154", ",", "154", ",", "255", ")", ",", "c2", "=", "(", "100", ",", "100", ",", "100", ",", "255", ")", ",", "s", "=", "6", ")", ":", "im", "=", ...
35.761905
13.095238
def project_workspace_addsitedir(sitedir): """ Similar to site.addsitedir() but prefers new sitedir over existing ones. Therefore, prefers local packages over installed packages. .. note:: This allows to support *.pth files and zip-/egg-imports similar to an installed site-packages dire...
[ "def", "project_workspace_addsitedir", "(", "sitedir", ")", ":", "assert", "os", ".", "path", ".", "isdir", "(", "sitedir", ")", "try", ":", "from", "site", "import", "addsitedir", "except", "ImportError", ":", "# -- USE: Python2.7 site.py package", "from", "pysit...
33.391304
16.26087
def translate_src(src, cortex): """ Convert source nodes to new surface (without medial wall). """ src_new = np.array(np.where(np.in1d(cortex, src))[0], dtype=np.int32) return src_new
[ "def", "translate_src", "(", "src", ",", "cortex", ")", ":", "src_new", "=", "np", ".", "array", "(", "np", ".", "where", "(", "np", ".", "in1d", "(", "cortex", ",", "src", ")", ")", "[", "0", "]", ",", "dtype", "=", "np", ".", "int32", ")", ...
28.285714
18
def decrypt(source, dest=None, passphrase=None): """Attempts to decrypt a file""" if not os.path.exists(source): raise CryptoritoError("Encrypted file %s not found" % source) cmd = [gnupg_bin(), gnupg_verbose(), "--decrypt", gnupg_home(), passphrase_file(passphrase)] if dest: ...
[ "def", "decrypt", "(", "source", ",", "dest", "=", "None", ",", "passphrase", "=", "None", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "source", ")", ":", "raise", "CryptoritoError", "(", "\"Encrypted file %s not found\"", "%", "source", ...
29.5
19.357143
def flatten(list_to_flatten): """Flatten out a list.""" def genflatten(lst): for elem in lst: if isinstance(elem, (list, tuple)): for x in flatten(elem): yield x else: yield elem return list(genflatten(list_to_flatten))
[ "def", "flatten", "(", "list_to_flatten", ")", ":", "def", "genflatten", "(", "lst", ")", ":", "for", "elem", "in", "lst", ":", "if", "isinstance", "(", "elem", ",", "(", "list", ",", "tuple", ")", ")", ":", "for", "x", "in", "flatten", "(", "elem"...
25.5
15.416667
def Zabransky_cubic_integral(T, a1, a2, a3, a4): r'''Calculates the integral of liquid heat capacity using the model developed in [1]_. Parameters ---------- T : float Temperature [K] a1-a4 : float Coefficients Returns ------- H : float Difference in enthal...
[ "def", "Zabransky_cubic_integral", "(", "T", ",", "a1", ",", "a2", ",", "a3", ",", "a4", ")", ":", "T", "=", "T", "/", "100.", "return", "100", "*", "R", "*", "T", "*", "(", "T", "*", "(", "T", "*", "(", "T", "*", "a4", "*", "0.25", "+", ...
26.272727
28.030303
def fromkeys(cls, seq, value=None, **kwargs): """ Create a new collection with keys from *seq* and values set to *value*. The keyword arguments are passed to the persistent ``Dict``. """ other = cls(**kwargs) other.update(((key, value) for key in seq)) return oth...
[ "def", "fromkeys", "(", "cls", ",", "seq", ",", "value", "=", "None", ",", "*", "*", "kwargs", ")", ":", "other", "=", "cls", "(", "*", "*", "kwargs", ")", "other", ".", "update", "(", "(", "(", "key", ",", "value", ")", "for", "key", "in", "...
34.888889
17.111111
def _suppressed(self, filename, line, code): """Return true if linter error code is suppressed inline. The suppression format is suppress(CODE1,CODE2,CODE3) etc. """ if code in self.suppress_codes: return True lines = self._file_lines(filename) # File is ze...
[ "def", "_suppressed", "(", "self", ",", "filename", ",", "line", ",", "code", ")", ":", "if", "code", "in", "self", ".", "suppress_codes", ":", "return", "True", "lines", "=", "self", ".", "_file_lines", "(", "filename", ")", "# File is zero length, cannot b...
34.645161
20.903226
def absorption_coefficient( dielectric ): """ Calculate the optical absorption coefficient from an input set of pymatgen vasprun dielectric constant data. Args: dielectric (list): A list containing the dielectric response function in the pymatgen vasprun format. ...
[ "def", "absorption_coefficient", "(", "dielectric", ")", ":", "energies_in_eV", "=", "np", ".", "array", "(", "dielectric", "[", "0", "]", ")", "real_dielectric", "=", "parse_dielectric_data", "(", "dielectric", "[", "1", "]", ")", "imag_dielectric", "=", "par...
43.517241
28.206897
def _get_key_from_raw_synset(raw_synset): """Derives synset key in the form of `lemma.pos.sense_no` from the provided eurown.py Synset class, Notes ----- Internal function. Do not call directly. Parameters ---------- raw_synset : eurown.Synset Synset representation from which lemma,...
[ "def", "_get_key_from_raw_synset", "(", "raw_synset", ")", ":", "pos", "=", "raw_synset", ".", "pos", "literal", "=", "raw_synset", ".", "variants", "[", "0", "]", ".", "literal", "sense", "=", "\"%02d\"", "%", "raw_synset", ".", "variants", "[", "0", "]",...
26.347826
21.73913
def extern_store_utf8(self, context_handle, utf8_ptr, utf8_len): """Given a context and UTF8 bytes, return a new Handle to represent the content.""" c = self._ffi.from_handle(context_handle) return c.to_value(self._ffi.string(utf8_ptr, utf8_len).decode('utf-8'))
[ "def", "extern_store_utf8", "(", "self", ",", "context_handle", ",", "utf8_ptr", ",", "utf8_len", ")", ":", "c", "=", "self", ".", "_ffi", ".", "from_handle", "(", "context_handle", ")", "return", "c", ".", "to_value", "(", "self", ".", "_ffi", ".", "str...
67.75
16
def asset(class_obj: type) -> type: """ Decorator to annotate the Asset class. Registers the decorated class as the Asset known type. """ assert isinstance(class_obj, type), "class_obj is not a Class" global _asset_resource_type _asset_resource_type = class_obj return class_obj
[ "def", "asset", "(", "class_obj", ":", "type", ")", "->", "type", ":", "assert", "isinstance", "(", "class_obj", ",", "type", ")", ",", "\"class_obj is not a Class\"", "global", "_asset_resource_type", "_asset_resource_type", "=", "class_obj", "return", "class_obj" ...
33.555556
12
def group(values, min_len=0, max_len=np.inf): """ Return the indices of values that are identical Parameters ---------- values: 1D array min_len: int, the shortest group allowed All groups will have len >= min_length max_len: int, the longest group allowed ...
[ "def", "group", "(", "values", ",", "min_len", "=", "0", ",", "max_len", "=", "np", ".", "inf", ")", ":", "original", "=", "np", ".", "asanyarray", "(", "values", ")", "# save the sorted order and then apply it", "order", "=", "original", ".", "argsort", "...
34.5
18.409091
def _save_customization(self, widgets): """ Save the complete customization to the activity. :param widgets: The complete set of widgets to be customized """ if len(widgets) > 0: # Get the current customization and only replace the 'ext' part of it custom...
[ "def", "_save_customization", "(", "self", ",", "widgets", ")", ":", "if", "len", "(", "widgets", ")", ">", "0", ":", "# Get the current customization and only replace the 'ext' part of it", "customization", "=", "self", ".", "activity", ".", "_json_data", ".", "get...
43.516129
24.548387
def flatten_if(cond: Callable[[Union[T, ActualIterable[T]]], bool]): """ >>> from Redy.Collections import Traversal, Flow >>> lst: Iterable[int] = [[1, 2, 3]] >>> x = Flow(lst)[Traversal.flatten_if(lambda _: isinstance(_, list))] >>> assert isinstance(x.unbox, Generator) and list(x.unbox) == [1, 2, ...
[ "def", "flatten_if", "(", "cond", ":", "Callable", "[", "[", "Union", "[", "T", ",", "ActualIterable", "[", "T", "]", "]", "]", ",", "bool", "]", ")", ":", "def", "inner", "(", "nested", ":", "ActualIterable", "[", "Union", "[", "T", ",", "ActualIt...
35.125
20.5
def get_cookie_browse_sorting(path, default): ''' Get sorting-cookie data for path of current request. :returns: sorting property :rtype: string ''' if request: for cpath, cprop in iter_cookie_browse_sorting(request.cookies): if path == cpath: return cprop ...
[ "def", "get_cookie_browse_sorting", "(", "path", ",", "default", ")", ":", "if", "request", ":", "for", "cpath", ",", "cprop", "in", "iter_cookie_browse_sorting", "(", "request", ".", "cookies", ")", ":", "if", "path", "==", "cpath", ":", "return", "cprop", ...
27.083333
21.75
def populateFromRow(self, quantificationSetRecord): """ Populates the instance variables of this RnaQuantificationSet from the specified DB row. """ self._dbFilePath = quantificationSetRecord.dataurl self.setAttributesJson(quantificationSetRecord.attributes) self....
[ "def", "populateFromRow", "(", "self", ",", "quantificationSetRecord", ")", ":", "self", ".", "_dbFilePath", "=", "quantificationSetRecord", ".", "dataurl", "self", ".", "setAttributesJson", "(", "quantificationSetRecord", ".", "attributes", ")", "self", ".", "_db",...
42.222222
14.888889
def count(self): """ Return the number of hits matching the query and filters. Note that only the actual number is returned. """ if hasattr(self, '_response'): return self._response.hits.total es = connections.get_connection(self._using) d = self.to_...
[ "def", "count", "(", "self", ")", ":", "if", "hasattr", "(", "self", ",", "'_response'", ")", ":", "return", "self", ".", "_response", ".", "hits", ".", "total", "es", "=", "connections", ".", "get_connection", "(", "self", ".", "_using", ")", "d", "...
28.352941
14.588235
def emit_code_from_ir(compound_match_query, compiler_metadata): """Return a MATCH query string from a CompoundMatchQuery.""" # If the compound match query contains only one match query, # just call `emit_code_from_single_match_query` # If there are multiple match queries, construct the query string for ...
[ "def", "emit_code_from_ir", "(", "compound_match_query", ",", "compiler_metadata", ")", ":", "# If the compound match query contains only one match query,", "# just call `emit_code_from_single_match_query`", "# If there are multiple match queries, construct the query string for each", "# indiv...
34.727273
23.333333
def container(self, cls, **kwargs): """Container context manager.""" self.start_container(cls, **kwargs) yield self.end_container()
[ "def", "container", "(", "self", ",", "cls", ",", "*", "*", "kwargs", ")", ":", "self", ".", "start_container", "(", "cls", ",", "*", "*", "kwargs", ")", "yield", "self", ".", "end_container", "(", ")" ]
31.8
9.4
def show_portindex_interface_info_input_all(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") show_portindex_interface_info = ET.Element("show_portindex_interface_info") config = show_portindex_interface_info input = ET.SubElement(show_portindex_in...
[ "def", "show_portindex_interface_info_input_all", "(", "self", ",", "*", "*", "kwargs", ")", ":", "config", "=", "ET", ".", "Element", "(", "\"config\"", ")", "show_portindex_interface_info", "=", "ET", ".", "Element", "(", "\"show_portindex_interface_info\"", ")", ...
42.272727
15.272727
def minkowski_distance(point1, point2, degree=2): """! @brief Calculate Minkowski distance between two vectors. \f[ dist(a, b) = \sqrt[p]{ \sum_{i=0}^{N}\left(a_{i} - b_{i}\right)^{p} }; \f] @param[in] point1 (array_like): The first vector. @param[in] point2 (array_like): The seco...
[ "def", "minkowski_distance", "(", "point1", ",", "point2", ",", "degree", "=", "2", ")", ":", "distance", "=", "0.0", "for", "i", "in", "range", "(", "len", "(", "point1", ")", ")", ":", "distance", "+=", "(", "point1", "[", "i", "]", "-", "point2"...
29.363636
23.227273
def unpack(self, buff, offset=0): """Unpack a binary message into this object's attributes. Unpack the binary value *buff* and update this object attributes based on the results. Args: buff (bytes): Binary data package to be unpacked. offset (int): Where to begi...
[ "def", "unpack", "(", "self", ",", "buff", ",", "offset", "=", "0", ")", ":", "try", ":", "unpacked_data", "=", "struct", ".", "unpack", "(", "'!4B'", ",", "buff", "[", "offset", ":", "offset", "+", "4", "]", ")", "self", ".", "_value", "=", "'.'...
37.35
23.95
def validate_headers(self): """ Check if CSV metadata files have the right format. """ super().validate() self.validate_header(self.channeldir, self.channelinfo, CHANNEL_INFO_HEADER) self.validate_header(self.channeldir, self.contentinfo, CONTENT_INFO_HEADER) if s...
[ "def", "validate_headers", "(", "self", ")", ":", "super", "(", ")", ".", "validate", "(", ")", "self", ".", "validate_header", "(", "self", ".", "channeldir", ",", "self", ".", "channelinfo", ",", "CHANNEL_INFO_HEADER", ")", "self", ".", "validate_header", ...
52.5
25.3
def maps_get_rules_output_rules_value(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") maps_get_rules = ET.Element("maps_get_rules") config = maps_get_rules output = ET.SubElement(maps_get_rules, "output") rules = ET.SubElement(output, "ru...
[ "def", "maps_get_rules_output_rules_value", "(", "self", ",", "*", "*", "kwargs", ")", ":", "config", "=", "ET", ".", "Element", "(", "\"config\"", ")", "maps_get_rules", "=", "ET", ".", "Element", "(", "\"maps_get_rules\"", ")", "config", "=", "maps_get_rules...
37.769231
10.153846
def fromargskw(argskw, argspecs, slf_or_clsm = False): """Turns a linearized list of args into (args, keywords) form according to given argspecs (like inspect module provides). """ res_args = argskw try: kwds = argspecs.keywords except AttributeError: kwds = argspecs.varkw if...
[ "def", "fromargskw", "(", "argskw", ",", "argspecs", ",", "slf_or_clsm", "=", "False", ")", ":", "res_args", "=", "argskw", "try", ":", "kwds", "=", "argspecs", ".", "keywords", "except", "AttributeError", ":", "kwds", "=", "argspecs", ".", "varkw", "if", ...
32.742857
14.171429
def encrypt_email(email): """ The default encryption function for storing emails in the database. This uses AES and the encryption key defined in the applications configuration. :param email: The email address. """ aes = SimpleAES(flask.current_app.config["AES_KEY"]) return aes.enc...
[ "def", "encrypt_email", "(", "email", ")", ":", "aes", "=", "SimpleAES", "(", "flask", ".", "current_app", ".", "config", "[", "\"AES_KEY\"", "]", ")", "return", "aes", ".", "encrypt", "(", "email", ")" ]
29.181818
21.181818
def set_info(self, key, value, append=True): """ Set any special info you wish to the given key. Each info is stored in a list and will be appended to rather then overriden unless append is False. """ if append: if key not in self.info: self.in...
[ "def", "set_info", "(", "self", ",", "key", ",", "value", ",", "append", "=", "True", ")", ":", "if", "append", ":", "if", "key", "not", "in", "self", ".", "info", ":", "self", ".", "info", "[", "key", "]", "=", "[", "]", "self", ".", "info", ...
34.25
14.083333
def check_infos(self, expected_info_messages=[], allowed_info_messages=[]): """ This method should be called whenever you need to check if there is some info. Normally you need only ``check_expected_infos`` called after each test (which you specify only once), but it will check infos onl...
[ "def", "check_infos", "(", "self", ",", "expected_info_messages", "=", "[", "]", ",", "allowed_info_messages", "=", "[", "]", ")", ":", "# Close unexpected alerts (it's blocking).", "self", ".", "close_alert", "(", "ignore_exception", "=", "True", ")", "expected_inf...
52.608696
29.73913
def compute_discounts(self, precision=None): ''' Returns the total amount of discounts for this line with a specific number of decimals. @param precision:int number of decimal places @return: Decimal ''' gross = self.compute_gross(precision) return min(gro...
[ "def", "compute_discounts", "(", "self", ",", "precision", "=", "None", ")", ":", "gross", "=", "self", ".", "compute_gross", "(", "precision", ")", "return", "min", "(", "gross", ",", "sum", "(", "[", "d", ".", "compute", "(", "gross", ",", "precision...
39.5
19.9
def _compare_lists(list1, list2, custom_cmp): """Compare twolists using given comparing function. :param list1: first list to compare :param list2: second list to compare :param custom_cmp: a function taking two arguments (element of list 1, element of list 2) and :return: True or False dep...
[ "def", "_compare_lists", "(", "list1", ",", "list2", ",", "custom_cmp", ")", ":", "if", "len", "(", "list1", ")", "!=", "len", "(", "list2", ")", ":", "return", "False", "for", "element1", ",", "element2", "in", "zip", "(", "list1", ",", "list2", ")"...
35.866667
12
def appendRandomLenPadding(str, blocksize=AES_blocksize): 'ISO 10126 Padding (withdrawn, 2007): Pad with random bytes + last byte equal to the number of padding bytes' pad_len = paddingLength(len(str), blocksize) - 1 from os import urandom padding = urandom(pad_len)+chr(pad_len) return str + padding
[ "def", "appendRandomLenPadding", "(", "str", ",", "blocksize", "=", "AES_blocksize", ")", ":", "pad_len", "=", "paddingLength", "(", "len", "(", "str", ")", ",", "blocksize", ")", "-", "1", "from", "os", "import", "urandom", "padding", "=", "urandom", "(",...
34.555556
27.444444
def _set_get_last_config_update_time(self, v, load=False): """ Setter method for get_last_config_update_time, mapped from YANG variable /brocade_vcs_rpc/get_last_config_update_time (rpc) If this variable is read-only (config: false) in the source YANG file, then _set_get_last_config_update_time is consi...
[ "def", "_set_get_last_config_update_time", "(", "self", ",", "v", ",", "load", "=", "False", ")", ":", "if", "hasattr", "(", "v", ",", "\"_utype\"", ")", ":", "v", "=", "v", ".", "_utype", "(", "v", ")", "try", ":", "t", "=", "YANGDynClass", "(", "...
78.36
38.32
def load_mib(filenames): """Load the conf.mib dict from a list of filenames""" the_mib = {'iso': ['1']} unresolved = {} for k in six.iterkeys(conf.mib): _mib_register(conf.mib[k], k.split("."), the_mib, unresolved) if isinstance(filenames, (str, bytes)): filenames = [filenames] ...
[ "def", "load_mib", "(", "filenames", ")", ":", "the_mib", "=", "{", "'iso'", ":", "[", "'1'", "]", "}", "unresolved", "=", "{", "}", "for", "k", "in", "six", ".", "iterkeys", "(", "conf", ".", "mib", ")", ":", "_mib_register", "(", "conf", ".", "...
36.59375
14.5
def set_web_index_page(self, container, page): """ Sets the header indicating the index page in a container when creating a static website. Note: the container must be CDN-enabled for this to have any effect. """ headers = {"X-Container-Meta-Web-Index": "%s" % pa...
[ "def", "set_web_index_page", "(", "self", ",", "container", ",", "page", ")", ":", "headers", "=", "{", "\"X-Container-Meta-Web-Index\"", ":", "\"%s\"", "%", "page", "}", "self", ".", "api", ".", "cdn_request", "(", "\"/%s\"", "%", "utils", ".", "get_name", ...
38.636364
16.636364
def true_neg_rate(self): """Calculates true negative rate :return: true negative rate """ false_pos = self.matrix[1][0] true_neg = self.matrix[1][1] return divide(1.0 * true_neg, true_neg + false_pos)
[ "def", "true_neg_rate", "(", "self", ")", ":", "false_pos", "=", "self", ".", "matrix", "[", "1", "]", "[", "0", "]", "true_neg", "=", "self", ".", "matrix", "[", "1", "]", "[", "1", "]", "return", "divide", "(", "1.0", "*", "true_neg", ",", "tru...
30.25
10.875
def cli(ctx, env): """Print shell help text.""" env.out("Welcome to the SoftLayer shell.") env.out("") formatter = formatting.HelpFormatter() commands = [] shell_commands = [] for name in cli_core.cli.list_commands(ctx): command = cli_core.cli.get_command(ctx, name) if comma...
[ "def", "cli", "(", "ctx", ",", "env", ")", ":", "env", ".", "out", "(", "\"Welcome to the SoftLayer shell.\"", ")", "env", ".", "out", "(", "\"\"", ")", "formatter", "=", "formatting", ".", "HelpFormatter", "(", ")", "commands", "=", "[", "]", "shell_com...
30.230769
13.307692
def filter_bandpass_fourier(t, data, method='stft', detrend='linear', df=None, harm=True, df_out=None, harm_out=True): """ Return bandpass FFT-filtered signal (and the rest) Optionnally include all higher harmonics Can also exclude a frequency interva...
[ "def", "filter_bandpass_fourier", "(", "t", ",", "data", ",", "method", "=", "'stft'", ",", "detrend", "=", "'linear'", ",", "df", "=", "None", ",", "harm", "=", "True", ",", "df_out", "=", "None", ",", "harm_out", "=", "True", ")", ":", "# Check / for...
40.19403
21.313433
def _prep_config(items, paired, work_dir): """Run initial configuration, generating a run directory for Manta. """ assert utils.which("configManta.py"), "Could not find installed configManta.py" out_file = os.path.join(work_dir, "runWorkflow.py") if not utils.file_exists(out_file) or _out_of_date(ou...
[ "def", "_prep_config", "(", "items", ",", "paired", ",", "work_dir", ")", ":", "assert", "utils", ".", "which", "(", "\"configManta.py\"", ")", ",", "\"Could not find installed configManta.py\"", "out_file", "=", "os", ".", "path", ".", "join", "(", "work_dir", ...
53.4
21.133333
def fingerprint(dirnames, prefix=None, previous=[]): #pylint:disable=dangerous-default-value """ Returns a list of paths available from *dirname*. When previous is specified, returns a list of additional files only. Example: [{ "Key": "abc.txt", "LastModified": "Mon, 05 Jan 2015 12:00:00...
[ "def", "fingerprint", "(", "dirnames", ",", "prefix", "=", "None", ",", "previous", "=", "[", "]", ")", ":", "#pylint:disable=dangerous-default-value", "results", "=", "[", "]", "for", "dirname", "in", "dirnames", ":", "for", "filename", "in", "os", ".", "...
38.694444
14.972222
def get_usrgos(self, fin_goids, prt): """Return source GO IDs .""" ret = self.get_goids(None, fin_goids, prt) # If there have been no GO IDs explicitly specified by the user if not ret: # If the GO-DAG is sufficiently small, print all GO IDs if self.max_gos is not...
[ "def", "get_usrgos", "(", "self", ",", "fin_goids", ",", "prt", ")", ":", "ret", "=", "self", ".", "get_goids", "(", "None", ",", "fin_goids", ",", "prt", ")", "# If there have been no GO IDs explicitly specified by the user", "if", "not", "ret", ":", "# If the ...
51.428571
18.857143
def generate_report(out_dir, latex_summaries, nb_markers, nb_samples, options): """Generates the report. :param out_dir: the output directory. :param latex_summaries: the list of LaTeX summaries. :param nb_markers: the final number of markers. :param nb_samples: the final number of samples. :pa...
[ "def", "generate_report", "(", "out_dir", ",", "latex_summaries", ",", "nb_markers", ",", "nb_samples", ",", "options", ")", ":", "# Getting the graphic paths file", "graphic_paths_fn", "=", "None", "if", "os", ".", "path", ".", "isfile", "(", "os", ".", "path",...
36.95
15.275
def cache(self, con): """Put a connection back into the pool cache.""" try: if self._reset == 2: con.reset() # reset the connection completely else: if self._reset or con._transaction: try: con.rollback(...
[ "def", "cache", "(", "self", ",", "con", ")", ":", "try", ":", "if", "self", ".", "_reset", "==", "2", ":", "con", ".", "reset", "(", ")", "# reset the connection completely", "else", ":", "if", "self", ".", "_reset", "or", "con", ".", "_transaction", ...
37.375
16.125
def accounts(): """Load the accounts YAML file and return a dict """ import yaml for path in account_files: try: c_dir = os.path.dirname(path) if not os.path.exists(c_dir): os.makedirs(c_dir) with open(path, 'rb') as f: return y...
[ "def", "accounts", "(", ")", ":", "import", "yaml", "for", "path", "in", "account_files", ":", "try", ":", "c_dir", "=", "os", ".", "path", ".", "dirname", "(", "path", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "c_dir", ")", ":", "...
20.947368
20.842105
def index(self, row, column, parent): """ Returns the index of the item in the model specified by the given row, column and parent index. row, column == int, parent == QModelIndex """ if not self.hasIndex(row, column, parent): return QtCore.QModelIndex() if not pare...
[ "def", "index", "(", "self", ",", "row", ",", "column", ",", "parent", ")", ":", "if", "not", "self", ".", "hasIndex", "(", "row", ",", "column", ",", "parent", ")", ":", "return", "QtCore", ".", "QModelIndex", "(", ")", "if", "not", "parent", ".",...
42.827586
18.344828
def execute_interactive_code(elem, doc): """Executes code blocks for a python shell. Parses the code in `elem.text` into blocks and executes them. Args: elem The AST element. doc The document. Return: The code with inline results. """ code_lines = [l[4:] for l in ...
[ "def", "execute_interactive_code", "(", "elem", ",", "doc", ")", ":", "code_lines", "=", "[", "l", "[", "4", ":", "]", "for", "l", "in", "elem", ".", "text", ".", "split", "(", "'\\n'", ")", "]", "code_blocks", "=", "[", "[", "code_lines", "[", "0"...
31.717949
17.769231
def list_reference_bases(self, id_, start=0, end=None): """ Returns an iterator over the bases from the server in the form of consecutive strings. This command does not conform to the patterns of the other search and get requests, and is implemented differently. """ ...
[ "def", "list_reference_bases", "(", "self", ",", "id_", ",", "start", "=", "0", ",", "end", "=", "None", ")", ":", "request", "=", "protocol", ".", "ListReferenceBasesRequest", "(", ")", "request", ".", "start", "=", "pb", ".", "int", "(", "start", ")"...
43.380952
15.857143
def render_template(templates_path, template_filename, context): """Render Jinja2 template for a NApp structure.""" template_env = Environment( autoescape=False, trim_blocks=False, loader=FileSystemLoader(str(templates_path))) return template_env.get_template(str(template...
[ "def", "render_template", "(", "templates_path", ",", "template_filename", ",", "context", ")", ":", "template_env", "=", "Environment", "(", "autoescape", "=", "False", ",", "trim_blocks", "=", "False", ",", "loader", "=", "FileSystemLoader", "(", "str", "(", ...
50.857143
13.142857
def flatten_to_documents(model, include_pointers=False): """Flatten the model to a list of documents (aka ``Document`` objects). This is to flatten a ``Binder``'ish model down to a list of documents. If ``include_pointers`` has been set to ``True``, ``DocumentPointers`` will also be included in the resu...
[ "def", "flatten_to_documents", "(", "model", ",", "include_pointers", "=", "False", ")", ":", "types", "=", "[", "Document", "]", "if", "include_pointers", ":", "types", ".", "append", "(", "DocumentPointer", ")", "types", "=", "tuple", "(", "types", ")", ...
32.8125
17.9375
def pack_dir_cmd(): 'List the contents of a subdirectory of a zipfile' parser = argparse.ArgumentParser(description=inspect.getdoc(part_edit_cmd)) parser.add_argument( 'path', help=( 'Path to list (including path to zip file, ' 'i.e. ./file.zipx or ./file.zipx/subdir)' ), ) args = parser.parse_args() ...
[ "def", "pack_dir_cmd", "(", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "inspect", ".", "getdoc", "(", "part_edit_cmd", ")", ")", "parser", ".", "add_argument", "(", "'path'", ",", "help", "=", "(", "'Path to list (in...
29.066667
20.666667
def primaryKeys(self, table, catalog=None, schema=None): # nopep8 """Creates a result set of column names that make up the primary key for a table by executing the SQLPrimaryKeys function.""" fut = self._run_operation(self._impl.primaryKeys, table, catalog=cata...
[ "def", "primaryKeys", "(", "self", ",", "table", ",", "catalog", "=", "None", ",", "schema", "=", "None", ")", ":", "# nopep8", "fut", "=", "self", ".", "_run_operation", "(", "self", ".", "_impl", ".", "primaryKeys", ",", "table", ",", "catalog", "=",...
58.833333
16.166667
def call_command_handler(command, pymux, arguments): """ Execute command. :param arguments: List of options. """ assert isinstance(arguments, list) # Resolve aliases. command = ALIASES.get(command, command) try: handler = COMMANDS_TO_HANDLERS[command] except KeyError: ...
[ "def", "call_command_handler", "(", "command", ",", "pymux", ",", "arguments", ")", ":", "assert", "isinstance", "(", "arguments", ",", "list", ")", "# Resolve aliases.", "command", "=", "ALIASES", ".", "get", "(", "command", ",", "command", ")", "try", ":",...
25
16.2
def add(self, *nonterminals): # type: (Iterable[Type[Nonterminal]]) -> None """ Add nonterminals into the set. :param nonterminals: Nonterminals to insert. :raise NotNonterminalException: If the object doesn't inherit from Nonterminal class. """ for nonterm in non...
[ "def", "add", "(", "self", ",", "*", "nonterminals", ")", ":", "# type: (Iterable[Type[Nonterminal]]) -> None", "for", "nonterm", "in", "nonterminals", ":", "if", "nonterm", "in", "self", ":", "continue", "_NonterminalSet", ".", "_control_nonterminal", "(", "nonterm...
39.384615
11.538462
def enable_passive_host_checks(self, host): """Enable passive checks for a host Format of the line that triggers function call:: ENABLE_PASSIVE_HOST_CHECKS;<host_name> :param host: host to edit :type host: alignak.objects.host.Host :return: None """ if n...
[ "def", "enable_passive_host_checks", "(", "self", ",", "host", ")", ":", "if", "not", "host", ".", "passive_checks_enabled", ":", "host", ".", "modified_attributes", "|=", "DICT_MODATTR", "[", "\"MODATTR_PASSIVE_CHECKS_ENABLED\"", "]", ".", "value", "host", ".", "...
37.266667
13.133333
def prepare( self, engine=None, mode=None, model=None, index=None, key=None, filter=None, projection=None, consistent=None, forward=None, parallel=None): """Validates the search parameters and builds the base request dict for each Query/Scan call.""" self.prepare_iterator_cls(en...
[ "def", "prepare", "(", "self", ",", "engine", "=", "None", ",", "mode", "=", "None", ",", "model", "=", "None", ",", "index", "=", "None", ",", "key", "=", "None", ",", "filter", "=", "None", ",", "projection", "=", "None", ",", "consistent", "=", ...
43.538462
19.230769
def notify(self, state, notifications): ''' Call this to schedule sending partner notification. ''' def do_append(desc, notifications): for notification in notifications: if not isinstance(notification, PendingNotification): raise ValueErr...
[ "def", "notify", "(", "self", ",", "state", ",", "notifications", ")", ":", "def", "do_append", "(", "desc", ",", "notifications", ")", ":", "for", "notification", "in", "notifications", ":", "if", "not", "isinstance", "(", "notification", ",", "PendingNotif...
46.705882
23.058824
def minimize(self, session=None, feed_dict=None, fetches=None, step_callback=None, loss_callback=None, **run_kwargs): """Minimize a scalar `Tensor`. Variables subject to optimization are updated in-place at the end of ...
[ "def", "minimize", "(", "self", ",", "session", "=", "None", ",", "feed_dict", "=", "None", ",", "fetches", "=", "None", ",", "step_callback", "=", "None", ",", "loss_callback", "=", "None", ",", "*", "*", "run_kwargs", ")", ":", "session", "=", "sessi...
41.649351
21.61039