text
stringlengths
75
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
0.18
def is_iterable_of_float(l): r""" Checks if l is iterable and contains only floating point types """ if not is_iterable(l): return False return all(is_float(value) for value in l)
[ "def", "is_iterable_of_float", "(", "l", ")", ":", "if", "not", "is_iterable", "(", "l", ")", ":", "return", "False", "return", "all", "(", "is_float", "(", "value", ")", "for", "value", "in", "l", ")" ]
32.5
0.01
def create(context, name, content=None, file_path=None, mime='text/plain', jobstate_id=None, md5=None, job_id=None, test_id=None): """Method to create a file on the Control-Server This method allows one to upload a file to the Control-Server. The file to be uploaded can be specified in two diffe...
[ "def", "create", "(", "context", ",", "name", ",", "content", "=", "None", ",", "file_path", "=", "None", ",", "mime", "=", "'text/plain'", ",", "jobstate_id", "=", "None", ",", "md5", "=", "None", ",", "job_id", "=", "None", ",", "test_id", "=", "No...
37.975
0.000642
def _place_ticks_vertical(self): """Display the ticks for a vertical slider.""" for tick, label in zip(self.ticks, self.ticklabels): y = self.convert_to_pixels(tick) label.place_configure(y=y)
[ "def", "_place_ticks_vertical", "(", "self", ")", ":", "for", "tick", ",", "label", "in", "zip", "(", "self", ".", "ticks", ",", "self", ".", "ticklabels", ")", ":", "y", "=", "self", ".", "convert_to_pixels", "(", "tick", ")", "label", ".", "place_con...
45.6
0.008621
def printWelcomeMessage(msg, place=10): ''' Print any welcome message ''' logging.debug('*' * 30) welcome = ' ' * place welcome+= msg logging.debug(welcome) logging.debug('*' * 30 + '\n')
[ "def", "printWelcomeMessage", "(", "msg", ",", "place", "=", "10", ")", ":", "logging", ".", "debug", "(", "'*'", "*", "30", ")", "welcome", "=", "' '", "*", "place", "welcome", "+=", "msg", "logging", ".", "debug", "(", "welcome", ")", "logging", "....
25.625
0.009434
def create_option( self, name, value, label, selected, index, subindex=None, attrs=None): """Patch to use nicer ids.""" index = str(index) if subindex is None else "%s%s%s" % ( index, self.id_separator, subindex) if attrs is None: attrs = {} ...
[ "def", "create_option", "(", "self", ",", "name", ",", "value", ",", "label", ",", "selected", ",", "index", ",", "subindex", "=", "None", ",", "attrs", "=", "None", ")", ":", "index", "=", "str", "(", "index", ")", "if", "subindex", "is", "None", ...
35.909091
0.001643
def walk_comic_archive(filename_full, image_format, optimize_after): """ Optimize a comic archive. This is done mostly inline to use the master processes process pool for workers. And to avoid calling back up into walk from a dedicated module or format processor. It does mean that we block on uncom...
[ "def", "walk_comic_archive", "(", "filename_full", ",", "image_format", ",", "optimize_after", ")", ":", "# uncompress archive", "tmp_dir", ",", "report_stats", "=", "comic", ".", "comic_archive_uncompress", "(", "filename_full", ",", "image_format", ")", "if", "tmp_d...
42.8
0.000762
def get_event_consumer(config, success_channel, error_channel, metrics, **kwargs): """Get a GPSEventConsumer client. A factory function that validates configuration, creates schema validator and parser clients, creates an auth and a pubsub client, and returns an event consumer (:...
[ "def", "get_event_consumer", "(", "config", ",", "success_channel", ",", "error_channel", ",", "metrics", ",", "*", "*", "kwargs", ")", ":", "builder", "=", "event_consumer", ".", "GPSEventConsumerBuilder", "(", "config", ",", "success_channel", ",", "error_channe...
44.222222
0.00082
def _my_eps_formatter(logodata, format, ordered_alphabets) : """ Generate a logo in Encapsulated Postscript (EPS) Modified from weblogo version 3.4 source code. *ordered_alphabets* is a dictionary keyed by zero-indexed consecutive sites, with values giving order of characters from bottom to t...
[ "def", "_my_eps_formatter", "(", "logodata", ",", "format", ",", "ordered_alphabets", ")", ":", "substitutions", "=", "{", "}", "from_format", "=", "[", "\"creation_date\"", ",", "\"logo_width\"", ",", "\"logo_height\"", ",", "\"lines_per_logo\"", ",", "\"line_width...
38.510345
0.01257
def parse_characters(self, character_page): """Parses the DOM and returns media character attributes in the sidebar. :type character_page: :class:`bs4.BeautifulSoup` :param character_page: MAL character page's DOM :rtype: dict :return: character attributes. """ media_info = self.parse_sid...
[ "def", "parse_characters", "(", "self", ",", "character_page", ")", ":", "media_info", "=", "self", ".", "parse_sidebar", "(", "character_page", ")", "try", ":", "character_title", "=", "filter", "(", "lambda", "x", ":", "u'Characters'", "in", "x", ".", "tex...
39.114286
0.013542
def get_design_matrix(self, names=None, format='long', mode='both', force=False, sampling_rate='TR', **kwargs): ''' Get design matrix and associated information. Args: names (list): Optional list of names of variables to include in the returned desi...
[ "def", "get_design_matrix", "(", "self", ",", "names", "=", "None", ",", "format", "=", "'long'", ",", "mode", "=", "'both'", ",", "force", "=", "False", ",", "sampling_rate", "=", "'TR'", ",", "*", "*", "kwargs", ")", ":", "sparse_df", ",", "dense_df"...
51.342466
0.001571
def _calc_coordinates(self): """ Calculate the coordinates to use when calling an interpolator. These are needed for `Background2D` and `BackgroundIDW2D`. Regular-grid interpolators require a 2D array of values. Some require a 2D meshgrid of x and y. Other require a strictly ...
[ "def", "_calc_coordinates", "(", "self", ")", ":", "# the position coordinates used to initialize an interpolation", "self", ".", "y", "=", "(", "self", ".", "mesh_yidx", "*", "self", ".", "box_size", "[", "0", "]", "+", "(", "self", ".", "box_size", "[", "0",...
41.142857
0.002262
def _create_p(s, h): """Parabolic derivative""" p = np.zeros_like(s) p[1:] = (s[:-1]*h[1:] + s[1:] * h[:-1]) / (h[1:] + h[:-1]) return p
[ "def", "_create_p", "(", "s", ",", "h", ")", ":", "p", "=", "np", ".", "zeros_like", "(", "s", ")", "p", "[", "1", ":", "]", "=", "(", "s", "[", ":", "-", "1", "]", "*", "h", "[", "1", ":", "]", "+", "s", "[", "1", ":", "]", "*", "h...
32.8
0.011905
def getFiltersFromArgs(kwargs): ''' getFiltersFromArgs - Returns a dictionary of each filter type, and the corrosponding field/value @param kwargs <dict> - Dictionary of filter arguments @return - Dictionary of each filter type (minus the ones that are optimized into others), each contain...
[ "def", "getFiltersFromArgs", "(", "kwargs", ")", ":", "# Create a copy of each possible filter in FILTER_TYPES and link to empty list.", "# This object will be filled with all of the filters requested", "ret", "=", "{", "filterType", ":", "list", "(", ")", "for", "filterType", "...
38.215385
0.009027
def get_blob_data(self, tag_target='asset', force=False): """ get asset version content using pg large object streams :param bool force: False by default, forces get content from database instead of using cached value :rtype: str :return: content in raw format ...
[ "def", "get_blob_data", "(", "self", ",", "tag_target", "=", "'asset'", ",", "force", "=", "False", ")", ":", "if", "hasattr", "(", "self", ",", "'_blob_data'", ")", "and", "not", "force", ":", "return", "self", ".", "_blob_data", "if", "six", ".", "PY...
38.090909
0.002328
def _init_multi_count_metrics(self, pplan_helper): """Initializes the default values for a necessary set of MultiCountMetrics""" to_init = [self.metrics[i] for i in self.to_multi_init if i in self.metrics and isinstance(self.metrics[i], MultiCountMetric)] for out_stream in pplan_helper.get_my...
[ "def", "_init_multi_count_metrics", "(", "self", ",", "pplan_helper", ")", ":", "to_init", "=", "[", "self", ".", "metrics", "[", "i", "]", "for", "i", "in", "self", ".", "to_multi_init", "if", "i", "in", "self", ".", "metrics", "and", "isinstance", "(",...
54
0.01139
def plot_gaussian_cdf(mean=0., variance=1., ax=None, xlim=None, ylim=(0., 1.), xlabel=None, ylabel=None, label=None): """ Plots a normal distribution CDF with the given mean and variance. x-axis contains the mean, the y-...
[ "def", "plot_gaussian_cdf", "(", "mean", "=", "0.", ",", "variance", "=", "1.", ",", "ax", "=", "None", ",", "xlim", "=", "None", ",", "ylim", "=", "(", "0.", ",", "1.", ")", ",", "xlabel", "=", "None", ",", "ylabel", "=", "None", ",", "label", ...
25.767857
0.000668
def text(self,txt): """ Print Utf8 encoded alpha-numeric text """ if not txt: return try: txt = txt.decode('utf-8') except: try: txt = txt.decode('utf-16') except: pass self.extra_chars = 0 ...
[ "def", "text", "(", "self", ",", "txt", ")", ":", "if", "not", "txt", ":", "return", "try", ":", "txt", "=", "txt", ".", "decode", "(", "'utf-8'", ")", "except", ":", "try", ":", "txt", "=", "txt", ".", "decode", "(", "'utf-16'", ")", "except", ...
39.419643
0.009501
def dependency_failed(test, results): """Returns an error string if any of the dependencies failed""" for d in (NoseDepUtils.test_name(i) for i in dependencies[test]): if results.get(d) and results.get(d) != 'passed': return "Required test '{}' {}".format(d, results.get(d).up...
[ "def", "dependency_failed", "(", "test", ",", "results", ")", ":", "for", "d", "in", "(", "NoseDepUtils", ".", "test_name", "(", "i", ")", "for", "i", "in", "dependencies", "[", "test", "]", ")", ":", "if", "results", ".", "get", "(", "d", ")", "an...
56.833333
0.008671
def _maybe_download_corpus(tmp_dir, vocab_type): """Download and unpack the corpus. Args: tmp_dir: directory containing dataset. vocab_type: which vocabulary are we using. Returns: The list of names of files. """ if vocab_type == text_problems.VocabType.CHARACTER: dataset_url = ("https://s3...
[ "def", "_maybe_download_corpus", "(", "tmp_dir", ",", "vocab_type", ")", ":", "if", "vocab_type", "==", "text_problems", ".", "VocabType", ".", "CHARACTER", ":", "dataset_url", "=", "(", "\"https://s3.amazonaws.com/research.metamind.io/wikitext\"", "\"/wikitext-103-raw-v1.z...
31.093023
0.013778
def builder_inited(app): """ Sets wavedrom_html_jsinline to False for all non-html builders for convenience (use ifconf etc.) We instruct sphinx to include some javascript files in the output html. Depending on the settings provided in the configuration, we take either the online files from the...
[ "def", "builder_inited", "(", "app", ")", ":", "if", "(", "app", ".", "config", ".", "wavedrom_html_jsinline", "and", "app", ".", "builder", ".", "name", "not", "in", "(", "'html'", ",", "'dirhtml'", ",", "'singlehtml'", ")", ")", ":", "app", ".", "con...
39.730769
0.00189
def dbcmd(action, *args): """ A dispatcher to the database server. :param action: database action to perform :param args: arguments """ global sock if sock is None: sock = zeromq.Socket( 'tcp://%s:%s' % (config.dbserver.host, DBSERVER_PORT), zeromq.zmq.REQ, '...
[ "def", "dbcmd", "(", "action", ",", "*", "args", ")", ":", "global", "sock", "if", "sock", "is", "None", ":", "sock", "=", "zeromq", ".", "Socket", "(", "'tcp://%s:%s'", "%", "(", "config", ".", "dbserver", ".", "host", ",", "DBSERVER_PORT", ")", ","...
29.764706
0.001916
def get_device_tree(self): """Get a tree of all devices.""" root = DevNode(None, None, [], None) device_nodes = { dev.object_path: DevNode(dev, dev.parent_object_path, [], self._ignore_device(dev)) for dev in self.udisks } ...
[ "def", "get_device_tree", "(", "self", ")", ":", "root", "=", "DevNode", "(", "None", ",", "None", ",", "[", "]", ",", "None", ")", "device_nodes", "=", "{", "dev", ".", "object_path", ":", "DevNode", "(", "dev", ",", "dev", ".", "parent_object_path", ...
38.954545
0.002278
def _image2array(filepath): ''' Utility function that converts an image file in 3 np arrays that can be fed into geo_image.GeoImage in order to generate a PyTROLL GeoImage object. ''' im = Pimage.open(filepath).convert('RGB') (width, height) = im.size _r = np.array(list(im.getdata(0)))/2...
[ "def", "_image2array", "(", "filepath", ")", ":", "im", "=", "Pimage", ".", "open", "(", "filepath", ")", ".", "convert", "(", "'RGB'", ")", "(", "width", ",", "height", ")", "=", "im", ".", "size", "_r", "=", "np", ".", "array", "(", "list", "("...
35.533333
0.001828
def run_continuously(self, interval=1): """Continuously run, while executing pending jobs at each elapsed time interval. @return cease_continuous_run: threading.Event which can be set to cease continuous run. Please note that it is *intended behavior that run_continuously() ...
[ "def", "run_continuously", "(", "self", ",", "interval", "=", "1", ")", ":", "cease_continuous_run", "=", "threading", ".", "Event", "(", ")", "class", "ScheduleThread", "(", "threading", ".", "Thread", ")", ":", "@", "classmethod", "def", "run", "(", "cls...
38.08
0.002049
def transform(self, X): """Transform X according to the fitted transformer. Parameters ---------- X : array-like, shape = [n_samples, n_features] Input vectors, where n_samples is the number of samples and n_features is the number of features. Returns ...
[ "def", "transform", "(", "self", ",", "X", ")", ":", "if", "not", "hasattr", "(", "self", ",", "'_best_programs'", ")", ":", "raise", "NotFittedError", "(", "'SymbolicTransformer not fitted.'", ")", "X", "=", "check_array", "(", "X", ")", "_", ",", "n_feat...
34.137931
0.001965
def validate(self, protocol_version): """Validate message.""" const = get_const(protocol_version) valid_node_ids = vol.All(vol.Coerce(int), vol.Range( min=0, max=BROADCAST_ID, msg='Not valid node_id: {}'.format( self.node_id))) valid_child_ids = vol.All(vol.Co...
[ "def", "validate", "(", "self", ",", "protocol_version", ")", ":", "const", "=", "get_const", "(", "protocol_version", ")", "valid_node_ids", "=", "vol", ".", "All", "(", "vol", ".", "Coerce", "(", "int", ")", ",", "vol", ".", "Range", "(", "min", "=",...
51.886364
0.00086
def _decode_stat_data(self, chunk): """ Return all items found in this chunk """ for date_str, statistics in chunk.iteritems(): date_obj = datetime.datetime.strptime( date_str.split(".")[0], '%Y-%m-%d %H:%M:%S') chunk_date = int(time.mktime(date_ob...
[ "def", "_decode_stat_data", "(", "self", ",", "chunk", ")", ":", "for", "date_str", ",", "statistics", "in", "chunk", ".", "iteritems", "(", ")", ":", "date_obj", "=", "datetime", ".", "datetime", ".", "strptime", "(", "date_str", ".", "split", "(", "\"....
44.619048
0.00209
def can_regex(self, field): '''Test if a given field supports regex lookups''' from django.conf import settings if settings.DATABASES['default']['ENGINE'].endswith('sqlite3'): return not isinstance(get_real_field(self.model, field), UNSUPPORTED_REGEX_FIELDS) else: ...
[ "def", "can_regex", "(", "self", ",", "field", ")", ":", "from", "django", ".", "conf", "import", "settings", "if", "settings", ".", "DATABASES", "[", "'default'", "]", "[", "'ENGINE'", "]", ".", "endswith", "(", "'sqlite3'", ")", ":", "return", "not", ...
46.571429
0.009036
def create_geom_filter(request, mapped_class, geom_attr): """Create MapFish geometry filter based on the request params. Either a box or within or geometry filter, depending on the request params. Additional named arguments are passed to the spatial filter. Arguments: request the request. ...
[ "def", "create_geom_filter", "(", "request", ",", "mapped_class", ",", "geom_attr", ")", ":", "tolerance", "=", "float", "(", "request", ".", "params", ".", "get", "(", "'tolerance'", ",", "0.0", ")", ")", "epsg", "=", "None", "if", "'epsg'", "in", "requ...
38.288889
0.000566
def convert_to_str(input_string): """ Returns a string of the input compatible between py2 and py3 :param input_string: :return: """ if sys.version < '3': if isinstance(input_string, str) \ or isinstance(input_string, unicode): # pragma: no cover py3 return i...
[ "def", "convert_to_str", "(", "input_string", ")", ":", "if", "sys", ".", "version", "<", "'3'", ":", "if", "isinstance", "(", "input_string", ",", "str", ")", "or", "isinstance", "(", "input_string", ",", "unicode", ")", ":", "# pragma: no cover py3", "retu...
23.809524
0.001923
def serialize_verifying_key(vk): """ Serialize a public key into SSH format (for exporting to text format). Currently, NIST256P1 and ED25519 elliptic curves are supported. Raise TypeError on unsupported key format. """ if isinstance(vk, ed25519.keys.VerifyingKey): pubkey = vk.to_bytes()...
[ "def", "serialize_verifying_key", "(", "vk", ")", ":", "if", "isinstance", "(", "vk", ",", "ed25519", ".", "keys", ".", "VerifyingKey", ")", ":", "pubkey", "=", "vk", ".", "to_bytes", "(", ")", "key_type", "=", "SSH_ED25519_KEY_TYPE", "blob", "=", "util", ...
37.636364
0.001178
def async_lru(size=100): """ An LRU cache for asyncio coroutines in Python 3.5 .. @async_lru(1024) async def slow_coroutine(*args, **kwargs): return await some_other_slow_coroutine() .. """ cache = collections.OrderedDict() def decorator(fn): ...
[ "def", "async_lru", "(", "size", "=", "100", ")", ":", "cache", "=", "collections", ".", "OrderedDict", "(", ")", "def", "decorator", "(", "fn", ")", ":", "@", "wraps", "(", "fn", ")", "@", "asyncio", ".", "coroutine", "def", "memoizer", "(", "*", ...
30.44
0.001274
def get_mon_map(service): """ Returns the current monitor map. :param service: six.string_types. The Ceph user name to run the command under :return: json string. :raise: ValueError if the monmap fails to parse. Also raises CalledProcessError if our ceph command fails """ try: mon_...
[ "def", "get_mon_map", "(", "service", ")", ":", "try", ":", "mon_status", "=", "check_output", "(", "[", "'ceph'", ",", "'--id'", ",", "service", ",", "'mon_status'", ",", "'--format=json'", "]", ")", "if", "six", ".", "PY3", ":", "mon_status", "=", "mon...
38
0.002334
def as_dict(self): """ Returns a dict representation of the resource """ result = {} for key in self._valid_properties: val = getattr(self, key) if isinstance(val, datetime): val = val.isoformat() # Parse custom classes elif val and...
[ "def", "as_dict", "(", "self", ")", ":", "result", "=", "{", "}", "for", "key", "in", "self", ".", "_valid_properties", ":", "val", "=", "getattr", "(", "self", ",", "key", ")", "if", "isinstance", "(", "val", ",", "datetime", ")", ":", "val", "=",...
37.461538
0.002002
def clean_egginfo(self): """Clean .egginfo directory""" dir_name = os.path.join(self.root, self.get_egginfo_dir()) self._clean_directory(dir_name)
[ "def", "clean_egginfo", "(", "self", ")", ":", "dir_name", "=", "os", ".", "path", ".", "join", "(", "self", ".", "root", ",", "self", ".", "get_egginfo_dir", "(", ")", ")", "self", ".", "_clean_directory", "(", "dir_name", ")" ]
41.75
0.011765
def check(table='filter', chain=None, rule=None, family='ipv4'): ''' Check for the existence of a rule in the table and chain This function accepts a rule in a standard nftables command format, starting with the chain. Trying to force users to adapt to a new method of creating rules would b...
[ "def", "check", "(", "table", "=", "'filter'", ",", "chain", "=", "None", ",", "rule", "=", "None", ",", "family", "=", "'ipv4'", ")", ":", "ret", "=", "{", "'comment'", ":", "''", ",", "'result'", ":", "False", "}", "if", "not", "chain", ":", "r...
31.759259
0.001697
def _execute_pep8(pep8_options, source): """Execute pycodestyle via python method calls.""" class QuietReport(pycodestyle.BaseReport): """Version of checker that does not print.""" def __init__(self, options): super(QuietReport, self).__init__(options) self.__full_error...
[ "def", "_execute_pep8", "(", "pep8_options", ",", "source", ")", ":", "class", "QuietReport", "(", "pycodestyle", ".", "BaseReport", ")", ":", "\"\"\"Version of checker that does not print.\"\"\"", "def", "__init__", "(", "self", ",", "options", ")", ":", "super", ...
37
0.000732
def adjust_events(events, labels=None, t_min=0.0, t_max=None, label_prefix='__'): """Adjust the given list of event times to span the range ``[t_min, t_max]``. Any event times outside of the specified range will be removed. If the times do not span ``[t_min, t_max]``, additional even...
[ "def", "adjust_events", "(", "events", ",", "labels", "=", "None", ",", "t_min", "=", "0.0", ",", "t_max", "=", "None", ",", "label_prefix", "=", "'__'", ")", ":", "if", "t_min", "is", "not", "None", ":", "first_idx", "=", "np", ".", "argwhere", "(",...
30.940299
0.000468
def _set_zfcp_config_files(self, fcp, target_wwpn, target_lun): """sles set WWPN and LUN in configuration files""" device = '0.0.%s' % fcp # host config host_config = '/sbin/zfcp_host_configure %s 1' % device # disk config disk_config = '/sbin/zfcp_disk_configure ' +\ ...
[ "def", "_set_zfcp_config_files", "(", "self", ",", "fcp", ",", "target_wwpn", ",", "target_lun", ")", ":", "device", "=", "'0.0.%s'", "%", "fcp", "# host config", "host_config", "=", "'/sbin/zfcp_host_configure %s 1'", "%", "device", "# disk config", "disk_config", ...
57.866667
0.000755
def on_tape(*files): """Determine whether any of the given files are on tape Parameters ---------- *files : `str` one or more paths to GWF files Returns ------- True/False : `bool` `True` if any of the files are determined to be on tape, otherwise `False` """ ...
[ "def", "on_tape", "(", "*", "files", ")", ":", "for", "path", "in", "files", ":", "try", ":", "if", "os", ".", "stat", "(", "path", ")", ".", "st_blocks", "==", "0", ":", "return", "True", "except", "AttributeError", ":", "# windows doesn't have st_block...
24.428571
0.001876
def uniontypes(type_: Type[Any]) -> Set[Type[Any]]: ''' Returns the types of a Union. Raises ValueError if the argument is not a Union and AttributeError when running on an unsupported Python version. ''' if not is_union(type_): raise ValueError('Not a Union: ' + str(type_)) if...
[ "def", "uniontypes", "(", "type_", ":", "Type", "[", "Any", "]", ")", "->", "Set", "[", "Type", "[", "Any", "]", "]", ":", "if", "not", "is_union", "(", "type_", ")", ":", "raise", "ValueError", "(", "'Not a Union: '", "+", "str", "(", "type_", ")"...
33.375
0.001821
def _netstat_linux(): ''' Return netstat information for Linux distros ''' ret = [] cmd = 'netstat -tulpnea' out = __salt__['cmd.run'](cmd) for line in out.splitlines(): comps = line.split() if line.startswith('tcp'): ret.append({ 'proto': comps[0]...
[ "def", "_netstat_linux", "(", ")", ":", "ret", "=", "[", "]", "cmd", "=", "'netstat -tulpnea'", "out", "=", "__salt__", "[", "'cmd.run'", "]", "(", "cmd", ")", "for", "line", "in", "out", ".", "splitlines", "(", ")", ":", "comps", "=", "line", ".", ...
31.225806
0.001002
def read_bonedata(self, fid): """Read bone data from an acclaim skeleton file stream.""" bone_count = 0 lin = self.read_line(fid) while lin[0]!=':': parts = lin.split() if parts[0] == 'begin': bone_count += 1 self.vertices.append(v...
[ "def", "read_bonedata", "(", "self", ",", "fid", ")", ":", "bone_count", "=", "0", "lin", "=", "self", ".", "read_line", "(", "fid", ")", "while", "lin", "[", "0", "]", "!=", "':'", ":", "parts", "=", "lin", ".", "split", "(", ")", "if", "parts",...
41.663366
0.009981
def AddArguments(cls, argument_group): """Adds command line arguments the helper supports to an argument group. This function takes an argument parser or an argument group object and adds to it all the command line arguments this helper supports. Args: argument_group (argparse._ArgumentGroup|arg...
[ "def", "AddArguments", "(", "cls", ",", "argument_group", ")", ":", "default_fields", "=", "','", ".", "join", "(", "cls", ".", "_DEFAULT_FIELDS", ")", "argument_group", ".", "add_argument", "(", "'--fields'", ",", "dest", "=", "'fields'", ",", "type", "=", ...
43.772727
0.001016
def update(cls, zone_id, old_record, new_record): """Update a record in a zone file""" cls.echo('Creating new zone file') new_version_id = Zone.new(zone_id) new_record = new_record.replace(' IN', '') new_record = new_record.split(' ', 4) params_newrecord = {'name': new_r...
[ "def", "update", "(", "cls", ",", "zone_id", ",", "old_record", ",", "new_record", ")", ":", "cls", ".", "echo", "(", "'Creating new zone file'", ")", "new_version_id", "=", "Zone", ".", "new", "(", "zone_id", ")", "new_record", "=", "new_record", ".", "re...
43.973684
0.001171
def _check_perms(obj_name, obj_type, new_perms, cur_perms, access_mode, ret): ''' Helper function used by ``check_perms`` for checking and setting Grant and Deny permissions. Args: obj_name (str): The name or full path to the object obj_type (Optional[str]): Th...
[ "def", "_check_perms", "(", "obj_name", ",", "obj_type", ",", "new_perms", ",", "cur_perms", ",", "access_mode", ",", "ret", ")", ":", "access_mode", "=", "access_mode", ".", "lower", "(", ")", "changes", "=", "{", "}", "for", "user", "in", "new_perms", ...
46.095808
0.002416
def _init_horizontal(self): """Create and grid the widgets for a horizontal orientation.""" self.scale.grid(row=0, sticky='ew') padx1, padx2 = 0, 0 pady1, pady2 = 0, 0 # showvalue if self._showvalue: self.label.configure(text=self._formatter.format(self._start...
[ "def", "_init_horizontal", "(", "self", ")", ":", "self", ".", "scale", ".", "grid", "(", "row", "=", "0", ",", "sticky", "=", "'ew'", ")", "padx1", ",", "padx2", "=", "0", ",", "0", "pady1", ",", "pady2", "=", "0", ",", "0", "# showvalue", "if",...
48.712329
0.002481
def add_ask(self, ask): """Add an ask to the cache :param ask: :return: """ self._asks[ask[0]] = float(ask[1]) if ask[1] == "0.00000000": del self._asks[ask[0]]
[ "def", "add_ask", "(", "self", ",", "ask", ")", ":", "self", ".", "_asks", "[", "ask", "[", "0", "]", "]", "=", "float", "(", "ask", "[", "1", "]", ")", "if", "ask", "[", "1", "]", "==", "\"0.00000000\"", ":", "del", "self", ".", "_asks", "["...
21.3
0.009009
def execute_cleanup_tasks(ctx, cleanup_tasks, dry_run=False): """Execute several cleanup tasks as part of the cleanup. REQUIRES: ``clean(ctx, dry_run=False)`` signature in cleanup tasks. :param ctx: Context object for the tasks. :param cleanup_tasks: Collection of cleanup tasks (as Colle...
[ "def", "execute_cleanup_tasks", "(", "ctx", ",", "cleanup_tasks", ",", "dry_run", "=", "False", ")", ":", "# pylint: disable=redefined-outer-name", "executor", "=", "Executor", "(", "cleanup_tasks", ",", "ctx", ".", "config", ")", "for", "cleanup_task", "in", "cle...
45.142857
0.00155
def _finalize(self): """ Various last-minute stuff to perform after file has been parsed and imported. In general, if you'll be adding stuff to the meta table, do it here. """ c = self.conn.cursor() directives = self.directives + self.iterator.directives ...
[ "def", "_finalize", "(", "self", ")", ":", "c", "=", "self", ".", "conn", ".", "cursor", "(", ")", "directives", "=", "self", ".", "directives", "+", "self", ".", "iterator", ".", "directives", "c", ".", "executemany", "(", "'''\n INSE...
41.375
0.001265
def get_history(self): """get all msg_ids, ordered by time submitted.""" msg_ids = self._records.keys() return sorted(msg_ids, key=lambda m: self._records[m]['submitted'])
[ "def", "get_history", "(", "self", ")", ":", "msg_ids", "=", "self", ".", "_records", ".", "keys", "(", ")", "return", "sorted", "(", "msg_ids", ",", "key", "=", "lambda", "m", ":", "self", ".", "_records", "[", "m", "]", "[", "'submitted'", "]", "...
48
0.010256
def _ip_frag_check(*args, func=None): """Check if arguments are valid IP fragments.""" func = func or inspect.stack()[2][3] for var in args: dict_check(var, func=func) bufid = var.get('bufid') str_check(bufid[3], func=func) bool_check(var.get('mf'), func=func) ip_chec...
[ "def", "_ip_frag_check", "(", "*", "args", ",", "func", "=", "None", ")", ":", "func", "=", "func", "or", "inspect", ".", "stack", "(", ")", "[", "2", "]", "[", "3", "]", "for", "var", "in", "args", ":", "dict_check", "(", "var", ",", "func", "...
44.5
0.001835
def get_next_step(self): """Find the proper step when user clicks the Next button. :returns: The step to be switched to :rtype: WizardStep instance or None """ if self.parent.parent_step: # Come back from KW to the parent IFCW thread. parent_step = self.p...
[ "def", "get_next_step", "(", "self", ")", ":", "if", "self", ".", "parent", ".", "parent_step", ":", "# Come back from KW to the parent IFCW thread.", "parent_step", "=", "self", ".", "parent", ".", "parent_step", "if", "self", ".", "parent", ".", "is_layer_compat...
49.69697
0.000598
def config_dict(config_file=None, auto_find=False, verify=True, **cfg_options): """ Return configuration options as dictionary. Accepts either a single config file or a list of files. Auto find will search for all .cfg, .config and .ini in the execution directory and package root (unsafe but handy). ...
[ "def", "config_dict", "(", "config_file", "=", "None", ",", "auto_find", "=", "False", ",", "verify", "=", "True", ",", "*", "*", "cfg_options", ")", ":", "if", "not", "config_file", ":", "config_file", "=", "[", "]", "cfg_parser", "=", "ConfigParser", "...
36.470588
0.000524
def _and32(ins): """ Compares & pops top 2 operands out of the stack, and checks if the 1st operand AND (Logical) 2nd operand (top of the stack). Pushes 0 if False, 1 if True. 32 bit un/signed version """ op1, op2 = tuple(ins.quad[2:]) if _int_ops(op1, op2): op1, op2 = ...
[ "def", "_and32", "(", "ins", ")", ":", "op1", ",", "op2", "=", "tuple", "(", "ins", ".", "quad", "[", "2", ":", "]", ")", "if", "_int_ops", "(", "op1", ",", "op2", ")", ":", "op1", ",", "op2", "=", "_int_ops", "(", "op1", ",", "op2", ")", "...
31.655172
0.002114
def get_identity(identity): """Returns some information about the currently authenticated identity""" return flask.Response( json.dumps( { 'identity': { 'id': identity.id, 'etag': identity.etag, 'name': identity.name...
[ "def", "get_identity", "(", "identity", ")", ":", "return", "flask", ".", "Response", "(", "json", ".", "dumps", "(", "{", "'identity'", ":", "{", "'id'", ":", "identity", ".", "id", ",", "'etag'", ":", "identity", ".", "etag", ",", "'name'", ":", "i...
33.842105
0.001513
def _process_origin(self, req, resp, origin): """Inspects the request and adds the Access-Control-Allow-Origin header if the requested origin is allowed. Returns: ``True`` if the header was added and the requested origin is allowed, ``False`` if the origin is not allowed...
[ "def", "_process_origin", "(", "self", ",", "req", ",", "resp", ",", "origin", ")", ":", "if", "self", ".", "_cors_config", "[", "'allow_all_origins'", "]", ":", "if", "self", ".", "supports_credentials", ":", "self", ".", "_set_allow_origin", "(", "resp", ...
35.333333
0.002041
def validateMemberName(n): """ Verifies that the supplied name is a valid DBus member name. Throws an L{error.MarshallingError} if the format is invalid @type n: C{string} @param n: A DBus member name """ try: if len(n) < 1: raise Exception('Name must be at least one byt...
[ "def", "validateMemberName", "(", "n", ")", ":", "try", ":", "if", "len", "(", "n", ")", "<", "1", ":", "raise", "Exception", "(", "'Name must be at least one byte in length'", ")", "if", "len", "(", "n", ")", ">", "255", ":", "raise", "Exception", "(", ...
36.65
0.00133
def minvar(X, order, sampling=1., NFFT=default_NFFT): r"""Minimum Variance Spectral Estimation (MV) This function computes the minimum variance spectral estimate using the Musicus procedure. The Burg algorithm from :func:`~spectrum.burg.arburg` is used for the estimation of the autoregressive paramete...
[ "def", "minvar", "(", "X", ",", "order", ",", "sampling", "=", "1.", ",", "NFFT", "=", "default_NFFT", ")", ":", "errors", ".", "is_positive_integer", "(", "order", ")", "errors", ".", "is_positive_integer", "(", "NFFT", ")", "psi", "=", "np", ".", "ze...
34.60177
0.001492
def from_Note(note, process_octaves=True, standalone=True): """Get a Note object and return the LilyPond equivalent in a string. If process_octaves is set to False, all data regarding octaves will be ignored. If standalone is True, the result can be used by functions like to_png and will produce a vali...
[ "def", "from_Note", "(", "note", ",", "process_octaves", "=", "True", ",", "standalone", "=", "True", ")", ":", "# Throw exception", "if", "not", "hasattr", "(", "note", ",", "'name'", ")", ":", "return", "False", "# Lower the case of the name", "result", "=",...
30.027027
0.000872
def _parse(self,filename): """ Reads an isochrone in the old Padova format (Girardi 2002, Marigo 2008) and determines the age (log10 yrs and Gyr), metallicity (Z and [Fe/H]), and creates arrays with the initial stellar mass and corresponding magnitudes for each step along...
[ "def", "_parse", "(", "self", ",", "filename", ")", ":", "try", ":", "columns", "=", "self", ".", "columns", "[", "self", ".", "survey", ".", "lower", "(", ")", "]", "except", "KeyError", "as", "e", ":", "logger", ".", "warning", "(", "'did not recog...
41.675676
0.008872
def project( self, X, projection="sum", scaler=preprocessing.MinMaxScaler(), distance_matrix=None, ): """Creates the projection/lens from a dataset. Input the data set. Specify a projection/lens type. Output the projected data/lens. Parameters -------...
[ "def", "project", "(", "self", ",", "X", ",", "projection", "=", "\"sum\"", ",", "scaler", "=", "preprocessing", ".", "MinMaxScaler", "(", ")", ",", "distance_matrix", "=", "None", ",", ")", ":", "# Sae original values off so they can be referenced by later function...
37.973451
0.002384
def accumulation_distribution(close_data, high_data, low_data, volume): """ Accumulation/Distribution. Formula: A/D = (Ct - Lt) - (Ht - Ct) / (Ht - Lt) * Vt + A/Dt-1 """ catch_errors.check_for_input_len_diff( close_data, high_data, low_data, volume ) ad = np.zeros(len(close...
[ "def", "accumulation_distribution", "(", "close_data", ",", "high_data", ",", "low_data", ",", "volume", ")", ":", "catch_errors", ".", "check_for_input_len_diff", "(", "close_data", ",", "high_data", ",", "low_data", ",", "volume", ")", "ad", "=", "np", ".", ...
28.809524
0.0016
def opt_args_decorator(func): """A decorator to be used on another decorator This is done to allow separate handling on the basis of argument values """ @wraps(func) def wrapped_dec(*args, **kwargs): if len(args) == 1 and len(kwargs) == 0 and callable(args[0]): # actual decorate...
[ "def", "opt_args_decorator", "(", "func", ")", ":", "@", "wraps", "(", "func", ")", "def", "wrapped_dec", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "len", "(", "args", ")", "==", "1", "and", "len", "(", "kwargs", ")", "==", "0", ...
32.2
0.002012
def mpub(self, topic, *messages): '''Publish messages to a topic''' with self.random_connection() as client: client.mpub(topic, *messages) return self.wait_response()
[ "def", "mpub", "(", "self", ",", "topic", ",", "*", "messages", ")", ":", "with", "self", ".", "random_connection", "(", ")", "as", "client", ":", "client", ".", "mpub", "(", "topic", ",", "*", "messages", ")", "return", "self", ".", "wait_response", ...
40.4
0.009709
def refund(request, invoice_id): ''' Marks an invoice as refunded and requests a credit note for the full amount paid against the invoice. This view requires a login, and the logged in user must be staff. Arguments: invoice_id (castable to int): The ID of the invoice to refund. Returns: ...
[ "def", "refund", "(", "request", ",", "invoice_id", ")", ":", "current_invoice", "=", "InvoiceController", ".", "for_id_or_404", "(", "invoice_id", ")", "try", ":", "current_invoice", ".", "refund", "(", ")", "messages", ".", "success", "(", "request", ",", ...
27.208333
0.001479
def match(self, field_name, field_value, **options): """ Returns first match found in :any:`get_all` >>> airtable.match('Name', 'John') {'fields': {'Name': 'John'} } Args: field_name (``str``): Name of field to match (column name). field_value (...
[ "def", "match", "(", "self", ",", "field_name", ",", "field_value", ",", "*", "*", "options", ")", ":", "from_name_and_value", "=", "AirtableParams", ".", "FormulaParam", ".", "from_name_and_value", "formula", "=", "from_name_and_value", "(", "field_name", ",", ...
41.870968
0.001506
def roles_required(*roles): """Decorator which specifies that a user must have all the specified roles. Example:: @app.route('/dashboard') @roles_required('admin', 'editor') def dashboard(): return 'Dashboard' The current user must have both the `admin` role and `editor...
[ "def", "roles_required", "(", "*", "roles", ")", ":", "def", "wrapper", "(", "fn", ")", ":", "@", "wraps", "(", "fn", ")", "def", "decorated_view", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "perms", "=", "[", "Permission", "(", "RoleNeed...
32.888889
0.001094
def get_lmv2_response(domain, username, password, server_challenge, client_challenge): """ Computes an appropriate LMv2 response based on the supplied arguments The algorithm is based on jCIFS. The response is 24 bytes, with the 16 bytes of hash concatenated with the 8 byte client client...
[ "def", "get_lmv2_response", "(", "domain", ",", "username", ",", "password", ",", "server_challenge", ",", "client_challenge", ")", ":", "ntlmv2_hash", "=", "PasswordAuthentication", ".", "ntowfv2", "(", "domain", ",", "username", ",", "password", ".", "encode", ...
54.588235
0.008475
def _create(self, uri, body, records=None, subdomains=None, return_none=False, return_raw=False, **kwargs): """ Handles the communication with the API when creating a new resource managed by this class. Since DNS works completely differently for create() than the other ...
[ "def", "_create", "(", "self", ",", "uri", ",", "body", ",", "records", "=", "None", ",", "subdomains", "=", "None", ",", "return_none", "=", "False", ",", "return_raw", "=", "False", ",", "*", "*", "kwargs", ")", ":", "self", ".", "run_hooks", "(", ...
41.310345
0.002447
def submit_link(self, title, url): """Submit link to this subreddit (POST). Calls :meth:`narwal.Reddit.submit_link`. :param title: title of submission :param url: url submission links to """ return self._reddit.submit_link(self.display_name, title, url)
[ "def", "submit_link", "(", "self", ",", "title", ",", "url", ")", ":", "return", "self", ".", "_reddit", ".", "submit_link", "(", "self", ".", "display_name", ",", "title", ",", "url", ")" ]
42.428571
0.013201
def check_signature(signature, private_key, full_path, payload): """ Checks signature received and verifies that we are able to re-create it from the private key, path, and payload given. :param signature: Signature received from request. :param private_key: Base 64, url encoded pri...
[ "def", "check_signature", "(", "signature", ",", "private_key", ",", "full_path", ",", "payload", ")", ":", "if", "isinstance", "(", "private_key", ",", "bytes", ")", ":", "private_key", "=", "private_key", ".", "decode", "(", "\"ascii\"", ")", "if", "isinst...
35.230769
0.002125
def exactly_n(iterable, n, predicate=bool): """Return ``True`` if exactly ``n`` items in the iterable are ``True`` according to the *predicate* function. >>> exactly_n([True, True, False], 2) True >>> exactly_n([True, True, False], 1) False >>> exactly_n([0, 1, 2, 3, 4, ...
[ "def", "exactly_n", "(", "iterable", ",", "n", ",", "predicate", "=", "bool", ")", ":", "return", "len", "(", "take", "(", "n", "+", "1", ",", "filter", "(", "predicate", ",", "iterable", ")", ")", ")", "==", "n" ]
33.75
0.001802
def transitionStates(self,state): """ Return the indices of new states and their rates. """ newstates,rates = self.transition(state) newindices = self.getStateIndex(newstates) return newindices,rates
[ "def", "transitionStates", "(", "self", ",", "state", ")", ":", "newstates", ",", "rates", "=", "self", ".", "transition", "(", "state", ")", "newindices", "=", "self", ".", "getStateIndex", "(", "newstates", ")", "return", "newindices", ",", "rates" ]
39.571429
0.031802
def is_installed_extension(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Test if a specific extension is...
[ "def", "is_installed_extension", "(", "name", ",", "user", "=", "None", ",", "host", "=", "None", ",", "port", "=", "None", ",", "maintenance_db", "=", "None", ",", "password", "=", "None", ",", "runas", "=", "None", ")", ":", "installed_ext", "=", "ge...
24.692308
0.001499
def normalize(self, stats:Collection[Tensor]=None, do_x:bool=True, do_y:bool=False)->None: "Add normalize transform using `stats` (defaults to `DataBunch.batch_stats`)" if getattr(self,'norm',False): raise Exception('Can not call normalize twice') if stats is None: self.stats = self.batch_stats(...
[ "def", "normalize", "(", "self", ",", "stats", ":", "Collection", "[", "Tensor", "]", "=", "None", ",", "do_x", ":", "bool", "=", "True", ",", "do_y", ":", "bool", "=", "False", ")", "->", "None", ":", "if", "getattr", "(", "self", ",", "'norm'", ...
61.75
0.043912
def demotivate(channel, rest): "Demotivate someone" if rest: r = rest.strip() else: r = channel karma.Karma.store.change(r, -1) return "you're doing horrible work, %s!" % r
[ "def", "demotivate", "(", "channel", ",", "rest", ")", ":", "if", "rest", ":", "r", "=", "rest", ".", "strip", "(", ")", "else", ":", "r", "=", "channel", "karma", ".", "Karma", ".", "store", ".", "change", "(", "r", ",", "-", "1", ")", "return...
21.75
0.044199
def _document_root(self, fully_qualified=True): """ Return the mets Element for the document root. """ nsmap = {"xsi": utils.NAMESPACES["xsi"], "xlink": utils.NAMESPACES["xlink"]} if fully_qualified: nsmap["mets"] = utils.NAMESPACES["mets"] else: n...
[ "def", "_document_root", "(", "self", ",", "fully_qualified", "=", "True", ")", ":", "nsmap", "=", "{", "\"xsi\"", ":", "utils", ".", "NAMESPACES", "[", "\"xsi\"", "]", ",", "\"xlink\"", ":", "utils", ".", "NAMESPACES", "[", "\"xlink\"", "]", "}", "if", ...
40.466667
0.008052
def rmp_deg_pixel_xys(vecX, vecY, vecPrfSd, tplPngSize, varExtXmin, varExtXmax, varExtYmin, varExtYmax): """Remap x, y, sigma parameters from degrees to pixel. Parameters ---------- vecX : 1D numpy array Array with possible x parametrs in degree vecY : 1D numpy array ...
[ "def", "rmp_deg_pixel_xys", "(", "vecX", ",", "vecY", ",", "vecPrfSd", ",", "tplPngSize", ",", "varExtXmin", ",", "varExtXmax", ",", "varExtYmin", ",", "varExtYmax", ")", ":", "# Remap modelled x-positions of the pRFs:", "vecXpxl", "=", "rmp_rng", "(", "vecX", ","...
41.474576
0.000399
def dtdElementDesc(self, name): """Search the DTD for the description of this element """ ret = libxml2mod.xmlGetDtdElementDesc(self._o, name) if ret is None:raise treeError('xmlGetDtdElementDesc() failed') __tmp = xmlElement(_obj=ret) return __tmp
[ "def", "dtdElementDesc", "(", "self", ",", "name", ")", ":", "ret", "=", "libxml2mod", ".", "xmlGetDtdElementDesc", "(", "self", ".", "_o", ",", "name", ")", "if", "ret", "is", "None", ":", "raise", "treeError", "(", "'xmlGetDtdElementDesc() failed'", ")", ...
47.166667
0.013889
def serialize_object(obj, buffer_threshold=MAX_BYTES, item_threshold=MAX_ITEMS): """Serialize an object into a list of sendable buffers. Parameters ---------- obj : object The object to be serialized buffer_threshold : int The threshold (in bytes) for pulling out data buffers ...
[ "def", "serialize_object", "(", "obj", ",", "buffer_threshold", "=", "MAX_BYTES", ",", "item_threshold", "=", "MAX_ITEMS", ")", ":", "buffers", "=", "[", "]", "if", "istype", "(", "obj", ",", "sequence_types", ")", "and", "len", "(", "obj", ")", "<", "it...
32.621622
0.001609
def validate_string_param(s, valid, param_name="param"): """ Raises a well formatted exception if s is not in valid, otherwise does not raise an exception. Uses ``param_name`` to identify the parameter. """ if s.lower() not in valid: raise YellowbrickValueError( "unknown {} '{}',...
[ "def", "validate_string_param", "(", "s", ",", "valid", ",", "param_name", "=", "\"param\"", ")", ":", "if", "s", ".", "lower", "(", ")", "not", "in", "valid", ":", "raise", "YellowbrickValueError", "(", "\"unknown {} '{}', chose from '{}'\"", ".", "format", "...
37
0.002398
def setTopLevelItems( self, items ): """ Sets the root item for this model to the inputed item. :param item | <XNavigationItem> """ self.blockSignals(True) root = self.invisibleRootItem() for row in range(root.rowCount()): root.t...
[ "def", "setTopLevelItems", "(", "self", ",", "items", ")", ":", "self", ".", "blockSignals", "(", "True", ")", "root", "=", "self", ".", "invisibleRootItem", "(", ")", "for", "row", "in", "range", "(", "root", ".", "rowCount", "(", ")", ")", ":", "ro...
26.9375
0.017937
def add_framework_search_paths(self, paths, recursive=True, escape=False, target_name=None, configuration_name=None): """ Adds paths to the FRAMEWORK_SEARCH_PATHS configuration. :param paths: A string or array of strings :param recursive: Add the paths ...
[ "def", "add_framework_search_paths", "(", "self", ",", "paths", ",", "recursive", "=", "True", ",", "escape", "=", "False", ",", "target_name", "=", "None", ",", "configuration_name", "=", "None", ")", ":", "self", ".", "add_search_paths", "(", "XCBuildConfigu...
62.076923
0.008547
def parse_schedule(self, data): """Parses the device sent schedule.""" sched = Schedule.parse(data) _LOGGER.debug("Got schedule data for day '%s'", sched.day) return sched
[ "def", "parse_schedule", "(", "self", ",", "data", ")", ":", "sched", "=", "Schedule", ".", "parse", "(", "data", ")", "_LOGGER", ".", "debug", "(", "\"Got schedule data for day '%s'\"", ",", "sched", ".", "day", ")", "return", "sched" ]
33.166667
0.009804
def update_font(self): """Update font from Preferences""" color_scheme = self.get_color_scheme() font = self.get_plugin_font() for editor in self.editors: editor.set_font(font, color_scheme)
[ "def", "update_font", "(", "self", ")", ":", "color_scheme", "=", "self", ".", "get_color_scheme", "(", ")", "font", "=", "self", ".", "get_plugin_font", "(", ")", "for", "editor", "in", "self", ".", "editors", ":", "editor", ".", "set_font", "(", "font"...
39
0.008368
def take_shas_of_all_files(G, settings): """ Takes sha1 hash of all dependencies and outputs of all targets Args: The graph we are going to build The settings dictionary Returns: A dictionary where the keys are the filenames and the value is the sha1 hash """ gl...
[ "def", "take_shas_of_all_files", "(", "G", ",", "settings", ")", ":", "global", "ERROR_FN", "sprint", "=", "settings", "[", "\"sprint\"", "]", "error", "=", "settings", "[", "\"error\"", "]", "ERROR_FN", "=", "error", "sha_dict", "=", "{", "}", "all_files", ...
35.145455
0.000503
def range_intersect(a, b, extend=0): """ Returns the intersection between two reanges. >>> range_intersect((30, 45), (55, 65)) >>> range_intersect((48, 65), (45, 55)) [48, 55] """ a_min, a_max = a if a_min > a_max: a_min, a_max = a_max, a_min b_min, b_max = b if b_min > ...
[ "def", "range_intersect", "(", "a", ",", "b", ",", "extend", "=", "0", ")", ":", "a_min", ",", "a_max", "=", "a", "if", "a_min", ">", "a_max", ":", "a_min", ",", "a_max", "=", "a_max", ",", "a_min", "b_min", ",", "b_max", "=", "b", "if", "b_min",...
24.173913
0.00173
def applicable_models(self): """ Returns a list of model classes that subclass Page and include a "tags" field. :rtype: list. """ Page = apps.get_model('wagtailcore', 'Page') applicable = [] for model in apps.get_models(): ...
[ "def", "applicable_models", "(", "self", ")", ":", "Page", "=", "apps", ".", "get_model", "(", "'wagtailcore'", ",", "'Page'", ")", "applicable", "=", "[", "]", "for", "model", "in", "apps", ".", "get_models", "(", ")", ":", "meta", "=", "getattr", "("...
28.944444
0.011152
def read_history_file(self): """Read the command history file -- possibly.""" histfile = self.debugger.intf[-1].histfile try: import readline readline.read_history_file(histfile) except IOError: pass except ImportError: pass ...
[ "def", "read_history_file", "(", "self", ")", ":", "histfile", "=", "self", ".", "debugger", ".", "intf", "[", "-", "1", "]", ".", "histfile", "try", ":", "import", "readline", "readline", ".", "read_history_file", "(", "histfile", ")", "except", "IOError"...
29.181818
0.009063
def _remove_default_tz_bindings(self, context, network_id): """Deconfigure any additional default transport zone bindings.""" default_tz = CONF.NVP.default_tz if not default_tz: LOG.warn("additional_default_tz_types specified, " "but no default_tz. Skipping " ...
[ "def", "_remove_default_tz_bindings", "(", "self", ",", "context", ",", "network_id", ")", ":", "default_tz", "=", "CONF", ".", "NVP", ".", "default_tz", "if", "not", "default_tz", ":", "LOG", ".", "warn", "(", "\"additional_default_tz_types specified, \"", "\"but...
40
0.002326
def bsmahal(a, b, n_boot=200): """ Bootstraps Mahalanobis distances for Shepherd's pi correlation. Parameters ---------- a : ndarray (shape=(n, 2)) Data b : ndarray (shape=(n, 2)) Data n_boot : int Number of bootstrap samples to calculate. Returns ------- ...
[ "def", "bsmahal", "(", "a", ",", "b", ",", "n_boot", "=", "200", ")", ":", "n", ",", "m", "=", "b", ".", "shape", "MD", "=", "np", ".", "zeros", "(", "(", "n", ",", "n_boot", ")", ")", "nr", "=", "np", ".", "arange", "(", "n", ")", "xB", ...
25.444444
0.001052
def named_entity_spans(self): """The spans of named entities.""" if not self.is_tagged(NAMED_ENTITIES): self.tag_named_entities() return self.spans(NAMED_ENTITIES)
[ "def", "named_entity_spans", "(", "self", ")", ":", "if", "not", "self", ".", "is_tagged", "(", "NAMED_ENTITIES", ")", ":", "self", ".", "tag_named_entities", "(", ")", "return", "self", ".", "spans", "(", "NAMED_ENTITIES", ")" ]
39
0.01005
def _cached_path_needs_update(ca_path, cache_length): """ Checks to see if a cache file needs to be refreshed :param ca_path: A unicode string of the path to the cache file :param cache_length: An integer representing the number of hours the cache is valid for :return: A b...
[ "def", "_cached_path_needs_update", "(", "ca_path", ",", "cache_length", ")", ":", "exists", "=", "os", ".", "path", ".", "exists", "(", "ca_path", ")", "if", "not", "exists", ":", "return", "True", "stats", "=", "os", ".", "stat", "(", "ca_path", ")", ...
23
0.00149
def count_string_diff(a,b): """Return the number of characters in two strings that don't exactly match""" shortest = min(len(a), len(b)) return sum(a[i] != b[i] for i in range(shortest))
[ "def", "count_string_diff", "(", "a", ",", "b", ")", ":", "shortest", "=", "min", "(", "len", "(", "a", ")", ",", "len", "(", "b", ")", ")", "return", "sum", "(", "a", "[", "i", "]", "!=", "b", "[", "i", "]", "for", "i", "in", "range", "(",...
48.75
0.015152
def register_dde_task(self, *args, **kwargs): """Register a Dde task.""" kwargs["task_class"] = DdeTask return self.register_task(*args, **kwargs)
[ "def", "register_dde_task", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "\"task_class\"", "]", "=", "DdeTask", "return", "self", ".", "register_task", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
41.75
0.011765
def idle_task(self): '''run periodic tasks''' now = time.time() if now - self.last_chan_check >= 1: self.last_chan_check = now self.update_channels()
[ "def", "idle_task", "(", "self", ")", ":", "now", "=", "time", ".", "time", "(", ")", "if", "now", "-", "self", ".", "last_chan_check", ">=", "1", ":", "self", ".", "last_chan_check", "=", "now", "self", ".", "update_channels", "(", ")" ]
32
0.010152
def wrap_text(text, width=78, initial_indent='', subsequent_indent='', preserve_paragraphs=False): """A helper function that intelligently wraps text. By default, it assumes that it operates on a single paragraph of text but if the `preserve_paragraphs` parameter is provided it will intellige...
[ "def", "wrap_text", "(", "text", ",", "width", "=", "78", ",", "initial_indent", "=", "''", ",", "subsequent_indent", "=", "''", ",", "preserve_paragraphs", "=", "False", ")", ":", "from", ".", "_textwrap", "import", "TextWrapper", "text", "=", "text", "."...
38.060606
0.000388
def x_lower_limit(self, limit=None): """Returns or sets (if a value is provided) the value at which the x-axis should start. By default this is zero (unless there are negative values). :param limit: If given, the chart's x_lower_limit will be set to this. :raises ValueError: if ...
[ "def", "x_lower_limit", "(", "self", ",", "limit", "=", "None", ")", ":", "if", "limit", "is", "None", ":", "if", "self", ".", "_x_lower_limit", "is", "None", ":", "if", "self", ".", "smallest_x", "(", ")", "<", "0", ":", "if", "self", ".", "smalle...
38.78125
0.001572
def modify_process_property(self, key, value, pid=None): ''' modify_process_property(self, key, value, pid=None) Modify process output property. Please note that the process property key provided must be declared as an output property in the relevant service specification. :Par...
[ "def", "modify_process_property", "(", "self", ",", "key", ",", "value", ",", "pid", "=", "None", ")", ":", "pid", "=", "self", ".", "_get_pid", "(", "pid", ")", "request_data", "=", "{", "\"key\"", ":", "key", ",", "\"value\"", ":", "value", "}", "r...
44.363636
0.008024