text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def create_file_new_actions(self, fnames): """Return actions for submenu 'New...'""" if not fnames: return [] new_file_act = create_action(self, _("File..."), icon=ima.icon('filenew'), triggered=lambda: ...
[ "def", "create_file_new_actions", "(", "self", ",", "fnames", ")", ":", "if", "not", "fnames", ":", "return", "[", "]", "new_file_act", "=", "create_action", "(", "self", ",", "_", "(", "\"File...\"", ")", ",", "icon", "=", "ima", ".", "icon", "(", "'f...
56.681818
19.409091
def evaluate(self, instance, step, extra): """Evaluate the current definition and fill its attributes. Uses attributes definition in the following order: - values defined when defining the ParameteredAttribute - additional values defined when instantiating the containing factory ...
[ "def", "evaluate", "(", "self", ",", "instance", ",", "step", ",", "extra", ")", ":", "defaults", "=", "dict", "(", "self", ".", "defaults", ")", "if", "extra", ":", "defaults", ".", "update", "(", "extra", ")", "return", "self", ".", "generate", "("...
36.947368
18.421053
def _get_req_fp(self, op): '''Decisions on what verb to use and content headers happen here Args: op a string specifying a http verb''' if(op): op = op.lower() if op == 'get': return requests.get, None if op == 'put': return requests.put, {'Content-Type': 'application/x-www-form-urlencoded'...
[ "def", "_get_req_fp", "(", "self", ",", "op", ")", ":", "if", "(", "op", ")", ":", "op", "=", "op", ".", "lower", "(", ")", "if", "op", "==", "'get'", ":", "return", "requests", ".", "get", ",", "None", "if", "op", "==", "'put'", ":", "return",...
32.875
22.375
def address(self) -> str: '''generate an address from pubkey''' return str(self._public_key.to_address( net_query(self.network)) )
[ "def", "address", "(", "self", ")", "->", "str", ":", "return", "str", "(", "self", ".", "_public_key", ".", "to_address", "(", "net_query", "(", "self", ".", "network", ")", ")", ")" ]
30
15
def rgb2gray(image_rgb_array): """! @brief Returns image as 1-dimension (gray colored) matrix, where one element of list describes pixel. @details Luma coding is used for transformation and that is calculated directly from gamma-compressed primary intensities as a weighted sum: \f[Y = 0.2989R ...
[ "def", "rgb2gray", "(", "image_rgb_array", ")", ":", "image_gray_array", "=", "[", "0.0", "]", "*", "len", "(", "image_rgb_array", ")", "for", "index", "in", "range", "(", "0", ",", "len", "(", "image_rgb_array", ")", ",", "1", ")", ":", "image_gray_arra...
39.08
31.68
def require_http_methods(request_methods): """ Decorator to make a function view only accept particular request methods. Usage:: @require_http_methods(["GET", "POST"]) def function_view(request): # HTTP methods != GET or POST results in 405 error code response """ if not...
[ "def", "require_http_methods", "(", "request_methods", ")", ":", "if", "not", "isinstance", "(", "request_methods", ",", "(", "list", ",", "tuple", ")", ")", ":", "raise", "ImproperlyConfigured", "(", "\"require_http_methods decorator must be called \"", "\"with a list ...
37.418182
14.145455
def appendAssayToStudy(assay, studyNum, pathToISATABFile): """ This function appends an Assay object to a study in an ISA file Typically, you should use the exploreISA function to check the contents of the ISA file and retrieve the assay and study number you are interested in! :param assay: The Assa...
[ "def", "appendAssayToStudy", "(", "assay", ",", "studyNum", ",", "pathToISATABFile", ")", ":", "from", "isatools", "import", "isatab", "try", ":", "isa", "=", "isatab", ".", "load", "(", "pathToISATABFile", ",", "skip_load_tables", "=", "True", ")", "std", "...
42.892857
15.964286
def pvcreate(devices, override=True, **kwargs): ''' Set a physical device to be used as an LVM physical volume override Skip devices, if they are already LVM physical volumes CLI Examples: .. code-block:: bash salt mymachine lvm.pvcreate /dev/sdb1,/dev/sdb2 salt mymachine...
[ "def", "pvcreate", "(", "devices", ",", "override", "=", "True", ",", "*", "*", "kwargs", ")", ":", "if", "not", "devices", ":", "return", "'Error: at least one device is required'", "if", "isinstance", "(", "devices", ",", "six", ".", "string_types", ")", "...
34.113208
21.924528
def evaluate_hourly_forecasts(self): """ Calculates ROC curves and Reliability scores for each forecast hour. Returns: A pandas DataFrame containing forecast metadata as well as DistributedROC and Reliability objects. """ score_columns = ["Run_Date", "Forecast_Hour",...
[ "def", "evaluate_hourly_forecasts", "(", "self", ")", ":", "score_columns", "=", "[", "\"Run_Date\"", ",", "\"Forecast_Hour\"", ",", "\"Ensemble Name\"", ",", "\"Model_Name\"", ",", "\"Forecast_Variable\"", ",", "\"Neighbor_Radius\"", ",", "\"Smoothing_Radius\"", ",", "...
71.761905
37.761905
def fermion_avg(efermi, norm_hopping, func): """calcules for every slave it's average over the desired observable""" if func == 'ekin': func = bethe_ekin_zeroT elif func == 'ocupation': func = bethe_filling_zeroT return np.asarray([func(ef, tz) for ef, tz in zip(efermi, norm_hopping)])
[ "def", "fermion_avg", "(", "efermi", ",", "norm_hopping", ",", "func", ")", ":", "if", "func", "==", "'ekin'", ":", "func", "=", "bethe_ekin_zeroT", "elif", "func", "==", "'ocupation'", ":", "func", "=", "bethe_filling_zeroT", "return", "np", ".", "asarray",...
39
15.625
def get_more(collection_name, num_to_return, cursor_id, ctx=None): """Get a **getMore** message.""" if ctx: return _get_more_compressed( collection_name, num_to_return, cursor_id, ctx) return _get_more_uncompressed(collection_name, num_to_return, cursor_id)
[ "def", "get_more", "(", "collection_name", ",", "num_to_return", ",", "cursor_id", ",", "ctx", "=", "None", ")", ":", "if", "ctx", ":", "return", "_get_more_compressed", "(", "collection_name", ",", "num_to_return", ",", "cursor_id", ",", "ctx", ")", "return",...
47.333333
19
def create_user(app, appbuilder, role, username, firstname, lastname, email, password): """ Create a user """ _appbuilder = import_application(app, appbuilder) role_object = _appbuilder.sm.find_role(role) user = _appbuilder.sm.add_user( username, firstname, lastname, email, role_obje...
[ "def", "create_user", "(", "app", ",", "appbuilder", ",", "role", ",", "username", ",", "firstname", ",", "lastname", ",", "email", ",", "password", ")", ":", "_appbuilder", "=", "import_application", "(", "app", ",", "appbuilder", ")", "role_object", "=", ...
38.384615
21.615385
def saveJSON(g, data, backup=False): """ Saves the current setup to disk. g : hcam_drivers.globals.Container Container with globals data : dict The current setup in JSON compatible dictionary format. backup : bool If we are saving a backup on close, don't prompt for filename """ ...
[ "def", "saveJSON", "(", "g", ",", "data", ",", "backup", "=", "False", ")", ":", "if", "not", "backup", ":", "fname", "=", "filedialog", ".", "asksaveasfilename", "(", "defaultextension", "=", "'.json'", ",", "filetypes", "=", "[", "(", "'json files'", "...
27.060606
18.454545
def _generate_default_grp_constraints(roles, network_constraints): """Generate default symetric grp constraints. """ default_delay = network_constraints.get('default_delay') default_rate = network_constraints.get('default_rate') default_loss = network_constraints.get('default_loss', 0) except_gr...
[ "def", "_generate_default_grp_constraints", "(", "roles", ",", "network_constraints", ")", ":", "default_delay", "=", "network_constraints", ".", "get", "(", "'default_delay'", ")", "default_rate", "=", "network_constraints", ".", "get", "(", "'default_rate'", ")", "d...
44.909091
15.090909
def u2ver(self): """ Get the major/minor version of the urllib2 lib. @return: The urllib2 version. @rtype: float """ try: part = u2.__version__.split('.', 1) n = float('.'.join(part)) return n except Exception as e: ...
[ "def", "u2ver", "(", "self", ")", ":", "try", ":", "part", "=", "u2", ".", "__version__", ".", "split", "(", "'.'", ",", "1", ")", "n", "=", "float", "(", "'.'", ".", "join", "(", "part", ")", ")", "return", "n", "except", "Exception", "as", "e...
26.538462
12.384615
def prepare_data(problem, hparams, params, config): """Construct input pipeline.""" input_fn = problem.make_estimator_input_fn( tf.estimator.ModeKeys.EVAL, hparams, force_repeat=True) dataset = input_fn(params, config) features, _ = dataset.make_one_shot_iterator().get_next() inputs, labels = features["...
[ "def", "prepare_data", "(", "problem", ",", "hparams", ",", "params", ",", "config", ")", ":", "input_fn", "=", "problem", ".", "make_estimator_input_fn", "(", "tf", ".", "estimator", ".", "ModeKeys", ".", "EVAL", ",", "hparams", ",", "force_repeat", "=", ...
47
11.416667
def identify(self,geometry,geometryType="esriGeometryPoint",mosaicRule=None, renderingRule=None,renderingRules=None,pixelSize=None,time=None, returnGeometry="false",returnCatalogItems="false"): """ The identify operation is performed on an image service resource. ...
[ "def", "identify", "(", "self", ",", "geometry", ",", "geometryType", "=", "\"esriGeometryPoint\"", ",", "mosaicRule", "=", "None", ",", "renderingRule", "=", "None", ",", "renderingRules", "=", "None", ",", "pixelSize", "=", "None", ",", "time", "=", "None"...
51.804124
27.474227
def ParseOptions(cls, options, analysis_plugin): """Parses and validates options. Args: options (argparse.Namespace): parser options. analysis_plugin (VirusTotalAnalysisPlugin): analysis plugin to configure. Raises: BadConfigObject: when the output module object is of the wrong type. ...
[ "def", "ParseOptions", "(", "cls", ",", "options", ",", "analysis_plugin", ")", ":", "if", "not", "isinstance", "(", "analysis_plugin", ",", "virustotal", ".", "VirusTotalAnalysisPlugin", ")", ":", "raise", "errors", ".", "BadConfigObject", "(", "'Analysis plugin ...
37.714286
21.742857
def schema(self, dataset_id, table_id): """Retrieve the schema of the table Obtain from BigQuery the field names and field types for the table defined by the parameters Parameters ---------- dataset_id : str Name of the BigQuery dataset for the table ...
[ "def", "schema", "(", "self", ",", "dataset_id", ",", "table_id", ")", ":", "table_ref", "=", "self", ".", "client", ".", "dataset", "(", "dataset_id", ")", ".", "table", "(", "table_id", ")", "try", ":", "table", "=", "self", ".", "client", ".", "ge...
29.676471
18.029412
def newProp(self, name, value): """Create a new property carried by a node. """ ret = libxml2mod.xmlNewProp(self._o, name, value) if ret is None:raise treeError('xmlNewProp() failed') __tmp = xmlAttr(_obj=ret) return __tmp
[ "def", "newProp", "(", "self", ",", "name", ",", "value", ")", ":", "ret", "=", "libxml2mod", ".", "xmlNewProp", "(", "self", ".", "_o", ",", "name", ",", "value", ")", "if", "ret", "is", "None", ":", "raise", "treeError", "(", "'xmlNewProp() failed'",...
42.833333
12.333333
def __read_block(self, size): """Read a block of 'size' bytes from the server. An internal buffer is used to read data from the server. If enough data is available from it, we return that data. Eventually, we try to grab the missing part from the server for Client.read_timeout ...
[ "def", "__read_block", "(", "self", ",", "size", ")", ":", "buf", "=", "b\"\"", "if", "len", "(", "self", ".", "__read_buffer", ")", ":", "limit", "=", "(", "size", "if", "size", "<=", "len", "(", "self", ".", "__read_buffer", ")", "else", "len", "...
35.21875
17.75
def raise_for_api_error(headers: MutableMapping, data: MutableMapping) -> None: """ Check request response for Slack API error Args: headers: Response headers data: Response data Raises: :class:`slack.exceptions.SlackAPIError` """ if not data["ok"]: raise excep...
[ "def", "raise_for_api_error", "(", "headers", ":", "MutableMapping", ",", "data", ":", "MutableMapping", ")", "->", "None", ":", "if", "not", "data", "[", "\"ok\"", "]", ":", "raise", "exceptions", ".", "SlackAPIError", "(", "data", ".", "get", "(", "\"err...
27.176471
23.176471
def qasm(self, prec=15): """Return the corresponding OPENQASM string.""" string = "gate " + self.name if self.arguments is not None: string += "(" + self.arguments.qasm(prec) + ")" string += " " + self.bitlist.qasm(prec) + "\n" string += "{\n" + self.body.qasm(prec) +...
[ "def", "qasm", "(", "self", ",", "prec", "=", "15", ")", ":", "string", "=", "\"gate \"", "+", "self", ".", "name", "if", "self", ".", "arguments", "is", "not", "None", ":", "string", "+=", "\"(\"", "+", "self", ".", "arguments", ".", "qasm", "(", ...
42.375
10.75
def get_catalogs_by_ids(self, *args, **kwargs): """Pass through to provider CatalogLookupSession.get_catalogs_by_ids""" # Implemented from kitosid template for - # osid.resource.BinLookupSession.get_bins_by_ids catalogs = self._get_provider_session('catalog_lookup_session').get_catalogs_...
[ "def", "get_catalogs_by_ids", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# Implemented from kitosid template for -", "# osid.resource.BinLookupSession.get_bins_by_ids", "catalogs", "=", "self", ".", "_get_provider_session", "(", "'catalog_lookup_sess...
57.444444
20.888889
def extract(self, doc): """From the defined JSONPath(s), pull out the values and insert them into a document with renamed field(s) then apply the Extractor and return the doc with the extracted values """ if isinstance(self.jsonpaths, JSONPath): input_field = self.extractor....
[ "def", "extract", "(", "self", ",", "doc", ")", ":", "if", "isinstance", "(", "self", ".", "jsonpaths", ",", "JSONPath", ")", ":", "input_field", "=", "self", ".", "extractor", ".", "get_renamed_input_fields", "(", ")", "if", "isinstance", "(", "self", "...
47.870968
18.983871
def insert(exif, image, new_file=None): """ py:function:: piexif.insert(exif_bytes, filename) Insert exif into JPEG. :param bytes exif_bytes: Exif as bytes :param str filename: JPEG """ if exif[0:6] != b"\x45\x78\x69\x66\x00\x00": raise ValueError("Given data is not exif data") ...
[ "def", "insert", "(", "exif", ",", "image", ",", "new_file", "=", "None", ")", ":", "if", "exif", "[", "0", ":", "6", "]", "!=", "b\"\\x45\\x78\\x69\\x66\\x00\\x00\"", ":", "raise", "ValueError", "(", "\"Given data is not exif data\"", ")", "output_file", "=",...
32.5
17.038462
def get_inbox_documents_per_page(self, per_page=1000, page=1): """ Get inbox documents per page :param per_page: How many objects per page. Default: 1000 :param page: Which page. Default: 1 :return: list """ return self._get_resource_per_page( resourc...
[ "def", "get_inbox_documents_per_page", "(", "self", ",", "per_page", "=", "1000", ",", "page", "=", "1", ")", ":", "return", "self", ".", "_get_resource_per_page", "(", "resource", "=", "INBOX_DOCUMENTS", ",", "per_page", "=", "per_page", ",", "page", "=", "...
30
13.692308
def update_user(self, ID, data): """Update a User.""" # http://teampasswordmanager.com/docs/api-users/#update_user log.info('Update user %s with %s' % (ID, data)) self.put('users/%s.json' % ID, data)
[ "def", "update_user", "(", "self", ",", "ID", ",", "data", ")", ":", "# http://teampasswordmanager.com/docs/api-users/#update_user", "log", ".", "info", "(", "'Update user %s with %s'", "%", "(", "ID", ",", "data", ")", ")", "self", ".", "put", "(", "'users/%s.j...
45.4
11
def print_solution(solution): """Prints a solution Arguments --------- solution : BaseSolution Example ------- :: [8, 9, 10, 7]: 160 [5, 6]: 131 [3, 4, 2]: 154 Total cost: 445 """ total_cost = 0 for solution in solution.routes()...
[ "def", "print_solution", "(", "solution", ")", ":", "total_cost", "=", "0", "for", "solution", "in", "solution", ".", "routes", "(", ")", ":", "cost", "=", "solution", ".", "length", "(", ")", "total_cost", "=", "total_cost", "+", "cost", "print", "(", ...
20.25
18.708333
def _try_parse_gene_association(self, reaction_id, s): """Try to parse the given gene association rule. Logs a warning if the association rule could not be parsed and returns the original string. Otherwise, returns the boolean.Expression object. """ s = s.strip() if s ==...
[ "def", "_try_parse_gene_association", "(", "self", ",", "reaction_id", ",", "s", ")", ":", "s", "=", "s", ".", "strip", "(", ")", "if", "s", "==", "''", ":", "return", "None", "try", ":", "return", "boolean", ".", "Expression", "(", "s", ")", "except...
34.3
18.95
def init_raspbian_disk(self, yes=0): """ Downloads the latest Raspbian image and writes it to a microSD card. Based on the instructions from: https://www.raspberrypi.org/documentation/installation/installing-images/linux.md """ self.assume_localhost() yes = int...
[ "def", "init_raspbian_disk", "(", "self", ",", "yes", "=", "0", ")", ":", "self", ".", "assume_localhost", "(", ")", "yes", "=", "int", "(", "yes", ")", "device_question", "=", "'SD card present at %s? '", "%", "self", ".", "env", ".", "sd_device", "if", ...
38.837838
24.891892
def list(self, filterfn=lambda x: True): """Return all direct descendands of directory `self` for which `filterfn` returns True. """ return [self / p for p in self.listdir() if filterfn(self / p)]
[ "def", "list", "(", "self", ",", "filterfn", "=", "lambda", "x", ":", "True", ")", ":", "return", "[", "self", "/", "p", "for", "p", "in", "self", ".", "listdir", "(", ")", "if", "filterfn", "(", "self", "/", "p", ")", "]" ]
45.4
7.2
def path_to_dir(*path_args): """Convert a UNIX-style path into platform specific directory spec.""" return os.path.join( *list(path_args[:-1]) + path_args[-1].split(posixpath.sep) )
[ "def", "path_to_dir", "(", "*", "path_args", ")", ":", "return", "os", ".", "path", ".", "join", "(", "*", "list", "(", "path_args", "[", ":", "-", "1", "]", ")", "+", "path_args", "[", "-", "1", "]", ".", "split", "(", "posixpath", ".", "sep", ...
42.6
17
def _get_template_list(self): " Get the hierarchy of templates belonging to the object/box_type given. " t_list = [] if hasattr(self.obj, 'category_id') and self.obj.category_id: cat = self.obj.category base_path = 'box/category/%s/content_type/%s/' % (cat.path, self.name...
[ "def", "_get_template_list", "(", "self", ")", ":", "t_list", "=", "[", "]", "if", "hasattr", "(", "self", ".", "obj", ",", "'category_id'", ")", "and", "self", ".", "obj", ".", "category_id", ":", "cat", "=", "self", ".", "obj", ".", "category", "ba...
45.52381
22.857143
def get_default_config(self): """ Returns the default collector settings """ config = super(MonitCollector, self).get_default_config() config.update({ 'host': '127.0.0.1', 'port': 2812, 'user': 'monit', 'pass...
[ "def", "get_default_config", "(", "self", ")", ":", "config", "=", "super", "(", "MonitCollector", ",", "self", ")", ".", "get_default_config", "(", ")", "config", ".", "update", "(", "{", "'host'", ":", "'127.0.0.1'", ",", "'port'", ":", "2812", ",", "'...
31.2
9.066667
def plot_transaction_rate_heterogeneity( model, suptitle="Heterogeneity in Transaction Rate", xlabel="Transaction Rate", ylabel="Density", suptitle_fontsize=14, **kwargs ): """ Plot the estimated gamma distribution of lambda (customers' propensities to purchase). Parameters ----...
[ "def", "plot_transaction_rate_heterogeneity", "(", "model", ",", "suptitle", "=", "\"Heterogeneity in Transaction Rate\"", ",", "xlabel", "=", "\"Transaction Rate\"", ",", "ylabel", "=", "\"Density\"", ",", "suptitle_fontsize", "=", "14", ",", "*", "*", "kwargs", ")",...
25.469388
21.265306
def getFileInfos(self): """Return a list of FileInfo objects""" data = self.searchIndex(False) self.data = data self.printd(" ") fileInfos = [] for datum in data: try: fileInfo = self.getFileInfo(datum[0], datum[1]) fileInfos.append(fileInfo) except NotImplementedError: self.printd("Error:...
[ "def", "getFileInfos", "(", "self", ")", ":", "data", "=", "self", ".", "searchIndex", "(", "False", ")", "self", ".", "data", "=", "data", "self", ".", "printd", "(", "\" \"", ")", "fileInfos", "=", "[", "]", "for", "datum", "in", "data", ":", "tr...
28.5
19.142857
def _resolve_class(self, new_class, namespace, qualifier_repo, verbose=None): """ Resolve the class defined by new_class by: 1. Validating that the new class provided is a valid class. 2. Validating the class against the repository to confirm that comp...
[ "def", "_resolve_class", "(", "self", ",", "new_class", ",", "namespace", ",", "qualifier_repo", ",", "verbose", "=", "None", ")", ":", "is_association_class", "=", "'Association'", "in", "new_class", ".", "qualifiers", "if", "new_class", ".", "superclass", ":",...
47.009434
20.632075
def calibrate_cameras(self): """Calibrate cameras based on found chessboard corners.""" criteria = (cv2.TERM_CRITERIA_MAX_ITER + cv2.TERM_CRITERIA_EPS, 100, 1e-5) flags = (cv2.CALIB_FIX_ASPECT_RATIO + cv2.CALIB_ZERO_TANGENT_DIST + cv2.CALIB_SAME_FOCAL_LENGTH)...
[ "def", "calibrate_cameras", "(", "self", ")", ":", "criteria", "=", "(", "cv2", ".", "TERM_CRITERIA_MAX_ITER", "+", "cv2", ".", "TERM_CRITERIA_EPS", ",", "100", ",", "1e-5", ")", "flags", "=", "(", "cv2", ".", "CALIB_FIX_ASPECT_RATIO", "+", "cv2", ".", "CA...
61.641509
23.264151
def hexblock_cb(cls, callback, data, address = None, bits = None, width = 16, cb_args = (), ...
[ "def", "hexblock_cb", "(", "cls", ",", "callback", ",", "data", ",", "address", "=", "None", ",", "bits", "=", "None", ",", "width", "=", "16", ",", "cb_args", "=", "(", ")", ",", "cb_kwargs", "=", "{", "}", ")", ":", "result", "=", "''", "if", ...
37.358491
22.90566
def _refresh_db_conditional(saltenv, **kwargs): ''' Internal use only in this module, has a different set of defaults and returns True or False. And supports checking the age of the existing generated metadata db, as well as ensure metadata db exists to begin with Args: saltenv (str): Salt ...
[ "def", "_refresh_db_conditional", "(", "saltenv", ",", "*", "*", "kwargs", ")", ":", "force", "=", "salt", ".", "utils", ".", "data", ".", "is_true", "(", "kwargs", ".", "pop", "(", "'force'", ",", "False", ")", ")", "failhard", "=", "salt", ".", "ut...
33.328358
25.477612
def make_statement(self, action, mention): """Makes an INDRA statement from a Geneways action and action mention. Parameters ---------- action : GenewaysAction The mechanism that the Geneways mention maps to. Note that several text mentions can correspond to the ...
[ "def", "make_statement", "(", "self", ",", "action", ",", "mention", ")", ":", "(", "statement_generator", ",", "is_direct", ")", "=", "geneways_action_to_indra_statement_type", "(", "mention", ".", "actiontype", ",", "action", ".", "plo", ")", "if", "statement_...
46.057971
20.826087
def parse_response(response, encoding='utf-8'): """Parse a multipart Requests.Response into a tuple of BodyPart objects. Args: response: Requests.Response encoding: The parser will assume that any text in the HTML body is encoded with this encoding when decoding it for use in the `...
[ "def", "parse_response", "(", "response", ",", "encoding", "=", "'utf-8'", ")", ":", "return", "requests_toolbelt", ".", "multipart", ".", "decoder", ".", "MultipartDecoder", ".", "from_response", "(", "response", ",", "encoding", ")", ".", "parts" ]
31.052632
25.421053
def setmem(vm_, memory, config=False, **kwargs): ''' Changes the amount of memory allocated to VM. The VM must be shutdown for this to work. :param vm_: name of the domain :param memory: memory amount to set in MB :param config: if True then libvirt will be asked to modify the config as well ...
[ "def", "setmem", "(", "vm_", ",", "memory", ",", "config", "=", "False", ",", "*", "*", "kwargs", ")", ":", "conn", "=", "__get_conn", "(", "*", "*", "kwargs", ")", "dom", "=", "_get_domain", "(", "conn", ",", "vm_", ")", "if", "VIRT_STATE_NAME_MAP",...
31.911111
24.266667
def get_orderbook(self): """Get orderbook for the instrument :Retruns: orderbook : dict orderbook dict for the instrument """ if self in self.parent.books.keys(): return self.parent.books[self] return { "bid": [0], "bidsize": ...
[ "def", "get_orderbook", "(", "self", ")", ":", "if", "self", "in", "self", ".", "parent", ".", "books", ".", "keys", "(", ")", ":", "return", "self", ".", "parent", ".", "books", "[", "self", "]", "return", "{", "\"bid\"", ":", "[", "0", "]", ","...
25.714286
14.571429
def create_switch(apps, schema_editor): """Create the `role_based_access_control` switch if it does not already exist.""" Switch = apps.get_model('waffle', 'Switch') Switch.objects.update_or_create(name=ENTERPRISE_ROLE_BASED_ACCESS_CONTROL_SWITCH, defaults={'active': False})
[ "def", "create_switch", "(", "apps", ",", "schema_editor", ")", ":", "Switch", "=", "apps", ".", "get_model", "(", "'waffle'", ",", "'Switch'", ")", "Switch", ".", "objects", ".", "update_or_create", "(", "name", "=", "ENTERPRISE_ROLE_BASED_ACCESS_CONTROL_SWITCH",...
71
20.25
def mode(data): """Return the most common data point from discrete or nominal data. ``mode`` assumes discrete data, and returns a single value. This is the standard treatment of the mode as commonly taught in schools: >>> mode([1, 1, 2, 3, 3, 3, 3, 4]) 3 This also works with nominal (non-nume...
[ "def", "mode", "(", "data", ")", ":", "# Generate a table of sorted (value, frequency) pairs.", "hist", "=", "collections", ".", "Counter", "(", "data", ")", "top", "=", "hist", ".", "most_common", "(", "2", ")", "if", "len", "(", "top", ")", "==", "1", ":...
28.413793
22.827586
def info(self, user_id): """Gets user information by user id Args: user_id(int): the id of user Returns: User Throws: RTMServiceError when request failed """ resp = self._rtm_client.get('v1/user.info?user_id={}'.format(user_id)) ...
[ "def", "info", "(", "self", ",", "user_id", ")", ":", "resp", "=", "self", ".", "_rtm_client", ".", "get", "(", "'v1/user.info?user_id={}'", ".", "format", "(", "user_id", ")", ")", "if", "resp", ".", "is_fail", "(", ")", ":", "raise", "RTMServiceError",...
25.647059
22
def writeLogToFile(self): """ writes the log to a """ if not os.path.exists(self.logFolder): os.mkdir(self.logFolder) with open(self.logFile, mode='a') as f: f.write('\n\n' + self.log)
[ "def", "writeLogToFile", "(", "self", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "self", ".", "logFolder", ")", ":", "os", ".", "mkdir", "(", "self", ".", "logFolder", ")", "with", "open", "(", "self", ".", "logFile", ",", "mode"...
26.777778
9.666667
def config_schema(self): """Returns the merged configuration data schema for this plugin type.""" from rez.config import _plugin_config_dict d = _plugin_config_dict.get(self.type_name, {}) for name, plugin_class in self.plugin_classes.iteritems(): if hasattr(plugin_c...
[ "def", "config_schema", "(", "self", ")", ":", "from", "rez", ".", "config", "import", "_plugin_config_dict", "d", "=", "_plugin_config_dict", ".", "get", "(", "self", ".", "type_name", ",", "{", "}", ")", "for", "name", ",", "plugin_class", "in", "self", ...
45.583333
15.333333
def _add_element(self, cls, **kwargs): """Add an element.""" # Convert stylename strings to actual style elements. kwargs = self._replace_stylename(kwargs) el = cls(**kwargs) self._doc.text.addElement(el)
[ "def", "_add_element", "(", "self", ",", "cls", ",", "*", "*", "kwargs", ")", ":", "# Convert stylename strings to actual style elements.", "kwargs", "=", "self", ".", "_replace_stylename", "(", "kwargs", ")", "el", "=", "cls", "(", "*", "*", "kwargs", ")", ...
39.833333
8
async def read(cls, *, hostnames: typing.Sequence[str] = None): """List nodes. :param hostnames: Sequence of hostnames to only return. :type hostnames: sequence of `str` """ params = {} if hostnames: params["hostname"] = [ normalize_hostname(h...
[ "async", "def", "read", "(", "cls", ",", "*", ",", "hostnames", ":", "typing", ".", "Sequence", "[", "str", "]", "=", "None", ")", ":", "params", "=", "{", "}", "if", "hostnames", ":", "params", "[", "\"hostname\"", "]", "=", "[", "normalize_hostname...
33.071429
12.571429
def emitFragment(fw, fragID, libID, shredded_seq, clr=None, qvchar='l', fasta=False): """ Print out the shredded sequence. """ if fasta: s = SeqRecord(shredded_seq, id=fragID, description="") SeqIO.write([s], fw, "fasta") return seq = str(shredded_seq) slen = len(seq) ...
[ "def", "emitFragment", "(", "fw", ",", "fragID", ",", "libID", ",", "shredded_seq", ",", "clr", "=", "None", ",", "qvchar", "=", "'l'", ",", "fasta", "=", "False", ")", ":", "if", "fasta", ":", "s", "=", "SeqRecord", "(", "shredded_seq", ",", "id", ...
29.25
20.75
def update_ride(api_client, ride_status, ride_id): """Use an UberRidesClient to update ride status and print the results. Parameters api_client (UberRidesClient) An authorized UberRidesClient with 'request' scope. ride_status (str) New ride status to update to. r...
[ "def", "update_ride", "(", "api_client", ",", "ride_status", ",", "ride_id", ")", ":", "try", ":", "update_product", "=", "api_client", ".", "update_sandbox_ride", "(", "ride_id", ",", "ride_status", ")", "except", "(", "ClientError", ",", "ServerError", ")", ...
32.666667
18.809524
def post(self, request, *args, **kwargs): """ Method for handling POST requests. Expects the 'vid' of the version to act on to be passed as in the POST variable 'version'. If a POST variable 'revert' is present this will call the revert method and then return a 'render ...
[ "def", "post", "(", "self", ",", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "versions", "=", "self", ".", "_get_versions", "(", ")", "url", "=", "self", ".", "get_done_url", "(", ")", "msg", "=", "None", "try", ":", "vid", "=...
36.47619
16.952381
def get_scenario_data(scenario_id,**kwargs): """ Get all the datasets from the group with the specified name @returns a list of dictionaries """ user_id = kwargs.get('user_id') scenario_data = db.DBSession.query(Dataset).filter(Dataset.id==ResourceScenario.dataset_id, ResourceScenario.s...
[ "def", "get_scenario_data", "(", "scenario_id", ",", "*", "*", "kwargs", ")", ":", "user_id", "=", "kwargs", ".", "get", "(", "'user_id'", ")", "scenario_data", "=", "db", ".", "DBSession", ".", "query", "(", "Dataset", ")", ".", "filter", "(", "Dataset"...
33.52381
23.142857
def fcoe_get_interface_output_fcoe_intf_list_interface_name(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") fcoe_get_interface = ET.Element("fcoe_get_interface") config = fcoe_get_interface output = ET.SubElement(fcoe_get_interface, "output") ...
[ "def", "fcoe_get_interface_output_fcoe_intf_list_interface_name", "(", "self", ",", "*", "*", "kwargs", ")", ":", "config", "=", "ET", ".", "Element", "(", "\"config\"", ")", "fcoe_get_interface", "=", "ET", ".", "Element", "(", "\"fcoe_get_interface\"", ")", "con...
50.8
21
def get(self, acl): """Get the ACL specified by ID belonging to this instance. See :py:meth:`Acls.get` for call signature. """ return self._instance._client.acls.get(self._instance.name, acl)
[ "def", "get", "(", "self", ",", "acl", ")", ":", "return", "self", ".", "_instance", ".", "_client", ".", "acls", ".", "get", "(", "self", ".", "_instance", ".", "name", ",", "acl", ")" ]
36.5
17.333333
def reversed(self): ''' Return a new FSM such that for every string that self accepts (e.g. "beer", the new FSM accepts the reversed string ("reeb"). ''' alphabet = self.alphabet # Start from a composite "state-set" consisting of all final states. # If there are no final states, this set is empty and w...
[ "def", "reversed", "(", "self", ")", ":", "alphabet", "=", "self", ".", "alphabet", "# Start from a composite \"state-set\" consisting of all final states.", "# If there are no final states, this set is empty and we'll find that", "# no other states get generated.", "initial", "=", "...
28.806452
22.741935
def get(self, robj, r=None, pr=None, timeout=None, basic_quorum=None, notfound_ok=None, head_only=False): """ Serialize get request and deserialize response """ msg_code = riak.pb.messages.MSG_CODE_GET_REQ codec = self._get_codec(msg_code) msg = codec.encode_g...
[ "def", "get", "(", "self", ",", "robj", ",", "r", "=", "None", ",", "pr", "=", "None", ",", "timeout", "=", "None", ",", "basic_quorum", "=", "None", ",", "notfound_ok", "=", "None", ",", "head_only", "=", "False", ")", ":", "msg_code", "=", "riak"...
44.083333
8.916667
def _strip(string, pattern): """Return complement of pattern in string""" m = re.compile(pattern).search(string) if m: return string[0:m.start()] + string[m.end():len(string)] else: return string
[ "def", "_strip", "(", "string", ",", "pattern", ")", ":", "m", "=", "re", ".", "compile", "(", "pattern", ")", ".", "search", "(", "string", ")", "if", "m", ":", "return", "string", "[", "0", ":", "m", ".", "start", "(", ")", "]", "+", "string"...
27.625
19.875
def get_java_binpath(cmd=None): """Retrieve path for java to use, handling custom BCBIO_JAVA_HOME Defaults to the dirname of cmd, or local anaconda directory """ if os.environ.get("BCBIO_JAVA_HOME"): test_cmd = os.path.join(os.environ["BCBIO_JAVA_HOME"], "bin", "java") if os.path.exists...
[ "def", "get_java_binpath", "(", "cmd", "=", "None", ")", ":", "if", "os", ".", "environ", ".", "get", "(", "\"BCBIO_JAVA_HOME\"", ")", ":", "test_cmd", "=", "os", ".", "path", ".", "join", "(", "os", ".", "environ", "[", "\"BCBIO_JAVA_HOME\"", "]", ","...
35.25
14.583333
def get_git_changeset(): """Get git identifier; taken from Django project.""" git_log = Popen( 'git log --pretty=format:%ct --quiet -1 HEAD', stdout=PIPE, stderr=PIPE, shell=True, universal_newlines=True) timestamp = git_log.communicate()[0] try: timestamp = datetime.utcfromtimes...
[ "def", "get_git_changeset", "(", ")", ":", "git_log", "=", "Popen", "(", "'git log --pretty=format:%ct --quiet -1 HEAD'", ",", "stdout", "=", "PIPE", ",", "stderr", "=", "PIPE", ",", "shell", "=", "True", ",", "universal_newlines", "=", "True", ")", "timestamp",...
38.090909
16.090909
def _key_values(self, sn: "SequenceNode") -> Union[EntryKeys, EntryValue]: """Parse leaf-list value or list keys.""" try: keys = self.up_to("/") except EndOfInput: keys = self.remaining() if not keys: raise UnexpectedInput(self, "entry value or keys") ...
[ "def", "_key_values", "(", "self", ",", "sn", ":", "\"SequenceNode\"", ")", "->", "Union", "[", "EntryKeys", ",", "EntryValue", "]", ":", "try", ":", "keys", "=", "self", ".", "up_to", "(", "\"/\"", ")", "except", "EndOfInput", ":", "keys", "=", "self"...
39.454545
14.954545
def codigo_ibge_uf(sigla): """Retorna o código do IBGE para a UF informada.""" idx = [s for s, i, n, r in UNIDADES_FEDERACAO].index(sigla) return UNIDADES_FEDERACAO[idx][_UF_CODIGO_IBGE]
[ "def", "codigo_ibge_uf", "(", "sigla", ")", ":", "idx", "=", "[", "s", "for", "s", ",", "i", ",", "n", ",", "r", "in", "UNIDADES_FEDERACAO", "]", ".", "index", "(", "sigla", ")", "return", "UNIDADES_FEDERACAO", "[", "idx", "]", "[", "_UF_CODIGO_IBGE", ...
48.75
12
def prepare_io_example_1() -> Tuple[devicetools.Nodes, devicetools.Elements]: # noinspection PyUnresolvedReferences """Prepare an IO example configuration. >>> from hydpy.core.examples import prepare_io_example_1 >>> nodes, elements = prepare_io_example_1() (1) Prepares a short initialisation peri...
[ "def", "prepare_io_example_1", "(", ")", "->", "Tuple", "[", "devicetools", ".", "Nodes", ",", "devicetools", ".", "Elements", "]", ":", "# noinspection PyUnresolvedReferences", "from", "hydpy", "import", "TestIO", "TestIO", ".", "clear", "(", ")", "from", "hydp...
34.885714
17.228571
def run(self, stdscr): """ Initialize curses and refresh in a loop """ self.win = stdscr curses.curs_set(0) stdscr.timeout(0) curses.init_pair(1, curses.COLOR_CYAN, curses.COLOR_BLACK) curses.init_pair(2, curses.COLOR_GREEN, curses.COLOR_BLACK) curses.init_pair(3,...
[ "def", "run", "(", "self", ",", "stdscr", ")", ":", "self", ".", "win", "=", "stdscr", "curses", ".", "curs_set", "(", "0", ")", "stdscr", ".", "timeout", "(", "0", ")", "curses", ".", "init_pair", "(", "1", ",", "curses", ".", "COLOR_CYAN", ",", ...
41.333333
16.066667
def get_load(jid): ''' Return the load data that marks a specified jid ''' jid = _escape_jid(jid) conn = _get_conn() if conn is None: return None cur = conn.cursor() sql = '''SELECT jid, tgt_type, cmd, tgt, kwargs, ret, username, arg,''' \ ''' fun FROM jids WHERE jid = ...
[ "def", "get_load", "(", "jid", ")", ":", "jid", "=", "_escape_jid", "(", "jid", ")", "conn", "=", "_get_conn", "(", ")", "if", "conn", "is", "None", ":", "return", "None", "cur", "=", "conn", ".", "cursor", "(", ")", "sql", "=", "'''SELECT jid, tgt_t...
26.235294
20
def _get_level(tag): """ Match the header level in the given tag name, or None if it's not a header tag. """ m = re.match(r'^h([123456])$', tag, flags=re.IGNORECASE) if not m: return None return int(m.group(1))
[ "def", "_get_level", "(", "tag", ")", ":", "m", "=", "re", ".", "match", "(", "r'^h([123456])$'", ",", "tag", ",", "flags", "=", "re", ".", "IGNORECASE", ")", "if", "not", "m", ":", "return", "None", "return", "int", "(", "m", ".", "group", "(", ...
30
12
def make_jagged_equity_info(num_assets, start_date, first_end, frequency, periods_between_ends, auto_close_delta): """ Create a DataFrame representing assets that all begin...
[ "def", "make_jagged_equity_info", "(", "num_assets", ",", "start_date", ",", "first_end", ",", "frequency", ",", "periods_between_ends", ",", "auto_close_delta", ")", ":", "frame", "=", "pd", ".", "DataFrame", "(", "{", "'symbol'", ":", "[", "chr", "(", "ord",...
32.270833
16.9375
def _get_csrf_token(self): """Return the CSRF Token of easyname login form.""" from bs4 import BeautifulSoup home_response = self.session.get(self.URLS['login']) self._log('Home', home_response) assert home_response.status_code == 200, \ 'Could not load Easyname login...
[ "def", "_get_csrf_token", "(", "self", ")", ":", "from", "bs4", "import", "BeautifulSoup", "home_response", "=", "self", ".", "session", ".", "get", "(", "self", ".", "URLS", "[", "'login'", "]", ")", "self", ".", "_log", "(", "'Home'", ",", "home_respon...
46.153846
14.846154
def fig2x(figure, format): """Returns svg from matplotlib chart""" # Save svg to file like object svg_io io = StringIO() figure.savefig(io, format=format) # Rewind the file like object io.seek(0) data = io.getvalue() io.close() return data
[ "def", "fig2x", "(", "figure", ",", "format", ")", ":", "# Save svg to file like object svg_io", "io", "=", "StringIO", "(", ")", "figure", ".", "savefig", "(", "io", ",", "format", "=", "format", ")", "# Rewind the file like object", "io", ".", "seek", "(", ...
19
21.357143
def get_normalized_url(url): """ Returns a normalized url, without params """ scheme, netloc, path, params, query, fragment = urlparse(url) # Exclude default port numbers. if scheme == 'http' and netloc[-3:] == ':80': netloc = netloc[:-3] elif scheme ...
[ "def", "get_normalized_url", "(", "url", ")", ":", "scheme", ",", "netloc", ",", "path", ",", "params", ",", "query", ",", "fragment", "=", "urlparse", "(", "url", ")", "# Exclude default port numbers.", "if", "scheme", "==", "'http'", "and", "netloc", "[", ...
39
16.25
def read_register(self, registeraddress, numberOfDecimals=0, functioncode=3, signed=False): """Read an integer from one 16-bit register in the slave, possibly scaling it. The slave register can hold integer values in the range 0 to 65535 ("Unsigned INT16"). Args: * registeraddress ...
[ "def", "read_register", "(", "self", ",", "registeraddress", ",", "numberOfDecimals", "=", "0", ",", "functioncode", "=", "3", ",", "signed", "=", "False", ")", ":", "_checkFunctioncode", "(", "functioncode", ",", "[", "3", ",", "4", "]", ")", "_checkInt",...
54.069767
35.813953
def bz2_opener(path, pattern='', verbose=False): """Opener that opens single bz2 compressed file. :param str path: Path. :param str pattern: Regular expression pattern. :return: Filehandle(s). """ source = path if is_url(path) else os.path.abspath(path) filename = os.path.basename(path) ...
[ "def", "bz2_opener", "(", "path", ",", "pattern", "=", "''", ",", "verbose", "=", "False", ")", ":", "source", "=", "path", "if", "is_url", "(", "path", ")", "else", "os", ".", "path", ".", "abspath", "(", "path", ")", "filename", "=", "os", ".", ...
36.136364
21.545455
def delete_reference_image( self, location, product_id, reference_image_id, project_id=None, retry=None, timeout=None, metadata=None, ): """ For the documentation see: :py:class:`~airflow.contrib.operators.gcp_vision_operator.Cl...
[ "def", "delete_reference_image", "(", "self", ",", "location", ",", "product_id", ",", "reference_image_id", ",", "project_id", "=", "None", ",", "retry", "=", "None", ",", "timeout", "=", "None", ",", "metadata", "=", "None", ",", ")", ":", "client", "=",...
35.913043
23.826087
def ReplaceHomoglyphs(s): """Returns s with unicode homoglyphs replaced by ascii equivalents.""" homoglyphs = { '\xa0': ' ', # &nbsp; ? '\u00e3': '', # TODO(gsfowler) drop after .proto spurious char elided '\u00a0': ' ', # &nbsp; ? '\u00a9': '(C)', # COPYRIGHT SIGN (would you...
[ "def", "ReplaceHomoglyphs", "(", "s", ")", ":", "homoglyphs", "=", "{", "'\\xa0'", ":", "' '", ",", "# &nbsp; ?", "'\\u00e3'", ":", "''", ",", "# TODO(gsfowler) drop after .proto spurious char elided", "'\\u00a0'", ":", "' '", ",", "# &nbsp; ?", "'\\u00a9'", ":", ...
36.212121
17.454545
def save(self): # type: () -> None """Save the currentin-memory state. """ self._ensure_have_load_only() for fname, parser in self._modified_parsers: logger.info("Writing to %s", fname) # Ensure directory exists. ensure_dir(os.path.dirname(fn...
[ "def", "save", "(", "self", ")", ":", "# type: () -> None", "self", ".", "_ensure_have_load_only", "(", ")", "for", "fname", ",", "parser", "in", "self", ".", "_modified_parsers", ":", "logger", ".", "info", "(", "\"Writing to %s\"", ",", "fname", ")", "# En...
27.5
14.214286
def grab_xml(host, token=None): """Grab XML data from Gateway, returned as a dict.""" urllib3.disable_warnings() if token: scheme = "https" if not token: scheme = "http" token = "1234567890" url = ( scheme + '://' + host + '/gwr/gop.php?cmd=GWRBatch&data=<gwrcmds>...
[ "def", "grab_xml", "(", "host", ",", "token", "=", "None", ")", ":", "urllib3", ".", "disable_warnings", "(", ")", "if", "token", ":", "scheme", "=", "\"https\"", "if", "not", "token", ":", "scheme", "=", "\"http\"", "token", "=", "\"1234567890\"", "url"...
48.714286
31.214286
def save(self, *args, **kwargs): """ **uid**: :code:`electiontype:{name}` """ self.uid = 'electiontype:{}'.format(self.slug) super(ElectionType, self).save(*args, **kwargs)
[ "def", "save", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "self", ".", "uid", "=", "'electiontype:{}'", ".", "format", "(", "self", ".", "slug", ")", "super", "(", "ElectionType", ",", "self", ")", ".", "save", "(", "*", "a...
34.5
6.833333
def convert(dbus_obj): """Converts dbus_obj from dbus type to python type. :param dbus_obj: dbus object. :returns: dbus_obj in python type. """ _isinstance = partial(isinstance, dbus_obj) ConvertType = namedtuple('ConvertType', 'pytype dbustypes') pyint = ConvertType(int, (dbus.Byte, dbus....
[ "def", "convert", "(", "dbus_obj", ")", ":", "_isinstance", "=", "partial", "(", "isinstance", ",", "dbus_obj", ")", "ConvertType", "=", "namedtuple", "(", "'ConvertType'", ",", "'pytype dbustypes'", ")", "pyint", "=", "ConvertType", "(", "int", ",", "(", "d...
38.028571
18.257143
def system_find_analyses(input_params={}, always_retry=True, **kwargs): """ Invokes the /system/findAnalyses API method. For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Search#API-method%3A-%2Fsystem%2FfindAnalyses """ return DXHTTPRequest('/system/findAnalyses', input_params...
[ "def", "system_find_analyses", "(", "input_params", "=", "{", "}", ",", "always_retry", "=", "True", ",", "*", "*", "kwargs", ")", ":", "return", "DXHTTPRequest", "(", "'/system/findAnalyses'", ",", "input_params", ",", "always_retry", "=", "always_retry", ",", ...
50.285714
31.142857
def debug(cls, message): """ Display debug message if verbose level allows it. """ if cls.verbose > 1: msg = '[DEBUG] %s' % message cls.echo(msg)
[ "def", "debug", "(", "cls", ",", "message", ")", ":", "if", "cls", ".", "verbose", ">", "1", ":", "msg", "=", "'[DEBUG] %s'", "%", "message", "cls", ".", "echo", "(", "msg", ")" ]
36.2
8.8
def as_block_string(txt): """Return a string formatted as a python block comment string, like the one you're currently reading. Special characters are escaped if necessary. """ import json lines = [] for line in txt.split('\n'): line_ = json.dumps(line) line_ = line_[1:-1].rstri...
[ "def", "as_block_string", "(", "txt", ")", ":", "import", "json", "lines", "=", "[", "]", "for", "line", "in", "txt", ".", "split", "(", "'\\n'", ")", ":", "line_", "=", "json", ".", "dumps", "(", "line", ")", "line_", "=", "line_", "[", "1", ":"...
31.307692
17.461538
def get_property_func(key): """ Get the accessor function for an instance to look for `key`. Look for it as an attribute, and if that does not work, look to see if it is a tag. """ def get_it(obj): try: return getattr(obj, key) except AttributeError: retu...
[ "def", "get_property_func", "(", "key", ")", ":", "def", "get_it", "(", "obj", ")", ":", "try", ":", "return", "getattr", "(", "obj", ",", "key", ")", "except", "AttributeError", ":", "return", "obj", ".", "tags", ".", "get", "(", "key", ")", "return...
26.615385
17.692308
def _is_field_serializable(self, field_name): """Return True if the field can be serialized into a JSON doc.""" return ( self._meta.get_field(field_name).get_internal_type() in self.SIMPLE_UPDATE_FIELD_TYPES )
[ "def", "_is_field_serializable", "(", "self", ",", "field_name", ")", ":", "return", "(", "self", ".", "_meta", ".", "get_field", "(", "field_name", ")", ".", "get_internal_type", "(", ")", "in", "self", ".", "SIMPLE_UPDATE_FIELD_TYPES", ")" ]
42
14.833333
def convert_scalar_multiply(net, node, model, builder): """Convert a scalar multiply layer from mxnet to coreml. Parameters ---------- net: network A mxnet network object. node: layer Node to convert. model: model An model for MXNet builder: NeuralNetworkBuilder ...
[ "def", "convert_scalar_multiply", "(", "net", ",", "node", ",", "model", ",", "builder", ")", ":", "import", "numpy", "as", "_np", "input_name", ",", "output_name", "=", "_get_input_output_name", "(", "net", ",", "node", ")", "name", "=", "node", "[", "'na...
27.75
19.791667
def _min_conflicts_value(problem, assignment, variable): ''' Return the value generate the less number of conflicts. In case of tie, a random value is selected among this values subset. ''' return argmin(problem.domains[variable], lambda x: _count_conflicts(problem, assignment, variable, x))
[ "def", "_min_conflicts_value", "(", "problem", ",", "assignment", ",", "variable", ")", ":", "return", "argmin", "(", "problem", ".", "domains", "[", "variable", "]", ",", "lambda", "x", ":", "_count_conflicts", "(", "problem", ",", "assignment", ",", "varia...
51.166667
33.166667
def mt_deconvolve(data_a, data_b, delta, nfft=None, time_bandwidth=None, number_of_tapers=None, weights="adaptive", demean=True, fmax=0.0): """ Deconvolve two time series using multitapers. This uses the eigencoefficients and the weights from the multitaper spectral ...
[ "def", "mt_deconvolve", "(", "data_a", ",", "data_b", ",", "delta", ",", "nfft", "=", "None", ",", "time_bandwidth", "=", "None", ",", "number_of_tapers", "=", "None", ",", "weights", "=", "\"adaptive\"", ",", "demean", "=", "True", ",", "fmax", "=", "0....
32.472441
21.023622
def run_chunk(environ, lowstate): ''' Expects a list of lowstate dictionaries that are executed and returned in order ''' client = environ['SALT_APIClient'] for chunk in lowstate: yield client.run(chunk)
[ "def", "run_chunk", "(", "environ", ",", "lowstate", ")", ":", "client", "=", "environ", "[", "'SALT_APIClient'", "]", "for", "chunk", "in", "lowstate", ":", "yield", "client", ".", "run", "(", "chunk", ")" ]
25.333333
22.888889
def heritability(args): """ %prog pg.tsv MZ-twins.csv DZ-twins.csv Plot composite figures ABCD on absolute difference of 4 traits, EFGH on heritability of 4 traits. The 4 traits are: telomere length, ccn.chrX, ccn.chrY, TRA.PPM """ p = OptionParser(heritability.__doc__) opts, args, iopt...
[ "def", "heritability", "(", "args", ")", ":", "p", "=", "OptionParser", "(", "heritability", ".", "__doc__", ")", "opts", ",", "args", ",", "iopts", "=", "p", ".", "set_image_options", "(", "args", ",", "figsize", "=", "\"12x18\"", ")", "if", "len", "(...
31.702703
18.189189
def kill_eaters(self): """ Returns a list of tuples containing the proper localized kill eater type strings and their values according to set/type/value "order" """ eaters = {} ranktypes = self._kill_types for attr in self: aname = attr.name.strip() ...
[ "def", "kill_eaters", "(", "self", ")", ":", "eaters", "=", "{", "}", "ranktypes", "=", "self", ".", "_kill_types", "for", "attr", "in", "self", ":", "aname", "=", "attr", ".", "name", ".", "strip", "(", ")", "aid", "=", "attr", ".", "id", "if", ...
39.403509
19.508772
async def send_mail( self, sender, recipients, message, mail_options=None, rcpt_options=None ): """ Alias for :meth:`SMTP.sendmail`. """ return await self.sendmail( sender, recipients, message, mail_options, rcpt_options )
[ "async", "def", "send_mail", "(", "self", ",", "sender", ",", "recipients", ",", "message", ",", "mail_options", "=", "None", ",", "rcpt_options", "=", "None", ")", ":", "return", "await", "self", ".", "sendmail", "(", "sender", ",", "recipients", ",", "...
30.888889
17.333333
def ssad(patch, cols, splits): """ Calculates an empirical intra-specific spatial abundance distribution Parameters ---------- {0} Returns ------- {1} Result has one column giving the individuals of species in each subplot. Notes ----- {2} {3} Examples --...
[ "def", "ssad", "(", "patch", ",", "cols", ",", "splits", ")", ":", "# Get and check SAD", "sad_results", "=", "sad", "(", "patch", ",", "cols", ",", "splits", ",", "clean", "=", "False", ")", "# Create dataframe with col for spp name and numbered col for each split"...
24.298701
27.701299
def delete_cloud_integration(self, id, **kwargs): # noqa: E501 """Delete a specific cloud integration # noqa: E501 # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.delete_c...
[ "def", "delete_cloud_integration", "(", "self", ",", "id", ",", "*", "*", "kwargs", ")", ":", "# noqa: E501", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'async_req'", ")", ":", "return", "self", ".", "del...
43.238095
20.047619
def expect_exitstatus(self, exit_status): """Wait for the running program to finish and expect some exit status. Args: exit_status (int): The expected exit status. Raises: WrongExitStatusException: The produced exit status is not the expected one. """ s...
[ "def", "expect_exitstatus", "(", "self", ",", "exit_status", ")", ":", "self", ".", "expect_end", "(", ")", "logger", ".", "debug", "(", "\"Checking exit status of '{0}', output so far: {1}\"", ".", "format", "(", "self", ".", "name", ",", "self", ".", "get_outp...
39.045455
16.818182
def separate_particles_into_groups(s, region_size=40, bounds=None): """ Given a state, returns a list of groups of particles. Each group of particles are located near each other in the image. Every particle located in the desired region is contained in exactly 1 group. Parameters: ----------- ...
[ "def", "separate_particles_into_groups", "(", "s", ",", "region_size", "=", "40", ",", "bounds", "=", "None", ")", ":", "imtile", "=", "(", "s", ".", "oshape", ".", "translate", "(", "-", "s", ".", "pad", ")", "if", "bounds", "is", "None", "else", "u...
38.862745
23.960784
def export_settings(settings, config_path): """ Export the given settings instance to the given file system path. type settings: IDASettingsInterface type config_path: str """ other = QtCore.QSettings(config_path, QtCore.QSettings.IniFormat) for k, v in settings.iteritems(): other.s...
[ "def", "export_settings", "(", "settings", ",", "config_path", ")", ":", "other", "=", "QtCore", ".", "QSettings", "(", "config_path", ",", "QtCore", ".", "QSettings", ".", "IniFormat", ")", "for", "k", ",", "v", "in", "settings", ".", "iteritems", "(", ...
32.4
13.2
async def get_artifacts(self, agent=None): '''Return artifacts published to the environment. :param agent: If not ``None``, then returns only artifacts created by the agent. :returns: All artifacts published (by the agent). :rtype: list If environment has a :attr:`...
[ "async", "def", "get_artifacts", "(", "self", ",", "agent", "=", "None", ")", ":", "# TODO: Figure better way for this", "if", "hasattr", "(", "self", ",", "'manager'", ")", "and", "self", ".", "manager", "is", "not", "None", ":", "artifacts", "=", "await", ...
40.142857
23.380952
def ready_print(worker, output, error): # pragma : no cover """Local test helper.""" global COUNTER COUNTER += 1 print(COUNTER, output, error)
[ "def", "ready_print", "(", "worker", ",", "output", ",", "error", ")", ":", "# pragma : no cover", "global", "COUNTER", "COUNTER", "+=", "1", "print", "(", "COUNTER", ",", "output", ",", "error", ")" ]
31
14.6