text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def get_svc_stats(self, svcs): """ Get statistics for Services, resp. Service entities """ stats = { "services.total": 0, "services.ok": 0, "services.warning": 0, "services.critical": 0, "services.unknown": 0, "services.flapping": 0...
[ "def", "get_svc_stats", "(", "self", ",", "svcs", ")", ":", "stats", "=", "{", "\"services.total\"", ":", "0", ",", "\"services.ok\"", ":", "0", ",", "\"services.warning\"", ":", "0", ",", "\"services.critical\"", ":", "0", ",", "\"services.unknown\"", ":", ...
39.363636
15.393939
def get(request, obj_id=None): """Lists all tags :returns: json """ res = Result() if obj_id: if obj_id == '0': obj = { 'id': 0, 'name': 'TAGLESS', 'artist': False, } else: obj = get_object_or_404(Ta...
[ "def", "get", "(", "request", ",", "obj_id", "=", "None", ")", ":", "res", "=", "Result", "(", ")", "if", "obj_id", ":", "if", "obj_id", "==", "'0'", ":", "obj", "=", "{", "'id'", ":", "0", ",", "'name'", ":", "'TAGLESS'", ",", "'artist'", ":", ...
27.354839
17.612903
def nas_auto_qos_set_cos(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") nas = ET.SubElement(config, "nas", xmlns="urn:brocade.com:mgmt:brocade-qos") auto_qos = ET.SubElement(nas, "auto-qos") set = ET.SubElement(auto_qos, "set") cos = ET....
[ "def", "nas_auto_qos_set_cos", "(", "self", ",", "*", "*", "kwargs", ")", ":", "config", "=", "ET", ".", "Element", "(", "\"config\"", ")", "nas", "=", "ET", ".", "SubElement", "(", "config", ",", "\"nas\"", ",", "xmlns", "=", "\"urn:brocade.com:mgmt:broca...
38.25
11
def _retf16(ins): """ Returns from a procedure / function a Fixed Point (32bits) value """ output = _f16_oper(ins.quad[1]) output.append('#pragma opt require hl,de') output.append('jp %s' % str(ins.quad[2])) return output
[ "def", "_retf16", "(", "ins", ")", ":", "output", "=", "_f16_oper", "(", "ins", ".", "quad", "[", "1", "]", ")", "output", ".", "append", "(", "'#pragma opt require hl,de'", ")", "output", ".", "append", "(", "'jp %s'", "%", "str", "(", "ins", ".", "...
34.142857
8.857143
def checkState(self): """ Returns Qt.Checked or Qt.Unchecked. """ if self.data is True: return Qt.Checked elif self.data is False: return Qt.Unchecked else: raise ValueError("Unexpected data: {!r}".format(self.data))
[ "def", "checkState", "(", "self", ")", ":", "if", "self", ".", "data", "is", "True", ":", "return", "Qt", ".", "Checked", "elif", "self", ".", "data", "is", "False", ":", "return", "Qt", ".", "Unchecked", "else", ":", "raise", "ValueError", "(", "\"U...
31.555556
12.888889
def find_target_container(portal_type, record): """Locates a target container for the given portal_type and record :param record: The dictionary representation of a content object :type record: dict :returns: folder which contains the object :rtype: object """ portal_type = portal_type or r...
[ "def", "find_target_container", "(", "portal_type", ",", "record", ")", ":", "portal_type", "=", "portal_type", "or", "record", ".", "get", "(", "\"portal_type\"", ")", "container", "=", "get_container_for", "(", "portal_type", ")", "if", "container", ":", "retu...
28.366667
19.4
def with_filter(self, filter_func): ''' Returns a new service which will process requests with the specified filter. Filtering operations can include logging, automatic retrying, etc... The filter is a lambda which receives the HTTPRequest and another lambda. The filter can pe...
[ "def", "with_filter", "(", "self", ",", "filter_func", ")", ":", "res", "=", "ServiceBusService", "(", "service_namespace", "=", "self", ".", "service_namespace", ",", "authentication", "=", "self", ".", "authentication", ")", "old_filter", "=", "self", ".", "...
40
22.8
def move(self, position, slowdown=0): """Move to the specified sample position. :param position: The target position. :param slowdown: The slowdown code, an integer in the range 0 to 14, used to scale the stepper motor speed. 0, the default, is the fastest rate and 14 th...
[ "def", "move", "(", "self", ",", "position", ",", "slowdown", "=", "0", ")", ":", "cmd", "=", "'MOVE'", ",", "[", "Float", ",", "Integer", ",", "Integer", "(", "min", "=", "0", ",", "max", "=", "14", ")", "]", "self", ".", "_write", "(", "cmd",...
40.363636
17.272727
def get_dict(dictionary, *keys,**kwargs): """ This function allows traversals over several keys to be performed by passing a list of keys:: get_dict(d,key1,key2,key3) = d[key1][key2][key3] """ if 'default' in kwargs: default = kwargs['default'] else: default = None ex...
[ "def", "get_dict", "(", "dictionary", ",", "*", "keys", ",", "*", "*", "kwargs", ")", ":", "if", "'default'", "in", "kwargs", ":", "default", "=", "kwargs", "[", "'default'", "]", "else", ":", "default", "=", "None", "existing", "=", "dictionary", "for...
20.291667
19.708333
def update_portal(self, portal_obj): """ Implements the Update device Portals API. This function is extremely dangerous. The portal object you pass in will completely overwrite the portal. http://docs.exosite.com/portals/#update-portal """ header...
[ "def", "update_portal", "(", "self", ",", "portal_obj", ")", ":", "headers", "=", "{", "'User-Agent'", ":", "self", ".", "user_agent", "(", ")", ",", "}", "headers", ".", "update", "(", "self", ".", "headers", "(", ")", ")", "r", "=", "requests", "."...
37.956522
17.26087
def strip_vl_extension(filename): """Strip the vega-lite extension (either vl.json or json) from filename""" for ext in ['.vl.json', '.json']: if filename.endswith(ext): return filename[:-len(ext)] else: return filename
[ "def", "strip_vl_extension", "(", "filename", ")", ":", "for", "ext", "in", "[", "'.vl.json'", ",", "'.json'", "]", ":", "if", "filename", ".", "endswith", "(", "ext", ")", ":", "return", "filename", "[", ":", "-", "len", "(", "ext", ")", "]", "else"...
36.142857
9.285714
def parse_timing(self, nids=None): """ Parse the timer data in the main output file(s) of Abinit. Requires timopt /= 0 in the input file (usually timopt = -1) Args: nids: optional list of node identifiers used to filter the tasks. Return: :class:`AbinitTimerParser` ...
[ "def", "parse_timing", "(", "self", ",", "nids", "=", "None", ")", ":", "# Get the list of output files according to nids.", "paths", "=", "[", "task", ".", "output_file", ".", "path", "for", "task", "in", "self", ".", "iflat_tasks", "(", "nids", "=", "nids", ...
34.35
20.85
def by_title(cls, title, conn=None, google_user=None, google_password=None): """ Open the first document with the given ``title`` that is returned by document search. """ conn = Connection.connect(conn=conn, google_user=google_user, google_passw...
[ "def", "by_title", "(", "cls", ",", "title", ",", "conn", "=", "None", ",", "google_user", "=", "None", ",", "google_password", "=", "None", ")", ":", "conn", "=", "Connection", ".", "connect", "(", "conn", "=", "conn", ",", "google_user", "=", "google...
51.75
10.916667
def validateElement(self, doc, elem): """Try to validate the subtree under an element """ if doc is None: doc__o = None else: doc__o = doc._o if elem is None: elem__o = None else: elem__o = elem._o ret = libxml2mod.xmlValidateElement(self._o, doc__o, elem__o) retu...
[ "def", "validateElement", "(", "self", ",", "doc", ",", "elem", ")", ":", "if", "doc", "is", "None", ":", "doc__o", "=", "None", "else", ":", "doc__o", "=", "doc", ".", "_o", "if", "elem", "is", "None", ":", "elem__o", "=", "None", "else", ":", "...
39.875
9.75
def get_datasource(self, source_id, datasource_id): """ Get a Datasource object :rtype: Datasource """ target_url = self.client.get_url('DATASOURCE', 'GET', 'single', {'source_id': source_id, 'datasource_id': datasource_id}) return self.client.get_manager(Datasource)._ge...
[ "def", "get_datasource", "(", "self", ",", "source_id", ",", "datasource_id", ")", ":", "target_url", "=", "self", ".", "client", ".", "get_url", "(", "'DATASOURCE'", ",", "'GET'", ",", "'single'", ",", "{", "'source_id'", ":", "source_id", ",", "'datasource...
40.75
23.75
def _apply_gradients_and_copy(self, opt, raw_grad_list, ps_var_grads): """ Apply averaged gradients to ps vars, and then copy the updated variables back to each tower. Args: raw_grad_list: Ngpu x Nvar x 2 gradient list from all towers ps_var_grads: Nvar x 2 (grad...
[ "def", "_apply_gradients_and_copy", "(", "self", ",", "opt", ",", "raw_grad_list", ",", "ps_var_grads", ")", ":", "# TODO do this for variables together?", "with", "tf", ".", "name_scope", "(", "'apply_gradients'", ")", ":", "var_update_ops", "=", "[", "]", "for", ...
44.62963
18.777778
def _supply_data(data_sink, context): """ Supply data to the data sink """ try: data_sink.sink(context) except Exception as e: ex = ValueError("An exception occurred while " "supplying data to data sink '{ds}'\n\n" "{e}\n\n" "{help}".format(ds=context.name...
[ "def", "_supply_data", "(", "data_sink", ",", "context", ")", ":", "try", ":", "data_sink", ".", "sink", "(", "context", ")", "except", "Exception", "as", "e", ":", "ex", "=", "ValueError", "(", "\"An exception occurred while \"", "\"supplying data to data sink '{...
33.416667
12.916667
def info(self, page, version=None): """Returns informations of *page*. Informations of the last version is returned if *version* is not set. """ return (self._dokuwiki.send('wiki.getPageInfoVersion', page, version) if version is not None else self._dokuwik...
[ "def", "info", "(", "self", ",", "page", ",", "version", "=", "None", ")", ":", "return", "(", "self", ".", "_dokuwiki", ".", "send", "(", "'wiki.getPageInfoVersion'", ",", "page", ",", "version", ")", "if", "version", "is", "not", "None", "else", "sel...
49.571429
10.714286
def _linalg_cho_factor(A, rho, lower=False, check_finite=True): """Patched version of :func:`sporco.linalg.cho_factor`.""" N, M = A.shape if N >= M: c, lwr = _cho_factor( A.T.dot(A) + rho * cp.identity(M, dtype=A.dtype), lower=lower, check_finite=check_finite) else: ...
[ "def", "_linalg_cho_factor", "(", "A", ",", "rho", ",", "lower", "=", "False", ",", "check_finite", "=", "True", ")", ":", "N", ",", "M", "=", "A", ".", "shape", "if", "N", ">=", "M", ":", "c", ",", "lwr", "=", "_cho_factor", "(", "A", ".", "T"...
35.769231
19.923077
def p_statement_list_1(self, p): '''statement_list : statement SEMICOLON statement_list''' p[0] = p[3] if p[1] is not None: p[0].children.insert(0, p[1])
[ "def", "p_statement_list_1", "(", "self", ",", "p", ")", ":", "p", "[", "0", "]", "=", "p", "[", "3", "]", "if", "p", "[", "1", "]", "is", "not", "None", ":", "p", "[", "0", "]", ".", "children", ".", "insert", "(", "0", ",", "p", "[", "1...
37
13.4
def add_unique_postfix(fn): """__source__ = 'http://code.activestate.com/recipes/577200-make-unique-file-name/'""" if not os.path.exists(fn): return fn path, name = os.path.split(fn) name, ext = os.path.splitext(name) make_fn = lambda i: os.path.join(path, '%s(%d)%s' % (name, i, ext)) ...
[ "def", "add_unique_postfix", "(", "fn", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "fn", ")", ":", "return", "fn", "path", ",", "name", "=", "os", ".", "path", ".", "split", "(", "fn", ")", "name", ",", "ext", "=", "os", ".",...
30.857143
17.142857
def _stmt_from_rule(model, rule_name, stmts): """Return the INDRA Statement corresponding to a given rule by name.""" stmt_uuid = None for ann in model.annotations: if ann.predicate == 'from_indra_statement': if ann.subject == rule_name: stmt_uuid = ann.object ...
[ "def", "_stmt_from_rule", "(", "model", ",", "rule_name", ",", "stmts", ")", ":", "stmt_uuid", "=", "None", "for", "ann", "in", "model", ".", "annotations", ":", "if", "ann", ".", "predicate", "==", "'from_indra_statement'", ":", "if", "ann", ".", "subject...
35.916667
9.666667
def get(self, id=None): """ 获取指定部门列表 https://work.weixin.qq.com/api/doc#90000/90135/90208 权限说明: 只能拉取token对应的应用的权限范围内的部门列表 :param id: 部门id。获取指定部门及其下的子部门。 如果不填,默认获取全量组织架构 :return: 部门列表 """ if id is None: res = self._get('department/lis...
[ "def", "get", "(", "self", ",", "id", "=", "None", ")", ":", "if", "id", "is", "None", ":", "res", "=", "self", ".", "_get", "(", "'department/list'", ")", "else", ":", "res", "=", "self", ".", "_get", "(", "'department/list'", ",", "params", "=", ...
24.705882
19.529412
def updatepLvlNextFunc(self): ''' A method that creates the pLvlNextFunc attribute as a sequence of linear functions, indicating constant expected permanent income growth across permanent income levels. Draws on the attribute PermGroFac, and installs a special retirement functio...
[ "def", "updatepLvlNextFunc", "(", "self", ")", ":", "orig_time", "=", "self", ".", "time_flow", "self", ".", "timeFwd", "(", ")", "pLvlNextFunc", "=", "[", "]", "for", "t", "in", "range", "(", "self", ".", "T_cycle", ")", ":", "pLvlNextFunc", ".", "app...
30.076923
24.692308
def create_external_feed_groups(self, url, group_id, header_match=None, verbosity=None): """ Create an external feed. Create a new external feed for the course or group. """ path = {} data = {} params = {} # REQUIRED - PATH - group_id ...
[ "def", "create_external_feed_groups", "(", "self", ",", "url", ",", "group_id", ",", "header_match", "=", "None", ",", "verbosity", "=", "None", ")", ":", "path", "=", "{", "}", "data", "=", "{", "}", "params", "=", "{", "}", "# REQUIRED - PATH - group_id\...
39.096774
23.032258
def reset(self): """Reset the instance - reset rows and header """ self._hline_string = None self._row_size = None self._header = [] self._rows = []
[ "def", "reset", "(", "self", ")", ":", "self", ".", "_hline_string", "=", "None", "self", ".", "_row_size", "=", "None", "self", ".", "_header", "=", "[", "]", "self", ".", "_rows", "=", "[", "]" ]
19.7
16.3
async def get_guild_count(self, bot_id: int=None): """This function is a coroutine. Gets a guild count from discordbots.org Parameters ========== bot_id: int[Optional] The bot_id of the bot you want to lookup. Defaults to the Bot provided in Client init...
[ "async", "def", "get_guild_count", "(", "self", ",", "bot_id", ":", "int", "=", "None", ")", ":", "if", "bot_id", "is", "None", ":", "bot_id", "=", "self", ".", "bot_id", "return", "await", "self", ".", "http", ".", "get_guild_count", "(", "bot_id", ")...
26.043478
21.043478
def create_raw(self, key, value): """Create method of CRUD operation for raw data. Args: key (string): The variable to write to the DB. value (any): The data to write to the DB. Returns: (string): Result of DB write. """ data = None i...
[ "def", "create_raw", "(", "self", ",", "key", ",", "value", ")", ":", "data", "=", "None", "if", "key", "is", "not", "None", "and", "value", "is", "not", "None", ":", "data", "=", "self", ".", "db", ".", "create", "(", "key", ".", "strip", "(", ...
31.5
18.1875
def GetMemSharedSavedMB(self): '''Retrieves the estimated amount of physical memory on the host saved from copy-on-write (COW) shared guest physical memory.''' counter = c_uint() ret = vmGuestLib.VMGuestLib_GetMemSharedSavedMB(self.handle.value, byref(counter)) if ret != VMGUE...
[ "def", "GetMemSharedSavedMB", "(", "self", ")", ":", "counter", "=", "c_uint", "(", ")", "ret", "=", "vmGuestLib", ".", "VMGuestLib_GetMemSharedSavedMB", "(", "self", ".", "handle", ".", "value", ",", "byref", "(", "counter", ")", ")", "if", "ret", "!=", ...
56.285714
26.571429
def transformation_get(node_id): """Get all the transformations of a node. The node id must be specified in the url. You can also pass transformation_type. """ exp = experiment(session) # get the parameters transformation_type = request_parameter(parameter="transformation_type", ...
[ "def", "transformation_get", "(", "node_id", ")", ":", "exp", "=", "experiment", "(", "session", ")", "# get the parameters", "transformation_type", "=", "request_parameter", "(", "parameter", "=", "\"transformation_type\"", ",", "parameter_type", "=", "\"known_class\""...
35.789474
20
def update_metadata(self, key, value): """Set *key* in the metadata to *value*. Returns the previous value of *key*, or None if the key was not previously set. """ old_value = self.contents['metadata'].get(key) self.contents['metadata'][key] = value self._log('Up...
[ "def", "update_metadata", "(", "self", ",", "key", ",", "value", ")", ":", "old_value", "=", "self", ".", "contents", "[", "'metadata'", "]", ".", "get", "(", "key", ")", "self", ".", "contents", "[", "'metadata'", "]", "[", "key", "]", "=", "value",...
37.4
13.7
def result_report_class_wise_average(self): """Report class-wise averages Returns ------- str result report in string format """ results = self.results_class_wise_average_metrics() output = self.ui.section_header('Class-wise average metrics (macro-...
[ "def", "result_report_class_wise_average", "(", "self", ")", ":", "results", "=", "self", ".", "results_class_wise_average_metrics", "(", ")", "output", "=", "self", ".", "ui", ".", "section_header", "(", "'Class-wise average metrics (macro-average)'", ",", "indent", ...
33.693878
28.265306
def backup_db(release=None, limit=5): """ Backup database and associate it with current release """ assert "mysql_user" in env, "Missing mysqL_user in env" assert "mysql_password" in env, "Missing mysql_password in env" assert "mysql_host" in env, "Missing mysql_host in env" assert "mysql_d...
[ "def", "backup_db", "(", "release", "=", "None", ",", "limit", "=", "5", ")", ":", "assert", "\"mysql_user\"", "in", "env", ",", "\"Missing mysqL_user in env\"", "assert", "\"mysql_password\"", "in", "env", ",", "\"Missing mysql_password in env\"", "assert", "\"mysq...
29.5625
22.0625
def _generate_placeholder(readable_text=None): """Generate a placeholder name to use while updating WeldObject. Parameters ---------- readable_text : str, optional Appended to the name for a more understandable placeholder. Returns ------- str ...
[ "def", "_generate_placeholder", "(", "readable_text", "=", "None", ")", ":", "name", "=", "'_interm_'", "+", "str", "(", "Cache", ".", "_counter", ")", "Cache", ".", "_counter", "+=", "1", "if", "readable_text", "is", "not", "None", ":", "assert", "isinsta...
25.272727
19.681818
def load_gene_exp_to_df(inst_path): ''' Loads gene expression data from 10x in sparse matrix format and returns a Pandas dataframe ''' import pandas as pd from scipy import io from scipy import sparse from ast import literal_eval as make_tuple # matrix Matrix = io.mmread( inst_...
[ "def", "load_gene_exp_to_df", "(", "inst_path", ")", ":", "import", "pandas", "as", "pd", "from", "scipy", "import", "io", "from", "scipy", "import", "sparse", "from", "ast", "import", "literal_eval", "as", "make_tuple", "# matrix", "Matrix", "=", "io", ".", ...
23.545455
21.262626
def tree_probe(self, **kwargs): """ Perform an os walk down a file system tree, starting from a **kwargs identified 'root', and return lists of files and directories found. kwargs: root = '/some/path' return { 'status': True, 'l...
[ "def", "tree_probe", "(", "self", ",", "*", "*", "kwargs", ")", ":", "str_topDir", "=", "\".\"", "l_dirs", "=", "[", "]", "l_files", "=", "[", "]", "b_status", "=", "False", "str_path", "=", "''", "l_dirsHere", "=", "[", "]", "l_filesHere", "=", "[",...
35.160714
19.660714
def shared(self, value, name=None): """ Create a shared theano scalar value. """ if type(value) == int: final_value = np.array(value, dtype="int32") elif type(value) == float: final_value = np.array(value, dtype=env.FLOATX) else: final_...
[ "def", "shared", "(", "self", ",", "value", ",", "name", "=", "None", ")", ":", "if", "type", "(", "value", ")", "==", "int", ":", "final_value", "=", "np", ".", "array", "(", "value", ",", "dtype", "=", "\"int32\"", ")", "elif", "type", "(", "va...
31.333333
12.333333
def get_template_file(args): """Returns valid template file, generating the default template file if it doesn't exist and one wasn't specified on command line. :param args: Argument collection as generated by parseargs :return file""" if args.template is None: template_filename = os.geten...
[ "def", "get_template_file", "(", "args", ")", ":", "if", "args", ".", "template", "is", "None", ":", "template_filename", "=", "os", ".", "getenv", "(", "\"HOME\"", ")", "+", "\"/.mvmany.template\"", "try", ":", "template_filename", "=", "open", "(", "templa...
34.83871
19.354839
def from_locale(cls, locale): """ Create a new Language instance from a locale string :param locale: locale as string :return: Language instance with instance.locale() == locale if locale is valid else instance of Unknown Language """ locale = str(locale) if local...
[ "def", "from_locale", "(", "cls", ",", "locale", ")", ":", "locale", "=", "str", "(", "locale", ")", "if", "locale", "is", "'unknown'", ":", "return", "UnknownLanguage", "(", "locale", ")", "try", ":", "return", "cls", ".", "_from_xyz", "(", "'locale'", ...
40.785714
14.071429
def setwinsize(fd, rows_cols): """ set the terminal size of a tty file descriptor. borrowed logic from pexpect.py """ rows, cols = rows_cols TIOCSWINSZ = getattr(termios, 'TIOCSWINSZ', -2146929561) s = struct.pack('HHHH', rows, cols, 0, 0) fcntl.ioctl(fd, TIOCSWINSZ, s)
[ "def", "setwinsize", "(", "fd", ",", "rows_cols", ")", ":", "rows", ",", "cols", "=", "rows_cols", "TIOCSWINSZ", "=", "getattr", "(", "termios", ",", "'TIOCSWINSZ'", ",", "-", "2146929561", ")", "s", "=", "struct", ".", "pack", "(", "'HHHH'", ",", "row...
36.125
11.875
def remove_dataset(self, dataset=None, **kwargs): """ Remove a dataset from the Bundle. This removes all matching Parameters from the dataset, model, and constraint contexts (by default if the context tag is not provided). You must provide some sort of filter or this will raise an Erro...
[ "def", "remove_dataset", "(", "self", ",", "dataset", "=", "None", ",", "*", "*", "kwargs", ")", ":", "self", ".", "_kwargs_checks", "(", "kwargs", ")", "# Let's avoid deleting ALL parameters from the matching contexts", "if", "dataset", "is", "None", "and", "not"...
38.445946
21.22973
def to_query_parameters(parameters): """Converts DB-API parameter values into query parameters. :type parameters: Mapping[str, Any] or Sequence[Any] :param parameters: A dictionary or sequence of query parameter values. :rtype: List[google.cloud.bigquery.query._AbstractQueryParameter] :returns: A ...
[ "def", "to_query_parameters", "(", "parameters", ")", ":", "if", "parameters", "is", "None", ":", "return", "[", "]", "if", "isinstance", "(", "parameters", ",", "collections_abc", ".", "Mapping", ")", ":", "return", "to_query_parameters_dict", "(", "parameters"...
33.8125
19.625
def to_xml(self, f=None): """Get this domain as an XML DOM Document :param f: Optional File to dump directly to :type f: File or Stream :return: File object where the XML has been dumped to :rtype: file """ if not f: from tempfile import TemporaryFile...
[ "def", "to_xml", "(", "self", ",", "f", "=", "None", ")", ":", "if", "not", "f", ":", "from", "tempfile", "import", "TemporaryFile", "f", "=", "TemporaryFile", "(", ")", "print", ">>", "f", ",", "'<?xml version=\"1.0\" encoding=\"UTF-8\"?>'", "print", ">>", ...
38.088235
14.264706
def removeLogicalInterfaceFromThingType(self, thingTypeId, logicalInterfaceId): """ Removes a logical interface from a thing type. Parameters: - thingTypeId (string) - the thing type - logicalInterfaceId (string) - the id returned by the platform on creation of the logica...
[ "def", "removeLogicalInterfaceFromThingType", "(", "self", ",", "thingTypeId", ",", "logicalInterfaceId", ")", ":", "req", "=", "ApiClient", ".", "oneThingTypeLogicalInterfaceUrl", "%", "(", "self", ".", "host", ",", "thingTypeId", ",", "logicalInterfaceId", ")", "r...
54.666667
28.533333
def import_status(handler, host=None, core_name=None, verbose=False): ''' Submits an import command to the specified handler using specified options. This command can only be run if the minion is configured with solr.type: 'master' handler : str The name of the data import handler. host...
[ "def", "import_status", "(", "handler", ",", "host", "=", "None", ",", "core_name", "=", "None", ",", "verbose", "=", "False", ")", ":", "if", "not", "_is_master", "(", ")", "and", "_get_none_or_value", "(", "host", ")", "is", "None", ":", "errors", "=...
32.176471
24.235294
def serialized(self, prepend_date=True): """Return a string fully representing the fact.""" name = self.serialized_name() datetime = self.serialized_time(prepend_date) return "%s %s" % (datetime, name)
[ "def", "serialized", "(", "self", ",", "prepend_date", "=", "True", ")", ":", "name", "=", "self", ".", "serialized_name", "(", ")", "datetime", "=", "self", ".", "serialized_time", "(", "prepend_date", ")", "return", "\"%s %s\"", "%", "(", "datetime", ","...
45.8
3.4
def add_markdown_cell(self, text): """Add a markdown cell to the notebook Parameters ---------- code : str Cell content """ markdown_cell = { "cell_type": "markdown", "metadata": {}, "source": [rst2md(text)] } ...
[ "def", "add_markdown_cell", "(", "self", ",", "text", ")", ":", "markdown_cell", "=", "{", "\"cell_type\"", ":", "\"markdown\"", ",", "\"metadata\"", ":", "{", "}", ",", "\"source\"", ":", "[", "rst2md", "(", "text", ")", "]", "}", "self", ".", "work_not...
25.642857
15.142857
def add_unique_template_variables(self, options): """Update map template variables specific to heatmap visual""" # set line stroke dash interval based on line_stroke property if self.line_stroke in ["dashed", "--"]: self.line_dash_array = [6, 4] elif self.line_stroke in ["do...
[ "def", "add_unique_template_variables", "(", "self", ",", "options", ")", ":", "# set line stroke dash interval based on line_stroke property", "if", "self", ".", "line_stroke", "in", "[", "\"dashed\"", ",", "\"--\"", "]", ":", "self", ".", "line_dash_array", "=", "["...
40.52
16.12
def set_object_cache(self, notify_func=None, getbuffer_func=None): """ Set the object cache "notifyObjectCompiled" and "getBuffer" callbacks to the given Python functions. """ self._object_cache_notify = notify_func self._object_cache_getbuffer = getbuffer_func # ...
[ "def", "set_object_cache", "(", "self", ",", "notify_func", "=", "None", ",", "getbuffer_func", "=", "None", ")", ":", "self", ".", "_object_cache_notify", "=", "notify_func", "self", ".", "_object_cache_getbuffer", "=", "getbuffer_func", "# Lifetime of the object cac...
46.75
15.416667
def _convert_agent_types(ind, to_string=False, **kwargs): '''Convenience method to allow specifying agents by class or class name.''' if to_string: return serialize_distribution(ind, **kwargs) return deserialize_distribution(ind, **kwargs)
[ "def", "_convert_agent_types", "(", "ind", ",", "to_string", "=", "False", ",", "*", "*", "kwargs", ")", ":", "if", "to_string", ":", "return", "serialize_distribution", "(", "ind", ",", "*", "*", "kwargs", ")", "return", "deserialize_distribution", "(", "in...
51
20.2
def task_view_link(self, ): """View the link of the current task :returns: None :rtype: None :raises: None """ if not self.cur_task: return e = self.cur_task.element if isinstance(e, djadapter.models.Asset): self.view_asset(e) ...
[ "def", "task_view_link", "(", "self", ",", ")", ":", "if", "not", "self", ".", "cur_task", ":", "return", "e", "=", "self", ".", "cur_task", ".", "element", "if", "isinstance", "(", "e", ",", "djadapter", ".", "models", ".", "Asset", ")", ":", "self"...
24.714286
14.785714
def accept(self, evt): """ write setting to the preferences """ # determine if application is a script file or frozen exe (pyinstaller) frozen = getattr(sys, 'frozen', False) if frozen: app_file = sys.executable else: app_file = Pa...
[ "def", "accept", "(", "self", ",", "evt", ")", ":", "# determine if application is a script file or frozen exe (pyinstaller)\r", "frozen", "=", "getattr", "(", "sys", ",", "'frozen'", ",", "False", ")", "if", "frozen", ":", "app_file", "=", "sys", ".", "executable...
42.837838
19.864865
def _path_has_ok_chars(path): """ Validate path for invalid characters. :param path: str possible filesystem path :return: path if it was ok otherwise raises error """ basename = os.path.basename(path) if any([bad_char in basename for bad_char in INVALID_PATH_CHARS]): raise argpa...
[ "def", "_path_has_ok_chars", "(", "path", ")", ":", "basename", "=", "os", ".", "path", ".", "basename", "(", "path", ")", "if", "any", "(", "[", "bad_char", "in", "basename", "for", "bad_char", "in", "INVALID_PATH_CHARS", "]", ")", ":", "raise", "argpar...
41.2
15.6
def analyze_section(section: SoS_Step, default_input: Optional[sos_targets] = None, default_output: Optional[sos_targets] = None, context={}, vars_and_output_only: bool = False) -> Dict[str, Any]: '''Analyze a section for how it uses in...
[ "def", "analyze_section", "(", "section", ":", "SoS_Step", ",", "default_input", ":", "Optional", "[", "sos_targets", "]", "=", "None", ",", "default_output", ":", "Optional", "[", "sos_targets", "]", "=", "None", ",", "context", "=", "{", "}", ",", "vars_...
43.196429
21.267857
def getOverlayWidthInMeters(self, ulOverlayHandle): """Returns the width of the overlay quad in meters. By default overlays are rendered on a quad that is 1 meter across""" fn = self.function_table.getOverlayWidthInMeters pfWidthInMeters = c_float() result = fn(ulOverlayHandle, byref(pf...
[ "def", "getOverlayWidthInMeters", "(", "self", ",", "ulOverlayHandle", ")", ":", "fn", "=", "self", ".", "function_table", ".", "getOverlayWidthInMeters", "pfWidthInMeters", "=", "c_float", "(", ")", "result", "=", "fn", "(", "ulOverlayHandle", ",", "byref", "("...
53.428571
13.714286
def run_top_task(self, task_name=None, sort=None, **kwargs): """Finds and runs a pending task that in the first of the sorting list. Parameters ----------- task_name : str The task name. sort : List of tuple PyMongo sort comment, search "PyMongo find one ...
[ "def", "run_top_task", "(", "self", ",", "task_name", "=", "None", ",", "sort", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "not", "isinstance", "(", "task_name", ",", "str", ")", ":", "# is None:", "raise", "Exception", "(", "\"task_name shoul...
44.166667
23.404762
def validity_duration(self): """ How long this parameter value is valid. .. note: There is also an option when subscribing to get updated when the parameter values expire. :type: :class:`~datetime.timedelta` """ if self._proto.HasField('expireMillis'): ...
[ "def", "validity_duration", "(", "self", ")", ":", "if", "self", ".", "_proto", ".", "HasField", "(", "'expireMillis'", ")", ":", "return", "timedelta", "(", "milliseconds", "=", "self", ".", "_proto", ".", "expireMillis", ")", "return", "None" ]
33
16.666667
def isInNet(host, pattern, mask): """ Pattern and mask specification is done the same way as for SOCKS configuration. :param str host: a DNS hostname, or IP address. If a hostname is passed, it will be resolved into an IP address by this function. :param str pattern: an IP address pattern in th...
[ "def", "isInNet", "(", "host", ",", "pattern", ",", "mask", ")", ":", "host_ip", "=", "host", "if", "is_ipv4_address", "(", "host", ")", "else", "dnsResolve", "(", "host", ")", "if", "not", "host_ip", "or", "not", "is_ipv4_address", "(", "pattern", ")", ...
51.75
27.25
def all(self, target=None, include_global=True): """ Get a dictionary of all aliases and their options. :param target: Include aliases for this specific field, model or app (optional). :param include_global: Include all non target-specific aliases (default ``True...
[ "def", "all", "(", "self", ",", "target", "=", "None", ",", "include_global", "=", "True", ")", ":", "aliases", "=", "{", "}", "for", "target_part", "in", "self", ".", "_get_targets", "(", "target", ",", "include_global", ")", ":", "aliases", ".", "upd...
36
21.777778
def log(x, base=None): """ log(x, base=e) Logarithmic function. """ _math = infer_math(x) if base is None: return _math.log(x) elif _math == math: return _math.log(x, base) else: # numpy has no option to set a base return _math.log(x) / _math.log(base)
[ "def", "log", "(", "x", ",", "base", "=", "None", ")", ":", "_math", "=", "infer_math", "(", "x", ")", "if", "base", "is", "None", ":", "return", "_math", ".", "log", "(", "x", ")", "elif", "_math", "==", "math", ":", "return", "_math", ".", "l...
25.083333
12
def get_pstats_print2list(fnames, filter_fnames=None, exclude_fnames=None, sort=None, sort_reverse=None, limit=None): """Print stats with a filter or exclude filenames, sort index and limit. :param list fnames: cProfile standard files to process. :param list filter_fnames: Relative...
[ "def", "get_pstats_print2list", "(", "fnames", ",", "filter_fnames", "=", "None", ",", "exclude_fnames", "=", "None", ",", "sort", "=", "None", ",", "sort_reverse", "=", "None", ",", "limit", "=", "None", ")", ":", "if", "isinstance", "(", "fnames", ",", ...
41.432432
15.22973
def support_scripting(self): """ Returns True if scripting is available. Checks are done in the client library (redis-py) AND the redis server. Result is cached, so done only one time. """ if not hasattr(self, '_support_scripting'): try: self._...
[ "def", "support_scripting", "(", "self", ")", ":", "if", "not", "hasattr", "(", "self", ",", "'_support_scripting'", ")", ":", "try", ":", "self", ".", "_support_scripting", "=", "self", ".", "redis_version", ">=", "(", "2", ",", "5", ")", "and", "hasatt...
41
18.076923
def get_sitecol_assetcol(oqparam, haz_sitecol=None, cost_types=()): """ :param oqparam: calculation parameters :param haz_sitecol: the hazard site collection :param cost_types: the expected cost types :returns: (site collection, asset collection, discarded) """ global exposure asset_haza...
[ "def", "get_sitecol_assetcol", "(", "oqparam", ",", "haz_sitecol", "=", "None", ",", "cost_types", "=", "(", ")", ")", ":", "global", "exposure", "asset_hazard_distance", "=", "oqparam", ".", "asset_hazard_distance", "[", "'default'", "]", "if", "exposure", "is"...
44.803571
16.017857
def sg_one_hot(tensor, opt): r"""Converts a tensor into a one-hot tensor. See `tf.one_hot()` in tensorflow. Args: tensor: A `Tensor` ( automatically given by chain ) opt: depth: The number of classes. name: If provided, replace current tensor's name. Returns: A...
[ "def", "sg_one_hot", "(", "tensor", ",", "opt", ")", ":", "assert", "opt", ".", "depth", "is", "not", "None", ",", "'depth is mandatory.'", "return", "tf", ".", "one_hot", "(", "tensor", ",", "opt", ".", "depth", ",", "name", "=", "opt", ".", "name", ...
27.1875
19.25
def build_articles_from_article_xmls(article_xmls, detail="full", build_parts=None, remove_tags=None): """ Given a list of article XML filenames, convert to article objects """ poa_articles = [] for article_xml in article_xmls: print("working on ", arti...
[ "def", "build_articles_from_article_xmls", "(", "article_xmls", ",", "detail", "=", "\"full\"", ",", "build_parts", "=", "None", ",", "remove_tags", "=", "None", ")", ":", "poa_articles", "=", "[", "]", "for", "article_xml", "in", "article_xmls", ":", "print", ...
35.1875
20.8125
def parse_setup(options: Union[List, str]) -> str: """Convert potentially a list of commands into a single string. This creates a single string with newlines between each element of the list so that they will all run after each other in a bash script. """ if isinstance(options, str): retur...
[ "def", "parse_setup", "(", "options", ":", "Union", "[", "List", ",", "str", "]", ")", "->", "str", ":", "if", "isinstance", "(", "options", ",", "str", ")", ":", "return", "options", "return", "\"\\n\"", ".", "join", "(", "options", ")" ]
35
19
def view_seq(self, seq): """View the given sequence on the sequence page :param seq: the sequence to view :type seq: :class:`jukeboxcore.djadapter.models.Sequence` :returns: None :rtype: None :raises: None """ log.debug('Viewing sequence %s', seq.name) ...
[ "def", "view_seq", "(", "self", ",", "seq", ")", ":", "log", ".", "debug", "(", "'Viewing sequence %s'", ",", "seq", ".", "name", ")", "self", ".", "cur_seq", "=", "None", "self", ".", "pages_tabw", ".", "setCurrentIndex", "(", "2", ")", "self", ".", ...
40.333333
16
def insert(self, **kwargs): """ Performs an INSERT statement on the model's table in the master database. :param values: A dictionary containing the values to be inserted. ``datetime``, ``dict`` and ``bool`` objects can be passed as is and will be correctly serialized by psycopg2. :type...
[ "def", "insert", "(", "self", ",", "*", "*", "kwargs", ")", ":", "if", "len", "(", "kwargs", "[", "'values'", "]", ")", "==", "0", ":", "config", ".", "logger", ".", "warning", "(", "'No values to insert.'", ")", "return", "values", "=", "kwargs", "[...
43.923077
16.076923
def create_gist(self, public, files, description=github.GithubObject.NotSet): """ :calls: `POST /gists <http://developer.github.com/v3/gists>`_ :param public: bool :param files: dict of string to :class:`github.InputFileContent.InputFileContent` :param description: string ...
[ "def", "create_gist", "(", "self", ",", "public", ",", "files", ",", "description", "=", "github", ".", "GithubObject", ".", "NotSet", ")", ":", "assert", "isinstance", "(", "public", ",", "bool", ")", ",", "public", "assert", "all", "(", "isinstance", "...
47.913043
23.652174
def _normalize_dates(self, context): ''' Build a timeline from given (or not) start and end dates ''' if 'start' in context: if isinstance(context['start'], dt.date): context['start'] = dt.date.strftime( context['start'], format='%Y-%m-%d')...
[ "def", "_normalize_dates", "(", "self", ",", "context", ")", ":", "if", "'start'", "in", "context", ":", "if", "isinstance", "(", "context", "[", "'start'", "]", ",", "dt", ".", "date", ")", ":", "context", "[", "'start'", "]", "=", "dt", ".", "date"...
41.111111
19.333333
def _nodes_replaced(self, object, name, old, new): """ Handles a list of nodes being set. """ self._delete_nodes(old) self._add_nodes(new)
[ "def", "_nodes_replaced", "(", "self", ",", "object", ",", "name", ",", "old", ",", "new", ")", ":", "self", ".", "_delete_nodes", "(", "old", ")", "self", ".", "_add_nodes", "(", "new", ")" ]
33.2
6.2
def load_stream(self, key, binary=False): """ Return a managed file-like object from which the calling code can read previously-serialized data. :param key: :return: A managed stream-like object """ value = self.load_value(key, binary=binary) yield io.Byt...
[ "def", "load_stream", "(", "self", ",", "key", ",", "binary", "=", "False", ")", ":", "value", "=", "self", ".", "load_value", "(", "key", ",", "binary", "=", "binary", ")", "yield", "io", ".", "BytesIO", "(", "value", ")", "if", "binary", "else", ...
35.6
14.6
def autoprops_decorate(cls, # type: Type[T] include=None, # type: Union[str, Tuple[str]] exclude=None # type: Union[str, Tuple[str]] ): # type: (...) -> Type[T] """ To automatically generate all properties getters and setters ...
[ "def", "autoprops_decorate", "(", "cls", ",", "# type: Type[T]", "include", "=", "None", ",", "# type: Union[str, Tuple[str]]", "exclude", "=", "None", "# type: Union[str, Tuple[str]]", ")", ":", "# type: (...) -> Type[T]", "# first check that we do not conflict with other known ...
48.147059
31.029412
def Search(path): """Search sys.path to find a source file that matches path. The provided input path may have an unknown number of irrelevant outer directories (e.g., /garbage1/garbage2/real1/real2/x.py'). This function does multiple search iterations until an actual Python module file that matches the inp...
[ "def", "Search", "(", "path", ")", ":", "def", "SearchCandidates", "(", "p", ")", ":", "\"\"\"Generates all candidates for the fuzzy search of p.\"\"\"", "while", "p", ":", "yield", "p", "(", "_", ",", "_", ",", "p", ")", "=", "p", ".", "partition", "(", "...
33.588235
22.517647
def rand_email(): """Random email. Usage Example:: >>> rand_email() Z4Lljcbdw7m@npa.net """ name = random.choice(string.ascii_letters) + \ rand_str(string.ascii_letters + string.digits, random.randint(4, 14)) domain = rand_str(string.ascii_lowercase, random.randint(2, ...
[ "def", "rand_email", "(", ")", ":", "name", "=", "random", ".", "choice", "(", "string", ".", "ascii_letters", ")", "+", "rand_str", "(", "string", ".", "ascii_letters", "+", "string", ".", "digits", ",", "random", ".", "randint", "(", "4", ",", "14", ...
30.769231
17.769231
def stat(filename, retry_params=None, _account_id=None): """Get GCSFileStat of a Google Cloud storage file. Args: filename: A Google Cloud Storage filename of form '/bucket/filename'. retry_params: An api_utils.RetryParams for this call to GCS. If None, the default one is used. _account_id: Inter...
[ "def", "stat", "(", "filename", ",", "retry_params", "=", "None", ",", "_account_id", "=", "None", ")", ":", "common", ".", "validate_file_path", "(", "filename", ")", "api", "=", "storage_api", ".", "_get_storage_api", "(", "retry_params", "=", "retry_params"...
37.75
19.15625
def update_route53_records(self, domain_name, dns_name): """ Updates Route53 Records following GW domain creation """ zone_id = self.get_hosted_zone_id_for_domain(domain_name) is_apex = self.route53.get_hosted_zone(Id=zone_id)['HostedZone']['Name'][:-1] == domain_name if...
[ "def", "update_route53_records", "(", "self", ",", "domain_name", ",", "dns_name", ")", ":", "zone_id", "=", "self", ".", "get_hosted_zone_id_for_domain", "(", "domain_name", ")", "is_apex", "=", "self", ".", "route53", ".", "get_hosted_zone", "(", "Id", "=", ...
37.92
23
def renew_voms_proxy(passwd="", vo=None, lifetime="196:00"): """ Renews the voms proxy using a password *passwd*, an optional virtual organization name *vo*, and a default *lifetime* of 8 days. The password is written to a temporary file first and piped into the renewal commad to ensure it is not visibl...
[ "def", "renew_voms_proxy", "(", "passwd", "=", "\"\"", ",", "vo", "=", "None", ",", "lifetime", "=", "\"196:00\"", ")", ":", "with", "tmp_file", "(", ")", "as", "(", "_", ",", "tmp", ")", ":", "with", "open", "(", "tmp", ",", "\"w\"", ")", "as", ...
47.235294
24.411765
def run(self, output): '''Generate the report to the given output. :param output: writable file-like object or file path ''' # Ensure folder exists. if self.folder_id not in self.folders.folders(self.user): print("E: folder not found: %s" % self.folder_name, ...
[ "def", "run", "(", "self", ",", "output", ")", ":", "# Ensure folder exists.", "if", "self", ".", "folder_id", "not", "in", "self", ".", "folders", ".", "folders", "(", "self", ".", "user", ")", ":", "print", "(", "\"E: folder not found: %s\"", "%", "self"...
34.508772
20.298246
def add(entry_point, all_entry_points, auto_write, scripts_path): '''Add Scrim scripts for a python project''' click.echo() if not entry_point and not all_entry_points: raise click.UsageError( 'Missing required option: --entry_point or --all_entry_points' ) if not os.path.ex...
[ "def", "add", "(", "entry_point", ",", "all_entry_points", ",", "auto_write", ",", "scripts_path", ")", ":", "click", ".", "echo", "(", ")", "if", "not", "entry_point", "and", "not", "all_entry_points", ":", "raise", "click", ".", "UsageError", "(", "'Missin...
33.157143
17.9
def _reload_version(self): """ Packages installed by distutils (e.g. numpy or scipy), which uses an old safe_version, and so their version numbers can get mangled when converted to filenames (e.g., 1.11.0.dev0+2329eae to 1.11.0.dev0_2329eae). These distributions will not ...
[ "def", "_reload_version", "(", "self", ")", ":", "md_version", "=", "self", ".", "_get_version", "(", ")", "if", "md_version", ":", "self", ".", "_version", "=", "md_version", "return", "self" ]
40.375
13
def __process_url_wrapper_elements(self, elements): """ Creates the url nodes for pelican.urlwrappers.Category and pelican.urlwrappers.Tag. :param elements: list of wrapper elements :type elements: list :return: the processes urls as HTML :rtype: str """ u...
[ "def", "__process_url_wrapper_elements", "(", "self", ",", "elements", ")", ":", "urls", "=", "''", "for", "url_wrapper", ",", "articles", "in", "elements", ":", "urls", "+=", "self", ".", "__create_url_node_for_content", "(", "url_wrapper", ",", "'others'", ","...
39.941176
18.764706
def set_proxy(self, host, port, user=None, password=None): ''' Sets the proxy server host and port for the HTTP CONNECT Tunnelling. host: Address of the proxy. Ex: '192.168.0.100' port: Port of the proxy. Ex: 6000 user: User for proxy authoriz...
[ "def", "set_proxy", "(", "self", ",", "host", ",", "port", ",", "user", "=", "None", ",", "password", "=", "None", ")", ":", "self", ".", "_httpclient", ".", "set_proxy", "(", "host", ",", "port", ",", "user", ",", "password", ")" ]
32.285714
21.285714
def filter_alias_create_namespace(namespace): """ Filter alias name and alias command inside alias create namespace to appropriate strings. Args namespace: The alias create namespace. Returns: Filtered namespace where excessive whitespaces are removed in strings. """ def filter...
[ "def", "filter_alias_create_namespace", "(", "namespace", ")", ":", "def", "filter_string", "(", "s", ")", ":", "return", "' '", ".", "join", "(", "s", ".", "strip", "(", ")", ".", "split", "(", ")", ")", "namespace", ".", "alias_name", "=", "filter_stri...
32.0625
23.0625
def build_block_with_transactions( self, transactions: Tuple[BaseTransaction, ...], parent_header: BlockHeader=None ) -> Tuple[BaseBlock, Tuple[Receipt, ...], Tuple[BaseComputation, ...]]: """ Generate a block with the provided transactions. This does *not* import...
[ "def", "build_block_with_transactions", "(", "self", ",", "transactions", ":", "Tuple", "[", "BaseTransaction", ",", "...", "]", ",", "parent_header", ":", "BlockHeader", "=", "None", ")", "->", "Tuple", "[", "BaseBlock", ",", "Tuple", "[", "Receipt", ",", "...
48.571429
25.809524
def make_mixture_prior(latent_size, mixture_components): """Creates the mixture of Gaussians prior distribution. Args: latent_size: The dimensionality of the latent representation. mixture_components: Number of elements of the mixture. Returns: random_prior: A `tfd.Distribution` instance representin...
[ "def", "make_mixture_prior", "(", "latent_size", ",", "mixture_components", ")", ":", "if", "mixture_components", "==", "1", ":", "# See the module docstring for why we don't learn the parameters here.", "return", "tfd", ".", "MultivariateNormalDiag", "(", "loc", "=", "tf",...
38.433333
19.033333
def process_get(self): """ Analyse the GET request :return: * :attr:`USER_NOT_AUTHENTICATED` if the user is not authenticated or is requesting for authentication renewal * :attr:`USER_AUTHENTICATED` if the user is authenticated and is no...
[ "def", "process_get", "(", "self", ")", ":", "# generate a new LT", "self", ".", "gen_lt", "(", ")", "if", "not", "self", ".", "request", ".", "session", ".", "get", "(", "\"authenticated\"", ")", "or", "self", ".", "renew", ":", "# authentication will be ne...
39.166667
18.611111
def get_edges_with_citations(self, citations: Iterable[Citation]) -> List[Edge]: """Get edges with one of the given citations.""" return self.session.query(Edge).join(Evidence).filter(Evidence.citation.in_(citations)).all()
[ "def", "get_edges_with_citations", "(", "self", ",", "citations", ":", "Iterable", "[", "Citation", "]", ")", "->", "List", "[", "Edge", "]", ":", "return", "self", ".", "session", ".", "query", "(", "Edge", ")", ".", "join", "(", "Evidence", ")", ".",...
79
33.666667
def _init_channel(self): """ build the grpc channel used for both publisher and subscriber :return: None """ host = self._get_host() port = self._get_grpc_port() if 'TLS_PEM_FILE' in os.environ: with open(os.environ['TLS_PEM_FILE'], mode='rb') as f: ...
[ "def", "_init_channel", "(", "self", ")", ":", "host", "=", "self", ".", "_get_host", "(", ")", "port", "=", "self", ".", "_get_grpc_port", "(", ")", "if", "'TLS_PEM_FILE'", "in", "os", ".", "environ", ":", "with", "open", "(", "os", ".", "environ", ...
38.411765
20.764706
def create_permissions(): """ Creates all permissions and add them to the ADMIN Role. """ current_app.appbuilder.add_permissions(update_perms=True) click.echo(click.style("Created all permissions", fg="green"))
[ "def", "create_permissions", "(", ")", ":", "current_app", ".", "appbuilder", ".", "add_permissions", "(", "update_perms", "=", "True", ")", "click", ".", "echo", "(", "click", ".", "style", "(", "\"Created all permissions\"", ",", "fg", "=", "\"green\"", ")",...
38.166667
14.166667
def xenon_interactive_worker( machine, worker_config, input_queue=None, stderr_sink=None): """Uses Xenon to run a single remote interactive worker. Jobs are read from stdin, and results written to stdout. :param machine: Specification of the machine on which to run. :type machine: nood...
[ "def", "xenon_interactive_worker", "(", "machine", ",", "worker_config", ",", "input_queue", "=", "None", ",", "stderr_sink", "=", "None", ")", ":", "if", "input_queue", "is", "None", ":", "input_queue", "=", "Queue", "(", ")", "registry", "=", "worker_config"...
30.814433
19.536082
def from_dict(cls, d): """ Reconstructs the SimplestChemenvStrategy object from a dict representation of the SimplestChemenvStrategy object created using the as_dict method. :param d: dict representation of the SimplestChemenvStrategy object :return: StructureEnvironments object ...
[ "def", "from_dict", "(", "cls", ",", "d", ")", ":", "return", "cls", "(", "distance_cutoff", "=", "d", "[", "\"distance_cutoff\"", "]", ",", "angle_cutoff", "=", "d", "[", "\"angle_cutoff\"", "]", ",", "additional_condition", "=", "d", "[", "\"additional_con...
58.272727
26.818182
def group(iterable, key): """ groupby which sorts the input, discards the key and returns the output as a sequence of lists. """ for _, grouped in groupby(sorted(iterable, key=key), key=key): yield list(grouped)
[ "def", "group", "(", "iterable", ",", "key", ")", ":", "for", "_", ",", "grouped", "in", "groupby", "(", "sorted", "(", "iterable", ",", "key", "=", "key", ")", ",", "key", "=", "key", ")", ":", "yield", "list", "(", "grouped", ")" ]
33.285714
14.428571
def menuitemenabled(self, window_name, object_name): """ Verify a menu item is enabled @param window_name: Window name to look for, either full name, LDTP's name convention, or a Unix glob. @type window_name: string @param object_name: Object name to look for, either ful...
[ "def", "menuitemenabled", "(", "self", ",", "window_name", ",", "object_name", ")", ":", "try", ":", "menu_handle", "=", "self", ".", "_get_menu_handle", "(", "window_name", ",", "object_name", ",", "False", ")", "if", "menu_handle", ".", "AXEnabled", ":", "...
34.045455
17.045455
def on_configurationdone_request(self, py_db, request): ''' :param ConfigurationDoneRequest request: ''' self.api.run(py_db) configuration_done_response = pydevd_base_schema.build_response(request) return NetCommand(CMD_RETURN, 0, configuration_done_response, is_json=True...
[ "def", "on_configurationdone_request", "(", "self", ",", "py_db", ",", "request", ")", ":", "self", ".", "api", ".", "run", "(", "py_db", ")", "configuration_done_response", "=", "pydevd_base_schema", ".", "build_response", "(", "request", ")", "return", "NetCom...
45
25.285714
def invert(self): ''' Return inverse mapping of dictionary with sorted values. USAGE >>> # Switch the keys and values >>> adv_dict({ ... 'A': [1, 2, 3], ... 'B': [4, 2], ... 'C': [1, 4], ... }).invert() {1: ['A', 'C'], 2: ['A', 'B'],...
[ "def", "invert", "(", "self", ")", ":", "inv_map", "=", "{", "}", "for", "k", ",", "v", "in", "self", ".", "items", "(", ")", ":", "if", "sys", ".", "version_info", "<", "(", "3", ",", "0", ")", ":", "acceptable_v_instance", "=", "isinstance", "(...
37.740741
17.074074
def frompath(path, accessor=None, ext=None, start=None, stop=None, recursive=False, npartitions=None, dims=None, dtype=None, labels=None, recount=False, engine=None, credentials=None): """ Load images from a path using the given accessor. Supports both local and remote filesystems. Parameters ----...
[ "def", "frompath", "(", "path", ",", "accessor", "=", "None", ",", "ext", "=", "None", ",", "start", "=", "None", ",", "stop", "=", "None", ",", "recursive", "=", "False", ",", "npartitions", "=", "None", ",", "dims", "=", "None", ",", "dtype", "="...
34.571429
21.84127
def checkerboard(img_spec1=None, img_spec2=None, patch_size=10, view_set=(0, 1, 2), num_slices=(10,), num_rows=2, rescale_method='global', background_threshold=0.05, annot=None, ...
[ "def", "checkerboard", "(", "img_spec1", "=", "None", ",", "img_spec2", "=", "None", ",", "patch_size", "=", "10", ",", "view_set", "=", "(", "0", ",", "1", ",", "2", ")", ",", "num_slices", "=", "(", "10", ",", ")", ",", "num_rows", "=", "2", ",...
36.511628
22.860465
def from_array(array): """ Deserialize a new UserProfilePhotos from a given dictionary. :return: new UserProfilePhotos instance. :rtype: UserProfilePhotos """ if array is None or not array: return None # end if assert_type_or_raise(array, dict...
[ "def", "from_array", "(", "array", ")", ":", "if", "array", "is", "None", "or", "not", "array", ":", "return", "None", "# end if", "assert_type_or_raise", "(", "array", ",", "dict", ",", "parameter_name", "=", "\"array\"", ")", "from", "pytgbot", ".", "api...
33.473684
19.157895
def from_file(cls, jss, filename): """Create a new JSSObject from an external XML file. Args: jss: A JSS object. filename: String path to an XML file. """ tree = ElementTree.parse(filename) root = tree.getroot() return cls(jss, root)
[ "def", "from_file", "(", "cls", ",", "jss", ",", "filename", ")", ":", "tree", "=", "ElementTree", ".", "parse", "(", "filename", ")", "root", "=", "tree", ".", "getroot", "(", ")", "return", "cls", "(", "jss", ",", "root", ")" ]
29.7
11.6