text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def from_missing_values(cls, is_leap_year=False): """Initalize an EPW object with all data missing or empty. Note that this classmethod is intended for workflows where one plans to set all of the data within the EPW object. The EPW file written out from the use of this method is not si...
[ "def", "from_missing_values", "(", "cls", ",", "is_leap_year", "=", "False", ")", ":", "# Initialize the class with all data missing", "epw_obj", "=", "cls", "(", "None", ")", "epw_obj", ".", "_is_leap_year", "=", "is_leap_year", "epw_obj", ".", "_location", "=", ...
42.797297
18.513514
def loadTFRecords(sc, input_dir, binary_features=[]): """Load TFRecords from disk into a Spark DataFrame. This will attempt to automatically convert the tf.train.Example features into Spark DataFrame columns of equivalent types. Note: TensorFlow represents both strings and binary types as tf.train.BytesList, an...
[ "def", "loadTFRecords", "(", "sc", ",", "input_dir", ",", "binary_features", "=", "[", "]", ")", ":", "import", "tensorflow", "as", "tf", "tfr_rdd", "=", "sc", ".", "newAPIHadoopFile", "(", "input_dir", ",", "\"org.tensorflow.hadoop.io.TFRecordFileInputFormat\"", ...
39.078947
27.763158
def dump(self,indent='',depth=0): """Diagnostic method for listing out the contents of a C{ParseResults}. Accepts an optional C{indent} argument so that this string can be embedded in a nested display of other data.""" out = [] out.append( indent+_ustr(self.asList()) )...
[ "def", "dump", "(", "self", ",", "indent", "=", "''", ",", "depth", "=", "0", ")", ":", "out", "=", "[", "]", "out", ".", "append", "(", "indent", "+", "_ustr", "(", "self", ".", "asList", "(", ")", ")", ")", "keys", "=", "self", ".", "items"...
39.1
13.65
def rotation_filename(self, default_name: str) -> str: """ Modify the filename of a log file when rotating. This is provided so that a custom filename can be provided. :param default_name: The default name for the log file. """ if self.namer is None: return ...
[ "def", "rotation_filename", "(", "self", ",", "default_name", ":", "str", ")", "->", "str", ":", "if", "self", ".", "namer", "is", "None", ":", "return", "default_name", "return", "self", ".", "namer", "(", "default_name", ")" ]
30.166667
18.333333
def get_all(self, fields=list(), limit=None, order_by=list(), offset=None): """DEPRECATED - see get_multiple()""" warnings.warn("get_all() is deprecated, please use get_multiple() instead", DeprecationWarning) return self.get_multiple(fields, limit, order_by, offset)
[ "def", "get_all", "(", "self", ",", "fields", "=", "list", "(", ")", ",", "limit", "=", "None", ",", "order_by", "=", "list", "(", ")", ",", "offset", "=", "None", ")", ":", "warnings", ".", "warn", "(", "\"get_all() is deprecated, please use get_multiple(...
72
30.75
def findAll(self, strSeq) : """Same as find but returns a list of all occurences""" arr = self.encode(strSeq) lst = [] lst = self._kmp_find(arr[0], self, lst) return lst
[ "def", "findAll", "(", "self", ",", "strSeq", ")", ":", "arr", "=", "self", ".", "encode", "(", "strSeq", ")", "lst", "=", "[", "]", "lst", "=", "self", ".", "_kmp_find", "(", "arr", "[", "0", "]", ",", "self", ",", "lst", ")", "return", "lst" ...
31.333333
16.5
def _comparator_eq(filter_value, tested_value): """ Tests if the filter value is equal to the tested value """ if isinstance(tested_value, ITERABLES): # Convert the list items to strings for value in tested_value: # Try with the string conversion if not is_string(...
[ "def", "_comparator_eq", "(", "filter_value", ",", "tested_value", ")", ":", "if", "isinstance", "(", "tested_value", ",", "ITERABLES", ")", ":", "# Convert the list items to strings", "for", "value", "in", "tested_value", ":", "# Try with the string conversion", "if", ...
29.956522
11.347826
def get_date(date): """ Get the date from a value that could be a date object or a string. :param date: The date object or string. :returns: The date object. """ if type(date) is str: return datetime.strptime(date, '%Y-%m-%d').date() else: return date
[ "def", "get_date", "(", "date", ")", ":", "if", "type", "(", "date", ")", "is", "str", ":", "return", "datetime", ".", "strptime", "(", "date", ",", "'%Y-%m-%d'", ")", ".", "date", "(", ")", "else", ":", "return", "date" ]
23.833333
19
def _install_signal_handlers(self): """ Installs signal handlers for handling SIGINT and SIGTERM gracefully. """ def stop(signum, frame): """ Register scheduler's death and exit and remove previously acquired lock and exit. """ ...
[ "def", "_install_signal_handlers", "(", "self", ")", ":", "def", "stop", "(", "signum", ",", "frame", ")", ":", "\"\"\"\n Register scheduler's death and exit\n and remove previously acquired lock and exit.\n \"\"\"", "self", ".", "log", ".", "in...
30.111111
11.777778
def is_inside_bounds(value, params): """Return ``True`` if ``value`` is contained in ``params``. This method supports broadcasting in the sense that for ``params.ndim >= 2``, if more than one value is given, the inputs are broadcast against each other. Parameters ---------- value : `array-...
[ "def", "is_inside_bounds", "(", "value", ",", "params", ")", ":", "if", "value", "in", "params", ":", "# Single parameter", "return", "True", "else", ":", "if", "params", ".", "ndim", "==", "1", ":", "return", "params", ".", "contains_all", "(", "np", "....
30.365385
20.365385
def shift(self, time: int) -> 'Interval': """Return a new interval shifted by `time` from self Args: time: time to be shifted Returns: Interval: interval shifted by `time` """ return Interval(self._begin + time, self._end + time)
[ "def", "shift", "(", "self", ",", "time", ":", "int", ")", "->", "'Interval'", ":", "return", "Interval", "(", "self", ".", "_begin", "+", "time", ",", "self", ".", "_end", "+", "time", ")" ]
28.6
16.5
def scons_subst_once(strSubst, env, key): """Perform single (non-recursive) substitution of a single construction variable keyword. This is used when setting a variable when copying or overriding values in an Environment. We want to capture (expand) the old value before we override it, so people c...
[ "def", "scons_subst_once", "(", "strSubst", ",", "env", ",", "key", ")", ":", "if", "isinstance", "(", "strSubst", ",", "str", ")", "and", "strSubst", ".", "find", "(", "'$'", ")", "<", "0", ":", "return", "strSubst", "matchlist", "=", "[", "'$'", "+...
31.8
16.577778
def insert_into_channel(api_key, api_secret, channel_key, video_key, **kwargs): """ Function which inserts video into a channel/playlist. :param api_key: <string> JWPlatform api-key :param api_secret: <string> JWPlatform shared-secret :param channel_key: <string> Key of the channel to which add a v...
[ "def", "insert_into_channel", "(", "api_key", ",", "api_secret", ",", "channel_key", ",", "video_key", ",", "*", "*", "kwargs", ")", ":", "jwplatform_client", "=", "jwplatform", ".", "Client", "(", "api_key", ",", "api_secret", ")", "logging", ".", "info", "...
49.5
24.954545
def from_user_config(cls): """ Initialize the :class:`TaskManager` from the YAML file 'manager.yaml'. Search first in the working directory and then in the AbiPy configuration directory. Raises: RuntimeError if file is not found. """ global _USER_CONFIG_TASKM...
[ "def", "from_user_config", "(", "cls", ")", ":", "global", "_USER_CONFIG_TASKMANAGER", "if", "_USER_CONFIG_TASKMANAGER", "is", "not", "None", ":", "return", "_USER_CONFIG_TASKMANAGER", "# Try in the current directory then in user configuration directory.", "path", "=", "os", ...
43.666667
21.37037
def resource_op_defaults_to(name, op_default, value, extra_args=None, cibname=None): ''' Ensure a resource operation default in the cluster is set to a given value Should be run on one cluster node only (there may be races) Can only be run on a node with a functional pacemaker/corosync name ...
[ "def", "resource_op_defaults_to", "(", "name", ",", "op_default", ",", "value", ",", "extra_args", "=", "None", ",", "cibname", "=", "None", ")", ":", "return", "_item_present", "(", "name", "=", "name", ",", "item", "=", "'resource'", ",", "item_id", "=",...
35.945946
22.27027
def metrics(self, *metrics): """ Add a list of Metric ingredients to the query. These can either be Metric objects or strings representing metrics on the shelf. The Metric expression will be added to the query's select statement. The metric value is a property of each row of the result....
[ "def", "metrics", "(", "self", ",", "*", "metrics", ")", ":", "for", "m", "in", "metrics", ":", "self", ".", "_cauldron", ".", "use", "(", "self", ".", "_shelf", ".", "find", "(", "m", ",", "Metric", ")", ")", "self", ".", "dirty", "=", "True", ...
40.25
19.3125
def _getThread(self, given_thread_id=None, given_thread_type=None): """ Checks if thread ID is given, checks if default is set and returns correct values :raises ValueError: If thread ID is not given and there is no default :return: Thread ID and thread type :rtype: tuple ...
[ "def", "_getThread", "(", "self", ",", "given_thread_id", "=", "None", ",", "given_thread_type", "=", "None", ")", ":", "if", "given_thread_id", "is", "None", ":", "if", "self", ".", "_default_thread_id", "is", "not", "None", ":", "return", "self", ".", "_...
41.066667
20.133333
def normaliseURL(url): """Normalising - strips and leading or trailing whitespace, - replaces HTML entities and character references, - removes any leading empty segments to avoid breaking urllib2. """ url = unicode_safe(url).strip() # XXX: brutal hack url = unescape(url) pu = list(...
[ "def", "normaliseURL", "(", "url", ")", ":", "url", "=", "unicode_safe", "(", "url", ")", ".", "strip", "(", ")", "# XXX: brutal hack", "url", "=", "unescape", "(", "url", ")", "pu", "=", "list", "(", "urlparse", "(", "url", ")", ")", "segments", "="...
29.047619
13.857143
def clone_git_repo(repo_url): """ input: repo_url output: path of the cloned repository steps: 1. clone the repo 2. parse 'site' into for templating assumptions: repo_url = "git@github.com:littleq0903/django-deployer-template-openshift-experiment.git" repo_local_loca...
[ "def", "clone_git_repo", "(", "repo_url", ")", ":", "REPO_PREFIX", "=", "\"djangodeployer-cache-\"", "REPO_POSTFIX_UUID", "=", "str", "(", "uuid", ".", "uuid4", "(", ")", ")", ".", "split", "(", "'-'", ")", "[", "-", "1", "]", "REPO_CACHE_NAME", "=", "REPO...
37.842105
21.421053
def fetch_logs(self, max_rows=1024, orientation=None): """Mocked. Retrieve the logs produced by the execution of the query. Can be called multiple times to fetch the logs produced after the previous call. :returns: list<str> :raises: ``ProgrammingError`` when no query has been started...
[ "def", "fetch_logs", "(", "self", ",", "max_rows", "=", "1024", ",", "orientation", "=", "None", ")", ":", "from", "pyhive", "import", "hive", "from", "TCLIService", "import", "ttypes", "from", "thrift", "import", "Thrift", "orientation", "=", "orientation", ...
40.146341
14.658537
def highlightBlock(self, text): """ Highlights a block of text. Please do not override, this method. Instead you should implement :func:`spyder.utils.syntaxhighplighters.SyntaxHighlighter.highlight_block`. :param text: text to highlight. """ self.highligh...
[ "def", "highlightBlock", "(", "self", ",", "text", ")", ":", "self", ".", "highlight_block", "(", "text", ")", "# Process blocks for fold detection\r", "current_block", "=", "self", ".", "currentBlock", "(", ")", "previous_block", "=", "self", ".", "_find_prev_non...
40.777778
16.111111
def subtract(df, new_column, column_1, column_2): """ DEPRECATED - use `formula` instead """ return _basic_math_operation(df, new_column, column_1, column_2, op='sub')
[ "def", "subtract", "(", "df", ",", "new_column", ",", "column_1", ",", "column_2", ")", ":", "return", "_basic_math_operation", "(", "df", ",", "new_column", ",", "column_1", ",", "column_2", ",", "op", "=", "'sub'", ")" ]
36
9.6
def _write_plan(self, stream): """Write the plan line to the stream. If we have a plan and have not yet written it out, write it to the given stream. """ if self.plan is not None: if not self._plan_written: print("1..{0}".format(self.plan), file=strea...
[ "def", "_write_plan", "(", "self", ",", "stream", ")", ":", "if", "self", ".", "plan", "is", "not", "None", ":", "if", "not", "self", ".", "_plan_written", ":", "print", "(", "\"1..{0}\"", ".", "format", "(", "self", ".", "plan", ")", ",", "file", ...
35.1
12.9
def highlight_occurences(editor): """ Highlights given editor current line. :param editor: Document editor. :type editor: QWidget :return: Method success. :rtype: bool """ format = editor.language.theme.get("accelerator.occurence") if not format: return False extra_sel...
[ "def", "highlight_occurences", "(", "editor", ")", ":", "format", "=", "editor", ".", "language", ".", "theme", ".", "get", "(", "\"accelerator.occurence\"", ")", "if", "not", "format", ":", "return", "False", "extra_selections", "=", "editor", ".", "extraSele...
36.771429
18.428571
def get_shape(bin_edges, sid): """ :returns: the shape of the disaggregation matrix for the given site, of form (#mags-1, #dists-1, #lons-1, #lats-1, #eps-1) """ mag_bins, dist_bins, lon_bins, lat_bins, eps_bins = bin_edges return (len(mag_bins) - 1, len(dist_bins) - 1, l...
[ "def", "get_shape", "(", "bin_edges", ",", "sid", ")", ":", "mag_bins", ",", "dist_bins", ",", "lon_bins", ",", "lat_bins", ",", "eps_bins", "=", "bin_edges", "return", "(", "len", "(", "mag_bins", ")", "-", "1", ",", "len", "(", "dist_bins", ")", "-",...
41.888889
17.444444
def create_post(self, path, **kw): """Create a new post.""" content = kw.pop('content', None) onefile = kw.pop('onefile', False) # is_page is not used by create_post as of now. kw.pop('is_page', False) metadata = {} metadata.update(self.default_metadata) m...
[ "def", "create_post", "(", "self", ",", "path", ",", "*", "*", "kw", ")", ":", "content", "=", "kw", ".", "pop", "(", "'content'", ",", "None", ")", "onefile", "=", "kw", ".", "pop", "(", "'onefile'", ",", "False", ")", "# is_page is not used by create...
40.1875
11.9375
def view_meta_admonition(admonition_name, name=None): """List all found admonition from all the rst files found in directory. view_meta_admonition is called by the 'meta' url: /__XXXXXXX__ where XXXXXXX represents and admonition name, like: * todo * warning * danger * ... .. note:: th...
[ "def", "view_meta_admonition", "(", "admonition_name", ",", "name", "=", "None", ")", ":", "print", "(", "\"meta admo: %s - %s\"", "%", "(", "admonition_name", ",", "name", ")", ")", "admonition", "=", "None", "if", "admonition_name", "==", "'todo'", ":", "adm...
37.459016
16.065574
def dissect(self, data): """ Dissect the field. :param bytes data: The data to extract the field value from :return: The rest of the data not used to dissect the field value :rtype: bytes """ size = struct.calcsize("B") if len(data) < size: r...
[ "def", "dissect", "(", "self", ",", "data", ")", ":", "size", "=", "struct", ".", "calcsize", "(", "\"B\"", ")", "if", "len", "(", "data", ")", "<", "size", ":", "raise", "NotEnoughData", "(", "\"Not enough data to decode field '%s' value\"", "%", "self", ...
32.541667
20.625
def filter(self, search): """ Add a ``post_filter`` to the search request narrowing the results based on the facet filters. """ if not self._filters: return search post_filter = MatchAll() for f in itervalues(self._filters): post_filter &=...
[ "def", "filter", "(", "self", ",", "search", ")", ":", "if", "not", "self", ".", "_filters", ":", "return", "search", "post_filter", "=", "MatchAll", "(", ")", "for", "f", "in", "itervalues", "(", "self", ".", "_filters", ")", ":", "post_filter", "&=",...
29.833333
13.333333
def block_jids(self, jids_to_block): """ Add the JIDs in the sequence `jids_to_block` to the client's blocklist. """ yield from self._check_for_blocking() if not jids_to_block: return cmd = blocking_xso.BlockCommand(jids_to_block) iq = aioxmp...
[ "def", "block_jids", "(", "self", ",", "jids_to_block", ")", ":", "yield", "from", "self", ".", "_check_for_blocking", "(", ")", "if", "not", "jids_to_block", ":", "return", "cmd", "=", "blocking_xso", ".", "BlockCommand", "(", "jids_to_block", ")", "iq", "=...
26.4375
15.8125
def filter_significance(diff, significance): """ Prune any changes in the patch which are due to numeric changes less than this level of significance. """ changed = diff['changed'] # remove individual field changes that are significant reduced = [{'key': delta['key'], 'field...
[ "def", "filter_significance", "(", "diff", ",", "significance", ")", ":", "changed", "=", "diff", "[", "'changed'", "]", "# remove individual field changes that are significant", "reduced", "=", "[", "{", "'key'", ":", "delta", "[", "'key'", "]", ",", "'fields'", ...
33.8
19.5
def get_markov_blanket(self, node): """ Returns a markov blanket for a random variable. In the case of Bayesian Networks, the markov blanket is the set of node's parents, its children and its children's other parents. Returns ------- list(blanket_nodes): List of ...
[ "def", "get_markov_blanket", "(", "self", ",", "node", ")", ":", "children", "=", "self", ".", "get_children", "(", "node", ")", "parents", "=", "self", ".", "get_parents", "(", "node", ")", "blanket_nodes", "=", "children", "+", "parents", "for", "child_n...
37.9375
17.9375
def add_interceptor(self, *interceptors): """ Adds one or multiple HTTP traffic interceptors to the current mocking engine. Interceptors are typically HTTP client specific wrapper classes that implements the pook interceptor interface. Arguments: interceptor...
[ "def", "add_interceptor", "(", "self", ",", "*", "interceptors", ")", ":", "for", "interceptor", "in", "interceptors", ":", "self", ".", "interceptors", ".", "append", "(", "interceptor", "(", "self", ".", "engine", ")", ")" ]
35.461538
18.230769
def _convert_connected_app(self): """Convert Connected App to service""" if self.services and "connected_app" in self.services: # already a service return connected_app = self.get_connected_app() if not connected_app: # not configured retur...
[ "def", "_convert_connected_app", "(", "self", ")", ":", "if", "self", ".", "services", "and", "\"connected_app\"", "in", "self", ".", "services", ":", "# already a service", "return", "connected_app", "=", "self", ".", "get_connected_app", "(", ")", "if", "not",...
40.083333
18.083333
def phonetic_i_umlaut(sound: Vowel) -> Vowel: """ >>> umlaut_a = OldNorsePhonology.phonetic_i_umlaut(a) >>> umlaut_a.ipar 'ɛ' >>> umlaut_au = OldNorsePhonology.phonetic_i_umlaut(DIPHTHONGS_IPA_class["au"]) >>> umlaut_au.ipar 'ɐy' :param sound: :r...
[ "def", "phonetic_i_umlaut", "(", "sound", ":", "Vowel", ")", "->", "Vowel", ":", "if", "sound", ".", "is_equal", "(", "a", ")", ":", "return", "ee", "elif", "sound", ".", "is_equal", "(", "a", ".", "lengthen", "(", ")", ")", ":", "return", "ee", "....
29.666667
15.444444
def content_type(self) -> ContentType: """Override superclass method.""" if self._ctype: return self._ctype return (ContentType.config if self.parent.config else ContentType.nonconfig)
[ "def", "content_type", "(", "self", ")", "->", "ContentType", ":", "if", "self", ".", "_ctype", ":", "return", "self", ".", "_ctype", "return", "(", "ContentType", ".", "config", "if", "self", ".", "parent", ".", "config", "else", "ContentType", ".", "no...
38.5
8.666667
def getitem(self, index, context=None): """Return the inference of a subscript. This is basically looking up the method in the metaclass and calling it. :returns: The inferred value of a subscript to this class. :rtype: NodeNG :raises AstroidTypeError: If this class does not d...
[ "def", "getitem", "(", "self", ",", "index", ",", "context", "=", "None", ")", ":", "try", ":", "methods", "=", "dunder_lookup", ".", "lookup", "(", "self", ",", "\"__getitem__\"", ")", "except", "exceptions", ".", "AttributeInferenceError", "as", "exc", "...
37.307692
24.153846
def get_bool(self, key, default=None): u""" Возвращает значение, приведенное к булеву """ return self.get_converted( key, ConversionTypeEnum.BOOL, default=default)
[ "def", "get_bool", "(", "self", ",", "key", ",", "default", "=", "None", ")", ":", "return", "self", ".", "get_converted", "(", "key", ",", "ConversionTypeEnum", ".", "BOOL", ",", "default", "=", "default", ")" ]
33.666667
5.833333
def QA_util_to_datetime(time): """ 字符串 '2018-01-01' 转变成 datatime 类型 :param time: 字符串str -- 格式必须是 2018-01-01 ,长度10 :return: 类型datetime.datatime """ if len(str(time)) == 10: _time = '{} 00:00:00'.format(time) elif len(str(time)) == 19: _time = str(time) else: QA_ut...
[ "def", "QA_util_to_datetime", "(", "time", ")", ":", "if", "len", "(", "str", "(", "time", ")", ")", "==", "10", ":", "_time", "=", "'{} 00:00:00'", ".", "format", "(", "time", ")", "elif", "len", "(", "str", "(", "time", ")", ")", "==", "19", ":...
32.769231
11.538462
def sense_dep(self, target): """Sense for an active DEP Target is not supported. The device only supports passive activation via sense_tta/sense_ttf. """ message = "{device} does not support sense for active DEP Target" raise nfc.clf.UnsupportedTargetError(message.format(device=...
[ "def", "sense_dep", "(", "self", ",", "target", ")", ":", "message", "=", "\"{device} does not support sense for active DEP Target\"", "raise", "nfc", ".", "clf", ".", "UnsupportedTargetError", "(", "message", ".", "format", "(", "device", "=", "self", ")", ")" ]
45.714286
19.714286
def class_can_run_parallel(test_class: unittest.TestSuite) -> bool: """ Checks if a given class of tests can be run in parallel or not :param test_class: the class to run :return: True if te class can be run in parallel, False otherwise """ for test_case in test_class: ...
[ "def", "class_can_run_parallel", "(", "test_class", ":", "unittest", ".", "TestSuite", ")", "->", "bool", ":", "for", "test_case", "in", "test_class", ":", "return", "not", "getattr", "(", "test_case", ",", "\"__no_parallel__\"", ",", "False", ")" ]
42
18.222222
def is_christmas_period(): """Is this the christmas period?""" now = datetime.date.today() if now.month != 12: return False if now.day < 15: return False if now.day > 27: return False return True
[ "def", "is_christmas_period", "(", ")", ":", "now", "=", "datetime", ".", "date", ".", "today", "(", ")", "if", "now", ".", "month", "!=", "12", ":", "return", "False", "if", "now", ".", "day", "<", "15", ":", "return", "False", "if", "now", ".", ...
23.4
16.5
def wait(self): """ Wait until all in progress and queued items are processed """ self._wait_called = True while self.tracked_coordinator_count() > 0 or \ self.waiting_coordinator_count() > 0: time.sleep(1) super(AsperaTransferCoordinatorController, self)....
[ "def", "wait", "(", "self", ")", ":", "self", ".", "_wait_called", "=", "True", "while", "self", ".", "tracked_coordinator_count", "(", ")", ">", "0", "or", "self", ".", "waiting_coordinator_count", "(", ")", ">", "0", ":", "time", ".", "sleep", "(", "...
44.125
13.75
def load_config_from_file(app, filepath): """Helper function to load config from a specified file""" try: app.config.from_pyfile(filepath) return True except IOError: # TODO: Can we print to sys.stderr in production? Should this go to # logs instead? print("Did not fi...
[ "def", "load_config_from_file", "(", "app", ",", "filepath", ")", ":", "try", ":", "app", ".", "config", ".", "from_pyfile", "(", "filepath", ")", "return", "True", "except", "IOError", ":", "# TODO: Can we print to sys.stderr in production? Should this go to", "# log...
41.8
21.8
def isPythonFile(filename): """Return True if filename points to a Python file.""" if filename.endswith('.py'): return True # Avoid obvious Emacs backup files if filename.endswith("~"): return False max_bytes = 128 try: with open(filename, 'rb') as f: text ...
[ "def", "isPythonFile", "(", "filename", ")", ":", "if", "filename", ".", "endswith", "(", "'.py'", ")", ":", "return", "True", "# Avoid obvious Emacs backup files", "if", "filename", ".", "endswith", "(", "\"~\"", ")", ":", "return", "False", "max_bytes", "=",...
23.952381
17.761905
def _validate_customer_service(self): """ Validate input parameters if customer service is on then create directory for tarball files with correct premissions for user and group. """ direc = self.customer_service_dir if not direc.exists: mode = 0o750 ...
[ "def", "_validate_customer_service", "(", "self", ")", ":", "direc", "=", "self", ".", "customer_service_dir", "if", "not", "direc", ".", "exists", ":", "mode", "=", "0o750", "print", "(", "\"Creating customer_service_dir %s with mode %s\"", "%", "(", "direc", ","...
41.142857
18.714286
def start(self): """Start listener in a background thread Returns: address of the Server as a tuple of (host, port) """ server_sock = self.start_listening_socket() # hostname may not be resolvable but IP address probably will be host = self.get_server_ip() port = server_sock.getsockn...
[ "def", "start", "(", "self", ")", ":", "server_sock", "=", "self", ".", "start_listening_socket", "(", ")", "# hostname may not be resolvable but IP address probably will be", "host", "=", "self", ".", "get_server_ip", "(", ")", "port", "=", "server_sock", ".", "get...
29.487805
19.463415
def dcshift(self, shift=0.0): '''Apply a DC shift to the audio. Parameters ---------- shift : float Amount to shift audio between -2 and 2. (Audio is between -1 and 1) See Also -------- highpass ''' if not is_number(shift) or shift <...
[ "def", "dcshift", "(", "self", ",", "shift", "=", "0.0", ")", ":", "if", "not", "is_number", "(", "shift", ")", "or", "shift", "<", "-", "2", "or", "shift", ">", "2", ":", "raise", "ValueError", "(", "'shift must be a number between -2 and 2.'", ")", "ef...
26.285714
24
def values(self, axis): """ Returns the values of the given axis from all the datasets within this chart. :param axis | <str> :return [<variant>, ..] """ output = [] for dataset in self.datasets(): output +...
[ "def", "values", "(", "self", ",", "axis", ")", ":", "output", "=", "[", "]", "for", "dataset", "in", "self", ".", "datasets", "(", ")", ":", "output", "+=", "dataset", ".", "values", "(", "axis", ")", "return", "output" ]
25.857143
15.428571
def pick_sdf(filename, directory=None): """Returns a full path to the chosen SDF file. The supplied file is not expected to contain a recognised SDF extension, this is added automatically. If a file with the extension `.sdf.gz` or `.sdf` is found the path to it (excluding the extension) is returned....
[ "def", "pick_sdf", "(", "filename", ",", "directory", "=", "None", ")", ":", "if", "directory", "is", "None", ":", "directory", "=", "utils", ".", "get_undecorated_calling_module", "(", ")", "# If the 'cwd' is not '/output' (which indicates we're in a Container)", "# th...
42.580645
15.83871
def send_identity(self): """ Send the identity of the service. """ service_name = {'service_name': self.messaging._service_name} service_name = _json.dumps(service_name).encode('utf8') identify_frame = (b'', b'IDENT', _...
[ "def", "send_identity", "(", "self", ")", ":", "service_name", "=", "{", "'service_name'", ":", "self", ".", "messaging", ".", "_service_name", "}", "service_name", "=", "_json", ".", "dumps", "(", "service_name", ")", ".", "encode", "(", "'utf8'", ")", "i...
36
17.92
def element_as_json(name): """ Get specified element json data by name :param name: name of element :return: json data representing element, else None """ if name: element = fetch_json_by_name(name) if element.json: return element.json
[ "def", "element_as_json", "(", "name", ")", ":", "if", "name", ":", "element", "=", "fetch_json_by_name", "(", "name", ")", "if", "element", ".", "json", ":", "return", "element", ".", "json" ]
27.5
13.1
def parse_block(lines, header=False): # type: (List[str], bool) -> List[str] """Parse and return a single block, popping off the start of `lines`. If parsing a header block, we stop after we reach a line that is not a comment. Otherwise, we stop after reaching an empty line. :param lines: list of lin...
[ "def", "parse_block", "(", "lines", ",", "header", "=", "False", ")", ":", "# type: (List[str], bool) -> List[str]", "block_lines", "=", "[", "]", "while", "lines", "and", "lines", "[", "0", "]", "and", "(", "not", "header", "or", "lines", "[", "0", "]", ...
42
20.142857
def add_file(self, f): """Add a partition identity as a child of a dataset identity.""" if not self.files: self.files = set() self.files.add(f) self.locations.set(f.type_)
[ "def", "add_file", "(", "self", ",", "f", ")", ":", "if", "not", "self", ".", "files", ":", "self", ".", "files", "=", "set", "(", ")", "self", ".", "files", ".", "add", "(", "f", ")", "self", ".", "locations", ".", "set", "(", "f", ".", "typ...
23.333333
20.222222
def bulk_refresh(self): """ Refreshes all refreshable tokens in the queryset. Deletes any tokens which fail to refresh. Deletes any tokens which are expired and cannot refresh. Excludes tokens for which the refresh was incomplete for other reasons. """ session = O...
[ "def", "bulk_refresh", "(", "self", ")", ":", "session", "=", "OAuth2Session", "(", "app_settings", ".", "ESI_SSO_CLIENT_ID", ")", "auth", "=", "requests", ".", "auth", ".", "HTTPBasicAuth", "(", "app_settings", ".", "ESI_SSO_CLIENT_ID", ",", "app_settings", "."...
50
20.190476
def get_implementation(cls, force: bool = False) -> AxesHandler: """ Fetch and initialize configured handler implementation and memoize it to avoid reinitialization. This method is re-entrant and can be called multiple times from e.g. Django application loader. """ if force or ...
[ "def", "get_implementation", "(", "cls", ",", "force", ":", "bool", "=", "False", ")", "->", "AxesHandler", ":", "if", "force", "or", "not", "cls", ".", "implementation", ":", "cls", ".", "implementation", "=", "import_string", "(", "settings", ".", "AXES_...
44
27.2
def createNetwork(dataSource): """Create and initialize a network.""" with open(_PARAMS_PATH, "r") as f: modelParams = yaml.safe_load(f)["modelParams"] # Create a network that will hold the regions. network = Network() # Add a sensor region. network.addRegion("sensor", "py.RecordSensor", '{}') # Se...
[ "def", "createNetwork", "(", "dataSource", ")", ":", "with", "open", "(", "_PARAMS_PATH", ",", "\"r\"", ")", "as", "f", ":", "modelParams", "=", "yaml", ".", "safe_load", "(", "f", ")", "[", "\"modelParams\"", "]", "# Create a network that will hold the regions....
37.05
22.15
def adapt_logger(logger): """ Adapt our custom logger.BaseLogger object into a standard logging.Logger object. Adaptations are: - NoOpLogger turns into a logger with a single NullHandler. - SimpleLogger turns into a logger with a StreamHandler and level. Args: logger: Possibly a logger.BaseLogger,...
[ "def", "adapt_logger", "(", "logger", ")", ":", "if", "isinstance", "(", "logger", ",", "logging", ".", "Logger", ")", ":", "return", "logger", "# Use the standard python logger created by these classes.", "if", "isinstance", "(", "logger", ",", "(", "SimpleLogger",...
29.26087
24.826087
def mmGetPlotStability(self, title="Stability", showReset=False, resetShading=0.25): """ Returns plot of the overlap metric between union SDRs within a sequence. @param title an optional title for the figure @return (Plot) plot """ plot = Plot(self, title) self._mmCo...
[ "def", "mmGetPlotStability", "(", "self", ",", "title", "=", "\"Stability\"", ",", "showReset", "=", "False", ",", "resetShading", "=", "0.25", ")", ":", "plot", "=", "Plot", "(", "self", ",", "title", ")", "self", ".", "_mmComputeSequenceRepresentationData", ...
38.444444
12.111111
def AIC(N, rho, k): r"""Akaike Information Criterion :param rho: rho at order k :param N: sample size :param k: AR order. If k is the AR order and N the size of the sample, then Akaike criterion is .. math:: AIC(k) = \log(\rho_k) + 2\frac{k+1}{N} :: AIC(64, [0.5,0.3,0.2], [1,2,3...
[ "def", "AIC", "(", "N", ",", "rho", ",", "k", ")", ":", "from", "numpy", "import", "log", ",", "array", "#k+1 #todo check convention. agrees with octave", "res", "=", "N", "*", "log", "(", "array", "(", "rho", ")", ")", "+", "2.", "*", "(", "array", ...
23.045455
22.181818
def get_json(self, force=False, silent=False, cache=True): """Parse :attr:`data` as JSON. If the mimetype does not indicate JSON (:mimetype:`application/json`, see :meth:`is_json`), this returns ``None``. If parsing fails, :meth:`on_json_loading_failed` is called and it...
[ "def", "get_json", "(", "self", ",", "force", "=", "False", ",", "silent", "=", "False", ",", "cache", "=", "True", ")", ":", "if", "cache", "and", "self", ".", "_cached_json", "[", "silent", "]", "is", "not", "Ellipsis", ":", "return", "self", ".", ...
31.590909
20.795455
def _cfg(key, default=None): ''' Return the requested value from the aws_kms key in salt configuration. If it's not set, return the default. ''' root_cfg = __salt__.get('config.get', __opts__.get) kms_cfg = root_cfg('aws_kms', {}) return kms_cfg.get(key, default)
[ "def", "_cfg", "(", "key", ",", "default", "=", "None", ")", ":", "root_cfg", "=", "__salt__", ".", "get", "(", "'config.get'", ",", "__opts__", ".", "get", ")", "kms_cfg", "=", "root_cfg", "(", "'aws_kms'", ",", "{", "}", ")", "return", "kms_cfg", "...
31.555556
19.333333
def cli_default_perms(self, *args): """Show default permissions for all schemata""" for key, item in schemastore.items(): # self.log(item, pretty=True) if item['schema'].get('no_perms', False): self.log('Schema without permissions:', key) continue...
[ "def", "cli_default_perms", "(", "self", ",", "*", "args", ")", ":", "for", "key", ",", "item", "in", "schemastore", ".", "items", "(", ")", ":", "# self.log(item, pretty=True)", "if", "item", "[", "'schema'", "]", ".", "get", "(", "'no_perms'", ",", "Fa...
40.565217
15.913043
def camelise(text, capital_first=True): """Convert lower_underscore to CamelCase.""" def camelcase(): if not capital_first: yield str.lower while True: yield str.capitalize if istype(text, 'unicode'): text = text.encode('utf8') c = camelcase() return...
[ "def", "camelise", "(", "text", ",", "capital_first", "=", "True", ")", ":", "def", "camelcase", "(", ")", ":", "if", "not", "capital_first", ":", "yield", "str", ".", "lower", "while", "True", ":", "yield", "str", ".", "capitalize", "if", "istype", "(...
28.230769
16.846154
def acquisition_function(self,x): """ Takes an acquisition and weights it so the domain and cost are taken into account. """ f_acqu = self._compute_acq(x) cost_x, _ = self.cost_withGradients(x) return -(f_acqu*self.space.indicator_constraints(x))/cost_x
[ "def", "acquisition_function", "(", "self", ",", "x", ")", ":", "f_acqu", "=", "self", ".", "_compute_acq", "(", "x", ")", "cost_x", ",", "_", "=", "self", ".", "cost_withGradients", "(", "x", ")", "return", "-", "(", "f_acqu", "*", "self", ".", "spa...
42.142857
13.285714
def _prepare_init_params_from_job_description(cls, job_details, model_channel_name=None): """Convert the job description to init params that can be handled by the class constructor Args: job_details: the returned job details from a describe_training_job API call. model_channel_n...
[ "def", "_prepare_init_params_from_job_description", "(", "cls", ",", "job_details", ",", "model_channel_name", "=", "None", ")", ":", "init_params", "=", "super", "(", "RLEstimator", ",", "cls", ")", ".", "_prepare_init_params_from_job_description", "(", "job_details", ...
43.378378
27.621622
def references(self): """ list: External links, or references, listed anywhere on the \ MediaWiki page Note: Not settable Note May include external links within page that are not \ technically cited anywhere """ if...
[ "def", "references", "(", "self", ")", ":", "if", "self", ".", "_references", "is", "None", ":", "self", ".", "_references", "=", "list", "(", ")", "self", ".", "__pull_combined_properties", "(", ")", "return", "self", ".", "_references" ]
37.583333
11.333333
def trim_data(xmin, xmax, xdata, *args): """ Removes all the data except that in which xdata is between xmin and xmax. This does not mutilate the input arrays, and additional arrays can be supplied via args (provided they match xdata in shape) xmin and xmax can be None """ # make sure it'...
[ "def", "trim_data", "(", "xmin", ",", "xmax", ",", "xdata", ",", "*", "args", ")", ":", "# make sure it's a numpy array", "if", "not", "isinstance", "(", "xdata", ",", "_n", ".", "ndarray", ")", ":", "xdata", "=", "_n", ".", "array", "(", "xdata", ")",...
29.1
20.5
def read_binary_matrix(filename): """Reads and returns binary formatted matrix stored in filename. The file format is described on the data set page: https://cs.nyu.edu/~ylclab/data/norb-v1.0-small/ Args: filename: String with path to the file. Returns: Numpy array contained in the file. """ wi...
[ "def", "read_binary_matrix", "(", "filename", ")", ":", "with", "tf", ".", "io", ".", "gfile", ".", "GFile", "(", "filename", ",", "\"rb\"", ")", "as", "f", ":", "s", "=", "f", ".", "read", "(", ")", "# Data is stored in little-endian byte order.", "int32_...
36.418605
22.627907
def _step5(self, word): """step5() removes a final -e if m() > 1, and changes -ll to -l if m() > 1. """ if word[-1] == 'e': a = self._m(word, len(word)-1) if a > 1 or (a == 1 and not self._cvc(word, len(word)-2)): word = word[:-1] if word.e...
[ "def", "_step5", "(", "self", ",", "word", ")", ":", "if", "word", "[", "-", "1", "]", "==", "'e'", ":", "a", "=", "self", ".", "_m", "(", "word", ",", "len", "(", "word", ")", "-", "1", ")", "if", "a", ">", "1", "or", "(", "a", "==", "...
34
16.083333
def get_reqv(self): """ :returns: an instance of class:`RjbEquivalent` if reqv_hdf5 is set """ if 'reqv' not in self.inputs: return return {key: valid.RjbEquivalent(value) for key, value in self.inputs['reqv'].items()}
[ "def", "get_reqv", "(", "self", ")", ":", "if", "'reqv'", "not", "in", "self", ".", "inputs", ":", "return", "return", "{", "key", ":", "valid", ".", "RjbEquivalent", "(", "value", ")", "for", "key", ",", "value", "in", "self", ".", "inputs", "[", ...
34.875
13.625
def _set_show_mpls_te_path(self, v, load=False): """ Setter method for show_mpls_te_path, mapped from YANG variable /brocade_mpls_rpc/show_mpls_te_path (rpc) If this variable is read-only (config: false) in the source YANG file, then _set_show_mpls_te_path is considered as a private method. Backends...
[ "def", "_set_show_mpls_te_path", "(", "self", ",", "v", ",", "load", "=", "False", ")", ":", "if", "hasattr", "(", "v", ",", "\"_utype\"", ")", ":", "v", "=", "v", ".", "_utype", "(", "v", ")", "try", ":", "t", "=", "YANGDynClass", "(", "v", ",",...
75
35.227273
def handle_pi(self, text): """Handle a processing instruction as a ProcessingInstruction object, possibly one with a %SOUP-ENCODING% slot into which an encoding will be plugged later.""" if text[:3] == "xml": text = u"xml version='1.0' encoding='%SOUP-ENCODING%'" self...
[ "def", "handle_pi", "(", "self", ",", "text", ")", ":", "if", "text", "[", ":", "3", "]", "==", "\"xml\"", ":", "text", "=", "u\"xml version='1.0' encoding='%SOUP-ENCODING%'\"", "self", ".", "_toStringSubclass", "(", "text", ",", "ProcessingInstruction", ")" ]
51.571429
14.285714
def open_url(url, headers=None): """ Opens a URL. If headers are passed as argument, no check is performed and the URL will be opened. @param url: the URL to open @type url: string @param headers: the headers to use @type headers: dictionary @return: a file-like object as returned by ...
[ "def", "open_url", "(", "url", ",", "headers", "=", "None", ")", ":", "request", "=", "urllib2", ".", "Request", "(", "url", ")", "if", "headers", ":", "for", "key", ",", "value", "in", "headers", ".", "items", "(", ")", ":", "request", ".", "add_h...
27.777778
15.666667
def clip(self, min=None, max=None): """ Clip values above and below. Parameters ---------- min : scalar or array-like Minimum value. If array, will be broadcasted max : scalar or array-like Maximum value. If array, will be broadcasted. ""...
[ "def", "clip", "(", "self", ",", "min", "=", "None", ",", "max", "=", "None", ")", ":", "return", "self", ".", "_constructor", "(", "self", ".", "values", ".", "clip", "(", "min", "=", "min", ",", "max", "=", "max", ")", ")", ".", "__finalize__",...
29.214286
15.071429
def unpackSample(self, rawData): """ unpacks a single sample of data (where sample length is based on the currently enabled sensors). :param rawData: the data to convert :return: a converted data set. """ length = len(rawData) # TODO error if not multiple of 2 ...
[ "def", "unpackSample", "(", "self", ",", "rawData", ")", ":", "length", "=", "len", "(", "rawData", ")", "# TODO error if not multiple of 2", "# logger.debug(\">> unpacking sample %d length %d\", self._sampleIdx, length)", "unpacked", "=", "struct", ".", "unpack", "(", "\...
45.473684
20.631579
def _poly(self, clade, merge_compressed): """ Function to resolve polytomies for a given parent node. If the number of the direct decendants is less than three (not a polytomy), does nothing. Otherwise, for each pair of nodes, assess the possible LH increase which could be gaine...
[ "def", "_poly", "(", "self", ",", "clade", ",", "merge_compressed", ")", ":", "from", ".", "branch_len_interpolator", "import", "BranchLenInterpolator", "zero_branch_slope", "=", "self", ".", "gtr", ".", "mu", "*", "self", ".", "seq_len", "def", "_c_gain", "("...
50.788618
28.00813
def get_max_instances_of_usb_controller_type(self, chipset, type_p): """Returns the maximum number of USB controller instances which can be configured for each VM. This corresponds to the number of USB controllers one can have. Value may depend on chipset type used. in chipset o...
[ "def", "get_max_instances_of_usb_controller_type", "(", "self", ",", "chipset", ",", "type_p", ")", ":", "if", "not", "isinstance", "(", "chipset", ",", "ChipsetType", ")", ":", "raise", "TypeError", "(", "\"chipset can only be an instance of type ChipsetType\"", ")", ...
45.347826
22.565217
def setChatPhoto(self, chat_id, photo): """ See: https://core.telegram.org/bots/api#setchatphoto """ p = _strip(locals(), more=['photo']) return self._api_request_with_file('setChatPhoto', _rectify(p), 'photo', photo)
[ "def", "setChatPhoto", "(", "self", ",", "chat_id", ",", "photo", ")", ":", "p", "=", "_strip", "(", "locals", "(", ")", ",", "more", "=", "[", "'photo'", "]", ")", "return", "self", ".", "_api_request_with_file", "(", "'setChatPhoto'", ",", "_rectify", ...
59.5
13
def create_index(self, fields, no_term_offsets=False, no_field_flags=False, stopwords = None): """ Create the search index. The index must not already exist. ### Parameters: - **fields**: a list of TextField or NumericField objects - **no_term_offsets**: If...
[ "def", "create_index", "(", "self", ",", "fields", ",", "no_term_offsets", "=", "False", ",", "no_field_flags", "=", "False", ",", "stopwords", "=", "None", ")", ":", "args", "=", "[", "self", ".", "CREATE_CMD", ",", "self", ".", "index_name", "]", "if",...
40.214286
23.785714
def normalize_choices(db_values, field_name, app=DEFAULT_APP, model_name='', human_readable=True, none_value='Null', blank_value='Unknown', missing_value='Unknown DB Code'): '''Output the human-readable strings associated with the list of database values for a model field. Uses the trans...
[ "def", "normalize_choices", "(", "db_values", ",", "field_name", ",", "app", "=", "DEFAULT_APP", ",", "model_name", "=", "''", ",", "human_readable", "=", "True", ",", "none_value", "=", "'Null'", ",", "blank_value", "=", "'Unknown'", ",", "missing_value", "="...
52.162162
32.378378
def get_default_config(self): """ Returns the default collector settings """ config = super(SidekiqWebCollector, self).get_default_config() config.update({ 'host': 'localhost', 'port': 9999, 'byte_unit': ['byte'], }) return conf...
[ "def", "get_default_config", "(", "self", ")", ":", "config", "=", "super", "(", "SidekiqWebCollector", ",", "self", ")", ".", "get_default_config", "(", ")", "config", ".", "update", "(", "{", "'host'", ":", "'localhost'", ",", "'port'", ":", "9999", ",",...
28.363636
12.909091
def get(app, name): '''Get a backend given its name''' backend = get_all(app).get(name) if not backend: msg = 'Harvest backend "{0}" is not registered'.format(name) raise EntrypointError(msg) return backend
[ "def", "get", "(", "app", ",", "name", ")", ":", "backend", "=", "get_all", "(", "app", ")", ".", "get", "(", "name", ")", "if", "not", "backend", ":", "msg", "=", "'Harvest backend \"{0}\" is not registered'", ".", "format", "(", "name", ")", "raise", ...
33.142857
14.857143
def defaults(self): """ Return a nested dicionary of all registered factory defaults. """ return { key: get_defaults(value) for key, value in self.all.items() }
[ "def", "defaults", "(", "self", ")", ":", "return", "{", "key", ":", "get_defaults", "(", "value", ")", "for", "key", ",", "value", "in", "self", ".", "all", ".", "items", "(", ")", "}" ]
24.111111
17.222222
def seconds_remaining(self, ttl): """Return number of seconds left before Imgur API needs to be queried for this instance. :param int ttl: Number of seconds before this is considered out of date. :return: Seconds left before this is expired. 0 indicated update needed (no negatives). :r...
[ "def", "seconds_remaining", "(", "self", ",", "ttl", ")", ":", "return", "max", "(", "0", ",", "ttl", "-", "(", "int", "(", "time", ".", "time", "(", ")", ")", "-", "self", ".", "mod_time", ")", ")" ]
44.111111
25.111111
def unhold(name=None, pkgs=None, **kwargs): ''' Remove specified package lock. root operate on a different root directory. CLI Example: .. code-block:: bash salt '*' pkg.remove_lock <package name> salt '*' pkg.remove_lock <package1>,<package2>,<package3> salt '*' ...
[ "def", "unhold", "(", "name", "=", "None", ",", "pkgs", "=", "None", ",", "*", "*", "kwargs", ")", ":", "ret", "=", "{", "}", "root", "=", "kwargs", ".", "get", "(", "'root'", ")", "if", "(", "not", "name", "and", "not", "pkgs", ")", "or", "(...
26.714286
23.857143
async def _create_rev_reg(self, rr_id: str, rr_size: int = None) -> None: """ Create revocation registry and new tails file (and association to corresponding revocation registry definition via symbolic link) for input revocation registry identifier. :param rr_id: revocation regi...
[ "async", "def", "_create_rev_reg", "(", "self", ",", "rr_id", ":", "str", ",", "rr_size", ":", "int", "=", "None", ")", "->", "None", ":", "LOGGER", ".", "debug", "(", "'Issuer._create_rev_reg >>> rr_id: %s, rr_size: %s'", ",", "rr_id", ",", "rr_size", ")", ...
42.156863
24.235294
def _cas_1(self): '''1 - The desired structure is entirely contained into one image.''' lonc = self._format_lon(self.lonm) latc = self._format_lat(self.latm) img = self._format_name_map(lonc, latc) img_map = BinaryTable(img, self.path_pdsfiles) return img_map.extract_gr...
[ "def", "_cas_1", "(", "self", ")", ":", "lonc", "=", "self", ".", "_format_lon", "(", "self", ".", "lonm", ")", "latc", "=", "self", ".", "_format_lat", "(", "self", ".", "latm", ")", "img", "=", "self", ".", "_format_name_map", "(", "lonc", ",", "...
39.777778
22.666667
def iter_insert_items(tree): """ Iterate over the items to insert from an INSERT statement """ if tree.list_values: keys = tree.attrs for values in tree.list_values: if len(keys) != len(values): raise SyntaxError( "Values '%s' do not match attribut...
[ "def", "iter_insert_items", "(", "tree", ")", ":", "if", "tree", ".", "list_values", ":", "keys", "=", "tree", ".", "attrs", "for", "values", "in", "tree", ".", "list_values", ":", "if", "len", "(", "keys", ")", "!=", "len", "(", "values", ")", ":", ...
36.111111
12.833333
def upload_template_and_reload(name): """ Uploads a template only if it has changed, and if so, reload the related service. """ template = get_templates()[name] local_path = template["local_path"] if not os.path.exists(local_path): project_root = os.path.dirname(os.path.abspath(__fil...
[ "def", "upload_template_and_reload", "(", "name", ")", ":", "template", "=", "get_templates", "(", ")", "[", "name", "]", "local_path", "=", "template", "[", "\"local_path\"", "]", "if", "not", "os", ".", "path", ".", "exists", "(", "local_path", ")", ":",...
38.685714
14.171429
def set_slats_level(self, slatsLevel=0.0, shutterLevel=None): """ sets the slats and shutter level Args: slatsLevel(float): the new level of the slats. 0.0 = open, 1.0 = closed, shutterLevel(float): the new level of the shutter. 0.0 = open, 1.0 = closed, None = use the current v...
[ "def", "set_slats_level", "(", "self", ",", "slatsLevel", "=", "0.0", ",", "shutterLevel", "=", "None", ")", ":", "if", "shutterLevel", "is", "None", ":", "shutterLevel", "=", "self", ".", "shutterLevel", "data", "=", "{", "\"channelIndex\"", ":", "1", ","...
39.166667
20.111111
def plot(self, x, y, panel='top', xlabel=None, **kws): """plot after clearing current plot """ panel = self.get_panel(panel) panel.plot(x, y, **kws) if xlabel is not None: self.xlabel = xlabel if self.xlabel is not None: self.panel_bot.set_xlabel(self.xlab...
[ "def", "plot", "(", "self", ",", "x", ",", "y", ",", "panel", "=", "'top'", ",", "xlabel", "=", "None", ",", "*", "*", "kws", ")", ":", "panel", "=", "self", ".", "get_panel", "(", "panel", ")", "panel", ".", "plot", "(", "x", ",", "y", ",", ...
39.5
7.375
def adduser(name, username, root=None): ''' Add a user in the group. name Name of the group to modify username Username to add to the group root Directory to chroot into CLI Example: .. code-block:: bash salt '*' group.adduser foo bar Verifies if a...
[ "def", "adduser", "(", "name", ",", "username", ",", "root", "=", "None", ")", ":", "on_redhat_5", "=", "__grains__", ".", "get", "(", "'os_family'", ")", "==", "'RedHat'", "and", "__grains__", ".", "get", "(", "'osmajorrelease'", ")", "==", "'5'", "on_s...
26.666667
23.952381
def get_supported( versions=None, # type: Optional[List[str]] noarch=False, # type: bool platform=None, # type: Optional[str] impl=None, # type: Optional[str] abi=None # type: Optional[str] ): # type: (...) -> List[Pep425Tag] """Return a list of supported tags for each version specified...
[ "def", "get_supported", "(", "versions", "=", "None", ",", "# type: Optional[List[str]]", "noarch", "=", "False", ",", "# type: bool", "platform", "=", "None", ",", "# type: Optional[str]", "impl", "=", "None", ",", "# type: Optional[str]", "abi", "=", "None", "# ...
38.915888
20.233645
def urlretrieve(self, url, filename, data=None): """ Similar to urllib.urlretrieve or urllib.request.urlretrieve only that *filname* is required. :param url: URL to download. :param filename: Filename to save the content to. :param data: Valid URL-encoded data. :...
[ "def", "urlretrieve", "(", "self", ",", "url", ",", "filename", ",", "data", "=", "None", ")", ":", "logger", ".", "info", "(", "'saving: \\'%s\\' to \\'%s\\''", ",", "url", ",", "filename", ")", "if", "_is_py3", ":", "return", "_urlretrieve_with_opener", "(...
36.875
18.625
def get_alt_date_bug_totals(self, startday, endday, bug_ids): """use previously fetched bug_ids to check for total failures exceeding 150 in 21 days""" bugs = (BugJobMap.failures.by_date(startday, endday) .filter(bug_id__in=bug_ids) ...
[ "def", "get_alt_date_bug_totals", "(", "self", ",", "startday", ",", "endday", ",", "bug_ids", ")", ":", "bugs", "=", "(", "BugJobMap", ".", "failures", ".", "by_date", "(", "startday", ",", "endday", ")", ".", "filter", "(", "bug_id__in", "=", "bug_ids", ...
54.6
19.9
def start(self, datas): """ Starts the pipeline by connecting the input ``Pipers`` of the pipeline to the input data, connecting the pipeline and starting the ``NuMap`` instances. The order of items in the "datas" argument sequence should correspond to the orde...
[ "def", "start", "(", "self", ",", "datas", ")", ":", "if", "not", "self", ".", "_started", ".", "isSet", "(", ")", "and", "not", "self", ".", "_running", ".", "isSet", "(", ")", "and", "not", "self", ".", "_pausing", ".", "isSet", "(", ")", ":", ...
38.465116
16.744186
def is_valid_method_view(endpoint): """ Return True if obj is MethodView """ klass = endpoint.__dict__.get('view_class', None) try: return issubclass(klass, MethodView) except TypeError: return False
[ "def", "is_valid_method_view", "(", "endpoint", ")", ":", "klass", "=", "endpoint", ".", "__dict__", ".", "get", "(", "'view_class'", ",", "None", ")", "try", ":", "return", "issubclass", "(", "klass", ",", "MethodView", ")", "except", "TypeError", ":", "r...
25.666667
10.777778
def _check_transition_target(self, transition): """Checks the validity of a transition target Checks whether the transition target is valid. :param rafcon.core.transition.Transition transition: The transition to be checked :return bool validity, str message: validity is True, when the ...
[ "def", "_check_transition_target", "(", "self", ",", "transition", ")", ":", "to_state_id", "=", "transition", ".", "to_state", "to_outcome_id", "=", "transition", ".", "to_outcome", "if", "to_state_id", "==", "self", ".", "state_id", ":", "if", "to_outcome_id", ...
41.217391
22.695652
def compress_pruned(table): """Compress table based on pruning mask. Only the rows/cols in which all of the elements are masked need to be pruned. """ if not isinstance(table, np.ma.core.MaskedArray): return table if table.ndim == 0: return table.data if table.ndim == 1: ...
[ "def", "compress_pruned", "(", "table", ")", ":", "if", "not", "isinstance", "(", "table", ",", "np", ".", "ma", ".", "core", ".", "MaskedArray", ")", ":", "return", "table", "if", "table", ".", "ndim", "==", "0", ":", "return", "table", ".", "data",...
26.761905
17.380952