text
stringlengths
75
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
0.18
def _line(self, text, indent=0): """Write 'text' word-wrapped at self.width characters.""" leading_space = ' ' * indent while len(leading_space) + len(text) > self.width: # The text is too wide; wrap if possible. # Find the rightmost space that would obey our width cons...
[ "def", "_line", "(", "self", ",", "text", ",", "indent", "=", "0", ")", ":", "leading_space", "=", "' '", "*", "indent", "while", "len", "(", "leading_space", ")", "+", "len", "(", "text", ")", ">", "self", ".", "width", ":", "# The text is too wide; ...
40.057143
0.004178
def WriteFileHeader(self, arcname=None, st=None): """Writes file header.""" if st is None: raise ValueError("Stat object can't be None.") self.cur_file_size = 0 self.cur_info = self._tar_fd.tarinfo() self.cur_info.tarfile = self._tar_fd self.cur_info.type = tarfile.REGTYPE self.cur_...
[ "def", "WriteFileHeader", "(", "self", ",", "arcname", "=", "None", ",", "st", "=", "None", ")", ":", "if", "st", "is", "None", ":", "raise", "ValueError", "(", "\"Stat object can't be None.\"", ")", "self", ".", "cur_file_size", "=", "0", "self", ".", "...
28.473684
0.003578
def process_user_input(self): """ This overrides the method in ConsoleMenu to allow for comma-delimited and range inputs. Examples: All of the following inputs would have the same result: * 1,2,3,4 * 1-4 * 1-2,3-4 * 1 -...
[ "def", "process_user_input", "(", "self", ")", ":", "user_input", "=", "self", ".", "screen", ".", "input", "(", ")", "try", ":", "indexes", "=", "self", ".", "__parse_range_list", "(", "user_input", ")", "# Subtract 1 from each number for its actual index number", ...
33.68
0.004619
def ufunc_functional_factory(name, nargin, nargout, docstring): """Create a ufunc `Functional` from a given specification.""" assert 0 <= nargin <= 2 def __init__(self, field): """Initialize an instance. Parameters ---------- field : `Field` The domain of the f...
[ "def", "ufunc_functional_factory", "(", "name", ",", "nargin", ",", "nargout", ",", "docstring", ")", ":", "assert", "0", "<=", "nargin", "<=", "2", "def", "__init__", "(", "self", ",", "field", ")", ":", "\"\"\"Initialize an instance.\n\n Parameters\n ...
30.180328
0.000526
def _stream_data_chunked(self, environ, block_size): """Get the data from a chunked transfer.""" # Chunked Transfer Coding # http://www.servlets.com/rfcs/rfc2616-sec3.html#sec3.6.1 if "Darwin" in environ.get("HTTP_USER_AGENT", "") and environ.get( "HTTP_X_EXPECTED_ENTITY_LEN...
[ "def", "_stream_data_chunked", "(", "self", ",", "environ", ",", "block_size", ")", ":", "# Chunked Transfer Coding", "# http://www.servlets.com/rfcs/rfc2616-sec3.html#sec3.6.1", "if", "\"Darwin\"", "in", "environ", ".", "get", "(", "\"HTTP_USER_AGENT\"", ",", "\"\"", ")"...
39.071429
0.001189
def _macaroon_id_ops(ops): '''Return operations suitable for serializing as part of a MacaroonId. It assumes that ops has been canonicalized and that there's at least one operation. ''' id_ops = [] for entity, entity_ops in itertools.groupby(ops, lambda x: x.entity): actions = map(lambd...
[ "def", "_macaroon_id_ops", "(", "ops", ")", ":", "id_ops", "=", "[", "]", "for", "entity", ",", "entity_ops", "in", "itertools", ".", "groupby", "(", "ops", ",", "lambda", "x", ":", "x", ".", "entity", ")", ":", "actions", "=", "map", "(", "lambda", ...
38.090909
0.002331
def pipinstall(packagename, pips=None, trypips=[], scripts=None): """ Install packages from pip. The primary advantage of using this function is that homely can automatically remove the package for you when you no longer want it. package: The name of the pip package to install pips: ...
[ "def", "pipinstall", "(", "packagename", ",", "pips", "=", "None", ",", "trypips", "=", "[", "]", ",", "scripts", "=", "None", ")", ":", "# `scripts` is an alternate location for bin scripts. Useful for bad", "# platforms that put pip2/pip3 scripts in the same bin dir such th...
38.346939
0.000519
def content(self, output=None, str_output=None, **kwargs): """Searches for `output` regex within HTML page. kwargs are passed to BeautifulSoup's find function to filter for tags.""" if self.response.mimetype != "text/html": raise Failure(_("expected request to return HTML, but it returned {}...
[ "def", "content", "(", "self", ",", "output", "=", "None", ",", "str_output", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "self", ".", "response", ".", "mimetype", "!=", "\"text/html\"", ":", "raise", "Failure", "(", "_", "(", "\"expected req...
51.3125
0.005981
def _kill_word(text, pos): """ Kill from pos to the end of the current word, or if between words, to the end of the next word. Word boundaries are the same as those used by _forward_word. """ text, end_pos = _forward_word(text, pos) return text[:pos] + text[end_pos:], pos
[ "def", "_kill_word", "(", "text", ",", "pos", ")", ":", "text", ",", "end_pos", "=", "_forward_word", "(", "text", ",", "pos", ")", "return", "text", "[", ":", "pos", "]", "+", "text", "[", "end_pos", ":", "]", ",", "pos" ]
36.625
0.003333
def match_patterns(codedata) : """ Match patterns by shaman.PatternMatcher Get average ratio of pattern and language """ ret = {} for index1, pattern in enumerate(shaman.PatternMatcher.PATTERNS) : print('Matching pattern %d "%s"' % (index1+1, pattern)) matcher = shaman.PatternMatcher(pattern) tmp = {} ...
[ "def", "match_patterns", "(", "codedata", ")", ":", "ret", "=", "{", "}", "for", "index1", ",", "pattern", "in", "enumerate", "(", "shaman", ".", "PatternMatcher", ".", "PATTERNS", ")", ":", "print", "(", "'Matching pattern %d \"%s\"'", "%", "(", "index1", ...
24.485714
0.035915
def get_custom_color_config_from_egrc(config): """ Get the ColorConfig from the egrc config object. Any colors not defined will be None. """ pound = _get_color_from_config(config, CONFIG_NAMES.pound) heading = _get_color_from_config(config, CONFIG_NAMES.heading) code = _get_color_from_config...
[ "def", "get_custom_color_config_from_egrc", "(", "config", ")", ":", "pound", "=", "_get_color_from_config", "(", "config", ",", "CONFIG_NAMES", ".", "pound", ")", "heading", "=", "_get_color_from_config", "(", "config", ",", "CONFIG_NAMES", ".", "heading", ")", "...
34
0.000794
def update(self): """ Finds record and update it based in serializer values """ obj = self.__model__.objects.get_for_update(id=self.id) for name, value in self.__dict__.items(): if name in self._properties: setattr(obj, name, value) obj.update(...
[ "def", "update", "(", "self", ")", ":", "obj", "=", "self", ".", "__model__", ".", "objects", ".", "get_for_update", "(", "id", "=", "self", ".", "id", ")", "for", "name", ",", "value", "in", "self", ".", "__dict__", ".", "items", "(", ")", ":", ...
33.1
0.005882
def _process_json(data): """ return a list of GradCommittee objects. """ requests = [] for item in data: committee = GradCommittee() committee.status = item.get('status') committee.committee_type = item.get('committeeType') committee.dept = item.get('dept') co...
[ "def", "_process_json", "(", "data", ")", ":", "requests", "=", "[", "]", "for", "item", "in", "data", ":", "committee", "=", "GradCommittee", "(", ")", "committee", ".", "status", "=", "item", ".", "get", "(", "'status'", ")", "committee", ".", "commi...
39.131579
0.000656
def items(self): """ Returns dictionary items """ return {dep.task: value for dep, value in self._result.items()}.items()
[ "def", "items", "(", "self", ")", ":", "return", "{", "dep", ".", "task", ":", "value", "for", "dep", ",", "value", "in", "self", ".", "_result", ".", "items", "(", ")", "}", ".", "items", "(", ")" ]
45.666667
0.014388
def rmon_alarm_entry_alarm_sample(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") rmon = ET.SubElement(config, "rmon", xmlns="urn:brocade.com:mgmt:brocade-rmon") alarm_entry = ET.SubElement(rmon, "alarm-entry") alarm_index_key = ET.SubElement(ala...
[ "def", "rmon_alarm_entry_alarm_sample", "(", "self", ",", "*", "*", "kwargs", ")", ":", "config", "=", "ET", ".", "Element", "(", "\"config\"", ")", "rmon", "=", "ET", ".", "SubElement", "(", "config", ",", "\"rmon\"", ",", "xmlns", "=", "\"urn:brocade.com...
46.230769
0.004894
def write_to_fil(self, filename_out, *args, **kwargs): """ Write data to .fil file. It check the file size then decides how to write the file. Args: filename_out (str): Name of output file """ #For timing how long it takes to write a file. t0 = time.time...
[ "def", "write_to_fil", "(", "self", ",", "filename_out", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "#For timing how long it takes to write a file.", "t0", "=", "time", ".", "time", "(", ")", "#Update header", "self", ".", "__update_header", "(", ")"...
28.52381
0.008078
def check_names_unique(self, ds): ''' Checks the variable names for uniqueness regardless of case. CF §2.3 names should not be distinguished purely by case, i.e., if case is disregarded, no two names should be the same. :param netCDF4.Dataset ds: An open netCDF dataset ...
[ "def", "check_names_unique", "(", "self", ",", "ds", ")", ":", "fails", "=", "[", "]", "total", "=", "len", "(", "ds", ".", "variables", ")", "names", "=", "defaultdict", "(", "int", ")", "for", "k", "in", "ds", ".", "variables", ":", "names", "[",...
38.789474
0.005298
def _printable_id_code(self): """ Returns the code in a printable form, filling with zeros if needed. :return: the ID code in a printable form """ code = str(self.id_code) while len(code) < self._code_size: code = '0' + code return code
[ "def", "_printable_id_code", "(", "self", ")", ":", "code", "=", "str", "(", "self", ".", "id_code", ")", "while", "len", "(", "code", ")", "<", "self", ".", "_code_size", ":", "code", "=", "'0'", "+", "code", "return", "code" ]
26.909091
0.006536
def initializeConnections(self): """ Initialize connection matrix, including: _permanences : permanence of synaptic connections (sparse matrix) _potentialPools: potential pool of connections for each cell (sparse binary matrix) _connectedSynapses: connected synapses ...
[ "def", "initializeConnections", "(", "self", ")", ":", "numColumns", "=", "self", ".", "_numColumns", "numInputs", "=", "self", ".", "_numInputs", "# The SP should be setup so that stimulusThreshold is reasonably high,", "# similar to a TP's activation threshold. The pct of connect...
54.782609
0.001559
def create_bzip2 (archive, compression, cmd, verbosity, interactive, filenames): """Create a BZIP2 archive with the bz2 Python module.""" if len(filenames) > 1: raise util.PatoolError('multi-file compression not supported in Python bz2') try: with bz2.BZ2File(archive, 'wb') as bz2file: ...
[ "def", "create_bzip2", "(", "archive", ",", "compression", ",", "cmd", ",", "verbosity", ",", "interactive", ",", "filenames", ")", ":", "if", "len", "(", "filenames", ")", ">", "1", ":", "raise", "util", ".", "PatoolError", "(", "'multi-file compression not...
43.6875
0.005602
def cs_axis_mapping(cls, part_info, # type: Dict[str, Optional[Sequence]] axes_to_move # type: Sequence[str] ): # type: (...) -> Tuple[str, Dict[str, MotorInfo]] """Given the motor infos for the parts, filter those with scannable ...
[ "def", "cs_axis_mapping", "(", "cls", ",", "part_info", ",", "# type: Dict[str, Optional[Sequence]]", "axes_to_move", "# type: Sequence[str]", ")", ":", "# type: (...) -> Tuple[str, Dict[str, MotorInfo]]", "cs_ports", "=", "set", "(", ")", "# type: Set[str]", "axis_mapping", ...
54.833333
0.003584
def recover_chain_id(storage: SQLiteStorage) -> ChainID: """We can reasonably assume, that any database has only one value for `chain_id` at this point in time. """ action_init_chain = json.loads(storage.get_state_changes(limit=1, offset=0)[0]) assert action_init_chain['_type'] == 'raiden.transfer....
[ "def", "recover_chain_id", "(", "storage", ":", "SQLiteStorage", ")", "->", "ChainID", ":", "action_init_chain", "=", "json", ".", "loads", "(", "storage", ".", "get_state_changes", "(", "limit", "=", "1", ",", "offset", "=", "0", ")", "[", "0", "]", ")"...
47.875
0.010256
def csv(self, fh): """Writes the report data to `fh` in CSV format and returns it. :param fh: file to write data to :type fh: file object :rtype: file object """ self._stats.to_csv(fh, encoding='utf-8', index=False) return fh
[ "def", "csv", "(", "self", ",", "fh", ")", ":", "self", ".", "_stats", ".", "to_csv", "(", "fh", ",", "encoding", "=", "'utf-8'", ",", "index", "=", "False", ")", "return", "fh" ]
27.4
0.007067
def get_attached_devices(self): """ Return list of connected devices to the router. Returns None if error occurred. """ _LOGGER.info("Get attached devices") success, response = self._make_request(SERVICE_DEVICE_INFO, "GetAt...
[ "def", "get_attached_devices", "(", "self", ")", ":", "_LOGGER", ".", "info", "(", "\"Get attached devices\"", ")", "success", ",", "response", "=", "self", ".", "_make_request", "(", "SERVICE_DEVICE_INFO", ",", "\"GetAttachDevice\"", ")", "if", "not", "success", ...
30.5
0.000858
def p_pkg_summary_1(self, p): """pkg_summary : PKG_SUM TEXT""" try: if six.PY2: value = p[2].decode(encoding='utf-8') else: value = p[2] self.builder.set_pkg_summary(self.document, value) except OrderError: self.orde...
[ "def", "p_pkg_summary_1", "(", "self", ",", "p", ")", ":", "try", ":", "if", "six", ".", "PY2", ":", "value", "=", "p", "[", "2", "]", ".", "decode", "(", "encoding", "=", "'utf-8'", ")", "else", ":", "value", "=", "p", "[", "2", "]", "self", ...
38.916667
0.004184
def delete_image(self, image, force=False): '''**Description** Delete image from the scanner. **Arguments** - None ''' _, _, image_digest = self._discover_inputimage(image) if not image_digest: return [False, "cannot use input image string: no...
[ "def", "delete_image", "(", "self", ",", "image", ",", "force", "=", "False", ")", ":", "_", ",", "_", ",", "image_digest", "=", "self", ".", "_discover_inputimage", "(", "image", ")", "if", "not", "image_digest", ":", "return", "[", "False", ",", "\"c...
35.294118
0.00487
def enable_directory_service(self, check_peer=False): """Enable the directory service. :param check_peer: If True, enables server authenticity enforcement. If False, enables directory service integration. :type check_peer: bool, optional ...
[ "def", "enable_directory_service", "(", "self", ",", "check_peer", "=", "False", ")", ":", "if", "check_peer", ":", "return", "self", ".", "set_directory_service", "(", "check_peer", "=", "True", ")", "return", "self", ".", "set_directory_service", "(", "enabled...
37.733333
0.003448
def write_member(self, data): """Writes the given data as one gzip member. The data can be a string, an iterator that gives strings or a file-like object. """ if isinstance(data, basestring): self.write(data) else: for text in data: ...
[ "def", "write_member", "(", "self", ",", "data", ")", ":", "if", "isinstance", "(", "data", ",", "basestring", ")", ":", "self", ".", "write", "(", "data", ")", "else", ":", "for", "text", "in", "data", ":", "self", ".", "write", "(", "text", ")", ...
32.363636
0.010929
def _get_files(self, attrs=None): """ Get a list of all files in this download; each entry has the attributes C{path} (relative to root), C{size} (in bytes), C{mtime}, C{prio} (0=off, 1=normal, 2=high), C{created}, and C{opened}. This is UNCACHED, use C{fetch("fi...
[ "def", "_get_files", "(", "self", ",", "attrs", "=", "None", ")", ":", "try", ":", "# Get info for all files", "f_multicall", "=", "self", ".", "_engine", ".", "_rpc", ".", "f", ".", "multicall", "f_params", "=", "[", "self", ".", "_fields", "[", "\"hash...
39.775
0.003681
def calc_time(lower_bound, upper_bound, latitude, longitude, attribute, value, altitude=0, pressure=101325, temperature=12, horizon='+0:00', xtol=1.0e-12): """ Calculate the time between lower_bound and upper_bound where the attribute is equal to value. Uses PyEphem for solar...
[ "def", "calc_time", "(", "lower_bound", ",", "upper_bound", ",", "latitude", ",", "longitude", ",", "attribute", ",", "value", ",", "altitude", "=", "0", ",", "pressure", "=", "101325", ",", "temperature", "=", "12", ",", "horizon", "=", "'+0:00'", ",", ...
32.927536
0.000427
def replica_present(name, source, db_instance_class=None, availability_zone=None, port=None, auto_minor_version_upgrade=None, iops=None, option_group_name=None, publicly_accessible=None, tags=None, region=None, key=None, keyid=None, ...
[ "def", "replica_present", "(", "name", ",", "source", ",", "db_instance_class", "=", "None", ",", "availability_zone", "=", "None", ",", "port", "=", "None", ",", "auto_minor_version_upgrade", "=", "None", ",", "iops", "=", "None", ",", "option_group_name", "=...
48.246154
0.003125
def add_shared_configs(p, base_dir=''): """Add configargparser/argparse configs for shared argument. Arguments: p - configargparse.ArgParser object base_dir - base directory for file/path defaults. """ p.add('--host', default='localhost', help="Service host") p.add('--port...
[ "def", "add_shared_configs", "(", "p", ",", "base_dir", "=", "''", ")", ":", "p", ".", "add", "(", "'--host'", ",", "default", "=", "'localhost'", ",", "help", "=", "\"Service host\"", ")", "p", ".", "add", "(", "'--port'", ",", "'-p'", ",", "type", ...
50.463415
0.001422
def load_pricing_adjustments(self, columns, dts, assets): """ Returns ------- adjustments : list[dict[int -> Adjustment]] A list, where each element corresponds to the `columns`, of mappings from index to adjustment objects to apply at that index. """ ...
[ "def", "load_pricing_adjustments", "(", "self", ",", "columns", ",", "dts", ",", "assets", ")", ":", "out", "=", "[", "None", "]", "*", "len", "(", "columns", ")", "for", "i", ",", "column", "in", "enumerate", "(", "columns", ")", ":", "adjs", "=", ...
36.375
0.00335
def cp2png(checkplotin, extrarows=None): '''This is just a shortened form of the function above for convenience. This only handles pickle files as input. Parameters ---------- checkplotin : str File name of a checkplot pickle file to convert to a PNG. extrarows : list of tuples ...
[ "def", "cp2png", "(", "checkplotin", ",", "extrarows", "=", "None", ")", ":", "if", "checkplotin", ".", "endswith", "(", "'.gz'", ")", ":", "outfile", "=", "checkplotin", ".", "replace", "(", "'.pkl.gz'", ",", "'.png'", ")", "else", ":", "outfile", "=", ...
39.432836
0.002216
def build_command(command, parameter_map): """ Build command line(s) using the given parameter map. Even if the passed a single `command`, this function will return a list of shell commands. It is the caller's responsibility to concatenate them, likely using the semicolon or double ampersands. ...
[ "def", "build_command", "(", "command", ",", "parameter_map", ")", ":", "if", "isinstance", "(", "parameter_map", ",", "list", ")", ":", "# Partially emulate old (pre-0.7) API for this function.", "parameter_map", "=", "LegacyParameterMap", "(", "parameter_map", ")", "o...
40.95
0.002982
def raw_comment(self): """Returns the raw comment text associated with that Cursor""" r = conf.lib.clang_Cursor_getRawCommentText(self) if not r: return None return str(r)
[ "def", "raw_comment", "(", "self", ")", ":", "r", "=", "conf", ".", "lib", ".", "clang_Cursor_getRawCommentText", "(", "self", ")", "if", "not", "r", ":", "return", "None", "return", "str", "(", "r", ")" ]
35
0.009302
def tomof(self, maxline=MAX_MOF_LINE): """ Return a MOF string with the declaration of this CIM class. The returned MOF string conforms to the ``classDeclaration`` ABNF rule defined in :term:`DSP0004`. The order of properties, methods, parameters, and qualifiers is pres...
[ "def", "tomof", "(", "self", ",", "maxline", "=", "MAX_MOF_LINE", ")", ":", "mof", "=", "[", "]", "mof", ".", "append", "(", "_qualifiers_tomof", "(", "self", ".", "qualifiers", ",", "MOF_INDENT", ",", "maxline", ")", ")", "mof", ".", "append", "(", ...
27
0.001521
def weighted(weights, sample_size, with_replacement=False): """ Return a set of random integers 0 <= N <= len(weights) - 1, where the weights determine the probability of each possible integer in the set. """ assert sample_size <= len(weights), "The sample size must be smaller \ ...
[ "def", "weighted", "(", "weights", ",", "sample_size", ",", "with_replacement", "=", "False", ")", ":", "assert", "sample_size", "<=", "len", "(", "weights", ")", ",", "\"The sample size must be smaller \\\nthan or equal to the number of weights it's taken from.\"", "# Conv...
36.615385
0.002047
def set_instrument(self, channel, instr, bank=1): """Add a program change and bank select event to the track_data.""" self.track_data += self.select_bank(channel, bank) self.track_data += self.program_change_event(channel, instr)
[ "def", "set_instrument", "(", "self", ",", "channel", ",", "instr", ",", "bank", "=", "1", ")", ":", "self", ".", "track_data", "+=", "self", ".", "select_bank", "(", "channel", ",", "bank", ")", "self", ".", "track_data", "+=", "self", ".", "program_c...
62.5
0.007905
def additional(self, additional, use_parent=False): """ Allows temporarily pushing an additional context, yields the new context into the following block. """ self.push(additional, use_parent) yield self.current self.pop()
[ "def", "additional", "(", "self", ",", "additional", ",", "use_parent", "=", "False", ")", ":", "self", ".", "push", "(", "additional", ",", "use_parent", ")", "yield", "self", ".", "current", "self", ".", "pop", "(", ")" ]
33.875
0.010791
def aggregate(self, pipeline, **kwargs): """Perform an aggregation and make sure that result will be everytime CommandCursor. Will take care for pymongo version differencies :param pipeline: {list} of aggregation pipeline stages :return: {pymongo.command_cursor.CommandCursor} """...
[ "def", "aggregate", "(", "self", ",", "pipeline", ",", "*", "*", "kwargs", ")", ":", "result", "=", "self", ".", "collection", ".", "aggregate", "(", "pipeline", ",", "*", "*", "kwargs", ")", "if", "pymongo", ".", "version_tuple", "<", "(", "3", ",",...
43.636364
0.004082
def _parse_blkio_metrics(self, stats): """Parse the blkio metrics.""" metrics = { 'io_read': 0, 'io_write': 0, } for line in stats: if 'Read' in line: metrics['io_read'] += int(line.split()[2]) if 'Write' in line: ...
[ "def", "_parse_blkio_metrics", "(", "self", ",", "stats", ")", ":", "metrics", "=", "{", "'io_read'", ":", "0", ",", "'io_write'", ":", "0", ",", "}", "for", "line", "in", "stats", ":", "if", "'Read'", "in", "line", ":", "metrics", "[", "'io_read'", ...
31.75
0.005102
def create_widget(self): """ Create the underlying QDoubleSpinBox widget. """ widget = QDoubleSpinBox(self.parent_widget()) widget.setKeyboardTracking(False) self.widget = widget
[ "def", "create_widget", "(", "self", ")", ":", "widget", "=", "QDoubleSpinBox", "(", "self", ".", "parent_widget", "(", ")", ")", "widget", ".", "setKeyboardTracking", "(", "False", ")", "self", ".", "widget", "=", "widget" ]
30.428571
0.009132
def new_mapping(self, lineup, station, channel, channelMinor, validFrom, validTo, onAirFrom, onAirTo): """Callback run for each new mapping within a lineup""" raise NotImplementedError()
[ "def", "new_mapping", "(", "self", ",", "lineup", ",", "station", ",", "channel", ",", "channelMinor", ",", "validFrom", ",", "validTo", ",", "onAirFrom", ",", "onAirTo", ")", ":", "raise", "NotImplementedError", "(", ")" ]
43.6
0.013514
def process_tables(key, value, fmt, meta): """Processes the attributed tables.""" global has_unnumbered_tables # pylint: disable=global-statement # Process block-level Table elements if key == 'Table': # Inspect the table if len(value) == 5: # Unattributed, bail out has_...
[ "def", "process_tables", "(", "key", ",", "value", ",", "fmt", ",", "meta", ")", ":", "global", "has_unnumbered_tables", "# pylint: disable=global-statement", "# Process block-level Table elements", "if", "key", "==", "'Table'", ":", "# Inspect the table", "if", "len", ...
40.545455
0.002627
def when_equal(self, key: Hashable, value: Any, **when_kwargs) -> StateWatcher: """ Block until ``state[key] == value``, and then return a copy of the state. .. include:: /api/state/get_when_equality.rst """ def _(snapshot): try: return snapshot[key]...
[ "def", "when_equal", "(", "self", ",", "key", ":", "Hashable", ",", "value", ":", "Any", ",", "*", "*", "when_kwargs", ")", "->", "StateWatcher", ":", "def", "_", "(", "snapshot", ")", ":", "try", ":", "return", "snapshot", "[", "key", "]", "==", "...
29.857143
0.006961
def with_meter(name, tick_interval=meter.DEFAULT_TICK_INTERVAL): """ Call-counting decorator: each time the wrapped function is called the named meter is incremented by one. metric_args and metric_kwargs are passed to new_meter() """ try: mmetric = new_meter(name, tick_interval) exc...
[ "def", "with_meter", "(", "name", ",", "tick_interval", "=", "meter", ".", "DEFAULT_TICK_INTERVAL", ")", ":", "try", ":", "mmetric", "=", "new_meter", "(", "name", ",", "tick_interval", ")", "except", "DuplicateMetricError", "as", "e", ":", "mmetric", "=", "...
29.366667
0.003297
def assert_script_in_current_directory(): """Assert fail if current directory is different from location of the script""" script = sys.argv[0] assert os.path.abspath(os.path.dirname(script)) == os.path.abspath( '.'), f"Change into directory of script {script} and run again."
[ "def", "assert_script_in_current_directory", "(", ")", ":", "script", "=", "sys", ".", "argv", "[", "0", "]", "assert", "os", ".", "path", ".", "abspath", "(", "os", ".", "path", ".", "dirname", "(", "script", ")", ")", "==", "os", ".", "path", ".", ...
46.833333
0.017483
def window_open(dev, temp, duration): """ Gets and sets the window open settings. """ click.echo("Window open: %s" % dev.window_open) if temp and duration: click.echo("Setting window open conf, temp: %s duration: %s" % (temp, duration)) dev.window_open_config(temp, duration)
[ "def", "window_open", "(", "dev", ",", "temp", ",", "duration", ")", ":", "click", ".", "echo", "(", "\"Window open: %s\"", "%", "dev", ".", "window_open", ")", "if", "temp", "and", "duration", ":", "click", ".", "echo", "(", "\"Setting window open conf, tem...
49.666667
0.006601
def _warn_bogus_options(self, **opts): """ Shows a warning for unsupported options for the current implementation. Called form set_options with remainig unsupported options. """ if opts: import warnings for i in opts: warnings.warn(...
[ "def", "_warn_bogus_options", "(", "self", ",", "*", "*", "opts", ")", ":", "if", "opts", ":", "import", "warnings", "for", "i", "in", "opts", ":", "warnings", ".", "warn", "(", "\"Unsupported option %s for %s\"", "%", "(", "i", ",", "self", ")", ",", ...
41
0.007958
def _getPrefix(self, node, nsuri): ''' Keyword arguments: node -- DOM Element Node nsuri -- namespace of attribute value ''' try: if node and (node.nodeType == node.ELEMENT_NODE) and \ (nsuri == self._dom.findDefaultNS(node)): ...
[ "def", "_getPrefix", "(", "self", ",", "node", ",", "nsuri", ")", ":", "try", ":", "if", "node", "and", "(", "node", ".", "nodeType", "==", "node", ".", "ELEMENT_NODE", ")", "and", "(", "nsuri", "==", "self", ".", "_dom", ".", "findDefaultNS", "(", ...
37.652174
0.006757
def cursor(self, status): """Turn underline cursor visibility on/off""" self._display_control = ByteUtil.apply_flag(self._display_control, Command.CURSOR_ON, status) self.command(self._display_control)
[ "def", "cursor", "(", "self", ",", "status", ")", ":", "self", ".", "_display_control", "=", "ByteUtil", ".", "apply_flag", "(", "self", ".", "_display_control", ",", "Command", ".", "CURSOR_ON", ",", "status", ")", "self", ".", "command", "(", "self", "...
55.5
0.013333
def batch_process(de_novo_path, temp_dir, output_path): """ sets up a lsf job array """ temp_dir = tempfile.mkdtemp(dir=temp_dir) count = split_denovos(de_novo_path, temp_dir) # set up run parameters job_name = "denovonear" job_id = "{0}[1-{1}]%20".format(job_name, count) ...
[ "def", "batch_process", "(", "de_novo_path", ",", "temp_dir", ",", "output_path", ")", ":", "temp_dir", "=", "tempfile", ".", "mkdtemp", "(", "dir", "=", "temp_dir", ")", "count", "=", "split_denovos", "(", "de_novo_path", ",", "temp_dir", ")", "# set up run p...
41.645161
0.016654
def cross(self, rhs): """ Return the cross product of this vector and *rhs*. """ return Vector( self.y * rhs.z - self.z * rhs.y, self.z * rhs.x - self.x * rhs.z, self.x * rhs.y - self.y * rhs.x)
[ "def", "cross", "(", "self", ",", "rhs", ")", ":", "return", "Vector", "(", "self", ".", "y", "*", "rhs", ".", "z", "-", "self", ".", "z", "*", "rhs", ".", "y", ",", "self", ".", "z", "*", "rhs", ".", "x", "-", "self", ".", "x", "*", "rhs...
24.555556
0.004367
def _advapi32_load_key(key_object, key_info, container): """ Loads a certificate, public key or private key into a Certificate, PublicKey or PrivateKey object via CryptoAPI :param key_object: An asn1crypto.x509.Certificate, asn1crypto.keys.PublicKeyInfo or asn1crypto.keys.PrivateKeyInfo...
[ "def", "_advapi32_load_key", "(", "key_object", ",", "key_info", ",", "container", ")", ":", "key_type", "=", "'public'", "if", "isinstance", "(", "key_info", ",", "keys", ".", "PublicKeyInfo", ")", "else", "'private'", "algo", "=", "key_info", ".", "algorithm...
30.650602
0.001904
def sinatra_path_to_regex(cls, path): """ Converts a sinatra-style path to a regex with named parameters. """ # Return the path if already a (compiled) regex if type(path) is cls.regex_type: return path # Build a regular expression string which is spl...
[ "def", "sinatra_path_to_regex", "(", "cls", ",", "path", ")", ":", "# Return the path if already a (compiled) regex", "if", "type", "(", "path", ")", "is", "cls", ".", "regex_type", ":", "return", "path", "# Build a regular expression string which is split on the '/' charac...
33.294118
0.005155
def _create_public_ip(self, public_ip_name, resource_group_name, region): """ Create dynamic public IP address in the resource group. """ public_ip_config = { 'location': region, 'public_ip_allocation_method': 'Dynamic' } try: public_i...
[ "def", "_create_public_ip", "(", "self", ",", "public_ip_name", ",", "resource_group_name", ",", "region", ")", ":", "public_ip_config", "=", "{", "'location'", ":", "region", ",", "'public_ip_allocation_method'", ":", "'Dynamic'", "}", "try", ":", "public_ip_setup"...
33.25
0.002924
def log_p(self,z): """ The unnormalized log posterior components (the quantity we want to approximate) RAO-BLACKWELLIZED! """ return np.array([self.log_p_blanket(i) for i in z])
[ "def", "log_p", "(", "self", ",", "z", ")", ":", "return", "np", ".", "array", "(", "[", "self", ".", "log_p_blanket", "(", "i", ")", "for", "i", "in", "z", "]", ")" ]
36.333333
0.022422
def migrate_process_schema(self, process, schema, from_state): """Migrate process schema. :param process: Process instance :param schema: Process schema to migrate :param from_state: Database model state :return: True if the process was migrated, False otherwise """ ...
[ "def", "migrate_process_schema", "(", "self", ",", "process", ",", "schema", ",", "from_state", ")", ":", "container", "=", "dict_dot", "(", "schema", ",", "'.'", ".", "join", "(", "self", ".", "field", "[", ":", "-", "1", "]", ")", ",", "default", "...
39.321429
0.00266
def add_route(self, view: View, path: str, exact: bool = True) -> None: """Add a view to the app. Parameters ---------- view : View path : str exact : bool, optional """ if path[0] != '/': path = '/' + path for route in self._routes: ...
[ "def", "add_route", "(", "self", ",", "view", ":", "View", ",", "path", ":", "str", ",", "exact", ":", "bool", "=", "True", ")", "->", "None", ":", "if", "path", "[", "0", "]", "!=", "'/'", ":", "path", "=", "'/'", "+", "path", "for", "route", ...
30
0.005102
def normal_surface_single_list(obj, param_list, normalize): """ Evaluates the surface normal vectors at the given list of parameter values. :param obj: input surface :type obj: abstract.Surface :param param_list: parameter list :type param_list: list or tuple :param normalize: if True, the retu...
[ "def", "normal_surface_single_list", "(", "obj", ",", "param_list", ",", "normalize", ")", ":", "ret_vector", "=", "[", "]", "for", "param", "in", "param_list", ":", "temp", "=", "normal_surface_single", "(", "obj", ",", "param", ",", "normalize", ")", "ret_...
36.764706
0.00468
def scale_to(self, scale_x, scale_y, no_reset=False): """Scale the image in a channel. This only changes the viewer settings; the image is not modified in any way. Also see :meth:`zoom_to`. Parameters ---------- scale_x, scale_y : float Scaling factors for t...
[ "def", "scale_to", "(", "self", ",", "scale_x", ",", "scale_y", ",", "no_reset", "=", "False", ")", ":", "try", ":", "self", ".", "_sanity_check_scale", "(", "scale_x", ",", "scale_y", ")", "except", "Exception", "as", "e", ":", "self", ".", "logger", ...
31.1875
0.001944
def run(handlers, command, parser, command_args, unknown_args): ''' Run the command :param command: :param parser: :param command_args: :param unknown_args: :return: ''' if command in handlers: return handlers[command].run(command, parser, command_args, unknown_args) else: err_context = 'Un...
[ "def", "run", "(", "handlers", ",", "command", ",", "parser", ",", "command_args", ",", "unknown_args", ")", ":", "if", "command", "in", "handlers", ":", "return", "handlers", "[", "command", "]", ".", "run", "(", "command", ",", "parser", ",", "command_...
27.466667
0.00939
def section_path_lengths(neurites, neurite_type=NeuriteType.all): '''Path lengths of a collection of neurites ''' # Calculates and stores the section lengths in one pass, # then queries the lengths in the path length iterations. # This avoids repeatedly calculating the lengths of the # same sections...
[ "def", "section_path_lengths", "(", "neurites", ",", "neurite_type", "=", "NeuriteType", ".", "all", ")", ":", "# Calculates and stores the section lengths in one pass,", "# then queries the lengths in the path length iterations.", "# This avoids repeatedly calculating the lengths of the...
39.352941
0.00146
def log_likelihood_bits(eval_data, predictions, scores, learner='ignored'): ''' Return the log likelihood of each correct output in base 2 (bits), computed from the scores in `scores` (which should be in base e, nats). >>> bits = log_likelihood_bits(None, None, [np.log(0.5), np.log(0.125), np.log(0.25)...
[ "def", "log_likelihood_bits", "(", "eval_data", ",", "predictions", ",", "scores", ",", "learner", "=", "'ignored'", ")", ":", "return", "(", "np", ".", "array", "(", "scores", ")", "/", "np", ".", "log", "(", "2.0", ")", ")", ".", "tolist", "(", ")"...
43
0.004556
def sdiv(computation: BaseComputation) -> None: """ Signed Division """ numerator, denominator = map( unsigned_to_signed, computation.stack_pop(num_items=2, type_hint=constants.UINT256), ) pos_or_neg = -1 if numerator * denominator < 0 else 1 if denominator == 0: re...
[ "def", "sdiv", "(", "computation", ":", "BaseComputation", ")", "->", "None", ":", "numerator", ",", "denominator", "=", "map", "(", "unsigned_to_signed", ",", "computation", ".", "stack_pop", "(", "num_items", "=", "2", ",", "type_hint", "=", "constants", "...
26.294118
0.00216
def createStyle(self, body, verbose=None): """ Creates a new Visual Style using the message body. Returns the title of the new Visual Style. If the title of the Visual Style already existed in the session, a new one will be automatically generated and returned. :param body: The...
[ "def", "createStyle", "(", "self", ",", "body", ",", "verbose", "=", "None", ")", ":", "PARAMS", "=", "set_param", "(", "[", "'body'", "]", ",", "[", "body", "]", ")", "response", "=", "api", "(", "url", "=", "self", ".", "___url", "+", "'styles'",...
40.4
0.012903
def writelines(self, lines, sep=b'\n', echo=None): """ Write a list of byte sequences to the channel and terminate them with a separator (line feed). Args: lines(list of bytes): The lines to send. sep(bytes): The separator to use after each line. echo...
[ "def", "writelines", "(", "self", ",", "lines", ",", "sep", "=", "b'\\n'", ",", "echo", "=", "None", ")", ":", "self", ".", "write", "(", "sep", ".", "join", "(", "lines", "+", "[", "b''", "]", ")", ",", "echo", ")" ]
34.066667
0.00381
def parse_value(parser, event, node): # pylint: disable=unused-argument """ Parse CIM/XML VALUE element and return the value""" value = '' (next_event, next_node) = six.next(parser) if next_event == pulldom.CHARACTERS: value = next_node.nodeValue (next_event, next_node) = six.next(pa...
[ "def", "parse_value", "(", "parser", ",", "event", ",", "node", ")", ":", "# pylint: disable=unused-argument", "value", "=", "''", "(", "next_event", ",", "next_node", ")", "=", "six", ".", "next", "(", "parser", ")", "if", "next_event", "==", "pulldom", "...
26.8125
0.004505
def tokenize(text, lowercase=False, deacc=False): """ Iteratively yield tokens as unicode strings, optionally also lowercasing them and removing accent marks. """ if lowercase: text = text.lower() if deacc: text = deaccent(text) for match in PAT_ALPHABETIC.finditer(text): ...
[ "def", "tokenize", "(", "text", ",", "lowercase", "=", "False", ",", "deacc", "=", "False", ")", ":", "if", "lowercase", ":", "text", "=", "text", ".", "lower", "(", ")", "if", "deacc", ":", "text", "=", "deaccent", "(", "text", ")", "for", "match"...
30.363636
0.005814
def download( self, resource_group_name, virtual_wan_name, vpn_sites=None, output_blob_sas_url=None, custom_headers=None, raw=False, polling=True, **operation_config): """Gives the sas-url to download the configurations for vpn-sites in a resource group. :param resource_group_name: ...
[ "def", "download", "(", "self", ",", "resource_group_name", ",", "virtual_wan_name", ",", "vpn_sites", "=", "None", ",", "output_blob_sas_url", "=", "None", ",", "custom_headers", "=", "None", ",", "raw", "=", "False", ",", "polling", "=", "True", ",", "*", ...
49.333333
0.003118
def createCircle(self, cx, cy, r, strokewidth=1, stroke='black', fill='none'): """ Creates a circle @type cx: string or int @param cx: starting x-coordinate @type cy: string or int @param cy: starting y-coordinate @type r: string or int @param r: ...
[ "def", "createCircle", "(", "self", ",", "cx", ",", "cy", ",", "r", ",", "strokewidth", "=", "1", ",", "stroke", "=", "'black'", ",", "fill", "=", "'none'", ")", ":", "style_dict", "=", "{", "'fill'", ":", "fill", ",", "'stroke-width'", ":", "strokew...
45.909091
0.010669
def get_customer(self, customer_id): """ Queries the information related to the customer. Args: customer_id: Identifier of the client from which you want to find the associated information. Returns: """ return self.client._get(self.url + 'customers/{}'.form...
[ "def", "get_customer", "(", "self", ",", "customer_id", ")", ":", "return", "self", ".", "client", ".", "_get", "(", "self", ".", "url", "+", "'customers/{}'", ".", "format", "(", "customer_id", ")", ",", "headers", "=", "self", ".", "get_headers", "(", ...
32.181818
0.010989
def get_projects_list(self): """ Get projects list """ try: result = self._request('/getprojectslist/') return [TildaProject(**p) for p in result] except NetworkError: return []
[ "def", "get_projects_list", "(", "self", ")", ":", "try", ":", "result", "=", "self", ".", "_request", "(", "'/getprojectslist/'", ")", "return", "[", "TildaProject", "(", "*", "*", "p", ")", "for", "p", "in", "result", "]", "except", "NetworkError", ":"...
33
0.008439
def member_add(self, repl_id, params): """create instance and add it to existing replcia Args: repl_id - replica set identity params - member params return True if operation success otherwise False """ repl = self[repl_id] member_id = repl.repl_me...
[ "def", "member_add", "(", "self", ",", "repl_id", ",", "params", ")", ":", "repl", "=", "self", "[", "repl_id", "]", "member_id", "=", "repl", ".", "repl_member_add", "(", "params", ")", "self", "[", "repl_id", "]", "=", "repl", "return", "member_id" ]
31.583333
0.005128
def create_entity(self, entity_type, term_ids, id=None): """ Create a new (named) entity and add it to the entities layer @type entity_type: string @param entity_type: The type of the entity @type term_ids: list @param term_ids: list of term ids @type id: string ...
[ "def", "create_entity", "(", "self", ",", "entity_type", ",", "term_ids", ",", "id", "=", "None", ")", ":", "new_entity", "=", "Centity", "(", "type", "=", "self", ".", "type", ")", "if", "id", "is", "None", ":", "n", "=", "1", "if", "self", ".", ...
38.952381
0.00358
def xy2rd(self,pos): """ This method would apply the WCS keywords to a position to generate a new sky position. The algorithm comes directly from 'imgtools.xy2rd' translate (x,y) to (ra, dec) """ if self.ctype1.find('TAN') < 0 or self.ctype2.find('TAN') < 0: ...
[ "def", "xy2rd", "(", "self", ",", "pos", ")", ":", "if", "self", ".", "ctype1", ".", "find", "(", "'TAN'", ")", "<", "0", "or", "self", ".", "ctype2", ".", "find", "(", "'TAN'", ")", "<", "0", ":", "print", "(", "'XY2RD only supported for TAN project...
32.682927
0.008696
def _spectrogram(y=None, S=None, n_fft=2048, hop_length=512, power=1, win_length=None, window='hann', center=True, pad_mode='reflect'): '''Helper function to retrieve a magnitude spectrogram. This is primarily used in feature extraction functions that can operate on either audio time-serie...
[ "def", "_spectrogram", "(", "y", "=", "None", ",", "S", "=", "None", ",", "n_fft", "=", "2048", ",", "hop_length", "=", "512", ",", "power", "=", "1", ",", "win_length", "=", "None", ",", "window", "=", "'hann'", ",", "center", "=", "True", ",", ...
31.777778
0.000848
def create_snapshot(kwargs=None, call=None, wait_to_finish=False): ''' Create a snapshot. volume_id The ID of the Volume from which to create a snapshot. description The optional description of the snapshot. CLI Exampe: .. code-block:: bash salt-cloud -f create_snaps...
[ "def", "create_snapshot", "(", "kwargs", "=", "None", ",", "call", "=", "None", ",", "wait_to_finish", "=", "False", ")", ":", "if", "call", "!=", "'function'", ":", "raise", "SaltCloudSystemExit", "(", "'The create_snapshot function must be called with -f '", "'or ...
29.757576
0.001971
def blocks(aln, threshold=0.5, weights=None): """Remove gappy columns from an alignment.""" assert len(aln) if weights == False: def pct_nongaps(col): return 1 - (float(col.count('-')) / len(col)) else: if weights in (None, True): weights = sequence_weights(aln, '...
[ "def", "blocks", "(", "aln", ",", "threshold", "=", "0.5", ",", "weights", "=", "None", ")", ":", "assert", "len", "(", "aln", ")", "if", "weights", "==", "False", ":", "def", "pct_nongaps", "(", "col", ")", ":", "return", "1", "-", "(", "float", ...
37
0.002927
def op_canonicalize(op_name, parsed_op): """ Get the canonical representation of a parsed operation's data. Meant for backwards-compatibility """ global CANONICALIZE_METHODS if op_name not in CANONICALIZE_METHODS: # no canonicalization needed return parsed_op else: r...
[ "def", "op_canonicalize", "(", "op_name", ",", "parsed_op", ")", ":", "global", "CANONICALIZE_METHODS", "if", "op_name", "not", "in", "CANONICALIZE_METHODS", ":", "# no canonicalization needed", "return", "parsed_op", "else", ":", "return", "CANONICALIZE_METHODS", "[", ...
29.583333
0.002732
def __remove_null_logging_handler(): ''' This function will run once the temporary logging has been configured. It just removes the NullHandler from the logging handlers. ''' global LOGGING_NULL_HANDLER if LOGGING_NULL_HANDLER is None: # Already removed return root_logger = ...
[ "def", "__remove_null_logging_handler", "(", ")", ":", "global", "LOGGING_NULL_HANDLER", "if", "LOGGING_NULL_HANDLER", "is", "None", ":", "# Already removed", "return", "root_logger", "=", "logging", ".", "getLogger", "(", ")", "for", "handler", "in", "root_logger", ...
33.611111
0.001608
def regularization_term(self): """ Compute the regularization term of an inversion. This term represents the sum of the difference in flux \ between every pair of neighboring pixels. This is computed as: s_T * H * s = solution_vector.T * regularization_matrix * solution_vector The term...
[ "def", "regularization_term", "(", "self", ")", ":", "return", "np", ".", "matmul", "(", "self", ".", "solution_vector", ".", "T", ",", "np", ".", "matmul", "(", "self", ".", "regularization_matrix", ",", "self", ".", "solution_vector", ")", ")" ]
60.916667
0.010782
def set_attributes(self, doc, data_type): """ :param Optional[str] doc: Documentation string of alias. :param data_type: The source data type referenced by the alias. """ self.raw_doc = doc self.doc = doc_unwrap(doc) self.data_type = data_type # Make sure...
[ "def", "set_attributes", "(", "self", ",", "doc", ",", "data_type", ")", ":", "self", ".", "raw_doc", "=", "doc", "self", ".", "doc", "=", "doc_unwrap", "(", "doc", ")", "self", ".", "data_type", "=", "data_type", "# Make sure we don't have a cyclic reference....
43.47619
0.002144
def use_valgrind(self, tool, xml, console, track_origins, valgrind_extra_params): """ Use Valgrind. :param tool: Tool name, must be memcheck, callgrind or massif :param xml: Boolean output xml :param console: Dump output to console, Boolean :param track_origins: Boolean,...
[ "def", "use_valgrind", "(", "self", ",", "tool", ",", "xml", ",", "console", ",", "track_origins", ",", "valgrind_extra_params", ")", ":", "self", ".", "valgrind", "=", "tool", "self", ".", "valgrind_xml", "=", "xml", "self", ".", "valgrind_console", "=", ...
42.789474
0.004813
def ip_rtm_config_route_static_route_nh_route_attributes_metric(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") ip = ET.SubElement(config, "ip", xmlns="urn:brocade.com:mgmt:brocade-common-def") rtm_config = ET.SubElement(ip, "rtm-config", xmlns="urn:broc...
[ "def", "ip_rtm_config_route_static_route_nh_route_attributes_metric", "(", "self", ",", "*", "*", "kwargs", ")", ":", "config", "=", "ET", ".", "Element", "(", "\"config\"", ")", "ip", "=", "ET", ".", "SubElement", "(", "config", ",", "\"ip\"", ",", "xmlns", ...
57.722222
0.006629
def download_url(url): '''download a URL and return the content''' if sys.version_info.major < 3: from urllib2 import urlopen as url_open from urllib2 import URLError as url_error else: from urllib.request import urlopen as url_open from urllib.error import URLError as url_er...
[ "def", "download_url", "(", "url", ")", ":", "if", "sys", ".", "version_info", ".", "major", "<", "3", ":", "from", "urllib2", "import", "urlopen", "as", "url_open", "from", "urllib2", "import", "URLError", "as", "url_error", "else", ":", "from", "urllib",...
32.733333
0.00198
def pdf_copy(input: str, output: str, pages: [int], yes_to_all=False): """ Copy pages from the input file in a new output file. :param input: name of the input pdf file :param output: name of the output pdf file :param pages: list containing the page numbers to copy in the new file """ if n...
[ "def", "pdf_copy", "(", "input", ":", "str", ",", "output", ":", "str", ",", "pages", ":", "[", "int", "]", ",", "yes_to_all", "=", "False", ")", ":", "if", "not", "os", ".", "path", ".", "isfile", "(", "input", ")", ":", "print", "(", "\"Error. ...
34.642857
0.001003
def _moments_central(data, center=None, order=1): """ Calculate the central image moments up to the specified order. Parameters ---------- data : 2D array-like The input 2D array. center : tuple of two floats or `None`, optional The ``(x, y)`` center position. If `None` it wil...
[ "def", "_moments_central", "(", "data", ",", "center", "=", "None", ",", "order", "=", "1", ")", ":", "data", "=", "np", ".", "asarray", "(", "data", ")", ".", "astype", "(", "float", ")", "if", "data", ".", "ndim", "!=", "2", ":", "raise", "Valu...
28.416667
0.000945
def _raise_error_if_not_drawing_classifier_input_sframe( dataset, feature, target): """ Performs some sanity checks on the SFrame provided as input to `turicreate.drawing_classifier.create` and raises a ToolkitError if something in the dataset is missing or wrong. """ from turicreate.toolki...
[ "def", "_raise_error_if_not_drawing_classifier_input_sframe", "(", "dataset", ",", "feature", ",", "target", ")", ":", "from", "turicreate", ".", "toolkits", ".", "_internal_utils", "import", "_raise_error_if_not_sframe", "_raise_error_if_not_sframe", "(", "dataset", ")", ...
54.458333
0.010526
def GenerateDSW(dswfile, source, env): """Generates a Solution/Workspace file based on the version of MSVS that is being used""" version_num = 6.0 if 'MSVS_VERSION' in env: version_num, suite = msvs_parse_version(env['MSVS_VERSION']) if version_num >= 7.0: g = _GenerateV7DSW(dswfile, so...
[ "def", "GenerateDSW", "(", "dswfile", ",", "source", ",", "env", ")", ":", "version_num", "=", "6.0", "if", "'MSVS_VERSION'", "in", "env", ":", "version_num", ",", "suite", "=", "msvs_parse_version", "(", "env", "[", "'MSVS_VERSION'", "]", ")", "if", "vers...
34.5
0.004706
def stochastic_event_set(sources, source_site_filter=nofilter): """ Generates a 'Stochastic Event Set' (that is a collection of earthquake ruptures) representing a possible *realization* of the seismicity as described by a source model. The calculator loops over sources. For each source, it loops o...
[ "def", "stochastic_event_set", "(", "sources", ",", "source_site_filter", "=", "nofilter", ")", ":", "for", "source", ",", "s_sites", "in", "source_site_filter", "(", "sources", ")", ":", "try", ":", "for", "rupture", "in", "source", ".", "iter_ruptures", "(",...
46.108108
0.000574
def add_command_formatting(self, command): """A utility function to format commands and groups. Parameters ------------ command: :class:`Command` The command to format. """ if command.description: self.paginator.add_line(command.description, empt...
[ "def", "add_command_formatting", "(", "self", ",", "command", ")", ":", "if", "command", ".", "description", ":", "self", ".", "paginator", ".", "add_line", "(", "command", ".", "description", ",", "empty", "=", "True", ")", "signature", "=", "self", ".", ...
32.807692
0.002278
def __load(file_name): """ Load pickled cache from file and return the object. """ if os.path.exists(file_name) and not os.path.isfile(file_name): raise RuntimeError( 'Cache should be initialized with valid full file name') if not os.path.exists(file_name): ...
[ "def", "__load", "(", "file_name", ")", ":", "if", "os", ".", "path", ".", "exists", "(", "file_name", ")", "and", "not", "os", ".", "path", ".", "isfile", "(", "file_name", ")", ":", "raise", "RuntimeError", "(", "'Cache should be initialized with valid ful...
43.470588
0.001324
def get_image_dimension(self, url): """ Return a tuple that contains (width, height) Pass in a url to an image and find out its size without loading the whole file If the image wxh could not be found, the tuple will contain `None` values """ w_h = (None, None) try...
[ "def", "get_image_dimension", "(", "self", ",", "url", ")", ":", "w_h", "=", "(", "None", ",", "None", ")", "try", ":", "if", "url", ".", "startswith", "(", "'//'", ")", ":", "url", "=", "'http:'", "+", "url", "data", "=", "requests", ".", "get", ...
34.611111
0.007813
def add_child(self, child, rangecheck=False): """Add a child feature to this feature.""" assert self.seqid == child.seqid, \ ( 'seqid mismatch for feature {} ({} vs {})'.format( self.fid, self.seqid, child.seqid ) ) if r...
[ "def", "add_child", "(", "self", ",", "child", ",", "rangecheck", "=", "False", ")", ":", "assert", "self", ".", "seqid", "==", "child", ".", "seqid", ",", "(", "'seqid mismatch for feature {} ({} vs {})'", ".", "format", "(", "self", ".", "fid", ",", "sel...
41.25
0.00237
def iter_entries(cls, stream): """ :return: Iterator yielding RefLogEntry instances, one for each line read sfrom the given stream. :param stream: file-like object containing the revlog in its native format or basestring instance pointing to a file to read""" new_...
[ "def", "iter_entries", "(", "cls", ",", "stream", ")", ":", "new_entry", "=", "RefLogEntry", ".", "from_line", "if", "isinstance", "(", "stream", ",", "string_types", ")", ":", "stream", "=", "file_contents_ro_filepath", "(", "stream", ")", "# END handle stream ...
39
0.005891
def create_invoice_from_albaran(pk, list_lines): """ la pk y list_lines son de albaranes, necesitamos la info de las lineas de pedidos """ context = {} if list_lines: new_list_lines = [x[0] for x in SalesLineAlbaran.objects.values_list('line_order__pk').filter( ...
[ "def", "create_invoice_from_albaran", "(", "pk", ",", "list_lines", ")", ":", "context", "=", "{", "}", "if", "list_lines", ":", "new_list_lines", "=", "[", "x", "[", "0", "]", "for", "x", "in", "SalesLineAlbaran", ".", "objects", ".", "values_list", "(", ...
46.814815
0.004651
def to_json(obj): """ Convert obj to json. Used mostly to convert the classes in json_span.py until we switch to nested dicts (or something better) :param obj: the object to serialize to json :return: json string """ try: return json.dumps(obj, default=lambda obj: {k.lower(): v fo...
[ "def", "to_json", "(", "obj", ")", ":", "try", ":", "return", "json", ".", "dumps", "(", "obj", ",", "default", "=", "lambda", "obj", ":", "{", "k", ".", "lower", "(", ")", ":", "v", "for", "k", ",", "v", "in", "obj", ".", "__dict__", ".", "i...
37.153846
0.006061
def is_closest_date_parameter(task, param_name): """ Return the parameter class of param_name on task. """ for name, obj in task.get_params(): if name == param_name: return hasattr(obj, 'use_closest_date') return False
[ "def", "is_closest_date_parameter", "(", "task", ",", "param_name", ")", ":", "for", "name", ",", "obj", "in", "task", ".", "get_params", "(", ")", ":", "if", "name", "==", "param_name", ":", "return", "hasattr", "(", "obj", ",", "'use_closest_date'", ")",...
40.833333
0.004