text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def compile_theme(theme_id=None): """Compiles a theme.""" from engineer.processors import convert_less from engineer.themes import ThemeManager if theme_id is None: themes = ThemeManager.themes().values() else: themes = [ThemeManager.theme(theme_id)] with(indent(2)): pu...
[ "def", "compile_theme", "(", "theme_id", "=", "None", ")", ":", "from", "engineer", ".", "processors", "import", "convert_less", "from", "engineer", ".", "themes", "import", "ThemeManager", "if", "theme_id", "is", "None", ":", "themes", "=", "ThemeManager", "....
38.391304
21.826087
def main(args): """ Validates the submission. """ print_in_box('Validating submission ' + args.submission_filename) random.seed() temp_dir = args.temp_dir delete_temp_dir = False if not temp_dir: temp_dir = tempfile.mkdtemp() logging.info('Created temporary directory: %s', temp_dir) delete_t...
[ "def", "main", "(", "args", ")", ":", "print_in_box", "(", "'Validating submission '", "+", "args", ".", "submission_filename", ")", "random", ".", "seed", "(", ")", "temp_dir", "=", "args", ".", "temp_dir", "delete_temp_dir", "=", "False", "if", "not", "tem...
37.5
17.681818
def compute(self): """ Run an iteration of this anomaly classifier """ result = self._constructClassificationRecord() # Classify this point after waiting the classification delay if result.ROWID >= self._autoDetectWaitRecords: self._updateState(result) # Save new classification recor...
[ "def", "compute", "(", "self", ")", ":", "result", "=", "self", ".", "_constructClassificationRecord", "(", ")", "# Classify this point after waiting the classification delay", "if", "result", ".", "ROWID", ">=", "self", ".", "_autoDetectWaitRecords", ":", "self", "."...
30.0625
17.6875
async def update_houses(self): """Lookup details for devices on the plum servers""" houses = await self.fetch_houses() for house_id in houses: asyncio.Task(self.update_house(house_id))
[ "async", "def", "update_houses", "(", "self", ")", ":", "houses", "=", "await", "self", ".", "fetch_houses", "(", ")", "for", "house_id", "in", "houses", ":", "asyncio", ".", "Task", "(", "self", ".", "update_house", "(", "house_id", ")", ")" ]
43.2
6.8
def ring2nest(nside, ipix): """Drop-in replacement for healpy `~healpy.pixelfunc.ring2nest`.""" ipix = np.atleast_1d(ipix).astype(np.int64, copy=False) return ring_to_nested(ipix, nside)
[ "def", "ring2nest", "(", "nside", ",", "ipix", ")", ":", "ipix", "=", "np", ".", "atleast_1d", "(", "ipix", ")", ".", "astype", "(", "np", ".", "int64", ",", "copy", "=", "False", ")", "return", "ring_to_nested", "(", "ipix", ",", "nside", ")" ]
48.75
8.5
def parse_map_d(self): """Alpha map""" Kd = os.path.join(self.dir, " ".join(self.values[1:])) self.this_material.set_texture_alpha(Kd)
[ "def", "parse_map_d", "(", "self", ")", ":", "Kd", "=", "os", ".", "path", ".", "join", "(", "self", ".", "dir", ",", "\" \"", ".", "join", "(", "self", ".", "values", "[", "1", ":", "]", ")", ")", "self", ".", "this_material", ".", "set_texture_...
38.75
12
def export_svgs(obj, filename=None, height=None, width=None, webdriver=None, timeout=5): ''' Export the SVG-enabled plots within a layout. Each plot will result in a distinct SVG file. If the filename is not given, it is derived from the script name (e.g. ``/foo/myplot.py`` will create ``/foo/myplot.sv...
[ "def", "export_svgs", "(", "obj", ",", "filename", "=", "None", ",", "height", "=", "None", ",", "width", "=", "None", ",", "webdriver", "=", "None", ",", "timeout", "=", "5", ")", ":", "svgs", "=", "get_svgs", "(", "obj", ",", "height", "=", "heig...
33.982759
29.568966
def evaluate(self, data, env): """ Evaluate the predicates and values """ # For each predicate-value, we keep track of the positions # that have been copied to the result, so that the later # more general values do not overwrite the previous ones. result = np.repe...
[ "def", "evaluate", "(", "self", ",", "data", ",", "env", ")", ":", "# For each predicate-value, we keep track of the positions", "# that have been copied to the result, so that the later", "# more general values do not overwrite the previous ones.", "result", "=", "np", ".", "repea...
45.047619
11.238095
def _vagrant_call(node, function, section, comment, status_when_done=None, **kwargs): ''' Helper to call the vagrant functions. Wildcards supported. :param node: The Salt-id or wildcard :param function: the vagrant submodule to call :param section: the name for the state call. :param comment: w...
[ "def", "_vagrant_call", "(", "node", ",", "function", ",", "section", ",", "comment", ",", "status_when_done", "=", "None", ",", "*", "*", "kwargs", ")", ":", "ret", "=", "{", "'name'", ":", "node", ",", "'changes'", ":", "{", "}", ",", "'result'", "...
40.117647
20.078431
def reset(self): """ Fill the screen with black pixels """ surface = Surface(self.width, self.height) surface.fill(BLACK) self.matrix = surface.matrix
[ "def", "reset", "(", "self", ")", ":", "surface", "=", "Surface", "(", "self", ".", "width", ",", "self", ".", "height", ")", "surface", ".", "fill", "(", "BLACK", ")", "self", ".", "matrix", "=", "surface", ".", "matrix" ]
27.428571
7.428571
def bottoms(panels): """ Finds bottom lines of all panels :param panels: :return: sorted by row list of tuples representing lines (col, row , col + len, row) """ bottom_lines = [(p['col'], p['row'] + p['size_y'], p['col'] + p['size_x'], p['row'] + p['size_y']) for p in panels] return sorted(...
[ "def", "bottoms", "(", "panels", ")", ":", "bottom_lines", "=", "[", "(", "p", "[", "'col'", "]", ",", "p", "[", "'row'", "]", "+", "p", "[", "'size_y'", "]", ",", "p", "[", "'col'", "]", "+", "p", "[", "'size_x'", "]", ",", "p", "[", "'row'"...
45
24.75
def jsonify(obj, **kwargs): """ A version of json.dumps that can handle numpy arrays by creating a custom encoder for numpy dtypes. Parameters -------------- obj : JSON- serializable blob **kwargs : Passed to json.dumps Returns -------------- dumped : str JSON dum...
[ "def", "jsonify", "(", "obj", ",", "*", "*", "kwargs", ")", ":", "class", "NumpyEncoder", "(", "json", ".", "JSONEncoder", ")", ":", "def", "default", "(", "self", ",", "obj", ")", ":", "# will work for numpy.ndarrays", "# as well as their int64/etc objects", ...
26.666667
15.851852
def build_homogeneisation_vehicules(temporary_store = None, year = None): assert temporary_store is not None """Compute vehicule numbers by type""" assert year is not None # Load data bdf_survey_collection = SurveyCollection.load( collection = 'budget_des_familles', config_files_directory =...
[ "def", "build_homogeneisation_vehicules", "(", "temporary_store", "=", "None", ",", "year", "=", "None", ")", ":", "assert", "temporary_store", "is", "not", "None", "assert", "year", "is", "not", "None", "# Load data", "bdf_survey_collection", "=", "SurveyCollection...
44.981818
25.454545
def _init_go2bordercolor(objcolors, **kws): """Initialize go2bordercolor with default to make hdrgos bright blue.""" go2bordercolor_ret = objcolors.get_bordercolor() if 'go2bordercolor' not in kws: return go2bordercolor_ret go2bordercolor_usr = kws['go2bordercolor'] g...
[ "def", "_init_go2bordercolor", "(", "objcolors", ",", "*", "*", "kws", ")", ":", "go2bordercolor_ret", "=", "objcolors", ".", "get_bordercolor", "(", ")", "if", "'go2bordercolor'", "not", "in", "kws", ":", "return", "go2bordercolor_ret", "go2bordercolor_usr", "=",...
49.9
10.9
def _main_loop(self): ''' Continuous loop that reads from a kafka topic and tries to validate incoming messages ''' self.logger.debug("Processing messages") old_time = 0 while True: self._process_messages() if self.settings['STATS_DUMP'] !=...
[ "def", "_main_loop", "(", "self", ")", ":", "self", ".", "logger", ".", "debug", "(", "\"Processing messages\"", ")", "old_time", "=", "0", "while", "True", ":", "self", ".", "_process_messages", "(", ")", "if", "self", ".", "settings", "[", "'STATS_DUMP'"...
35.333333
16.333333
def _top(self): """ g """ # Goto top of the list self.top.body.focus_position = 2 if self.compact is False else 0 self.top.keypress(self.size, "")
[ "def", "_top", "(", "self", ")", ":", "# Goto top of the list", "self", ".", "top", ".", "body", ".", "focus_position", "=", "2", "if", "self", ".", "compact", "is", "False", "else", "0", "self", ".", "top", ".", "keypress", "(", "self", ".", "size", ...
34.8
13.4
def _write_version1(self,new_filename,update_regul=False): """write a version 1 pest control file Parameters ---------- new_filename : str name of the new pest control file update_regul : (boolean) flag to update zero-order Tikhonov prior information ...
[ "def", "_write_version1", "(", "self", ",", "new_filename", ",", "update_regul", "=", "False", ")", ":", "self", ".", "new_filename", "=", "new_filename", "self", ".", "rectify_pgroups", "(", ")", "self", ".", "rectify_pi", "(", ")", "self", ".", "_update_co...
41.946565
20.274809
def find_rdataset(self, name, rdtype, covers=dns.rdatatype.NONE, create=False): """Look for rdata with the specified name and type in the zone, and return an rdataset encapsulating it. The I{name}, I{rdtype}, and I{covers} parameters may be strings, in which case t...
[ "def", "find_rdataset", "(", "self", ",", "name", ",", "rdtype", ",", "covers", "=", "dns", ".", "rdatatype", ".", "NONE", ",", "create", "=", "False", ")", ":", "name", "=", "self", ".", "_validate_name", "(", "name", ")", "if", "isinstance", "(", "...
40.857143
18.285714
def OSPFNeighborState_originator_switch_info_switchVcsId(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") OSPFNeighborState = ET.SubElement(config, "OSPFNeighborState", xmlns="http://brocade.com/ns/brocade-notification-stream") originator_switch_info = ET...
[ "def", "OSPFNeighborState_originator_switch_info_switchVcsId", "(", "self", ",", "*", "*", "kwargs", ")", ":", "config", "=", "ET", ".", "Element", "(", "\"config\"", ")", "OSPFNeighborState", "=", "ET", ".", "SubElement", "(", "config", ",", "\"OSPFNeighborState\...
53.181818
26.181818
def import_start_event_to_graph(diagram_graph, process_id, process_attributes, element): """ Adds to graph the new element that represents BPMN start event. Start event inherits attribute parallelMultiple from CatchEvent type and sequence of eventDefinitionRef from Event type. Se...
[ "def", "import_start_event_to_graph", "(", "diagram_graph", ",", "process_id", ",", "process_attributes", ",", "element", ")", ":", "element_id", "=", "element", ".", "getAttribute", "(", "consts", ".", "Consts", ".", "id", ")", "start_event_definitions", "=", "{"...
70.64
37.12
def load_metadata_from_desc_file(self, desc_file, partition='train', max_duration=16.0,): """ Read metadata from the description file (possibly takes long, depending on the filesize) Params: desc_file (str): Path to a JSON-line file that cont...
[ "def", "load_metadata_from_desc_file", "(", "self", ",", "desc_file", ",", "partition", "=", "'train'", ",", "max_duration", "=", "16.0", ",", ")", ":", "logger", "=", "logUtil", ".", "getlogger", "(", ")", "logger", ".", "info", "(", "'Reading description fil...
46.408163
13.22449
def run_parallel(pipeline, input_gen, options={}, ncpu=4, chunksize=200): """ Run a pipeline in parallel over a input generator cutting it into small chunks. >>> # if we have a simple component >>> from reliure.pipeline import Composable >>> # that we want to run over a given input: >>> input =...
[ "def", "run_parallel", "(", "pipeline", ",", "input_gen", ",", "options", "=", "{", "}", ",", "ncpu", "=", "4", ",", "chunksize", "=", "200", ")", ":", "t0", "=", "time", "(", ")", "#FIXME: there is a know issue when pipeline results are \"big\" object, the merge ...
41.018519
19.166667
def _Open(self, path_spec=None, mode='rb'): """Opens the file-like object defined by path specification. Args: path_spec (PathSpec): path specification. mode (Optional[str]): file access mode. Raises: AccessError: if the access to open the file was denied. IOError: if the file-like...
[ "def", "_Open", "(", "self", ",", "path_spec", "=", "None", ",", "mode", "=", "'rb'", ")", ":", "if", "not", "path_spec", ":", "raise", "ValueError", "(", "'Missing path specification.'", ")", "data_stream", "=", "getattr", "(", "path_spec", ",", "'data_stre...
36.583333
20.388889
def to_gsea(graph: BELGraph, file: Optional[TextIO] = None) -> None: """Write the genes/gene products to a GRP file for use with GSEA gene set enrichment analysis. .. seealso:: - GRP `format specification <http://software.broadinstitute.org/cancer/software/gsea/wiki/index.php/Data_formats#GRP:_Gene_se...
[ "def", "to_gsea", "(", "graph", ":", "BELGraph", ",", "file", ":", "Optional", "[", "TextIO", "]", "=", "None", ")", "->", "None", ":", "print", "(", "'# {}'", ".", "format", "(", "graph", ".", "name", ")", ",", "file", "=", "file", ")", "nodes", ...
42.125
28.4375
def area(self): """ Estimate the area of the polygon. Returns ------- number Area of the polygon. """ if len(self.exterior) < 3: raise Exception("Cannot compute the polygon's area because it contains less than three points.") poly...
[ "def", "area", "(", "self", ")", ":", "if", "len", "(", "self", ".", "exterior", ")", "<", "3", ":", "raise", "Exception", "(", "\"Cannot compute the polygon's area because it contains less than three points.\"", ")", "poly", "=", "self", ".", "to_shapely_polygon", ...
25.714286
20
def requestField(self, field_name, required=False, strict=False): """Request the specified field from the OpenID user @param field_name: the unqualified simple registration field name @type field_name: str @param required: whether the given field should be presented to the ...
[ "def", "requestField", "(", "self", ",", "field_name", ",", "required", "=", "False", ",", "strict", "=", "False", ")", ":", "checkFieldName", "(", "field_name", ")", "if", "strict", ":", "if", "field_name", "in", "self", ".", "required", "or", "field_name...
34.583333
21.361111
def add_scaled_residues_highlight_to_nglview(self, view, structure_resnums, chain=None, color='red', unique_colors=False, opacity_range=(0.5,1), scale_range=(.7, 10), multiplier=None): """Add a list of residue numb...
[ "def", "add_scaled_residues_highlight_to_nglview", "(", "self", ",", "view", ",", "structure_resnums", ",", "chain", "=", "None", ",", "color", "=", "'red'", ",", "unique_colors", "=", "False", ",", "opacity_range", "=", "(", "0.5", ",", "1", ")", ",", "scal...
54.694444
32.5
def _get_cpu_info_from_ibm_pa_features(): ''' Returns the CPU info gathered from lsprop /proc/device-tree/cpus/*/ibm,pa-features Returns {} if lsprop is not found or ibm,pa-features does not have the desired info. ''' try: # Just return {} if there is no lsprop if not DataSource.has_ibm_pa_features(): retur...
[ "def", "_get_cpu_info_from_ibm_pa_features", "(", ")", ":", "try", ":", "# Just return {} if there is no lsprop", "if", "not", "DataSource", ".", "has_ibm_pa_features", "(", ")", ":", "return", "{", "}", "# If ibm,pa-features fails return {}", "returncode", ",", "output",...
29.058824
13.579832
def _collect_pops(stack, depth, pops, skip): """Recursively collects stack entries off the top of the stack according to the stack entry's depth.""" if depth >= 0: return pops set_current_depth_after_recursion = False set_skip_for_current_entry_children = False set_skip_after_current_entry = False extr...
[ "def", "_collect_pops", "(", "stack", ",", "depth", ",", "pops", ",", "skip", ")", ":", "if", "depth", ">=", "0", ":", "return", "pops", "set_current_depth_after_recursion", "=", "False", "set_skip_for_current_entry_children", "=", "False", "set_skip_after_current_e...
41.865854
25.871951
def deserialize_subject_info(subject_info_xml_path): """Deserialize a SubjectInfo XML file to a PyXB object.""" try: with open(subject_info_xml_path) as f: return d1_common.xml.deserialize(f.read()) except ValueError as e: raise d1_common.types.exceptions.InvalidToken( ...
[ "def", "deserialize_subject_info", "(", "subject_info_xml_path", ")", ":", "try", ":", "with", "open", "(", "subject_info_xml_path", ")", "as", "f", ":", "return", "d1_common", ".", "xml", ".", "deserialize", "(", "f", ".", "read", "(", ")", ")", "except", ...
39.25
18.75
def load_config(self, settings=None): """ Load the configuration either from the config file, or from the given settings. Args: settings (dict): If given, the settings are pulled from this dictionary. Otherwise, the config file is used. """ self._load...
[ "def", "load_config", "(", "self", ",", "settings", "=", "None", ")", ":", "self", ".", "_load_defaults", "(", ")", "if", "settings", ":", "self", ".", "update", "(", "settings", ")", "else", ":", "config_paths", "=", "_get_config_files", "(", ")", "for"...
33.388889
16.722222
def annotate(node): """Annotate a node with the stack frame describing the SConscript file and line number that created it.""" tb = sys.exc_info()[2] while tb and stack_bottom not in tb.tb_frame.f_locals: tb = tb.tb_next if not tb: # We did not find any exec of an SConscript file: wh...
[ "def", "annotate", "(", "node", ")", ":", "tb", "=", "sys", ".", "exc_info", "(", ")", "[", "2", "]", "while", "tb", "and", "stack_bottom", "not", "in", "tb", ".", "tb_frame", ".", "f_locals", ":", "tb", "=", "tb", ".", "tb_next", "if", "not", "t...
44.7
17
def K_swing_check_valve_Crane(D=None, fd=None, angled=True): r'''Returns the loss coefficient for a swing check valve as shown in [1]_. .. math:: K_2 = N\cdot f_d For angled swing check valves N = 100; for straight valves, N = 50. Parameters ---------- D : float, o...
[ "def", "K_swing_check_valve_Crane", "(", "D", "=", "None", ",", "fd", "=", "None", ",", "angled", "=", "True", ")", ":", "if", "D", "is", "None", "and", "fd", "is", "None", ":", "raise", "ValueError", "(", "'Either `D` or `fd` must be specified'", ")", "if...
29.354167
26.4375
def create(self, to, channel, custom_message=values.unset): """ Create a new VerificationInstance :param unicode to: To phonenumber :param unicode channel: sms or call :param unicode custom_message: A custom message for this verification :returns: Newly created Verifica...
[ "def", "create", "(", "self", ",", "to", ",", "channel", ",", "custom_message", "=", "values", ".", "unset", ")", ":", "data", "=", "values", ".", "of", "(", "{", "'To'", ":", "to", ",", "'Channel'", ":", "channel", ",", "'CustomMessage'", ":", "cust...
36.55
24.35
def channel(self, rpc_timeout=60, lazy=False): """Open Channel. :param int rpc_timeout: Timeout before we give up waiting for an RPC response from the server. :raises AMQPInvalidArgument: Invalid Parameters :raises AMQPChannelError: Raises if the channel...
[ "def", "channel", "(", "self", ",", "rpc_timeout", "=", "60", ",", "lazy", "=", "False", ")", ":", "LOGGER", ".", "debug", "(", "'Opening a new Channel'", ")", "if", "not", "compatibility", ".", "is_integer", "(", "rpc_timeout", ")", ":", "raise", "AMQPInv...
43.730769
18.923077
def add_service(self, loadbal_id, service_group_id, ip_address_id, port=80, enabled=True, hc_type=21, weight=1): """Adds a new service to the service group. :param int loadbal_id: The id of the loadbal where the service resides :param int service_group_id: The group to add t...
[ "def", "add_service", "(", "self", ",", "loadbal_id", ",", "service_group_id", ",", "ip_address_id", ",", "port", "=", "80", ",", "enabled", "=", "True", ",", "hc_type", "=", "21", ",", "weight", "=", "1", ")", ":", "kwargs", "=", "utils", ".", "Nested...
43.25641
16.897436
def init_workers(): """Waiting function, used to wake up the process pool""" setproctitle('oq-worker') # unregister raiseMasterKilled in oq-workers to avoid deadlock # since processes are terminated via pool.terminate() signal.signal(signal.SIGTERM, signal.SIG_DFL) # prctl is still useful (on Li...
[ "def", "init_workers", "(", ")", ":", "setproctitle", "(", "'oq-worker'", ")", "# unregister raiseMasterKilled in oq-workers to avoid deadlock", "# since processes are terminated via pool.terminate()", "signal", ".", "signal", "(", "signal", ".", "SIGTERM", ",", "signal", "."...
36.866667
17
def proximal_huber(space, gamma): """Proximal factory of the Huber norm. Parameters ---------- space : `TensorSpace` The domain of the functional gamma : float The smoothing parameter of the Huber norm functional. Returns ------- prox_factory : function Factory ...
[ "def", "proximal_huber", "(", "space", ",", "gamma", ")", ":", "gamma", "=", "float", "(", "gamma", ")", "class", "ProximalHuber", "(", "Operator", ")", ":", "\"\"\"Proximal operator of Huber norm.\"\"\"", "def", "__init__", "(", "self", ",", "sigma", ")", ":"...
27.983333
21.766667
def get_in(keys, coll, default=None, no_default=False): """ NB: This is a straight copy of the get_in implementation found in the toolz library (https://github.com/pytoolz/toolz/). It works with persistent data structures as well as the corresponding datastructures from the stdlib. ...
[ "def", "get_in", "(", "keys", ",", "coll", ",", "default", "=", "None", ",", "no_default", "=", "False", ")", ":", "try", ":", "return", "reduce", "(", "operator", ".", "getitem", ",", "keys", ",", "coll", ")", "except", "(", "KeyError", ",", "IndexE...
39.358974
19.769231
def read(self, src): """ Download GeoJSON file of US counties from url (S3 bucket) """ geojson = None if not self.is_valid_src(src): error = "File < {0} > does not exists or does start with 'http'." raise ValueError(error.format(src)) if not self.is_url(src): ...
[ "def", "read", "(", "self", ",", "src", ")", ":", "geojson", "=", "None", "if", "not", "self", ".", "is_valid_src", "(", "src", ")", ":", "error", "=", "\"File < {0} > does not exists or does start with 'http'.\"", "raise", "ValueError", "(", "error", ".", "fo...
43.35
13.2
def on_all_ok(self): """ This method is called when all the q-points have been computed. It runs `mrgscr` in sequential on the local machine to produce the final SCR file in the outdir of the `Work`. """ final_scr = self.merge_scrfiles() return self.Results(node=s...
[ "def", "on_all_ok", "(", "self", ")", ":", "final_scr", "=", "self", ".", "merge_scrfiles", "(", ")", "return", "self", ".", "Results", "(", "node", "=", "self", ",", "returncode", "=", "0", ",", "message", "=", "\"mrgscr done\"", ",", "final_scr", "=", ...
46.875
19.125
def copy_type_comments_to_annotations(args): """Copies argument type comments from the legacy long form to annotations in the entire function signature. """ for arg in args.args: copy_type_comment_to_annotation(arg) if args.vararg: copy_type_comment_to_annotation(args.vararg) f...
[ "def", "copy_type_comments_to_annotations", "(", "args", ")", ":", "for", "arg", "in", "args", ".", "args", ":", "copy_type_comment_to_annotation", "(", "arg", ")", "if", "args", ".", "vararg", ":", "copy_type_comment_to_annotation", "(", "args", ".", "vararg", ...
29.933333
15
def read_pattern(self, patterns, reverse=False, terminate_on_match=False, postprocess=str): """ General pattern reading. Uses monty's regrep method. Takes the same arguments. Args: patterns (dict): A dict of patterns, e.g., {"energy": r"e...
[ "def", "read_pattern", "(", "self", ",", "patterns", ",", "reverse", "=", "False", ",", "terminate_on_match", "=", "False", ",", "postprocess", "=", "str", ")", ":", "matches", "=", "regrep", "(", "self", ".", "filename", ",", "patterns", ",", "reverse", ...
50.896552
23.655172
def get_command(self, ctx, cmd_name): """ Allow for partial commands. """ rv = click.Group.get_command(self, ctx, cmd_name) if rv is not None: return rv matches = [x for x in self.list_commands(ctx) if x.startswith(cmd_name)] if not matches: ...
[ "def", "get_command", "(", "self", ",", "ctx", ",", "cmd_name", ")", ":", "rv", "=", "click", ".", "Group", ".", "get_command", "(", "self", ",", "ctx", ",", "cmd_name", ")", "if", "rv", "is", "not", "None", ":", "return", "rv", "matches", "=", "["...
40
11.923077
def rfc2425encode(name,value,parameters=None,charset="utf-8"): """Encodes a vCard field into an RFC2425 line. :Parameters: - `name`: field type name - `value`: field value - `parameters`: optional parameters - `charset`: encoding of the output and of the `value` (if not ...
[ "def", "rfc2425encode", "(", "name", ",", "value", ",", "parameters", "=", "None", ",", "charset", "=", "\"utf-8\"", ")", ":", "if", "not", "parameters", ":", "parameters", "=", "{", "}", "if", "type", "(", "value", ")", "is", "unicode", ":", "value", ...
31.230769
13.923077
def f_measure(reference_beats, estimated_beats, f_measure_threshold=0.07): """Compute the F-measure of correct vs incorrectly predicted beats. "Correctness" is determined over a small window. Examples -------- >>> reference_beats = mir_eval.io.load_events('reference.txt'...
[ "def", "f_measure", "(", "reference_beats", ",", "estimated_beats", ",", "f_measure_threshold", "=", "0.07", ")", ":", "validate", "(", "reference_beats", ",", "estimated_beats", ")", "# When estimated beats are empty, no beats are correct; metric is 0", "if", "estimated_beat...
36.302326
18.581395
def preprocess(train_dataset, output_dir, eval_dataset, checkpoint, pipeline_option): """Preprocess data in Cloud with DataFlow.""" import apache_beam as beam import google.datalab.utils from . import _preprocess if checkpoint is None: checkpoint = _util._DEFAULT_CHECKPOINT_GSURL job_na...
[ "def", "preprocess", "(", "train_dataset", ",", "output_dir", ",", "eval_dataset", ",", "checkpoint", ",", "pipeline_option", ")", ":", "import", "apache_beam", "as", "beam", "import", "google", ".", "datalab", ".", "utils", "from", ".", "import", "_preprocess",...
42.719298
21.333333
def parseVersionParts(text, seps=vseps): ''' Extract a list of major/minor/version integer strings from a string. Args: text (str): String to parse seps (tuple): A tuple or list of separators to use when parsing the version string. Examples: Parse a simple version string into a...
[ "def", "parseVersionParts", "(", "text", ",", "seps", "=", "vseps", ")", ":", "# Join seps together", "seps", "=", "''", ".", "join", "(", "seps", ")", "# Strip whitespace", "text", "=", "text", ".", "strip", "(", ")", "# Strip off leading chars", "text", "=...
33.272727
28.181818
def venv_pth(self, dirs): ''' Add the directories in `dirs` to the `sys.path`. A venv.pth file will be written in the site-packages dir of this virtualenv to add dirs to sys.path. dirs: a list of directories. ''' # Create venv.pth to add dirs to sys.path when us...
[ "def", "venv_pth", "(", "self", ",", "dirs", ")", ":", "# Create venv.pth to add dirs to sys.path when using the virtualenv.", "text", "=", "StringIO", ".", "StringIO", "(", ")", "text", ".", "write", "(", "\"# Autogenerated file. Do not modify.\\n\"", ")", "for", "pat...
41
22.857143
def get_sql_results( ctask, query_id, rendered_query, return_results=True, store_results=False, user_name=None, start_time=None): """Executes the sql query returns the results.""" with session_scope(not ctask.request.called_directly) as session: try: return execute_sql_statement...
[ "def", "get_sql_results", "(", "ctask", ",", "query_id", ",", "rendered_query", ",", "return_results", "=", "True", ",", "store_results", "=", "False", ",", "user_name", "=", "None", ",", "start_time", "=", "None", ")", ":", "with", "session_scope", "(", "no...
45.733333
19
def user_group_perms_processor(request): """ return context variables with org permissions to the user. """ org = None group = None if hasattr(request, "user"): if request.user.is_anonymous: group = None else: group = request.user.get_org_group() ...
[ "def", "user_group_perms_processor", "(", "request", ")", ":", "org", "=", "None", "group", "=", "None", "if", "hasattr", "(", "request", ",", "\"user\"", ")", ":", "if", "request", ".", "user", ".", "is_anonymous", ":", "group", "=", "None", "else", ":"...
24.304348
19.434783
def calc_upper_bca_percentile(alpha_percent, bias_correction, acceleration): """ Calculate the lower values of the Bias Corrected and Accelerated (BCa) bootstrap confidence intervals. Parameters ---------- alpha_percent : float in (0.0, 100.0). `100 - confidence_percentage`, where `conf...
[ "def", "calc_upper_bca_percentile", "(", "alpha_percent", ",", "bias_correction", ",", "acceleration", ")", ":", "z_upper", "=", "norm", ".", "ppf", "(", "1", "-", "alpha_percent", "/", "(", "100.0", "*", "2", ")", ")", "numerator", "=", "bias_correction", "...
41.311111
25
def group_pairs(pair_list): """ Groups a list of items using the first element in each pair as the item and the second element as the groupid. Args: pair_list (list): list of 2-tuples (item, groupid) Returns: dict: groupid_to_items: maps a groupid to a list of items SeeAlso: ...
[ "def", "group_pairs", "(", "pair_list", ")", ":", "# Initialize dict of lists", "groupid_to_items", "=", "defaultdict", "(", "list", ")", "# Insert each item into the correct group", "for", "item", ",", "groupid", "in", "pair_list", ":", "groupid_to_items", "[", "groupi...
27.8
18.2
def get_countdown(self, retries) -> int: """Calculate the countdown for a celery task retry.""" retry_delay = self.retry_delay if self.retry_exponential_backoff: return min( max(2 ** retries, retry_delay), # Exp. backoff self.max_retry_delay # The co...
[ "def", "get_countdown", "(", "self", ",", "retries", ")", "->", "int", ":", "retry_delay", "=", "self", ".", "retry_delay", "if", "self", ".", "retry_exponential_backoff", ":", "return", "min", "(", "max", "(", "2", "**", "retries", ",", "retry_delay", ")"...
43.444444
14.333333
def CreateAd(client, opener, ad_group_id): """Creates a ResponsiveDisplayAd. Args: client: an AdWordsClient instance. opener: an OpenerDirector instance. ad_group_id: an int ad group ID. Returns: The ad group ad that was successfully created. """ ad_group_ad_service = client.GetService('AdGr...
[ "def", "CreateAd", "(", "client", ",", "opener", ",", "ad_group_id", ")", ":", "ad_group_ad_service", "=", "client", ".", "GetService", "(", "'AdGroupAdService'", ",", "'v201809'", ")", "media_service", "=", "client", ".", "GetService", "(", "'MediaService'", ",...
34.507042
19.380282
def value_dp_matrix(self): """ :return: DataProperty for table data. :rtype: list """ if self.__value_dp_matrix is None: self.__value_dp_matrix = self.__dp_extractor.to_dp_matrix( to_value_matrix(self.headers, self.rows) ) return ...
[ "def", "value_dp_matrix", "(", "self", ")", ":", "if", "self", ".", "__value_dp_matrix", "is", "None", ":", "self", ".", "__value_dp_matrix", "=", "self", ".", "__dp_extractor", ".", "to_dp_matrix", "(", "to_value_matrix", "(", "self", ".", "headers", ",", "...
27.583333
16.416667
def convertLengthList(self, svgAttr): """Convert a list of lengths.""" return [self.convertLength(a) for a in self.split_attr_list(svgAttr)]
[ "def", "convertLengthList", "(", "self", ",", "svgAttr", ")", ":", "return", "[", "self", ".", "convertLength", "(", "a", ")", "for", "a", "in", "self", ".", "split_attr_list", "(", "svgAttr", ")", "]" ]
51.333333
13.333333
def line_ribbon(self): '''Display the protein secondary structure as a white lines that passes through the backbone chain. ''' # Control points are the CA (C alphas) backbone = np.array(self.topology['atom_names']) == 'CA' smoothline = self.add_representation('smoothl...
[ "def", "line_ribbon", "(", "self", ")", ":", "# Control points are the CA (C alphas)", "backbone", "=", "np", ".", "array", "(", "self", ".", "topology", "[", "'atom_names'", "]", ")", "==", "'CA'", "smoothline", "=", "self", ".", "add_representation", "(", "'...
44.8
29.066667
def accept_C_C(self, inst): ''' A Component contains packageable elements ''' for child in many(inst).PE_PE[8003](): self.accept(child)
[ "def", "accept_C_C", "(", "self", ",", "inst", ")", ":", "for", "child", "in", "many", "(", "inst", ")", ".", "PE_PE", "[", "8003", "]", "(", ")", ":", "self", ".", "accept", "(", "child", ")" ]
29
16
def get_subject_without_validation(jwt_bu64): """Extract subject from the JWT without validating the JWT. - The extracted subject cannot be trusted for authn or authz. Args: jwt_bu64: bytes JWT, encoded using a a URL safe flavor of Base64. Returns: str: The subject contained in th...
[ "def", "get_subject_without_validation", "(", "jwt_bu64", ")", ":", "try", ":", "jwt_dict", "=", "get_jwt_dict", "(", "jwt_bu64", ")", "except", "JwtException", "as", "e", ":", "return", "log_jwt_bu64_info", "(", "logging", ".", "error", ",", "str", "(", "e", ...
28.47619
21.333333
def get_distance_function(distance): """ Returns the distance function from the string name provided :param distance: The string name of the distributions :return: """ # If we provided distance function ourselves, use it if callable(distance): return distance try: return...
[ "def", "get_distance_function", "(", "distance", ")", ":", "# If we provided distance function ourselves, use it", "if", "callable", "(", "distance", ")", ":", "return", "distance", "try", ":", "return", "_supported_distances_lookup", "(", ")", "[", "distance", "]", "...
32.5
19.357143
def _upgrades(self, sid, transport): """Return the list of possible upgrades for a client connection.""" if not self.allow_upgrades or self._get_socket(sid).upgraded or \ self._async['websocket'] is None or transport == 'websocket': return [] return ['websocket']
[ "def", "_upgrades", "(", "self", ",", "sid", ",", "transport", ")", ":", "if", "not", "self", ".", "allow_upgrades", "or", "self", ".", "_get_socket", "(", "sid", ")", ".", "upgraded", "or", "self", ".", "_async", "[", "'websocket'", "]", "is", "None",...
51.666667
17.5
def response_change(self, request, obj): """ Overrides the default to be able to forward to the directory listing instead of the default change_list_view """ r = super(FolderAdmin, self).response_change(request, obj) # Code borrowed from django ModelAdmin to determine cha...
[ "def", "response_change", "(", "self", ",", "request", ",", "obj", ")", ":", "r", "=", "super", "(", "FolderAdmin", ",", "self", ")", ".", "response_change", "(", "request", ",", "obj", ")", "# Code borrowed from django ModelAdmin to determine changelist on the", ...
44.458333
18.541667
def _chunk_len_type(self): """ Reads just enough of the input to determine the next chunk's length and type; return a (*length*, *type*) pair where *type* is a byte sequence. If there are no more chunks, ``None`` is returned. """ x = self.file.read(8) if ...
[ "def", "_chunk_len_type", "(", "self", ")", ":", "x", "=", "self", ".", "file", ".", "read", "(", "8", ")", "if", "not", "x", ":", "return", "None", "if", "len", "(", "x", ")", "!=", "8", ":", "raise", "FormatError", "(", "'End of file whilst reading...
39.52
15.76
def handle_input(self, input_str, place=True, check=False): '''Transfer user input to valid chess position''' user = self.get_player() pos = self.validate_input(input_str) if pos[0] == 'u': self.undo(pos[1]) return pos if place: result = self.s...
[ "def", "handle_input", "(", "self", ",", "input_str", ",", "place", "=", "True", ",", "check", "=", "False", ")", ":", "user", "=", "self", ".", "get_player", "(", ")", "pos", "=", "self", ".", "validate_input", "(", "input_str", ")", "if", "pos", "[...
32.5
15
def check_password_expired(user): """ Return True if password is expired and system is using password expiration, False otherwise. """ if not settings.ACCOUNT_PASSWORD_USE_HISTORY: return False if hasattr(user, "password_expiry"): # user-specific value expiry = user.pass...
[ "def", "check_password_expired", "(", "user", ")", ":", "if", "not", "settings", ".", "ACCOUNT_PASSWORD_USE_HISTORY", ":", "return", "False", "if", "hasattr", "(", "user", ",", "\"password_expiry\"", ")", ":", "# user-specific value", "expiry", "=", "user", ".", ...
26.741935
17.83871
def add_http_endpoint(self, url, request_handler): """ This method provides a programatic way of added invidual routes to the http server. Args: url (str): the url to be handled by the request_handler request_handler (nautilus.network.RequestH...
[ "def", "add_http_endpoint", "(", "self", ",", "url", ",", "request_handler", ")", ":", "self", ".", "app", ".", "router", ".", "add_route", "(", "'*'", ",", "url", ",", "request_handler", ")" ]
41.2
21.4
def add_xml_to_node(self, node): """ For exporting, set data on etree.Element `node`. """ super(XBlock, self).add_xml_to_node(node) # Add children for each of our children. self.add_children_to_node(node)
[ "def", "add_xml_to_node", "(", "self", ",", "node", ")", ":", "super", "(", "XBlock", ",", "self", ")", ".", "add_xml_to_node", "(", "node", ")", "# Add children for each of our children.", "self", ".", "add_children_to_node", "(", "node", ")" ]
35.142857
6
def pairwise(seq): """ Pair an iterable, e.g., (1, 2, 3, 4) -> ((1, 2), (2, 3), (3, 4)) """ for i in range(0, len(seq) - 1): yield (seq[i], seq[i + 1])
[ "def", "pairwise", "(", "seq", ")", ":", "for", "i", "in", "range", "(", "0", ",", "len", "(", "seq", ")", "-", "1", ")", ":", "yield", "(", "seq", "[", "i", "]", ",", "seq", "[", "i", "+", "1", "]", ")" ]
28.333333
10
def capture(self, commit = ""): """Capture the current state of a project based on its provider Commit is relevant only for upstream providers. If empty, the latest commit from provider repository is taken. It is ignored for distribution providers. :param provider: project provider, e.g. upstream repository...
[ "def", "capture", "(", "self", ",", "commit", "=", "\"\"", ")", ":", "self", ".", "_validateProvider", "(", "self", ".", "_provider", ")", "# get client for repository", "# TODO(jchaloup): read config file to switch between local and remove clients", "# TODO(jchaloup): remote...
43
26.259259
def add_enumerable_item_to_dict(dict_, key, item): """Add an item to a list contained in a dict. For example: If the dict is ``{'some_key': ['an_item']}``, then calling this function will alter the dict to ``{'some_key': ['an_item', 'another_item']}``. If the key doesn't exist yet, the function initia...
[ "def", "add_enumerable_item_to_dict", "(", "dict_", ",", "key", ",", "item", ")", ":", "dict_", ".", "setdefault", "(", "key", ",", "[", "]", ")", "if", "isinstance", "(", "item", ",", "(", "list", ",", "tuple", ")", ")", ":", "dict_", "[", "key", ...
34.272727
24.727273
def extract_prefix_attr(cls, req): """ Extract prefix attributes from arbitary dict. """ # TODO: add more? attr = {} if 'id' in req: attr['id'] = int(req['id']) if 'prefix' in req: attr['prefix'] = req['prefix'] if 'pool' in req: ...
[ "def", "extract_prefix_attr", "(", "cls", ",", "req", ")", ":", "# TODO: add more?", "attr", "=", "{", "}", "if", "'id'", "in", "req", ":", "attr", "[", "'id'", "]", "=", "int", "(", "req", "[", "'id'", "]", ")", "if", "'prefix'", "in", "req", ":",...
28.727273
12
def save(potential, f): """ Write a :class:`~gala.potential.PotentialBase` object out to a text (YAML) file. Parameters ---------- potential : :class:`~gala.potential.PotentialBase` The instantiated :class:`~gala.potential.PotentialBase` object. f : str, file_like A filename...
[ "def", "save", "(", "potential", ",", "f", ")", ":", "d", "=", "to_dict", "(", "potential", ")", "if", "hasattr", "(", "f", ",", "'write'", ")", ":", "yaml", ".", "dump", "(", "d", ",", "f", ",", "default_flow_style", "=", "False", ")", "else", "...
28.7
22.4
def update(self, data): """Updates the object information based on live data, if there were any changes made. Any changes will be automatically applied to the object, but will not be automatically persisted. You must manually call `db.session.add(instance)` on the object. Args: ...
[ "def", "update", "(", "self", ",", "data", ")", ":", "# If the instance was terminated, remove it", "updated", "=", "self", ".", "set_property", "(", "'state'", ",", "data", "[", "'state'", "]", ")", "updated", "|=", "self", ".", "set_property", "(", "'notes'"...
38.9
25.6
def add_book(self, publisher=None, place=None, date=None): """ Make a dictionary that is representing a book. :param publisher: publisher name :type publisher: string :param place: place of publication :type place: string :param date: A (partial) date in any f...
[ "def", "add_book", "(", "self", ",", "publisher", "=", "None", ",", "place", "=", "None", ",", "date", "=", "None", ")", ":", "imprint", "=", "{", "}", "if", "date", "is", "not", "None", ":", "imprint", "[", "'date'", "]", "=", "normalize_date", "(...
26.185185
17.222222
def to_signed(cls, t): """ Return signed type or equivalent """ assert isinstance(t, SymbolTYPE) t = t.final assert t.is_basic if cls.is_unsigned(t): return {cls.ubyte: cls.byte_, cls.uinteger: cls.integer, cls.ulong: cl...
[ "def", "to_signed", "(", "cls", ",", "t", ")", ":", "assert", "isinstance", "(", "t", ",", "SymbolTYPE", ")", "t", "=", "t", ".", "final", "assert", "t", ".", "is_basic", "if", "cls", ".", "is_unsigned", "(", "t", ")", ":", "return", "{", "cls", ...
32.076923
9.076923
def allow_bare_decorator(cls): """ Wrapper for a class decorator which allows for bare decorator and argument syntax """ @wraps(cls) def wrapper(*args, **kwargs): """"Wrapper for real decorator""" # If we weren't only passed a bare class, return class instance if kwargs or ...
[ "def", "allow_bare_decorator", "(", "cls", ")", ":", "@", "wraps", "(", "cls", ")", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "\"\"\"\"Wrapper for real decorator\"\"\"", "# If we weren't only passed a bare class, return class instance", "i...
32.235294
21.823529
def _fill_properties(verdict, result, testcase, testcase_id, testcase_title): """Adds properties into testcase element.""" properties = etree.SubElement(testcase, "properties") etree.SubElement( properties, "property", {"name": "polarion-testcase-id", "value":...
[ "def", "_fill_properties", "(", "verdict", ",", "result", ",", "testcase", ",", "testcase_id", ",", "testcase_title", ")", ":", "properties", "=", "etree", ".", "SubElement", "(", "testcase", ",", "\"properties\"", ")", "etree", ".", "SubElement", "(", "proper...
37
21.592593
def encap(self, pkt): """encapsulate a frame using this Secure Association""" if pkt.name != Ether().name: raise TypeError('cannot encapsulate packet in MACsec, must be Ethernet') # noqa: E501 hdr = copy.deepcopy(pkt) payload = hdr.payload del hdr.payload tag...
[ "def", "encap", "(", "self", ",", "pkt", ")", ":", "if", "pkt", ".", "name", "!=", "Ether", "(", ")", ".", "name", ":", "raise", "TypeError", "(", "'cannot encapsulate packet in MACsec, must be Ethernet'", ")", "# noqa: E501", "hdr", "=", "copy", ".", "deepc...
44.142857
13.357143
def parse_iso_utc(s): """ Parses an ISO time with a hard-coded Z for zulu-time (UTC) at the end. Other timezones are not supported. :param str s: the ISO-formatted time :rtype: datetime.datetime :return: an timezone-naive datetime object >>> parse_iso_utc('2016-04-27T00:28:04.000Z') ...
[ "def", "parse_iso_utc", "(", "s", ")", ":", "m", "=", "rfc3339_datetime_re", "(", ")", ".", "match", "(", "s", ")", "if", "not", "m", ":", "raise", "ValueError", "(", "'Not a valid ISO datetime in UTC: '", "+", "s", ")", "else", ":", "fmt", "=", "'%Y-%m-...
32.692308
18.846154
def do_teardown_appcontext(self, exc=None): """Called when an application context is popped. This works pretty much the same as :meth:`do_teardown_request` but for the application context. .. versionadded:: 0.9 """ if exc is None: exc = sys.exc_info()[1] ...
[ "def", "do_teardown_appcontext", "(", "self", ",", "exc", "=", "None", ")", ":", "if", "exc", "is", "None", ":", "exc", "=", "sys", ".", "exc_info", "(", ")", "[", "1", "]", "for", "func", "in", "reversed", "(", "self", ".", "teardown_appcontext_funcs"...
36.75
15.583333
def detach(self, *items): """ Unlinks all of the specified items from the tree. The items and all of their descendants are still present, and may be reinserted at another point in the tree, but will not be displayed. The root item may not be detached. :param items: list...
[ "def", "detach", "(", "self", ",", "*", "items", ")", ":", "self", ".", "_visual_drag", ".", "detach", "(", "*", "items", ")", "ttk", ".", "Treeview", ".", "detach", "(", "self", ",", "*", "items", ")" ]
35.230769
15.230769
def _on_file_deleted(self, event: FileSystemEvent): """ Called when a file in the monitored directory has been deleted. :param event: the file system event """ if not event.is_directory and self.is_data_file(event.src_path): assert event.src_path in self._origin_mappe...
[ "def", "_on_file_deleted", "(", "self", ",", "event", ":", "FileSystemEvent", ")", ":", "if", "not", "event", ".", "is_directory", "and", "self", ".", "is_data_file", "(", "event", ".", "src_path", ")", ":", "assert", "event", ".", "src_path", "in", "self"...
48.333333
14.777778
def imgur_role(name, rawtext, text, *_): """Imgur ":imgur-title:`a/abc1234`" or ":imgur-description:`abc1234`" rst inline roles. "Schedules" an API query. :raises ImgurError: if text has invalid Imgur ID. :param str name: Role name (e.g. 'imgur-title'). :param str rawtext: Entire role and value m...
[ "def", "imgur_role", "(", "name", ",", "rawtext", ",", "text", ",", "*", "_", ")", ":", "if", "not", "RE_IMGUR_ID", ".", "match", "(", "text", ")", ":", "message", "=", "'Invalid Imgur ID specified. Must be 5-10 letters and numbers. Got \"{}\" from \"{}\".'", "raise...
42.421053
24.842105
def version(self): """Get the QS Mobile version.""" # requests.get destroys the ? import urllib with urllib.request.urlopen(URL_VERSION.format(self._url)) as response: return response.read().decode('utf-8') return False
[ "def", "version", "(", "self", ")", ":", "# requests.get destroys the ?", "import", "urllib", "with", "urllib", ".", "request", ".", "urlopen", "(", "URL_VERSION", ".", "format", "(", "self", ".", "_url", ")", ")", "as", "response", ":", "return", "response"...
37.857143
16.142857
def Header(self): """ Get the block header. Returns: neo.Core.Header: """ if not self._header: self._header = Header(self.PrevHash, self.MerkleRoot, self.Timestamp, self.Index, self.ConsensusData, self.NextConsensus, self...
[ "def", "Header", "(", "self", ")", ":", "if", "not", "self", ".", "_header", ":", "self", ".", "_header", "=", "Header", "(", "self", ".", "PrevHash", ",", "self", ".", "MerkleRoot", ",", "self", ".", "Timestamp", ",", "self", ".", "Index", ",", "s...
28.833333
22.833333
def zipfiles(fnames, archive, mode='w', log=lambda msg: None, cleanup=False): """ Build a zip archive from the given file names. :param fnames: list of path names :param archive: path of the archive """ prefix = len(os.path.commonprefix([os.path.dirname(f) for f in fnames])) with zipfile.Zi...
[ "def", "zipfiles", "(", "fnames", ",", "archive", ",", "mode", "=", "'w'", ",", "log", "=", "lambda", "msg", ":", "None", ",", "cleanup", "=", "False", ")", ":", "prefix", "=", "len", "(", "os", ".", "path", ".", "commonprefix", "(", "[", "os", "...
35.882353
14.705882
def unwrap(lines, max_wrap_lines, min_header_lines, min_quoted_lines): """ Returns a tuple of: - Type ('forward', 'reply', 'headers', 'quoted') - Range of the text at the top of the wrapped message (or None) - Headers dict (or None) - Range of the text of the wrapped message (or None) - Rang...
[ "def", "unwrap", "(", "lines", ",", "max_wrap_lines", ",", "min_header_lines", ",", "min_quoted_lines", ")", ":", "headers", "=", "{", "}", "# Get line number and wrapping type.", "start", ",", "end", ",", "typ", "=", "find_unwrap_start", "(", "lines", ",", "max...
46.52
25.48
def get_merge_command(self, revision): """Get the command to merge a revision into the current branch (without committing the result).""" return [ 'git', '-c', 'user.name=%s' % self.author.name, '-c', 'user.email=%s' % self.author.email, 'merge', '--no-com...
[ "def", "get_merge_command", "(", "self", ",", "revision", ")", ":", "return", "[", "'git'", ",", "'-c'", ",", "'user.name=%s'", "%", "self", ".", "author", ".", "name", ",", "'-c'", ",", "'user.email=%s'", "%", "self", ".", "author", ".", "email", ",", ...
40
14.444444
def parse(self, args, ignore_help=False): """Parse the (command-line) arguments.""" options = self._default_dict() seen = set() # Do not alter the arguments. We may need them later. args = copy.copy(args) while args: opt = args.pop(0) seen.add(o...
[ "def", "parse", "(", "self", ",", "args", ",", "ignore_help", "=", "False", ")", ":", "options", "=", "self", ".", "_default_dict", "(", ")", "seen", "=", "set", "(", ")", "# Do not alter the arguments. We may need them later.", "args", "=", "copy", ".", "co...
32.849057
20.150943
def format_hexadecimal_field(spec, prec, number, locale): """Formats a hexadeciaml field.""" if number < 0: # Take two's complement. number &= (1 << (8 * int(math.log(-number, 1 << 8) + 1))) - 1 format_ = u'0%d%s' % (int(prec or 0), spec) return format(number, format_)
[ "def", "format_hexadecimal_field", "(", "spec", ",", "prec", ",", "number", ",", "locale", ")", ":", "if", "number", "<", "0", ":", "# Take two's complement.", "number", "&=", "(", "1", "<<", "(", "8", "*", "int", "(", "math", ".", "log", "(", "-", "...
42.142857
12.714286
def clusters(self): """returns the clusters functions if supported in resources""" if self._resources is None: self.__init() if "clusters" in self._resources: url = self._url + "/clusters" return _clusters.Cluster(url=url, ...
[ "def", "clusters", "(", "self", ")", ":", "if", "self", ".", "_resources", "is", "None", ":", "self", ".", "__init", "(", ")", "if", "\"clusters\"", "in", "self", ".", "_resources", ":", "url", "=", "self", ".", "_url", "+", "\"/clusters\"", "return", ...
43.692308
14.461538
def rotate(file_name, rotate, suffix='rotated', tempdir=None): """Rotate PDF by increments of 90 degrees.""" # Set output file name if tempdir: outfn = NamedTemporaryFile(suffix='.pdf', dir=tempdir, delete=False).name elif suffix: outfn = os.path.join(os.path.dirname(file_name), add_suff...
[ "def", "rotate", "(", "file_name", ",", "rotate", ",", "suffix", "=", "'rotated'", ",", "tempdir", "=", "None", ")", ":", "# Set output file name", "if", "tempdir", ":", "outfn", "=", "NamedTemporaryFile", "(", "suffix", "=", "'.pdf'", ",", "dir", "=", "te...
33.875
23.833333
def fail(message, code=-1): """Fail with an error.""" print('Error: %s' % message, file=sys.stderr) sys.exit(code)
[ "def", "fail", "(", "message", ",", "code", "=", "-", "1", ")", ":", "print", "(", "'Error: %s'", "%", "message", ",", "file", "=", "sys", ".", "stderr", ")", "sys", ".", "exit", "(", "code", ")" ]
30.75
11
def collect(self, top, sup, argv=None, parent=""): """ means this element is part of a larger object, hence a property of that object """ try: argv_copy = sd_copy(argv) return [self.repr(top, sup, argv_copy, parent=parent)], [] except AttributeError as e...
[ "def", "collect", "(", "self", ",", "top", ",", "sup", ",", "argv", "=", "None", ",", "parent", "=", "\"\"", ")", ":", "try", ":", "argv_copy", "=", "sd_copy", "(", "argv", ")", "return", "[", "self", ".", "repr", "(", "top", ",", "sup", ",", "...
37.2
13
def state_set(self, state, use_active_range=False): """Sets the internal state of the df Example: >>> import vaex >>> df = vaex.from_scalars(x=1, y=2) >>> df # x y r 0 1 2 2.23607 >>> df['r'] = (df.x**2 + df.y**2)**0.5 >>>...
[ "def", "state_set", "(", "self", ",", "state", ",", "use_active_range", "=", "False", ")", ":", "self", ".", "description", "=", "state", "[", "'description'", "]", "if", "use_active_range", ":", "self", ".", "_index_start", ",", "self", ".", "_index_end", ...
41.820896
17.507463
def drinkAdmins(self, objects=False): """ Returns a list of drink admins uids """ admins = self.group('drink', objects=objects) return admins
[ "def", "drinkAdmins", "(", "self", ",", "objects", "=", "False", ")", ":", "admins", "=", "self", ".", "group", "(", "'drink'", ",", "objects", "=", "objects", ")", "return", "admins" ]
33.8
7
def add_arguments(parser): """ adds arguments for the swap urls command """ parser.add_argument('-o', '--old-environment', help='Old environment name', required=True) parser.add_argument('-n', '--new-environment', help='New environment name', required=True)
[ "def", "add_arguments", "(", "parser", ")", ":", "parser", ".", "add_argument", "(", "'-o'", ",", "'--old-environment'", ",", "help", "=", "'Old environment name'", ",", "required", "=", "True", ")", "parser", ".", "add_argument", "(", "'-n'", ",", "'--new-env...
45.333333
21
def deploy(self): """ Open a ZIP archive, validate requirements then deploy the webfont into project static files """ self._info("* Opening archive: {}", self.archive_path) if not os.path.exists(self.archive_path): self._error("Given path does not exists: {}",...
[ "def", "deploy", "(", "self", ")", ":", "self", ".", "_info", "(", "\"* Opening archive: {}\"", ",", "self", ".", "archive_path", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "self", ".", "archive_path", ")", ":", "self", ".", "_error", "("...
47.432432
29.918919
def pairwise_compare(afa, leven, threads, print_list, ignore_gaps): """ make pairwise sequence comparisons between aligned sequences """ # load sequences into dictionary seqs = {seq[0]: seq for seq in nr_fasta([afa], append_index = True)} num_seqs = len(seqs) # define all pairs pairs = (...
[ "def", "pairwise_compare", "(", "afa", ",", "leven", ",", "threads", ",", "print_list", ",", "ignore_gaps", ")", ":", "# load sequences into dictionary", "seqs", "=", "{", "seq", "[", "0", "]", ":", "seq", "for", "seq", "in", "nr_fasta", "(", "[", "afa", ...
39.65
19.55