text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def doWorksheetLogic(base, action, analysis): """ This function checks if the actions contains worksheet actions. There is a selection list in each action section. This select has the following options and consequence. 1) "To the current worksheet" (selected by default) 2) "To another workshee...
[ "def", "doWorksheetLogic", "(", "base", ",", "action", ",", "analysis", ")", ":", "otherWS", "=", "action", ".", "get", "(", "'otherWS'", ",", "False", ")", "worksheet_catalog", "=", "getToolByName", "(", "base", ",", "CATALOG_WORKSHEET_LISTING", ")", "if", ...
48.008333
21.675
def discover_modules(directory): """ Attempts to list all of the modules and submodules found within a given directory tree. This function searches the top-level of the directory tree for potential python modules and returns a list of candidate names. **Note:** This function returns a list of strin...
[ "def", "discover_modules", "(", "directory", ")", ":", "found", "=", "list", "(", ")", "if", "os", ".", "path", ".", "isdir", "(", "directory", ")", ":", "for", "entry", "in", "os", ".", "listdir", "(", "directory", ")", ":", "next_dir", "=", "os", ...
35.318182
22.590909
def run(*args): """ Check and/or create Django migrations. If --check is present in the arguments then migrations are checked only. """ if not settings.configured: settings.configure(**DEFAULT_SETTINGS) django.setup() parent = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, parent) if "--ch...
[ "def", "run", "(", "*", "args", ")", ":", "if", "not", "settings", ".", "configured", ":", "settings", ".", "configure", "(", "*", "*", "DEFAULT_SETTINGS", ")", "django", ".", "setup", "(", ")", "parent", "=", "os", ".", "path", ".", "dirname", "(", ...
23.166667
21.388889
def generate_files(engine, crypto_factory, min_dt=None, max_dt=None, logger=None): """ Create a generator of decrypted files. Files are yielded in ascending order of their timestamp. This function selects all current notebooks (optionally, falling within a datetime range), decry...
[ "def", "generate_files", "(", "engine", ",", "crypto_factory", ",", "min_dt", "=", "None", ",", "max_dt", "=", "None", ",", "logger", "=", "None", ")", ":", "return", "_generate_notebooks", "(", "files", ",", "files", ".", "c", ".", "created_at", ",", "e...
43
20.571429
def setup(self): """ Setup py3status and spawn i3status/events/modules threads. """ # SIGTSTP will be received from i3bar indicating that all output should # stop and we should consider py3status suspended. It is however # important that any processes using i3 ipc shoul...
[ "def", "setup", "(", "self", ")", ":", "# SIGTSTP will be received from i3bar indicating that all output should", "# stop and we should consider py3status suspended. It is however", "# important that any processes using i3 ipc should continue to receive", "# those events otherwise it can lead to ...
39.639344
18.311475
def qzordered(A,B,crit=1.0): "Eigenvalues bigger than crit are sorted in the top-left." TOL = 1e-10 def select(alpha, beta): return alpha**2>crit*beta**2 [S,T,alpha,beta,U,V] = ordqz(A,B,output='real',sort=select) eigval = abs(numpy.diag(S)/numpy.diag(T)) return [S,T,U,V,eigval]
[ "def", "qzordered", "(", "A", ",", "B", ",", "crit", "=", "1.0", ")", ":", "TOL", "=", "1e-10", "def", "select", "(", "alpha", ",", "beta", ")", ":", "return", "alpha", "**", "2", ">", "crit", "*", "beta", "**", "2", "[", "S", ",", "T", ",", ...
23.384615
24.307692
def search(cls, name, lookup=[]): """ Search name in all directories specified in lookup. First without, then with common extensions. Return first hit. """ if os.path.isfile(name): return name for spath in lookup: fname = os.path.join(spath, name) if os.path.isfil...
[ "def", "search", "(", "cls", ",", "name", ",", "lookup", "=", "[", "]", ")", ":", "if", "os", ".", "path", ".", "isfile", "(", "name", ")", ":", "return", "name", "for", "spath", "in", "lookup", ":", "fname", "=", "os", ".", "path", ".", "join"...
45.090909
6.545455
def set_more_headers(self, req, extra_headers=None): """Set content-type, content-md5, date to the request Returns a new `PreparedRequest` :param req: the origin unsigned request :param extra_headers: extra headers you want to set, pass as dict """ oss_url = url.URL(req....
[ "def", "set_more_headers", "(", "self", ",", "req", ",", "extra_headers", "=", "None", ")", ":", "oss_url", "=", "url", ".", "URL", "(", "req", ".", "url", ")", "req", ".", "headers", ".", "update", "(", "extra_headers", "or", "{", "}", ")", "# set c...
35.95
19.25
def _lookup_nexus_bindings(query_type, session=None, **bfilter): """Look up 'query_type' Nexus bindings matching the filter. :param query_type: 'all', 'one' or 'first' :param session: db session :param bfilter: filter for bindings query :returns: bindings if query gave a result, else r...
[ "def", "_lookup_nexus_bindings", "(", "query_type", ",", "session", "=", "None", ",", "*", "*", "bfilter", ")", ":", "if", "session", "is", "None", ":", "session", "=", "bc", ".", "get_reader_session", "(", ")", "query_method", "=", "getattr", "(", "sessio...
35.65
13.65
def create_ap(self, args): """申请接入点 申请指定配置的接入点资源。 Args: - args: 请求参数(json),参考 http://kirk-docs.qiniu.com/apidocs/ Returns: 返回一个tuple对象,其格式为(<result>, <ResponseInfo>) - result 成功返回申请到的接入点信息,失败返回{"error": "<errMsg string>"} - Re...
[ "def", "create_ap", "(", "self", ",", "args", ")", ":", "url", "=", "'{0}/v3/aps'", ".", "format", "(", "self", ".", "host", ")", "return", "self", ".", "__post", "(", "url", ",", "args", ")" ]
28.533333
19.666667
def get_log(self, offset, count=10, callback=None): ''' Retrieve log records from camera. cmd: getLog param: offset: log offset for first record count: number of records to return ''' params = {'offset': offset, 'count': count} return self.ex...
[ "def", "get_log", "(", "self", ",", "offset", ",", "count", "=", "10", ",", "callback", "=", "None", ")", ":", "params", "=", "{", "'offset'", ":", "offset", ",", "'count'", ":", "count", "}", "return", "self", ".", "execute_command", "(", "'getLog'", ...
36.1
17.1
def run(self, files, stack): "Convert dates" for filename, post in files.items(): if self.date_field in post.metadata: post[self.date_field] = parse(post[self.date_field])
[ "def", "run", "(", "self", ",", "files", ",", "stack", ")", ":", "for", "filename", ",", "post", "in", "files", ".", "items", "(", ")", ":", "if", "self", ".", "date_field", "in", "post", ".", "metadata", ":", "post", "[", "self", ".", "date_field"...
42.2
13.8
def _multi_rpush_pipeline(self, pipe, queue, values, bulk_size=0): ''' Pushes multiple elements to a list in a given pipeline If bulk_size is set it will execute the pipeline every bulk_size elements ''' cont = 0 for value in values: pipe.rpush(queue, value)...
[ "def", "_multi_rpush_pipeline", "(", "self", ",", "pipe", ",", "queue", ",", "values", ",", "bulk_size", "=", "0", ")", ":", "cont", "=", "0", "for", "value", "in", "values", ":", "pipe", ".", "rpush", "(", "queue", ",", "value", ")", "if", "bulk_siz...
44.666667
21.333333
def similar_text(self, *args, **kwargs): """ Search for documents that are similar to directly supplied text or to the textual content of an existing document. Args: text -- Text to found something similar to. len -- Number of keywords to extract from the source. quo...
[ "def", "similar_text", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "SimilarRequest", "(", "self", ",", "*", "args", ",", "mode", "=", "'text'", ",", "*", "*", "kwargs", ")", ".", "send", "(", ")" ]
45.222222
24.5
def maybe_expire(self, request_timeout_ms, retry_backoff_ms, linger_ms, is_full): """Expire batches if metadata is not available A batch whose metadata is not available should be expired if one of the following is true: * the batch is not in retry AND request timeout has elapsed afte...
[ "def", "maybe_expire", "(", "self", ",", "request_timeout_ms", ",", "retry_backoff_ms", ",", "linger_ms", ",", "is_full", ")", ":", "now", "=", "time", ".", "time", "(", ")", "since_append", "=", "now", "-", "self", ".", "last_append", "since_ready", "=", ...
46.151515
25.818182
def connection_count(self): """Number of currently open connections to the database. (Stored in table sqlarray_master.) """ return self.sql("SELECT value FROM %(master)s WHERE name = 'connection_counter'" % vars(self), cache=False, asrecarray=False)[0][0]
[ "def", "connection_count", "(", "self", ")", ":", "return", "self", ".", "sql", "(", "\"SELECT value FROM %(master)s WHERE name = 'connection_counter'\"", "%", "vars", "(", "self", ")", ",", "cache", "=", "False", ",", "asrecarray", "=", "False", ")", "[", "0", ...
43.714286
19.571429
def batch_contains_deleted(self): "Check if current batch contains already deleted images." if not self._duplicates: return False imgs = [self._all_images[:self._batch_size][0][1], self._all_images[:self._batch_size][1][1]] return any(img in self._deleted_fns for img in imgs)
[ "def", "batch_contains_deleted", "(", "self", ")", ":", "if", "not", "self", ".", "_duplicates", ":", "return", "False", "imgs", "=", "[", "self", ".", "_all_images", "[", ":", "self", ".", "_batch_size", "]", "[", "0", "]", "[", "1", "]", ",", "self...
60.8
23.6
def apply(self, cls, originalMemberNameList, classNamingConvention): """ :type cls: type :type originalMemberNameList: list(str) :type classNamingConvention: INamingConvention """ self._memberDelegate.apply(cls = cls, originalMemberNameList = originalMember...
[ "def", "apply", "(", "self", ",", "cls", ",", "originalMemberNameList", ",", "classNamingConvention", ")", ":", "self", ".", "_memberDelegate", ".", "apply", "(", "cls", "=", "cls", ",", "originalMemberNameList", "=", "originalMemberNameList", ",", "memberName", ...
49.5
18.5
def get_sub_array_ids(): """Return list of sub-array Id's currently known to SDP""" ids = set() for key in sorted(DB.keys(pattern='scheduling_block/*')): config = json.loads(DB.get(key)) ids.add(config['sub_array_id']) return sorted(list(ids))
[ "def", "get_sub_array_ids", "(", ")", ":", "ids", "=", "set", "(", ")", "for", "key", "in", "sorted", "(", "DB", ".", "keys", "(", "pattern", "=", "'scheduling_block/*'", ")", ")", ":", "config", "=", "json", ".", "loads", "(", "DB", ".", "get", "(...
38.428571
10.714286
def _begin(self, retry_id=None): """Begin the transaction. Args: retry_id (Optional[bytes]): Transaction ID of a transaction to be retried. Raises: ValueError: If the current transaction has already begun. """ if self.in_progress: ...
[ "def", "_begin", "(", "self", ",", "retry_id", "=", "None", ")", ":", "if", "self", ".", "in_progress", ":", "msg", "=", "_CANT_BEGIN", ".", "format", "(", "self", ".", "_id", ")", "raise", "ValueError", "(", "msg", ")", "transaction_response", "=", "s...
33.1
19.5
def _timeout_handler(self, signum, frame): """ internal timeout handler """ msgfmt = 'plugin timed out after {0} seconds' self.exit(code=self._timeout_code, message=msgfmt.format(self._timeout_delay))
[ "def", "_timeout_handler", "(", "self", ",", "signum", ",", "frame", ")", ":", "msgfmt", "=", "'plugin timed out after {0} seconds'", "self", ".", "exit", "(", "code", "=", "self", ".", "_timeout_code", ",", "message", "=", "msgfmt", ".", "format", "(", "sel...
36
6.571429
def confusion_matrix(self): """ Returns the normalised confusion matrix """ confusion_matrix = self.pixel_classification_sum.astype(np.float) confusion_matrix = np.divide(confusion_matrix.T, self.pixel_truth_sum.T).T return confusion_matrix * 100.0
[ "def", "confusion_matrix", "(", "self", ")", ":", "confusion_matrix", "=", "self", ".", "pixel_classification_sum", ".", "astype", "(", "np", ".", "float", ")", "confusion_matrix", "=", "np", ".", "divide", "(", "confusion_matrix", ".", "T", ",", "self", "."...
36.25
17
def create_record(self, bucket_name, record_key, record_data, record_metadata=None, record_mimetype='', record_encoding='', overwrite=True): ''' a method for adding a record to an S3 bucket :param bucket_name: string with name of bucket :param record_key: string with na...
[ "def", "create_record", "(", "self", ",", "bucket_name", ",", "record_key", ",", "record_data", ",", "record_metadata", "=", "None", ",", "record_mimetype", "=", "''", ",", "record_encoding", "=", "''", ",", "overwrite", "=", "True", ")", ":", "title", "=", ...
43.728814
23.40678
def run(self): """Run the server, whose behavior is like. >>> while receive(x): ... if is_command x: controller(x) ... else if is_key_value x: updater(x) """ _ctrl_proto = ctypes.CFUNCTYPE(None, ctypes.c_int, ctypes.c_char_p, ctypes.c_void_p) check_call(...
[ "def", "run", "(", "self", ")", ":", "_ctrl_proto", "=", "ctypes", ".", "CFUNCTYPE", "(", "None", ",", "ctypes", ".", "c_int", ",", "ctypes", ".", "c_char_p", ",", "ctypes", ".", "c_void_p", ")", "check_call", "(", "_LIB", ".", "MXKVStoreRunServer", "(",...
38.7
24
def _bytes_to_values(self, bs, width=None): """Convert a packed row of bytes into a row of values. Result will be a freshly allocated object, not shared with the argument. """ if self.bitdepth == 8: return bytearray(bs) if self.bitdepth == 16: ret...
[ "def", "_bytes_to_values", "(", "self", ",", "bs", ",", "width", "=", "None", ")", ":", "if", "self", ".", "bitdepth", "==", "8", ":", "return", "bytearray", "(", "bs", ")", "if", "self", ".", "bitdepth", "==", "16", ":", "return", "array", "(", "'...
32.916667
12.791667
def title(self): """ Title of the object. This schema element is purely informative. """ value = self._schema.get("title", None) if value is None: return if not isinstance(value, basestring): raise SchemaError( "title value...
[ "def", "title", "(", "self", ")", ":", "value", "=", "self", ".", "_schema", ".", "get", "(", "\"title\"", ",", "None", ")", "if", "value", "is", "None", ":", "return", "if", "not", "isinstance", "(", "value", ",", "basestring", ")", ":", "raise", ...
28.230769
14.692308
def run_xenon_simple(workflow, machine, worker_config): """Run a workflow using a single Xenon remote worker. :param workflow: |Workflow| or |PromisedObject| to evaluate. :param machine: |Machine| instance. :param worker_config: Configuration for the pilot job.""" scheduler = Scheduler() retur...
[ "def", "run_xenon_simple", "(", "workflow", ",", "machine", ",", "worker_config", ")", ":", "scheduler", "=", "Scheduler", "(", ")", "return", "scheduler", ".", "run", "(", "xenon_interactive_worker", "(", "machine", ",", "worker_config", ")", ",", "get_workflow...
35
17.5
def sex2dec(ra, dec): ''' Convert sexadecimal hours to decimal degrees. Adapted from `PyKE <http://keplergo.arc.nasa.gov/PyKE.shtml>`_. :param float ra: The right ascension :param float dec: The declination :returns: The same values, but in decimal degrees ''' ra = re.sub('\s+', '|',...
[ "def", "sex2dec", "(", "ra", ",", "dec", ")", ":", "ra", "=", "re", ".", "sub", "(", "'\\s+'", ",", "'|'", ",", "ra", ".", "strip", "(", ")", ")", "ra", "=", "re", ".", "sub", "(", "':'", ",", "'|'", ",", "ra", ".", "strip", "(", ")", ")"...
30.03125
19.90625
def hash(self): """Return an hash for the simulation parameters (excluding ID and EID) This can be used to generate unique file names for simulations that have the same parameters and just different ID or EID. """ hash_numeric = 't_step=%.3e, t_max=%.2f, np=%d, conc=%.2e' % \ ...
[ "def", "hash", "(", "self", ")", ":", "hash_numeric", "=", "'t_step=%.3e, t_max=%.2f, np=%d, conc=%.2e'", "%", "(", "self", ".", "t_step", ",", "self", ".", "t_max", ",", "self", ".", "num_particles", ",", "self", ".", "concentration", "(", ")", ")", "hash_l...
57
21.7
def from_nibabel(nib_image): """ Convert a nibabel image to an ANTsImage """ tmpfile = mktemp(suffix='.nii.gz') nib_image.to_filename(tmpfile) new_img = iio2.image_read(tmpfile) os.remove(tmpfile) return new_img
[ "def", "from_nibabel", "(", "nib_image", ")", ":", "tmpfile", "=", "mktemp", "(", "suffix", "=", "'.nii.gz'", ")", "nib_image", ".", "to_filename", "(", "tmpfile", ")", "new_img", "=", "iio2", ".", "image_read", "(", "tmpfile", ")", "os", ".", "remove", ...
26.111111
7.222222
def cmd_serve(self, *args): '''Serve the bin directory via SimpleHTTPServer ''' try: from http.server import SimpleHTTPRequestHandler from socketserver import TCPServer except ImportError: from SimpleHTTPServer import SimpleHTTPRequestHandler ...
[ "def", "cmd_serve", "(", "self", ",", "*", "args", ")", ":", "try", ":", "from", "http", ".", "server", "import", "SimpleHTTPRequestHandler", "from", "socketserver", "import", "TCPServer", "except", "ImportError", ":", "from", "SimpleHTTPServer", "import", "Simp...
39.8125
17.8125
def post_copy_metacolums(self, cursor): """ Performs post-copy to fill metadata columns. """ logger.info('Executing post copy metadata queries') for query in self.metadata_queries: cursor.execute(query)
[ "def", "post_copy_metacolums", "(", "self", ",", "cursor", ")", ":", "logger", ".", "info", "(", "'Executing post copy metadata queries'", ")", "for", "query", "in", "self", ".", "metadata_queries", ":", "cursor", ".", "execute", "(", "query", ")" ]
35.428571
6
def do_GET(self): """Implement the HTTP GET method. The bulk of this code is wrapped in a big try block and anywhere within the code may raise an IIIFError which then results in an IIIF error response (section 5 of spec). """ self.compliance_uri = None self.iiif ...
[ "def", "do_GET", "(", "self", ")", ":", "self", ".", "compliance_uri", "=", "None", "self", ".", "iiif", "=", "IIIFRequest", "(", "baseurl", "=", "'/'", ")", "try", ":", "(", "of", ",", "mime_type", ")", "=", "self", ".", "do_GET_body", "(", ")", "...
41.027778
14.416667
def convert_tokens_into_matrix(self, token_list): ''' Create matrix of sentences. Args: token_list: The list of tokens. Returns: 2-D `np.ndarray` of sentences. Each row means one hot vectors of one sentence. ''' ...
[ "def", "convert_tokens_into_matrix", "(", "self", ",", "token_list", ")", ":", "return", "np", ".", "array", "(", "self", ".", "vectorize", "(", "token_list", ")", ")", ".", "astype", "(", "np", ".", "float32", ")" ]
31
20.833333
def tridi_inverse_iteration(d, e, w, x0=None, rtol=1e-8): """Perform an inverse iteration to find the eigenvector corresponding to the given eigenvalue in a symmetric tridiagonal system. Parameters ---------- d : ndarray main diagonal of the tridiagonal system e : ndarray offdiagon...
[ "def", "tridi_inverse_iteration", "(", "d", ",", "e", ",", "w", ",", "x0", "=", "None", ",", "rtol", "=", "1e-8", ")", ":", "eig_diag", "=", "d", "-", "w", "if", "x0", "is", "None", ":", "x0", "=", "np", ".", "random", ".", "randn", "(", "len",...
26.461538
19.282051
def add_relations(spec_dict: Mapping[str, Any]) -> Mapping[str, Any]: """Add relation keys to spec_dict Args: spec_dict (Mapping[str, Any]): bel specification dictionary Returns: Mapping[str, Any]: bel specification dictionary with added relation keys """ # Class 'Mapping' does no...
[ "def", "add_relations", "(", "spec_dict", ":", "Mapping", "[", "str", ",", "Any", "]", ")", "->", "Mapping", "[", "str", ",", "Any", "]", ":", "# Class 'Mapping' does not define '__setitem__', so the '[]' operator cannot be used on its instances", "spec_dict", "[", "\"r...
41.258065
28.225806
def update(self, branch='default'): ''' Ensure we are using the latest revision in the hg repository ''' log.debug('Updating hg repo from hg_pillar module (pull)') self.repo.pull() log.debug('Updating hg repo from hg_pillar module (update)') self.repo.update(branc...
[ "def", "update", "(", "self", ",", "branch", "=", "'default'", ")", ":", "log", ".", "debug", "(", "'Updating hg repo from hg_pillar module (pull)'", ")", "self", ".", "repo", ".", "pull", "(", ")", "log", ".", "debug", "(", "'Updating hg repo from hg_pillar mod...
40.875
20.625
def proxy(request): """Pass an HTTP request on to another server.""" # TODO: don't hardcode http uri = "http://" + HOST + request.META['PATH_INFO'] if request.META['QUERY_STRING']: uri += '?' + request.META['QUERY_STRING'] headers = {} for name, val in six.iteritems(request.environ): ...
[ "def", "proxy", "(", "request", ")", ":", "# TODO: don't hardcode http", "uri", "=", "\"http://\"", "+", "HOST", "+", "request", ".", "META", "[", "'PATH_INFO'", "]", "if", "request", ".", "META", "[", "'QUERY_STRING'", "]", ":", "uri", "+=", "'?'", "+", ...
30.846154
15.692308
def create_layer(self, lipid_indices=None, flip_orientation=False): """Create a monolayer of lipids. Parameters ---------- lipid_indices : list, optional, default=None A list of indices associated with each lipid in the layer. flip_orientation : bool, optional, defau...
[ "def", "create_layer", "(", "self", ",", "lipid_indices", "=", "None", ",", "flip_orientation", "=", "False", ")", ":", "layer", "=", "mb", ".", "Compound", "(", ")", "if", "not", "lipid_indices", ":", "lipid_indices", "=", "list", "(", "range", "(", "se...
42.410256
17.820513
def get_scope_info(cls): """Returns a ScopeInfo instance representing this Optionable's options scope.""" if cls.options_scope is None or cls.options_scope_category is None: raise OptionsError( '{} must set options_scope and options_scope_category.'.format(cls.__name__)) return ScopeInfo(cls.o...
[ "def", "get_scope_info", "(", "cls", ")", ":", "if", "cls", ".", "options_scope", "is", "None", "or", "cls", ".", "options_scope_category", "is", "None", ":", "raise", "OptionsError", "(", "'{} must set options_scope and options_scope_category.'", ".", "format", "("...
60.166667
23.166667
def timer(self, key, **dims): """Adds timer with dimensions to the registry""" return super(RegexRegistry, self).timer(self._get_key(key), **dims)
[ "def", "timer", "(", "self", ",", "key", ",", "*", "*", "dims", ")", ":", "return", "super", "(", "RegexRegistry", ",", "self", ")", ".", "timer", "(", "self", ".", "_get_key", "(", "key", ")", ",", "*", "*", "dims", ")" ]
53.333333
15.333333
def create(self, request): """ Change password for logged in django staff user """ # TODO: Decorate api with sensitive post parameters as Django admin do? password_form = PasswordChangeForm(request.user, data=request.data) if not password_form.is_valid(): ra...
[ "def", "create", "(", "self", ",", "request", ")", ":", "# TODO: Decorate api with sensitive post parameters as Django admin do?", "password_form", "=", "PasswordChangeForm", "(", "request", ".", "user", ",", "data", "=", "request", ".", "data", ")", "if", "not", "p...
34.066667
22.733333
def list_backends(backend=None): '''return a list of backends installed for the user, which is based on the config file keys found present Parameters ========== backend: a specific backend to list. If defined, just list parameters. ''' settings = read_client_secrets() # B...
[ "def", "list_backends", "(", "backend", "=", "None", ")", ":", "settings", "=", "read_client_secrets", "(", ")", "# Backend names are the keys", "backends", "=", "list", "(", "settings", ".", "keys", "(", ")", ")", "backends", "=", "[", "b", "for", "b", "i...
31.478261
20.521739
def verify_config_container(object_): """Verify object is a valid config container Valid config containers provide zope.interface.common.mapping.IEnumerableMapping or an iterable of zope.interface.common.mapping.IEnumerableMapping. verification is performed by checking required interfaces attr...
[ "def", "verify_config_container", "(", "object_", ")", ":", "try", ":", "#check for a map", "_verify_map", "(", "object_", ")", "except", "BrokenImplementation", "as", "e", ":", "#check for a iterable of maps", "try", ":", "for", "m", "in", "object_", ":", "_verif...
35.590909
19.818182
def _get_elements(self): ''' Yields all elements as PathElements ''' for index, el in enumerate(self._elements): if isinstance(el, tuple): el = PathElement(*el) self._elements[index] = el yield el
[ "def", "_get_elements", "(", "self", ")", ":", "for", "index", ",", "el", "in", "enumerate", "(", "self", ".", "_elements", ")", ":", "if", "isinstance", "(", "el", ",", "tuple", ")", ":", "el", "=", "PathElement", "(", "*", "el", ")", "self", ".",...
30.666667
12.888889
def set_data(self, data): """ Update the data attribute, making sure it's a dictionary. """ # Make sure a dict got passed it if not isinstance(data, type({})): raise TypeError("This attribute must be a dictionary.") # Set the attribute self.__dict__['d...
[ "def", "set_data", "(", "self", ",", "data", ")", ":", "# Make sure a dict got passed it", "if", "not", "isinstance", "(", "data", ",", "type", "(", "{", "}", ")", ")", ":", "raise", "TypeError", "(", "\"This attribute must be a dictionary.\"", ")", "# Set the a...
38
10.666667
def _handle_account(self, data, ts): """ Handles Account related data. translation table for channel names: Data Channels os - Orders hos - Historical Orders ps - Positions hts - Trades (snapshot) te ...
[ "def", "_handle_account", "(", "self", ",", "data", ",", "ts", ")", ":", "# channel_short, data", "chan_id", ",", "channel_short_name", ",", "", "*", "data", "=", "data", "entry", "=", "(", "channel_short_name", ",", "data", ",", "ts", ")", "self", ".", ...
31.363636
9.424242
def from_db_value(self, value, expression, connection, context): """ "Called in all circumstances when the data is loaded from the database, including in aggregates and values() calls." """ if value is None: return value return json_decode(value)
[ "def", "from_db_value", "(", "self", ",", "value", ",", "expression", ",", "connection", ",", "context", ")", ":", "if", "value", "is", "None", ":", "return", "value", "return", "json_decode", "(", "value", ")" ]
37.375
14.125
def confd_state_webui_listen_ssl_ip(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") confd_state = ET.SubElement(config, "confd-state", xmlns="http://tail-f.com/yang/confd-monitoring") webui = ET.SubElement(confd_state, "webui") listen = ET.SubEle...
[ "def", "confd_state_webui_listen_ssl_ip", "(", "self", ",", "*", "*", "kwargs", ")", ":", "config", "=", "ET", ".", "Element", "(", "\"config\"", ")", "confd_state", "=", "ET", ".", "SubElement", "(", "config", ",", "\"confd-state\"", ",", "xmlns", "=", "\...
41.230769
13.615385
def _extend(self, newsub): ''' Append a subclass (extension) after the base class. For parser internal use. ''' current = self while hasattr(current, '_sub'): current = current._sub _set(current, '_sub', newsub) try: object.__delattr__(self...
[ "def", "_extend", "(", "self", ",", "newsub", ")", ":", "current", "=", "self", "while", "hasattr", "(", "current", ",", "'_sub'", ")", ":", "current", "=", "current", ".", "_sub", "_set", "(", "current", ",", "'_sub'", ",", "newsub", ")", "try", ":"...
29.416667
18.916667
def MAKE_WPARAM(wParam): """ Convert arguments to the WPARAM type. Used automatically by SendMessage, PostMessage, etc. You shouldn't need to call this function. """ wParam = ctypes.cast(wParam, LPVOID).value if wParam is None: wParam = 0 return wParam
[ "def", "MAKE_WPARAM", "(", "wParam", ")", ":", "wParam", "=", "ctypes", ".", "cast", "(", "wParam", ",", "LPVOID", ")", ".", "value", "if", "wParam", "is", "None", ":", "wParam", "=", "0", "return", "wParam" ]
28.3
10.7
def SendGrrMessageThroughFleetspeak(grr_id, msg): """Sends the given GrrMessage through FS.""" fs_msg = fs_common_pb2.Message( message_type="GrrMessage", destination=fs_common_pb2.Address( client_id=GRRIDToFleetspeakID(grr_id), service_name="GRR")) fs_msg.data.Pack(msg.AsPrimitiveProto()) ...
[ "def", "SendGrrMessageThroughFleetspeak", "(", "grr_id", ",", "msg", ")", ":", "fs_msg", "=", "fs_common_pb2", ".", "Message", "(", "message_type", "=", "\"GrrMessage\"", ",", "destination", "=", "fs_common_pb2", ".", "Address", "(", "client_id", "=", "GRRIDToFlee...
46.125
9.125
def run(self): """ Run all steps """ for line_ in self.region_string.split('\n'): for line in line_.split(";"): self.parse_line(line) log.debug('Global state: {}'.format(self))
[ "def", "run", "(", "self", ")", ":", "for", "line_", "in", "self", ".", "region_string", ".", "split", "(", "'\\n'", ")", ":", "for", "line", "in", "line_", ".", "split", "(", "\";\"", ")", ":", "self", ".", "parse_line", "(", "line", ")", "log", ...
30.625
9.875
def update_state(self, session=None): """ Determines the overall state of the DagRun based on the state of its TaskInstances. :return: State """ dag = self.get_dag() tis = self.get_task_instances(session=session) self.log.debug("Updating state for %s co...
[ "def", "update_state", "(", "self", ",", "session", "=", "None", ")", ":", "dag", "=", "self", ".", "get_dag", "(", ")", "tis", "=", "self", ".", "get_task_instances", "(", "session", "=", "session", ")", "self", ".", "log", ".", "debug", "(", "\"Upd...
41.920455
22.238636
def touched_files(self, parent): """ :API: public """ try: return self._scm.changed_files(from_commit=parent, include_untracked=True, relative_to=get_buildroot()) except Scm.ScmException as e: raise self.WorkspaceE...
[ "def", "touched_files", "(", "self", ",", "parent", ")", ":", "try", ":", "return", "self", ".", "_scm", ".", "changed_files", "(", "from_commit", "=", "parent", ",", "include_untracked", "=", "True", ",", "relative_to", "=", "get_buildroot", "(", ")", ")"...
35.4
16.2
def has_receipt(item): """ Verify if a item has a receipt. """ pronac_id = str(item['idPronac']) item_id = str(item["idPlanilhaItens"]) combined_id = f'{pronac_id}/{item_id}' return combined_id in data.receipt.index
[ "def", "has_receipt", "(", "item", ")", ":", "pronac_id", "=", "str", "(", "item", "[", "'idPronac'", "]", ")", "item_id", "=", "str", "(", "item", "[", "\"idPlanilhaItens\"", "]", ")", "combined_id", "=", "f'{pronac_id}/{item_id}'", "return", "combined_id", ...
23.6
11.4
def _parse_subnet(self, subnet_dict): """Return the subnet, start, end, gateway of a subnet. """ if not subnet_dict: return alloc_pool = subnet_dict.get('allocation_pools') cidr = subnet_dict.get('cidr') subnet = cidr.split('/')[0] start = alloc_pool[0].get('s...
[ "def", "_parse_subnet", "(", "self", ",", "subnet_dict", ")", ":", "if", "not", "subnet_dict", ":", "return", "alloc_pool", "=", "subnet_dict", ".", "get", "(", "'allocation_pools'", ")", "cidr", "=", "subnet_dict", ".", "get", "(", "'cidr'", ")", "subnet", ...
44.692308
9.923077
def iter_attribute(iterable_name) -> Union[Iterable, Callable]: """Decorator implementing Iterator interface with nicer manner. Example ------- @iter_attribute('my_attr'): class DecoratedClass: ... Warning: ======== When using PyCharm or MYPY you'll probably see issues with d...
[ "def", "iter_attribute", "(", "iterable_name", ")", "->", "Union", "[", "Iterable", ",", "Callable", "]", ":", "def", "create_new_class", "(", "decorated_class", ")", "->", "Union", "[", "Iterable", ",", "Callable", "]", ":", "\"\"\"Class extender implementing __n...
39.566265
26.481928
def main(in_base, out_base, compiled_files, source_files, outfile=None, showasm=None, showast=False, do_verify=False, showgrammar=False, raise_on_error=False, do_linemaps=False, do_fragments=False): """ in_base base directory for input files out_base base directory for output file...
[ "def", "main", "(", "in_base", ",", "out_base", ",", "compiled_files", ",", "source_files", ",", "outfile", "=", "None", ",", "showasm", "=", "None", ",", "showast", "=", "False", ",", "do_verify", "=", "False", ",", "showgrammar", "=", "False", ",", "ra...
41.189944
17.759777
def document_core_programs(p): """ Document a subset of core programs with purpose (and intent) """ p.comment('programs.py', 'collects list of aikif programs to show progress and allows comments to be added to each file') p.comment('cls_file_mapping.py', 'uses ontology to get list of files to s...
[ "def", "document_core_programs", "(", "p", ")", ":", "p", ".", "comment", "(", "'programs.py'", ",", "'collects list of aikif programs to show progress and allows comments to be added to each file'", ")", "p", ".", "comment", "(", "'cls_file_mapping.py'", ",", "'uses ontology...
75.873016
40.920635
def uuid(self): '''Universally unique identifier for an instance of a :class:`Model`. ''' pk = self.pkvalue() if not pk: raise self.DoesNotExist( 'Object not saved. Cannot obtain universally unique id') return self.get_uuid(pk)
[ "def", "uuid", "(", "self", ")", ":", "pk", "=", "self", ".", "pkvalue", "(", ")", "if", "not", "pk", ":", "raise", "self", ".", "DoesNotExist", "(", "'Object not saved. Cannot obtain universally unique id'", ")", "return", "self", ".", "get_uuid", "(", "pk"...
36.875
20.875
def print_last_commands(): """Print the last 10 commands.""" iterable = archive.list_command_history(descending=True) for entry in islice(iterable, 0, 10): print(entry)
[ "def", "print_last_commands", "(", ")", ":", "iterable", "=", "archive", ".", "list_command_history", "(", "descending", "=", "True", ")", "for", "entry", "in", "islice", "(", "iterable", ",", "0", ",", "10", ")", ":", "print", "(", "entry", ")" ]
36.8
11
def update_r(self, fs=None, qinv=None, fc=None, kappa_c=1.0, kappa_tst_re=1.0, kappa_tst_im=0.0, kappa_pu_re=1.0, kappa_pu_im=0.0): """ Calculate the response function R(f,t) given the new parameters kappa_c(t), kappa_a(t), f_c(t), fs, and qinv. Parameters ...
[ "def", "update_r", "(", "self", ",", "fs", "=", "None", ",", "qinv", "=", "None", ",", "fc", "=", "None", ",", "kappa_c", "=", "1.0", ",", "kappa_tst_re", "=", "1.0", ",", "kappa_tst_im", "=", "0.0", ",", "kappa_pu_re", "=", "1.0", ",", "kappa_pu_im"...
40.375
19.525
def _collect_colored_outputs(unspent_outputs, asset_id, asset_quantity): """ Returns a list of colored outputs for the specified quantity. :param list[SpendableOutput] unspent_outputs: The list of available outputs. :param bytes asset_id: The ID of the asset to collect. :param i...
[ "def", "_collect_colored_outputs", "(", "unspent_outputs", ",", "asset_id", ",", "asset_quantity", ")", ":", "total_amount", "=", "0", "result", "=", "[", "]", "for", "output", "in", "unspent_outputs", ":", "if", "output", ".", "output", ".", "asset_id", "==",...
40.666667
18.857143
def _python_to_mod_new(changes: Changeset) -> Dict[str, List[List[bytes]]]: """ Convert a LdapChanges object to a modlist for add operation. """ table: LdapObjectClass = type(changes.src) fields = table.get_fields() result: Dict[str, List[List[bytes]]] = {} for name, field in fields.items(): ...
[ "def", "_python_to_mod_new", "(", "changes", ":", "Changeset", ")", "->", "Dict", "[", "str", ",", "List", "[", "List", "[", "bytes", "]", "]", "]", ":", "table", ":", "LdapObjectClass", "=", "type", "(", "changes", ".", "src", ")", "fields", "=", "t...
35.411765
16.823529
def authenticate(self, name=None, password=None, source=None, mechanism='DEFAULT', **kwargs): """**DEPRECATED**: Authenticate to use this database. Authentication lasts for the life of the underlying client instance, or until :meth:`logout` is called. Raises :class...
[ "def", "authenticate", "(", "self", ",", "name", "=", "None", ",", "password", "=", "None", ",", "source", "=", "None", ",", "mechanism", "=", "'DEFAULT'", ",", "*", "*", "kwargs", ")", ":", "if", "name", "is", "not", "None", "and", "not", "isinstanc...
44.609195
24.195402
def stop_serve_forever(self): """Stop serve_forever_stoppable().""" assert hasattr( self, "stop_request" ), "serve_forever_stoppable() must be called before" assert not self.stop_request, "stop_serve_forever() must only be called once" # # Flag stop request ...
[ "def", "stop_serve_forever", "(", "self", ")", ":", "assert", "hasattr", "(", "self", ",", "\"stop_request\"", ")", ",", "\"serve_forever_stoppable() must be called before\"", "assert", "not", "self", ".", "stop_request", ",", "\"stop_serve_forever() must only be called onc...
40.810811
19.27027
def apply_K(df, k): """Apply the geometric factors to the dataset and compute (apparent) resistivities/conductivities """ if 'k' not in df.columns: df['k'] = k if 'rho_a' not in df.columns: df['rho_a'] = df['r'] * df['k'] if 'sigma_a' not in df.columns: df['sigma_a'] = ...
[ "def", "apply_K", "(", "df", ",", "k", ")", ":", "if", "'k'", "not", "in", "df", ".", "columns", ":", "df", "[", "'k'", "]", "=", "k", "if", "'rho_a'", "not", "in", "df", ".", "columns", ":", "df", "[", "'rho_a'", "]", "=", "df", "[", "'r'", ...
25.8125
15.25
def where(cls, **kwargs): """ Returns a generator which yields instances matching the given query arguments. For example, this would yield all :py:class:`.Project`:: Project.where() And this would yield all launch approved :py:class:`.Project`:: Projec...
[ "def", "where", "(", "cls", ",", "*", "*", "kwargs", ")", ":", "_id", "=", "kwargs", ".", "pop", "(", "'id'", ",", "''", ")", "return", "cls", ".", "paginated_results", "(", "*", "cls", ".", "http_get", "(", "_id", ",", "params", "=", "kwargs", "...
28.375
24
def sendDAT(self): """This method sends the next DAT packet based on the data in the context. It returns a boolean indicating whether the transfer is finished.""" finished = False blocknumber = self.context.next_block # Test hook if DELAY_BLOCK and DELAY_BLOCK == ...
[ "def", "sendDAT", "(", "self", ")", ":", "finished", "=", "False", "blocknumber", "=", "self", ".", "context", ".", "next_block", "# Test hook", "if", "DELAY_BLOCK", "and", "DELAY_BLOCK", "==", "blocknumber", ":", "import", "time", "log", ".", "debug", "(", ...
40.733333
12.833333
def _create_barrier_entities(root_pipeline_key, child_pipeline_key, purpose, blocking_slot_keys): """Creates all of the entities required for a _BarrierRecord. Args: root_pipeline_key: The root pipeline this is p...
[ "def", "_create_barrier_entities", "(", "root_pipeline_key", ",", "child_pipeline_key", ",", "purpose", ",", "blocking_slot_keys", ")", ":", "result", "=", "[", "]", "blocking_slot_keys", "=", "list", "(", "blocking_slot_keys", ")", "barrier", "=", "_BarrierRecord", ...
37.5
19.045455
def mksls(src, dst=None): ''' Convert a kickstart file to an SLS file ''' mode = 'command' sls = {} ks_opts = {} with salt.utils.files.fopen(src, 'r') as fh_: for line in fh_: if line.startswith('#'): continue if mode == 'command': ...
[ "def", "mksls", "(", "src", ",", "dst", "=", "None", ")", ":", "mode", "=", "'command'", "sls", "=", "{", "}", "ks_opts", "=", "{", "}", "with", "salt", ".", "utils", ".", "files", ".", "fopen", "(", "src", ",", "'r'", ")", "as", "fh_", ":", ...
43.930556
16.409722
def hash_name(name, script_pubkey, register_addr=None): """ Generate the hash over a name and hex-string script pubkey """ bin_name = b40_to_bin(name) name_and_pubkey = bin_name + unhexlify(script_pubkey) if register_addr is not None: name_and_pubkey += str(register_addr) return hex_has...
[ "def", "hash_name", "(", "name", ",", "script_pubkey", ",", "register_addr", "=", "None", ")", ":", "bin_name", "=", "b40_to_bin", "(", "name", ")", "name_and_pubkey", "=", "bin_name", "+", "unhexlify", "(", "script_pubkey", ")", "if", "register_addr", "is", ...
30.090909
13.909091
def _long2bytesBigEndian(n, blocksize=0): """Convert a long integer to a byte string. If optional blocksize is given and greater than zero, pad the front of the byte string with binary zeros so that the length is a multiple of blocksize. """ # After much testing, this algorithm was deemed to b...
[ "def", "_long2bytesBigEndian", "(", "n", ",", "blocksize", "=", "0", ")", ":", "# After much testing, this algorithm was deemed to be the fastest.", "s", "=", "b''", "pack", "=", "struct", ".", "pack", "while", "n", ">", "0", ":", "s", "=", "pack", "(", "'>I'"...
26.875
22.375
def errors(self): # type: () -> List[Text] """ Returns all errors found with the bundle. """ try: self._errors.extend(self._validator) # type: List[Text] except StopIteration: pass return self._errors
[ "def", "errors", "(", "self", ")", ":", "# type: () -> List[Text]", "try", ":", "self", ".", "_errors", ".", "extend", "(", "self", ".", "_validator", ")", "# type: List[Text]", "except", "StopIteration", ":", "pass", "return", "self", ".", "_errors" ]
24.727273
16.727273
def _aggregate_on_chunks(x, f_agg, chunk_len): """ Takes the time series x and constructs a lower sampled version of it by applying the aggregation function f_agg on consecutive chunks of length chunk_len :param x: the time series to calculate the aggregation of :type x: numpy.ndarray :param f_...
[ "def", "_aggregate_on_chunks", "(", "x", ",", "f_agg", ",", "chunk_len", ")", ":", "return", "[", "getattr", "(", "x", "[", "i", "*", "chunk_len", ":", "(", "i", "+", "1", ")", "*", "chunk_len", "]", ",", "f_agg", ")", "(", ")", "for", "i", "in",...
49
27.8
def release(self): """ Release the lock. """ if self.is_locked_by_me(): os.remove(self.lock_filename) logger.debug('The lock {} is released by me (pid: {}).'.format(self.lock_filename, self.pid)) if self.fd: os.close(self.fd) ...
[ "def", "release", "(", "self", ")", ":", "if", "self", ".", "is_locked_by_me", "(", ")", ":", "os", ".", "remove", "(", "self", ".", "lock_filename", ")", "logger", ".", "debug", "(", "'The lock {} is released by me (pid: {}).'", ".", "format", "(", "self", ...
29.727273
17
def NTU_from_effectiveness(effectiveness, Cr, subtype='counterflow'): r'''Returns the Number of Transfer Units of a heat exchanger at a specified heat capacity rate, effectiveness, and configuration. The following configurations are supported: * Counterflow (ex. double-pipe) * Para...
[ "def", "NTU_from_effectiveness", "(", "effectiveness", ",", "Cr", ",", "subtype", "=", "'counterflow'", ")", ":", "if", "Cr", ">", "1", ":", "raise", "Exception", "(", "'Heat capacity rate must be less than 1 by definition.'", ")", "if", "subtype", "==", "'counterfl...
43.12605
27.588235
def norm_and_check(source_tree, requested): """Normalise and check a backend path. Ensure that the requested backend path is specified as a relative path, and resolves to a location under the given source tree. Return an absolute version of the requested path. """ if os.path.isabs(requested): ...
[ "def", "norm_and_check", "(", "source_tree", ",", "requested", ")", ":", "if", "os", ".", "path", ".", "isabs", "(", "requested", ")", ":", "raise", "ValueError", "(", "\"paths must be relative\"", ")", "abs_source", "=", "os", ".", "path", ".", "abspath", ...
41.090909
20.5
def generate_base_provider_parser(): """Function that generates the base provider to be used by all dns providers.""" parser = argparse.ArgumentParser(add_help=False) parser.add_argument('action', help='specify the action to take', default='list', choices=['create', 'list', 'update',...
[ "def", "generate_base_provider_parser", "(", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", "add_help", "=", "False", ")", "parser", ".", "add_argument", "(", "'action'", ",", "help", "=", "'specify the action to take'", ",", "default", "=", "'...
63.76
30.32
def handle_template(bot_or_project, name, target=None, **options): """ Copy either a bot layout template or a Trading-Bots project layout template into the specified directory. :param bot_or_project: The string 'bot' or 'project'. :param name: The name of the bot or project. :param target: The d...
[ "def", "handle_template", "(", "bot_or_project", ",", "name", ",", "target", "=", "None", ",", "*", "*", "options", ")", ":", "bot_or_project", "=", "bot_or_project", "paths_to_remove", "=", "[", "]", "verbosity", "=", "int", "(", "options", "[", "'verbosity...
41.042017
19.042017
def adjust_widths(self, max_width, colstats): """ Adjust column widths based on the least negative affect it will have on the viewing experience. We take note of the total character mass that will be clipped when each column should be narrowed. The actual score for clipping is based on...
[ "def", "adjust_widths", "(", "self", ",", "max_width", ",", "colstats", ")", ":", "adj_colstats", "=", "[", "]", "for", "x", "in", "colstats", ":", "if", "not", "x", "[", "'preformatted'", "]", ":", "adj_colstats", ".", "append", "(", "x", ")", "else",...
50.785714
14.892857
def set_energy_range(self, logemin, logemax): """Set the energy bounds of the analysis. This restricts the evaluation of the likelihood to the data that falls in this range. Input values will be rounded to the closest bin edge value. If either argument is None then the lower or upper ...
[ "def", "set_energy_range", "(", "self", ",", "logemin", ",", "logemax", ")", ":", "if", "logemin", "is", "None", ":", "logemin", "=", "self", ".", "log_energies", "[", "0", "]", "else", ":", "imin", "=", "int", "(", "utils", ".", "val_to_edge", "(", ...
30.761905
21.238095
def add_data(self, data): """ Add POST data. Args: data (dict): key => value dictionary """ if not self._data: self._data = {} self._data.update(data)
[ "def", "add_data", "(", "self", ",", "data", ")", ":", "if", "not", "self", ".", "_data", ":", "self", ".", "_data", "=", "{", "}", "self", ".", "_data", ".", "update", "(", "data", ")" ]
23
14
def get_term_freq_mat(self): ''' Returns ------- np.array with columns as categories and rows as terms ''' freq_mat = np.zeros(shape=(self.get_num_terms(), self.get_num_categories()), dtype=int) for cat_i in range(self.get_num_categories()): freq_mat[:...
[ "def", "get_term_freq_mat", "(", "self", ")", ":", "freq_mat", "=", "np", ".", "zeros", "(", "shape", "=", "(", "self", ".", "get_num_terms", "(", ")", ",", "self", ".", "get_num_categories", "(", ")", ")", ",", "dtype", "=", "int", ")", "for", "cat_...
38.6
26
def neigh(G: Graph, n: Node) -> RDFGraph: """ neigh(G, n) is the neighbourhood of the node n in the graph G. neigh(G, n) = arcsOut(G, n) ∪ arcsIn(G, n) """ return arcsOut(G, n) | arcsIn(G, n)
[ "def", "neigh", "(", "G", ":", "Graph", ",", "n", ":", "Node", ")", "->", "RDFGraph", ":", "return", "arcsOut", "(", "G", ",", "n", ")", "|", "arcsIn", "(", "G", ",", "n", ")" ]
34.833333
8.833333
def _get_acceptable_response_type(): """Return the mimetype for this request.""" if ('Accept' not in request.headers or request.headers['Accept'] in ALL_CONTENT_TYPES): return JSON acceptable_content_types = set( request.headers['ACCEPT'].strip().split(',')) if acceptable_con...
[ "def", "_get_acceptable_response_type", "(", ")", ":", "if", "(", "'Accept'", "not", "in", "request", ".", "headers", "or", "request", ".", "headers", "[", "'Accept'", "]", "in", "ALL_CONTENT_TYPES", ")", ":", "return", "JSON", "acceptable_content_types", "=", ...
36.714286
14.071429
def check_suspension(user_twitter_id_list): """ Looks up a list of user ids and checks whether they are currently suspended. Input: - user_twitter_id_list: A python list of Twitter user ids in integer format to be looked-up. Outputs: - suspended_user_twitter_id_list: A python list of suspended Twitter...
[ "def", "check_suspension", "(", "user_twitter_id_list", ")", ":", "####################################################################################################################", "# Log into my application.", "###################################################################################...
58.761905
34.920635
def update_user_settings(self, id, collapse_global_nav=None, manual_mark_as_read=None): """ Update user settings. Update an existing user's settings. """ path = {} data = {} params = {} # REQUIRED - PATH - id """ID""" path["id...
[ "def", "update_user_settings", "(", "self", ",", "id", ",", "collapse_global_nav", "=", "None", ",", "manual_mark_as_read", "=", "None", ")", ":", "path", "=", "{", "}", "data", "=", "{", "}", "params", "=", "{", "}", "# REQUIRED - PATH - id\r", "\"\"\"ID\"\...
40.444444
22.37037
def is_nonlinear(self): """If nonlinear properties are specified.""" return any( isinstance(p, NonlinearProperty) for p in [self.mod_reduc, self.damping])
[ "def", "is_nonlinear", "(", "self", ")", ":", "return", "any", "(", "isinstance", "(", "p", ",", "NonlinearProperty", ")", "for", "p", "in", "[", "self", ".", "mod_reduc", ",", "self", ".", "damping", "]", ")" ]
38
10.8
def ping(self, params=None): """ Returns True if the cluster is up, False otherwise. """ try: self.transport.perform_request('HEAD', '/', params=params) except TransportError: raise gen.Return(False) raise gen.Return(True)
[ "def", "ping", "(", "self", ",", "params", "=", "None", ")", ":", "try", ":", "self", ".", "transport", ".", "perform_request", "(", "'HEAD'", ",", "'/'", ",", "params", "=", "params", ")", "except", "TransportError", ":", "raise", "gen", ".", "Return"...
38.857143
13.571429
def POST(self, func, data): """Send POST request to execute Ndrive API :param func: The function name you want to execute in Ndrive API. :param params: Parameter data for HTTP request. :returns: ``metadata`` when success or ``False`` when failed """ s, message = self.ch...
[ "def", "POST", "(", "self", ",", "func", ",", "data", ")", ":", "s", ",", "message", "=", "self", ".", "checkAccount", "(", ")", "if", "s", "is", "False", ":", "return", "False", ",", "message", "url", "=", "nurls", "[", "func", "]", "r", "=", ...
31.588235
17.735294
def load_config(config_file='~/.stancache.ini'): """ Load config file into default settings """ if not os.path.exists(config_file): logging.warning('Config file does not exist: {}. Using default settings.'.format(config_file)) return ## get user-level config in *.ini format config = ...
[ "def", "load_config", "(", "config_file", "=", "'~/.stancache.ini'", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "config_file", ")", ":", "logging", ".", "warning", "(", "'Config file does not exist: {}. Using default settings.'", ".", "format", ...
41.357143
14
def _try_redeem_disposable_app(file, client): """ Attempt to redeem a one time code registred on the client. """ redeemedClient = client.redeem_onetime_code(None) if redeemedClient is None: return None else: return _BlotreDisposableApp(file, redeemedClient.client, ...
[ "def", "_try_redeem_disposable_app", "(", "file", ",", "client", ")", ":", "redeemedClient", "=", "client", ".", "redeem_onetime_code", "(", "None", ")", "if", "redeemedClient", "is", "None", ":", "return", "None", "else", ":", "return", "_BlotreDisposableApp", ...
32.583333
9.416667
def escape_path(path): """Escape any invalid characters in HTTP URL, and uppercase all escapes.""" # There's no knowing what character encoding was used to create URLs # containing %-escapes, but since we have to pick one to escape invalid # path characters, we pick UTF-8, as recommended in the HTML 4.0...
[ "def", "escape_path", "(", "path", ")", ":", "# There's no knowing what character encoding was used to create URLs", "# containing %-escapes, but since we have to pick one to escape invalid", "# path characters, we pick UTF-8, as recommended in the HTML 4.0", "# specification:", "# http://www.w3...
52.076923
19.076923
def merge_files(sources, destination): """Copy content of multiple files into a single file. :param list(str) sources: source file names (paths) :param str destination: destination file name (path) :return: """ with open(destination, 'w') as hout: for f in sources: if os.pa...
[ "def", "merge_files", "(", "sources", ",", "destination", ")", ":", "with", "open", "(", "destination", ",", "'w'", ")", "as", "hout", ":", "for", "f", "in", "sources", ":", "if", "os", ".", "path", ".", "exists", "(", "f", ")", ":", "with", "open"...
32.533333
14.8
def get_active_terms_not_agreed_to(user): """Checks to see if a specified user has agreed to all the latest terms and conditions""" if TERMS_EXCLUDE_USERS_WITH_PERM is not None: if user.has_perm(TERMS_EXCLUDE_USERS_WITH_PERM) and not user.is_superuser: # Django's has_perm() ...
[ "def", "get_active_terms_not_agreed_to", "(", "user", ")", ":", "if", "TERMS_EXCLUDE_USERS_WITH_PERM", "is", "not", "None", ":", "if", "user", ".", "has_perm", "(", "TERMS_EXCLUDE_USERS_WITH_PERM", ")", "and", "not", "user", ".", "is_superuser", ":", "# Django's has...
48.190476
27.666667
def layer_permutation(self, layer_partition, layout, qubit_subset): """Find a swap circuit that implements a permutation for this layer. The goal is to swap qubits such that qubits in the same two-qubit gates are adjacent. Based on Sergey Bravyi's algorithm. The layer_partitio...
[ "def", "layer_permutation", "(", "self", ",", "layer_partition", ",", "layout", ",", "qubit_subset", ")", ":", "if", "self", ".", "seed", "is", "None", ":", "self", ".", "seed", "=", "np", ".", "random", ".", "randint", "(", "0", ",", "np", ".", "iin...
45.833333
20.013333
def _print_header(cls): """ Decide if we print or not the header. """ if ( not PyFunceble.CONFIGURATION["quiet"] and not PyFunceble.CONFIGURATION["header_printed"] ): # * The quiet mode is not activated. # and # * The h...
[ "def", "_print_header", "(", "cls", ")", ":", "if", "(", "not", "PyFunceble", ".", "CONFIGURATION", "[", "\"quiet\"", "]", "and", "not", "PyFunceble", ".", "CONFIGURATION", "[", "\"header_printed\"", "]", ")", ":", "# * The quiet mode is not activated.", "# and", ...
31.129032
20.548387
def contains_one_of(self, elements): """ Ensures :attr:`subject` contains exactly one of *elements*, which must be an iterable. """ if sum(e in self._subject for e in elements) != 1: raise self._error_factory(_format("Expected {} to have exactly one of {}", self._subject, ele...
[ "def", "contains_one_of", "(", "self", ",", "elements", ")", ":", "if", "sum", "(", "e", "in", "self", ".", "_subject", "for", "e", "in", "elements", ")", "!=", "1", ":", "raise", "self", ".", "_error_factory", "(", "_format", "(", "\"Expected {} to have...
52.285714
21.714286