text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def month_indices(months): """Convert string labels for months to integer indices. Parameters ---------- months : str, int If int, number of the desired month, where January=1, February=2, etc. If str, must match either 'ann' or some subset of 'jfmamjjasond'. If 'ann', use...
[ "def", "month_indices", "(", "months", ")", ":", "if", "not", "isinstance", "(", "months", ",", "(", "int", ",", "str", ")", ")", ":", "raise", "TypeError", "(", "\"`months` must be of type int or str: \"", "\"type(months) == {}\"", ".", "format", "(", "type", ...
35.452381
20.119048
def create_load_balancer(self, name, zones, listeners, subnets=None, security_groups=None): """ Create a new load balancer for your account. By default the load balancer will be created in EC2. To create a load balancer inside a VPC, parameter zones must be set to None and subnet...
[ "def", "create_load_balancer", "(", "self", ",", "name", ",", "zones", ",", "listeners", ",", "subnets", "=", "None", ",", "security_groups", "=", "None", ")", ":", "params", "=", "{", "'LoadBalancerName'", ":", "name", "}", "for", "index", ",", "listener"...
47.703704
23.777778
def convert_serializer_field(field, is_input=True): """ Converts a django rest frameworks field to a graphql field and marks the field as required if we are creating an input type and the field itself is required """ graphql_type = get_graphene_type_from_serializer_field(field) args = [] ...
[ "def", "convert_serializer_field", "(", "field", ",", "is_input", "=", "True", ")", ":", "graphql_type", "=", "get_graphene_type_from_serializer_field", "(", "field", ")", "args", "=", "[", "]", "kwargs", "=", "{", "\"description\"", ":", "field", ".", "help_tex...
38.361111
19.472222
def list_submissions(): """List the past submissions with information about them""" submissions = [] try: submissions = session.query(Submission).all() except SQLAlchemyError as e: session.rollback() return render_template('list_submissions.html', submissions=submissions)
[ "def", "list_submissions", "(", ")", ":", "submissions", "=", "[", "]", "try", ":", "submissions", "=", "session", ".", "query", "(", "Submission", ")", ".", "all", "(", ")", "except", "SQLAlchemyError", "as", "e", ":", "session", ".", "rollback", "(", ...
37.625
17.5
def plot_campaign(self, campaign=0, annotate_channels=True, **kwargs): """Plot all the active channels of a campaign.""" fov = getKeplerFov(campaign) corners = fov.getCoordsOfChannelCorners() for ch in np.arange(1, 85, dtype=int): if ch in fov.brokenChannels: ...
[ "def", "plot_campaign", "(", "self", ",", "campaign", "=", "0", ",", "annotate_channels", "=", "True", ",", "*", "*", "kwargs", ")", ":", "fov", "=", "getKeplerFov", "(", "campaign", ")", "corners", "=", "fov", ".", "getCoordsOfChannelCorners", "(", ")", ...
50.333333
15.041667
def unmarkelect_comment(self, msg_data_id, index, user_comment_id): """ 将评论取消精选 """ return self._post( 'comment/unmarkelect', data={ 'msg_data_id': msg_data_id, 'index': index, 'user_comment_id': user_comment_id, ...
[ "def", "unmarkelect_comment", "(", "self", ",", "msg_data_id", ",", "index", ",", "user_comment_id", ")", ":", "return", "self", ".", "_post", "(", "'comment/unmarkelect'", ",", "data", "=", "{", "'msg_data_id'", ":", "msg_data_id", ",", "'index'", ":", "index...
29.181818
13
def add_text_item(self, collection_uri, name, metadata, text, title=None): """Add a new item to a collection containing a single text document. The full text of the text document is specified as the text argument and will be stored with the same name as the item and a .txt exten...
[ "def", "add_text_item", "(", "self", ",", "collection_uri", ",", "name", ",", "metadata", ",", "text", ",", "title", "=", "None", ")", ":", "docname", "=", "name", "+", "\".txt\"", "if", "title", "is", "None", ":", "title", "=", "name", "metadata", "["...
36.333333
25.47619
def calc_new_nonce_hash(self, new_nonce, number): """ Calculates the new nonce hash based on the current attributes. :param new_nonce: the new nonce to be hashed. :param number: number to prepend before the hash. :return: the hash for the given new nonce. """ new...
[ "def", "calc_new_nonce_hash", "(", "self", ",", "new_nonce", ",", "number", ")", ":", "new_nonce", "=", "new_nonce", ".", "to_bytes", "(", "32", ",", "'little'", ",", "signed", "=", "True", ")", "data", "=", "new_nonce", "+", "struct", ".", "pack", "(", ...
43.769231
20.538462
def set_layer(self, layer=None, keywords=None): """Set layer and update UI accordingly. :param layer: A QgsVectorLayer. :type layer: QgsVectorLayer :param keywords: Keywords for the layer. :type keywords: dict, None """ if self.field_mapping_widget is not None: ...
[ "def", "set_layer", "(", "self", ",", "layer", "=", "None", ",", "keywords", "=", "None", ")", ":", "if", "self", ".", "field_mapping_widget", "is", "not", "None", ":", "self", ".", "field_mapping_widget", ".", "setParent", "(", "None", ")", "self", ".",...
39.107692
16
def download_and_calibrate_parallel(list_of_ids, n=None): """Download and calibrate in parallel. Parameters ---------- list_of_ids : list, optional container with img_ids to process n : int Number of cores for the parallel processing. Default: n_cores_system//2 """ setup_clu...
[ "def", "download_and_calibrate_parallel", "(", "list_of_ids", ",", "n", "=", "None", ")", ":", "setup_cluster", "(", "n_cores", "=", "n", ")", "c", "=", "Client", "(", ")", "lbview", "=", "c", ".", "load_balanced_view", "(", ")", "lbview", ".", "map_async"...
32.466667
17.2
def to_str(self): ''' Returns string representation of a social account. Includes the name of the user. ''' dflt = super(DataportenAccount, self).to_str() return '%s (%s)' % ( self.account.extra_data.get('name', ''), dflt, )
[ "def", "to_str", "(", "self", ")", ":", "dflt", "=", "super", "(", "DataportenAccount", ",", "self", ")", ".", "to_str", "(", ")", "return", "'%s (%s)'", "%", "(", "self", ".", "account", ".", "extra_data", ".", "get", "(", "'name'", ",", "''", ")", ...
29.5
22.9
def collect_dashboard_js(collector): """Generate dashboard javascript for each dashboard""" dashmat = collector.configuration["dashmat"] modules = collector.configuration["__active_modules__"] compiled_static_prep = dashmat.compiled_static_prep compiled_static_folder = dashmat.compiled_static_folde...
[ "def", "collect_dashboard_js", "(", "collector", ")", ":", "dashmat", "=", "collector", ".", "configuration", "[", "\"dashmat\"", "]", "modules", "=", "collector", ".", "configuration", "[", "\"__active_modules__\"", "]", "compiled_static_prep", "=", "dashmat", ".",...
50.684211
25
def save_obj(self, path, update_normals=True): """Save data with OBJ format :param stl path: :param bool update_normals: """ if update_normals: self.update_normals() # Create triangle_list vectors_key_list = [] vectors_list = [] normal...
[ "def", "save_obj", "(", "self", ",", "path", ",", "update_normals", "=", "True", ")", ":", "if", "update_normals", ":", "self", ".", "update_normals", "(", ")", "# Create triangle_list", "vectors_key_list", "=", "[", "]", "vectors_list", "=", "[", "]", "norm...
37.2
14.636364
def _launch(self, run_config, args, **kwargs): """Launch the process and return the process object.""" del kwargs try: with sw("popen"): return subprocess.Popen(args, cwd=run_config.cwd, env=run_config.env) except OSError: logging.exception("Failed to launch") raise SC2LaunchEr...
[ "def", "_launch", "(", "self", ",", "run_config", ",", "args", ",", "*", "*", "kwargs", ")", ":", "del", "kwargs", "try", ":", "with", "sw", "(", "\"popen\"", ")", ":", "return", "subprocess", ".", "Popen", "(", "args", ",", "cwd", "=", "run_config",...
38.444444
17.666667
def has_path(nodes, A, B): r"""Test if nodes from a breadth_first_order search lead from A to B. Parameters ---------- nodes : array_like Nodes from breadth_first_oder_seatch A : array_like The set of educt states B : array_like The set of product states Returns...
[ "def", "has_path", "(", "nodes", ",", "A", ",", "B", ")", ":", "x1", "=", "np", ".", "intersect1d", "(", "nodes", ",", "A", ")", ".", "size", ">", "0", "x2", "=", "np", ".", "intersect1d", "(", "nodes", ",", "B", ")", ".", "size", ">", "0", ...
22.636364
18.590909
def update(self, instance_id: str, details: UpdateDetails, async_allowed: bool) -> UpdateServiceSpec: """ Further readings `CF Broker API#Update <https://docs.cloudfoundry.org/services/api.html#updating_service_instance>`_ :param instance_id: Instance id provided by the platform :param ...
[ "def", "update", "(", "self", ",", "instance_id", ":", "str", ",", "details", ":", "UpdateDetails", ",", "async_allowed", ":", "bool", ")", "->", "UpdateServiceSpec", ":", "raise", "NotImplementedError", "(", ")" ]
51.636364
26.363636
def connect(self): """Connects the object to the host:port. Returns: Future: a Future object with True as result if the connection process was ok. """ if self.is_connected() or self.is_connecting(): raise tornado.gen.Return(True) if self.u...
[ "def", "connect", "(", "self", ")", ":", "if", "self", ".", "is_connected", "(", ")", "or", "self", ".", "is_connecting", "(", ")", ":", "raise", "tornado", ".", "gen", ".", "Return", "(", "True", ")", "if", "self", ".", "unix_domain_socket", "is", "...
46.297872
16.531915
def sort(args): """ %prog sort gffile Sort gff file using plain old unix sort based on [chromosome, start coordinate]. or topologically based on hierarchy of features using the gt (genometools) toolkit """ valid_sort_methods = ("unix", "topo") p = OptionParser(sort.__doc__) p.add_optio...
[ "def", "sort", "(", "args", ")", ":", "valid_sort_methods", "=", "(", "\"unix\"", ",", "\"topo\"", ")", "p", "=", "OptionParser", "(", "sort", ".", "__doc__", ")", "p", ".", "add_option", "(", "\"--method\"", ",", "default", "=", "\"unix\"", ",", "choice...
36.595745
21.361702
def triangle_coordinates(i, j, k): """ Computes coordinates of the constituent triangles of a triangulation for the simplex. These triangules are parallel to the lower axis on the lower side. Parameters ---------- i,j,k: enumeration of the desired triangle Returns ------- A numpy a...
[ "def", "triangle_coordinates", "(", "i", ",", "j", ",", "k", ")", ":", "return", "[", "(", "i", ",", "j", ",", "k", ")", ",", "(", "i", "+", "1", ",", "j", ",", "k", "-", "1", ")", ",", "(", "i", ",", "j", "+", "1", ",", "k", "-", "1"...
28.266667
24.133333
def isEnabled(self): """ Return whether or not this layer is enabled and can be set as the \ current layer. :sa linkEnabledToCurrent :return <bool> """ if self._linkEnabledToCurrent: addtl = self.isCurrent() e...
[ "def", "isEnabled", "(", "self", ")", ":", "if", "self", ".", "_linkEnabledToCurrent", ":", "addtl", "=", "self", ".", "isCurrent", "(", ")", "else", ":", "addtl", "=", "True", "return", "self", ".", "_enabled", "and", "addtl" ]
23.875
16.875
async def get(self, public_key): """Retrieves all users contents Accepts: - public key """ # Sign-verifying functional if settings.SIGNATURE_VERIFICATION: super().verify() page = self.get_query_argument("page", 1) cids = await self.account.getuserscontent(public_key=public_key) logging.debug("\n...
[ "async", "def", "get", "(", "self", ",", "public_key", ")", ":", "# Sign-verifying functional", "if", "settings", ".", "SIGNATURE_VERIFICATION", ":", "super", "(", ")", ".", "verify", "(", ")", "page", "=", "self", ".", "get_query_argument", "(", "\"page\"", ...
24.692308
20.015385
def getFeatureReport(self, report_num=0, length=63): """ Receive a feature report. Blocks, unless you configured provided file (descriptor) to be non-blocking. """ length += 1 buf = bytearray(length) buf[0] = report_num self._ioctl( _HI...
[ "def", "getFeatureReport", "(", "self", ",", "report_num", "=", "0", ",", "length", "=", "63", ")", ":", "length", "+=", "1", "buf", "=", "bytearray", "(", "length", ")", "buf", "[", "0", "]", "=", "report_num", "self", ".", "_ioctl", "(", "_HIDIOCGF...
28.6
15
def QA_SU_save_stock_list(engine, client=DATABASE): """save stock_list Arguments: engine {[type]} -- [description] Keyword Arguments: client {[type]} -- [description] (default: {DATABASE}) """ engine = select_save_engine(engine) engine.QA_SU_save_stock_list(client=client)
[ "def", "QA_SU_save_stock_list", "(", "engine", ",", "client", "=", "DATABASE", ")", ":", "engine", "=", "select_save_engine", "(", "engine", ")", "engine", ".", "QA_SU_save_stock_list", "(", "client", "=", "client", ")" ]
25.333333
17.083333
def setup_logging(namespace): """ setup global logging """ loglevel = { 0: logging.ERROR, 1: logging.WARNING, 2: logging.INFO, 3: logging.DEBUG, }.get(namespace.verbosity, logging.DEBUG) if namespace.verbosity > 1: logformat = '%(levelname)s csvpandas %(...
[ "def", "setup_logging", "(", "namespace", ")", ":", "loglevel", "=", "{", "0", ":", "logging", ".", "ERROR", ",", "1", ":", "logging", ".", "WARNING", ",", "2", ":", "logging", ".", "INFO", ",", "3", ":", "logging", ".", "DEBUG", ",", "}", ".", "...
25.5
19.166667
def authenticate(self, req_data, key=None): """ Authenticates a given request data by verifying signatures from any registered authenticators. If the request is a query returns immediately, if no registered authenticator can authenticate then an exception is raised. :para...
[ "def", "authenticate", "(", "self", ",", "req_data", ",", "key", "=", "None", ")", ":", "identifiers", "=", "set", "(", ")", "typ", "=", "req_data", ".", "get", "(", "OPERATION", ",", "{", "}", ")", ".", "get", "(", "TXN_TYPE", ")", "if", "key", ...
40
18.068966
def detect_state_variable_shadowing(contracts): """ Detects all overshadowing and overshadowed state variables in the provided contracts. :param contracts: The contracts to detect shadowing within. :return: Returns a set of tuples (overshadowing_contract, overshadowing_state_var, overshadowed_contract, ...
[ "def", "detect_state_variable_shadowing", "(", "contracts", ")", ":", "results", "=", "set", "(", ")", "for", "contract", "in", "contracts", ":", "variables_declared", "=", "{", "variable", ".", "name", ":", "variable", "for", "variable", "in", "contract", "."...
58.684211
30.684211
def file_or_default(path, default, function = None): """ Return a default value if a file does not exist """ try: result = file_get_contents(path) if function != None: return function(result) return result except IOError as e: if e.errno == errno.ENOENT: return default ...
[ "def", "file_or_default", "(", "path", ",", "default", ",", "function", "=", "None", ")", ":", "try", ":", "result", "=", "file_get_contents", "(", "path", ")", "if", "function", "!=", "None", ":", "return", "function", "(", "result", ")", "return", "res...
35.444444
14.222222
def from_str(cls, tagstring): """Create a tag by parsing the tag of a message :param tagstring: A tag string described in the irc protocol :type tagstring: :class:`str` :returns: A tag :rtype: :class:`Tag` :raises: None """ m = cls._parse_regexp.match(tag...
[ "def", "from_str", "(", "cls", ",", "tagstring", ")", ":", "m", "=", "cls", ".", "_parse_regexp", ".", "match", "(", "tagstring", ")", "return", "cls", "(", "name", "=", "m", ".", "group", "(", "'name'", ")", ",", "value", "=", "m", ".", "group", ...
37.090909
16.909091
def get(self, path, data=None, return_fields=None): """Call the Infoblox device to get the obj for the data passed in :param str obj_reference: The object reference data :param dict data: The data for the get request :rtype: requests.Response """ return self.session.get...
[ "def", "get", "(", "self", ",", "path", ",", "data", "=", "None", ",", "return_fields", "=", "None", ")", ":", "return", "self", ".", "session", ".", "get", "(", "self", ".", "_request_url", "(", "path", ",", "return_fields", ")", ",", "data", "=", ...
42.454545
17.909091
def list_objects(self, bucket_name=None, **kwargs): """ This method is primarily for illustration and just calls the boto3 client implementation of list_objects but is a common task for first time Predix BlobStore users. """ if not bucket_name: bucket_name = self.bucket_...
[ "def", "list_objects", "(", "self", ",", "bucket_name", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "not", "bucket_name", ":", "bucket_name", "=", "self", ".", "bucket_name", "return", "self", ".", "client", ".", "list_objects", "(", "Bucket", ...
48.375
15.625
def _configure_manager(self): """ Creates a manager to handle autoscale operations. """ self._manager = ScalingGroupManager(self, resource_class=ScalingGroup, response_key="group", uri_base="groups")
[ "def", "_configure_manager", "(", "self", ")", ":", "self", ".", "_manager", "=", "ScalingGroupManager", "(", "self", ",", "resource_class", "=", "ScalingGroup", ",", "response_key", "=", "\"group\"", ",", "uri_base", "=", "\"groups\"", ")" ]
36.714286
9.857143
def install_paths(version=None, iddname=None): """Get the install paths for EnergyPlus executable and weather files. We prefer to get the install path from the IDD name but fall back to getting it from the version number for backwards compatibility and to simplify tests. Parameters ---------- ...
[ "def", "install_paths", "(", "version", "=", "None", ",", "iddname", "=", "None", ")", ":", "try", ":", "eplus_exe", ",", "eplus_home", "=", "paths_from_iddname", "(", "iddname", ")", "except", "(", "AttributeError", ",", "TypeError", ",", "ValueError", ")",...
31.034483
21.586207
def get_draft(self): """ Return self if this object is a draft, otherwise return the draft copy of a published item. """ if self.is_draft: return self elif self.is_published: draft = self.publishing_draft # Previously the reverse relati...
[ "def", "get_draft", "(", "self", ")", ":", "if", "self", ".", "is_draft", ":", "return", "self", "elif", "self", ".", "is_published", ":", "draft", "=", "self", ".", "publishing_draft", "# Previously the reverse relation could be `DraftItemBoobyTrapped`", "# in some c...
44.944444
17.5
def remove_slp(img, gstd1=GSTD1, gstd2=GSTD2, gstd3=GSTD3, ksize=KSIZE, w=W): """Remove the SLP from kinect IR image The input image should be a float32 numpy array, and should NOT be a square root image Parameters ------------------ img : (M, N) float ndarray Kinect NIR image with ...
[ "def", "remove_slp", "(", "img", ",", "gstd1", "=", "GSTD1", ",", "gstd2", "=", "GSTD2", ",", "gstd3", "=", "GSTD3", ",", "ksize", "=", "KSIZE", ",", "w", "=", "W", ")", ":", "gf1", "=", "cv2", ".", "getGaussianKernel", "(", "ksize", ",", "gstd1", ...
33.5
15.842105
def validate_instance(self, instance, import_validation_errors=None, validate_unique=True): """ Takes any validation errors that were raised by :meth:`~import_export.resources.Resource.import_obj`, and combines them with validation errors raised by the instance's ``full_clean()`` ...
[ "def", "validate_instance", "(", "self", ",", "instance", ",", "import_validation_errors", "=", "None", ",", "validate_unique", "=", "True", ")", ":", "if", "import_validation_errors", "is", "None", ":", "errors", "=", "{", "}", "else", ":", "errors", "=", "...
40.666667
18.666667
def get_build_report(self, project, build_id, type=None): """GetBuildReport. [Preview API] Gets a build report. :param str project: Project ID or project name :param int build_id: The ID of the build. :param str type: :rtype: :class:`<BuildReportMetadata> <azure.devops.v5...
[ "def", "get_build_report", "(", "self", ",", "project", ",", "build_id", ",", "type", "=", "None", ")", ":", "route_values", "=", "{", "}", "if", "project", "is", "not", "None", ":", "route_values", "[", "'project'", "]", "=", "self", ".", "_serialize", ...
51.181818
19.590909
def update_score_summary(sender, **kwargs): """ Listen for new Scores and update the relevant ScoreSummary. Args: sender: not used Kwargs: instance (Score): The score model whose save triggered this receiver. """ score = kwargs['instance'] ...
[ "def", "update_score_summary", "(", "sender", ",", "*", "*", "kwargs", ")", ":", "score", "=", "kwargs", "[", "'instance'", "]", "try", ":", "score_summary", "=", "ScoreSummary", ".", "objects", ".", "get", "(", "student_item", "=", "score", ".", "student_...
36.710526
19.078947
def pkg_contents(self): """Print packages contents """ packages = self.args[1:] options = [ "-d", "--display" ] if len(self.args) > 1 and self.args[0] in options: PackageManager(packages).display() else: usage("")
[ "def", "pkg_contents", "(", "self", ")", ":", "packages", "=", "self", ".", "args", "[", "1", ":", "]", "options", "=", "[", "\"-d\"", ",", "\"--display\"", "]", "if", "len", "(", "self", ".", "args", ")", ">", "1", "and", "self", ".", "args", "[...
25.5
15.583333
def _get_stack_frame(stacklevel): """ utility functions to get a stackframe, skipping internal frames. """ stacklevel = stacklevel + 1 if stacklevel <= 1 or _is_internal_frame(sys._getframe(1)): # If frame is too small to care or if the warning originated in # internal code, then do ...
[ "def", "_get_stack_frame", "(", "stacklevel", ")", ":", "stacklevel", "=", "stacklevel", "+", "1", "if", "stacklevel", "<=", "1", "or", "_is_internal_frame", "(", "sys", ".", "_getframe", "(", "1", ")", ")", ":", "# If frame is too small to care or if the warning ...
38.352941
14.117647
def kp_pan_zoom_set(self, viewer, event, data_x, data_y, msg=True): """Sets the pan position under the cursor.""" if self.canpan: reg = 1 with viewer.suppress_redraw: viewer.panset_xy(data_x, data_y) scale_x, scale_y = self._save.get((viewer, 'scal...
[ "def", "kp_pan_zoom_set", "(", "self", ",", "viewer", ",", "event", ",", "data_x", ",", "data_y", ",", "msg", "=", "True", ")", ":", "if", "self", ".", "canpan", ":", "reg", "=", "1", "with", "viewer", ".", "suppress_redraw", ":", "viewer", ".", "pan...
45.2
15.7
def make_env(env_type, real_env, sim_env_kwargs): """Factory function for envs.""" return { "real": lambda: real_env.new_like( # pylint: disable=g-long-lambda batch_size=sim_env_kwargs["batch_size"], store_rollouts=False, ), "simulated": lambda: rl_utils.SimulatedBatchGymEnvWi...
[ "def", "make_env", "(", "env_type", ",", "real_env", ",", "sim_env_kwargs", ")", ":", "return", "{", "\"real\"", ":", "lambda", ":", "real_env", ".", "new_like", "(", "# pylint: disable=g-long-lambda", "batch_size", "=", "sim_env_kwargs", "[", "\"batch_size\"", "]...
37.818182
24.181818
def name(self): """str: name of the file entry, which does not include the full path. Raises: BackEndError: if pytsk3 returns a non UTF-8 formatted name. """ if self._name is None: # If pytsk3.FS_Info.open() was used file.info has an attribute name # (pytsk3.TSK_FS_FILE) that contains...
[ "def", "name", "(", "self", ")", ":", "if", "self", ".", "_name", "is", "None", ":", "# If pytsk3.FS_Info.open() was used file.info has an attribute name", "# (pytsk3.TSK_FS_FILE) that contains the name string. Otherwise the", "# name from the path specification is used.", "if", "g...
35.653846
21.807692
def relative_noise_size(self, data, noise): ''' :data: original data as numpy matrix :noise: noise matrix as numpy matrix ''' return np.mean([ sci_dist.cosine(u / la.norm(u), v / la.norm(v)) for u, v in zip(noise, data) ])
[ "def", "relative_noise_size", "(", "self", ",", "data", ",", "noise", ")", ":", "return", "np", ".", "mean", "(", "[", "sci_dist", ".", "cosine", "(", "u", "/", "la", ".", "norm", "(", "u", ")", ",", "v", "/", "la", ".", "norm", "(", "v", ")", ...
31.777778
14.888889
def close(self): """ Write final shp, shx, and dbf headers, close opened files. """ # Check if any of the files have already been closed shp_open = self.shp and not (hasattr(self.shp, 'closed') and self.shp.closed) shx_open = self.shx and not (hasattr(self.shx, 'clo...
[ "def", "close", "(", "self", ")", ":", "# Check if any of the files have already been closed\r", "shp_open", "=", "self", ".", "shp", "and", "not", "(", "hasattr", "(", "self", ".", "shp", ",", "'closed'", ")", "and", "self", ".", "shp", ".", "closed", ")", ...
45.285714
19.571429
def locate_fixed_differences(ac1, ac2): """Locate variants with no shared alleles between two populations. Parameters ---------- ac1 : array_like, int, shape (n_variants, n_alleles) Allele counts array from the first population. ac2 : array_like, int, shape (n_variants, n_alleles) A...
[ "def", "locate_fixed_differences", "(", "ac1", ",", "ac2", ")", ":", "# check inputs", "ac1", "=", "asarray_ndim", "(", "ac1", ",", "2", ")", "ac2", "=", "asarray_ndim", "(", "ac2", ",", "2", ")", "check_dim0_aligned", "(", "ac1", ",", "ac2", ")", "ac1",...
30.561404
21.105263
def startDrag(self, index): """start a drag operation with a PandasCellPayload on defined index. Args: index (QModelIndex): model index you want to start the drag operation. """ if not index.isValid(): return dataFrame = self.model().dat...
[ "def", "startDrag", "(", "self", ",", "index", ")", ":", "if", "not", "index", ".", "isValid", "(", ")", ":", "return", "dataFrame", "=", "self", ".", "model", "(", ")", ".", "dataFrame", "(", ")", "# get all infos from dataFrame", "dfindex", "=", "dataF...
31.972222
16.666667
def locked_blocks_iterator(blockfile, start_info=(0, 0), cached_headers=50, batch_size=50): """ This method loads blocks from disk, skipping any orphan blocks. """ f = blockfile current_state = [] def change_state(bc, ops): for op, bh, work in ops: if op == 'add': ...
[ "def", "locked_blocks_iterator", "(", "blockfile", ",", "start_info", "=", "(", "0", ",", "0", ")", ",", "cached_headers", "=", "50", ",", "batch_size", "=", "50", ")", ":", "f", "=", "blockfile", "current_state", "=", "[", "]", "def", "change_state", "(...
30
15.333333
def find_faderport_input_name(number=0): """ Find the MIDI input name for a connected FaderPort. NOTE! Untested for more than one FaderPort attached. :param number: 0 unless you've got more than one FaderPort attached. In which case 0 is the first, 1 is the second etc :return: Po...
[ "def", "find_faderport_input_name", "(", "number", "=", "0", ")", ":", "ins", "=", "[", "i", "for", "i", "in", "mido", ".", "get_input_names", "(", ")", "if", "i", ".", "lower", "(", ")", ".", "startswith", "(", "'faderport'", ")", "]", "if", "0", ...
35.785714
18.5
def replace_version_tag(self): """find the next major/minor/trivial version number if applicable""" version_tag = self.arguments.get('<version>') special_keywords = ['current', 'latest'] if version_tag in special_keywords: logger.error("releasing version '{}' is disallowed. D...
[ "def", "replace_version_tag", "(", "self", ")", ":", "version_tag", "=", "self", ".", "arguments", ".", "get", "(", "'<version>'", ")", "special_keywords", "=", "[", "'current'", ",", "'latest'", "]", "if", "version_tag", "in", "special_keywords", ":", "logger...
54.052632
16.578947
def _parse_plan(self, match): """Parse a matching plan line.""" expected_tests = int(match.group("expected")) directive = Directive(match.group("directive")) # Only SKIP directives are allowed in the plan. if directive.text and not directive.skip: return Unknown() ...
[ "def", "_parse_plan", "(", "self", ",", "match", ")", ":", "expected_tests", "=", "int", "(", "match", ".", "group", "(", "\"expected\"", ")", ")", "directive", "=", "Directive", "(", "match", ".", "group", "(", "\"directive\"", ")", ")", "# Only SKIP dire...
35.6
16.1
def _compare_dbs_getter(self, db): """Retrieve a dictionary of table_name, row count key value pairs for a DB.""" # Change DB connection if needed if self.database != db: self.change_db(db) return self.count_rows_all()
[ "def", "_compare_dbs_getter", "(", "self", ",", "db", ")", ":", "# Change DB connection if needed", "if", "self", ".", "database", "!=", "db", ":", "self", ".", "change_db", "(", "db", ")", "return", "self", ".", "count_rows_all", "(", ")" ]
42.833333
4.833333
def get(self, id): """Get a object by id Args: id (int): Object id Returns: Object: Object with specified id None: If object not found """ for obj in self.model.db: if obj["id"] == id: return sel...
[ "def", "get", "(", "self", ",", "id", ")", ":", "for", "obj", "in", "self", ".", "model", ".", "db", ":", "if", "obj", "[", "\"id\"", "]", "==", "id", ":", "return", "self", ".", "_cast_model", "(", "obj", ")", "return", "None" ]
24.714286
14.285714
def _learner_distributed(learn:Learner, cuda_id:int, cache_dir:PathOrStr='tmp'): "Put `learn` on distributed training with `cuda_id`." learn.callbacks.append(DistributedTrainer(learn, cuda_id)) learn.callbacks.append(DistributedRecorder(learn, cuda_id, cache_dir)) return learn
[ "def", "_learner_distributed", "(", "learn", ":", "Learner", ",", "cuda_id", ":", "int", ",", "cache_dir", ":", "PathOrStr", "=", "'tmp'", ")", ":", "learn", ".", "callbacks", ".", "append", "(", "DistributedTrainer", "(", "learn", ",", "cuda_id", ")", ")"...
57.8
27.4
def start(self, initializer=None, initargs=()): '''Spawn a server process for this manager object''' assert self._state.value == State.INITIAL if (initializer is not None and not hasattr(initializer, '__call__')): raise TypeError('initializer must be a callable') ...
[ "def", "start", "(", "self", ",", "initializer", "=", "None", ",", "initargs", "=", "(", ")", ")", ":", "assert", "self", ".", "_state", ".", "value", "==", "State", ".", "INITIAL", "if", "(", "initializer", "is", "not", "None", "and", "not", "hasatt...
36.705882
17.764706
def parse_description_xml(location): """ Extract serial number, base ip, and img url from description.xml missing data from XML returns AttributeError malformed XML returns ParseError Refer to included example for URLBase and serialNumber elements """ class _URLBase(str): """ Convenien...
[ "def", "parse_description_xml", "(", "location", ")", ":", "class", "_URLBase", "(", "str", ")", ":", "\"\"\" Convenient access to hostname (ip) portion of the URL \"\"\"", "@", "property", "def", "hostname", "(", "self", ")", ":", "return", "urlsplit", "(", "self", ...
40.897436
18.282051
def _potInt(x,y,z,a2,b2,c2,n): """Integral involed in the potential at (x,y,z) integrates 1/A B^(n+1) where A = sqrt((tau+a)(tau+b)(tau+c)) and B = (1-x^2/(tau+a)-y^2/(tau+b)-z^2/(tau+c)) from lambda to infty with respect to tau. The lower limit lambda is given by lowerlim function. """ def ...
[ "def", "_potInt", "(", "x", ",", "y", ",", "z", ",", "a2", ",", "b2", ",", "c2", ",", "n", ")", ":", "def", "integrand", "(", "tau", ")", ":", "return", "_FracInt", "(", "x", ",", "y", ",", "z", ",", "a2", ",", "b2", ",", "c2", ",", "tau"...
46.4
15.6
def make_srcmap_manifest(self, components, name_factory): """ Build a yaml file that specfies how to make the srcmap files for a particular model Parameters ---------- components : list The binning components used in this analysis name_factory : `NameFactory` ...
[ "def", "make_srcmap_manifest", "(", "self", ",", "components", ",", "name_factory", ")", ":", "ret_dict", "=", "{", "}", "for", "comp", "in", "components", ":", "compkey", "=", "comp", ".", "make_key", "(", "'{ebin_name}_{evtype_name}'", ")", "zcut", "=", "\...
44.038462
16.75
def monitor(self, pk, parent_pk=None, timeout=None, interval=0.5, outfile=sys.stdout, **kwargs): """ Stream the standard output from a job, project update, or inventory udpate. =====API DOCS===== Stream the standard output from a job run to stdout. :param pk: Primary key of the...
[ "def", "monitor", "(", "self", ",", "pk", ",", "parent_pk", "=", "None", ",", "timeout", "=", "None", ",", "interval", "=", "0.5", ",", "outfile", "=", "sys", ".", "stdout", ",", "*", "*", "kwargs", ")", ":", "# If we do not have the unified job info, infe...
44.035294
27.776471
def run_task(self, task_name, task_args=[], task_kwargs={}): """ Run asynchronous task on a :class:`carotte.Worker`. :param string task_name: Name of task to execute :param list task_args: (optional) List of arguments to give to task :param dict task_kwargs: (optional) Dict of k...
[ "def", "run_task", "(", "self", ",", "task_name", ",", "task_args", "=", "[", "]", ",", "task_kwargs", "=", "{", "}", ")", ":", "data", "=", "{", "'action'", ":", "'run_task'", ",", "'name'", ":", "task_name", ",", "'args'", ":", "task_args", ",", "'...
32.761905
17.142857
def emit(self, **kwargs): """Emit signal by calling all connected slots. The arguments supplied have to match the signal definition. Args: kwargs: Keyword arguments to be passed to connected slots. Raises: :exc:`InvalidEmit`: If arguments don't match signal spe...
[ "def", "emit", "(", "self", ",", "*", "*", "kwargs", ")", ":", "self", ".", "_ensure_emit_kwargs", "(", "kwargs", ")", "for", "slot", "in", "self", ".", "slots", ":", "slot", "(", "*", "*", "kwargs", ")" ]
30.714286
21.785714
def add_component(self, alias: str, type: Union[str, type] = None, **config): """ Add a child component. This will instantiate a component class, as specified by the ``type`` argument. If the second argument is omitted, the value of ``alias`` is used as its value. The locally ...
[ "def", "add_component", "(", "self", ",", "alias", ":", "str", ",", "type", ":", "Union", "[", "str", ",", "type", "]", "=", "None", ",", "*", "*", "config", ")", ":", "assert", "check_argument_types", "(", ")", "if", "not", "isinstance", "(", "alias...
48.216216
31.783784
def wide_to_long(df, stubnames, i, j, sep="", suffix=r'\d+'): r""" Wide panel to long format. Less flexible but more user-friendly than melt. With stubnames ['A', 'B'], this function expects to find one or more group of columns with format A-suffix1, A-suffix2,..., B-suffix1, B-suffix2,... You ...
[ "def", "wide_to_long", "(", "df", ",", "stubnames", ",", "i", ",", "j", ",", "sep", "=", "\"\"", ",", "suffix", "=", "r'\\d+'", ")", ":", "def", "get_var_names", "(", "df", ",", "stub", ",", "sep", ",", "suffix", ")", ":", "regex", "=", "r'^{stub}{...
33.701068
20.259786
def set_memcached_backend(self, config): """ Select the most suitable Memcached backend based on the config and on what's installed """ # This is the preferred backend as it is the fastest and most fully # featured, so we use this by default config['BACKEND'] = 'd...
[ "def", "set_memcached_backend", "(", "self", ",", "config", ")", ":", "# This is the preferred backend as it is the fastest and most fully", "# featured, so we use this by default", "config", "[", "'BACKEND'", "]", "=", "'django_pylibmc.memcached.PyLibMCCache'", "if", "is_importabl...
50.5
19.916667
def extra_args_from_config(cp, section, skip_args=None, dtypes=None): """Gets any additional keyword in the given config file. Parameters ---------- cp : WorkflowConfigParser Config file parser to read. section : str The name of the section to read. ...
[ "def", "extra_args_from_config", "(", "cp", ",", "section", ",", "skip_args", "=", "None", ",", "dtypes", "=", "None", ")", ":", "kwargs", "=", "{", "}", "if", "dtypes", "is", "None", ":", "dtypes", "=", "{", "}", "if", "skip_args", "is", "None", ":"...
34.578947
17.447368
def make_job(job_name, **kwargs): """ Decorator to create a Job from a function. Give a job name and add extra fields to the job. @make_job("ExecuteDecJob", command=mongoengine.StringField(required=True), output=mongoengine.StringField(default=None)) def ...
[ "def", "make_job", "(", "job_name", ",", "*", "*", "kwargs", ")", ":", "def", "wraps", "(", "func", ")", ":", "kwargs", "[", "'process'", "]", "=", "func", "job", "=", "type", "(", "job_name", ",", "(", "Job", ",", ")", ",", "kwargs", ")", "globa...
38.15
19.85
def _ProcessFileSource(self, source): """Glob paths and return StatEntry objects.""" if source.path_type != rdf_paths.PathSpec.PathType.OS: raise ValueError("Only supported path type is OS.") paths = artifact_utils.InterpolateListKbAttributes( source.base_source.attributes["paths"], self.kno...
[ "def", "_ProcessFileSource", "(", "self", ",", "source", ")", ":", "if", "source", ".", "path_type", "!=", "rdf_paths", ".", "PathSpec", ".", "PathType", ".", "OS", ":", "raise", "ValueError", "(", "\"Only supported path type is OS.\"", ")", "paths", "=", "art...
38.8125
20.4375
def delete_set(self, x): """Removes the equivalence class containing `x`.""" if x not in self._parents: return members = list(self.members(x)) for v in members: del self._parents[v] del self._weights[v] del self._prev_next[v] de...
[ "def", "delete_set", "(", "self", ",", "x", ")", ":", "if", "x", "not", "in", "self", ".", "_parents", ":", "return", "members", "=", "list", "(", "self", ".", "members", "(", "x", ")", ")", "for", "v", "in", "members", ":", "del", "self", ".", ...
33.2
8.7
def append_partition_by_name(self, db_name, tbl_name, part_name): """ Parameters: - db_name - tbl_name - part_name """ self.send_append_partition_by_name(db_name, tbl_name, part_name) return self.recv_append_partition_by_name()
[ "def", "append_partition_by_name", "(", "self", ",", "db_name", ",", "tbl_name", ",", "part_name", ")", ":", "self", ".", "send_append_partition_by_name", "(", "db_name", ",", "tbl_name", ",", "part_name", ")", "return", "self", ".", "recv_append_partition_by_name",...
28.222222
17.777778
def log(self, message, level=None): """ Write a message to log """ if level is None: level = logging.INFO current_app.logger.log(msg=message, level=level)
[ "def", "log", "(", "self", ",", "message", ",", "level", "=", "None", ")", ":", "if", "level", "is", "None", ":", "level", "=", "logging", ".", "INFO", "current_app", ".", "logger", ".", "log", "(", "msg", "=", "message", ",", "level", "=", "level"...
31
14
def start_blocking(self): """ Start the advertiser in the background, but wait until it is ready """ self._cav_started.clear() self.start() self._cav_started.wait()
[ "def", "start_blocking", "(", "self", ")", ":", "self", ".", "_cav_started", ".", "clear", "(", ")", "self", ".", "start", "(", ")", "self", ".", "_cav_started", ".", "wait", "(", ")" ]
32
15
def finalize_structure(self): """Any functions needed to cleanup the structure.""" self.group_list.append(self.current_group) group_set = get_unique_groups(self.group_list) for item in self.group_list: self.group_type_list.append(group_set.index(item)) self.group_list...
[ "def", "finalize_structure", "(", "self", ")", ":", "self", ".", "group_list", ".", "append", "(", "self", ".", "current_group", ")", "group_set", "=", "get_unique_groups", "(", "self", ".", "group_list", ")", "for", "item", "in", "self", ".", "group_list", ...
51
12.428571
def users_register(self, email, name, password, username, **kwargs): """Register a new user.""" return self.__call_api_post('users.register', email=email, name=name, password=password, username=username, kwargs=kwargs)
[ "def", "users_register", "(", "self", ",", "email", ",", "name", ",", "password", ",", "username", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "__call_api_post", "(", "'users.register'", ",", "email", "=", "email", ",", "name", "=", "name",...
66.75
28.25
def copy(self, name=None): """ shallow copy of the instruction. Args: name (str): name to be given to the copied circuit, if None then the name stays the same Returns: Instruction: a shallow copy of the current instruction, with the name upda...
[ "def", "copy", "(", "self", ",", "name", "=", "None", ")", ":", "cpy", "=", "copy", ".", "copy", "(", "self", ")", "if", "name", ":", "cpy", ".", "name", "=", "name", "return", "cpy" ]
27.0625
17.8125
def list_view_changed(self, widget, event, data=None): """ Function shows last rows. """ adj = self.scrolled_window.get_vadjustment() adj.set_value(adj.get_upper() - adj.get_page_size())
[ "def", "list_view_changed", "(", "self", ",", "widget", ",", "event", ",", "data", "=", "None", ")", ":", "adj", "=", "self", ".", "scrolled_window", ".", "get_vadjustment", "(", ")", "adj", ".", "set_value", "(", "adj", ".", "get_upper", "(", ")", "-"...
36.833333
8.833333
def registration_packet(self): """Serialize this into a tuple suitable for returning from an RPC. Returns: tuple: The serialized values. """ return (self.hw_type, self.api_info[0], self.api_info[1], self.name, self.fw_info[0], self.fw_info[1], self.fw_info[2], ...
[ "def", "registration_packet", "(", "self", ")", ":", "return", "(", "self", ".", "hw_type", ",", "self", ".", "api_info", "[", "0", "]", ",", "self", ".", "api_info", "[", "1", "]", ",", "self", ".", "name", ",", "self", ".", "fw_info", "[", "0", ...
44.222222
29
def _mkpart(root, fs_format, fs_opts, mount_dir): ''' Make a partition, and make it bootable .. versionadded:: Beryllium ''' __salt__['partition.mklabel'](root, 'msdos') loop1 = __salt__['cmd.run']('losetup -f') log.debug('First loop device is %s', loop1) __salt__['cmd.run']('losetup {0...
[ "def", "_mkpart", "(", "root", ",", "fs_format", ",", "fs_opts", ",", "mount_dir", ")", ":", "__salt__", "[", "'partition.mklabel'", "]", "(", "root", ",", "'msdos'", ")", "loop1", "=", "__salt__", "[", "'cmd.run'", "]", "(", "'losetup -f'", ")", "log", ...
38.171429
14.457143
def required_length(nmin, nmax): """ For use with argparse's action argument. Allows setting a range for nargs. Example: nargs='+', action=required_length(2, 3) :param int nmin: Minimum number of arguments :param int nmax: Maximum number of arguments :return: RequiredLength object """ c...
[ "def", "required_length", "(", "nmin", ",", "nmax", ")", ":", "class", "RequiredLength", "(", "argparse", ".", "Action", ")", ":", "def", "__call__", "(", "self", ",", "parser", ",", "args", ",", "values", ",", "option_string", "=", "None", ")", ":", "...
43
15
def _update_index(self, url=None): """A helper function that ensures that self._index is up-to-date. If the index is older than self.INDEX_TIMEOUT, then download it again.""" # Check if the index is aleady up-to-date. If so, do nothing. if not (self._index is None or url is not None or tim...
[ "def", "_update_index", "(", "self", ",", "url", "=", "None", ")", ":", "# Check if the index is aleady up-to-date. If so, do nothing.", "if", "not", "(", "self", ".", "_index", "is", "None", "or", "url", "is", "not", "None", "or", "time", ".", "time", "(", ...
29.228571
18.4
def save_persistent_attributes(self): # type: () -> None """Save persistent attributes to the persistence layer if a persistence adapter is provided. :rtype: None :raises: :py:class:`ask_sdk_core.exceptions.AttributesManagerException` if trying to save persistence at...
[ "def", "save_persistent_attributes", "(", "self", ")", ":", "# type: () -> None", "if", "not", "self", ".", "_persistence_adapter", ":", "raise", "AttributesManagerException", "(", "\"Cannot save PersistentAttributes without \"", "\"persistence adapter!\"", ")", "if", "self",...
44.294118
13.588235
def nsx_controller_connection_addr_address(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") nsx_controller = ET.SubElement(config, "nsx-controller", xmlns="urn:brocade.com:mgmt:brocade-tunnels") name_key = ET.SubElement(nsx_controller, "name") nam...
[ "def", "nsx_controller_connection_addr_address", "(", "self", ",", "*", "*", "kwargs", ")", ":", "config", "=", "ET", ".", "Element", "(", "\"config\"", ")", "nsx_controller", "=", "ET", ".", "SubElement", "(", "config", ",", "\"nsx-controller\"", ",", "xmlns"...
46.923077
17.923077
def regexp_replace(str, pattern, replacement): r"""Replace all substrings of the specified string value that match regexp with rep. >>> df = spark.createDataFrame([('100-200',)], ['str']) >>> df.select(regexp_replace('str', r'(\d+)', '--').alias('d')).collect() [Row(d=u'-----')] """ sc = SparkC...
[ "def", "regexp_replace", "(", "str", ",", "pattern", ",", "replacement", ")", ":", "sc", "=", "SparkContext", ".", "_active_spark_context", "jc", "=", "sc", ".", "_jvm", ".", "functions", ".", "regexp_replace", "(", "_to_java_column", "(", "str", ")", ",", ...
44.7
18.8
def clear(self, username, project): """Clear the cache for given project.""" method = 'DELETE' url = ('/project/{username}/{project}/build-cache?' 'circle-token={token}'.format(username=username, project=project, ...
[ "def", "clear", "(", "self", ",", "username", ",", "project", ")", ":", "method", "=", "'DELETE'", "url", "=", "(", "'/project/{username}/{project}/build-cache?'", "'circle-token={token}'", ".", "format", "(", "username", "=", "username", ",", "project", "=", "p...
49
16.111111
def _get_context_and_user_ids(self, context_name, user_name): """Helper to get the context ID and user ID from the given names.""" if context_name is None: return None, None context_id = self.get_context_info(context_name)['id'] user_id = None if user_name: ...
[ "def", "_get_context_and_user_ids", "(", "self", ",", "context_name", ",", "user_name", ")", ":", "if", "context_name", "is", "None", ":", "return", "None", ",", "None", "context_id", "=", "self", ".", "get_context_info", "(", "context_name", ")", "[", "'id'",...
37.181818
19.727273
def on(self, events, callback, times=None): """ Registers the given *callback* with the given *events* (string or list of strings) that will get called whenever the given *event* is triggered (using :meth:`self.trigger`). If *times* is given the *callback* will only be fired tha...
[ "def", "on", "(", "self", ",", "events", ",", "callback", ",", "times", "=", "None", ")", ":", "# Make sure our _on_off_events dict is present (if first invokation)", "if", "not", "hasattr", "(", "self", ",", "'_on_off_events'", ")", ":", "self", ".", "_on_off_eve...
41.625
18.875
def prt_outfiles_flat(self, goea_results, outfiles): """Write to outfiles.""" kws = {'indent':self.args.indent, 'itemid2name':self.itemid2name} for outfile in outfiles: if outfile.endswith(".xlsx"): self.objgoea.wr_xlsx(outfile, goea_results, **kws) #elif ...
[ "def", "prt_outfiles_flat", "(", "self", ",", "goea_results", ",", "outfiles", ")", ":", "kws", "=", "{", "'indent'", ":", "self", ".", "args", ".", "indent", ",", "'itemid2name'", ":", "self", ".", "itemid2name", "}", "for", "outfile", "in", "outfiles", ...
44.9
15.7
def _function(self, x, a, b, c, d, s): """Lorentzian asymmetric function x: frequency coordinate a: peak position b: half width c: area proportional parameter d: base line s: asymmetry parameter """ return c/(np.pi*self._g_a(x, a, b, s)*(1.0+((x-a)...
[ "def", "_function", "(", "self", ",", "x", ",", "a", ",", "b", ",", "c", ",", "d", ",", "s", ")", ":", "return", "c", "/", "(", "np", ".", "pi", "*", "self", ".", "_g_a", "(", "x", ",", "a", ",", "b", ",", "s", ")", "*", "(", "1.0", "...
34.3
12.7
def chmod_plus(path, add_bits=stat.S_IWUSR): """Change a file's mode by adding a few bits. Like chmod +<bits> <path> in a Unix shell. """ try: os.chmod(path, stat.S_IMODE(os.stat(path).st_mode) | add_bits) except OSError: # pragma: nocover pass
[ "def", "chmod_plus", "(", "path", ",", "add_bits", "=", "stat", ".", "S_IWUSR", ")", ":", "try", ":", "os", ".", "chmod", "(", "path", ",", "stat", ".", "S_IMODE", "(", "os", ".", "stat", "(", "path", ")", ".", "st_mode", ")", "|", "add_bits", ")...
30.444444
15.777778
def save(self, commit=True): ''' If a staff member is reporting substitute teaching for a second time, then we should update the list of occurrences for which they are a substitute on their existing EventStaffMember record, rather than creating a new record and creating database issues. ...
[ "def", "save", "(", "self", ",", "commit", "=", "True", ")", ":", "existing_record", "=", "EventStaffMember", ".", "objects", ".", "filter", "(", "staffMember", "=", "self", ".", "cleaned_data", ".", "get", "(", "'staffMember'", ")", ",", "event", "=", "...
47.85
24.05
def plot_seebeck_eff_mass_mu(self, temps=[300], output='average', Lambda=0.5): """ Plot respect to the chemical potential of the Seebeck effective mass calculated as explained in Ref. Gibbs, Z. M. et al., Effective mass and fermi surface complexity factor...
[ "def", "plot_seebeck_eff_mass_mu", "(", "self", ",", "temps", "=", "[", "300", "]", ",", "output", "=", "'average'", ",", "Lambda", "=", "0.5", ")", ":", "import", "matplotlib", ".", "pyplot", "as", "plt", "plt", ".", "figure", "(", "figsize", "=", "("...
44.540984
18.57377
def upgrade(self, dependencies=False, prerelease=False, force=False): """ Upgrade the package unconditionaly Args: dependencies: update package dependencies if True (see pip --no-deps) prerelease: update to pre-release and development versions force: reinstall...
[ "def", "upgrade", "(", "self", ",", "dependencies", "=", "False", ",", "prerelease", "=", "False", ",", "force", "=", "False", ")", ":", "pip_args", "=", "[", "'install'", ",", "self", ".", "pkg", "]", "found", "=", "self", ".", "_get_current", "(", ...
32.380952
20.52381
def add_result(self, scan_id, result_type, host='', name='', value='', port='', test_id='', severity='', qod=''): """ Add a result to a scan in the table. """ assert scan_id assert len(name) or len(value) result = dict() result['type'] = result_type re...
[ "def", "add_result", "(", "self", ",", "scan_id", ",", "result_type", ",", "host", "=", "''", ",", "name", "=", "''", ",", "value", "=", "''", ",", "port", "=", "''", ",", "test_id", "=", "''", ",", "severity", "=", "''", ",", "qod", "=", "''", ...
38.421053
14
def tile_images(data, padsize=1, padval=0): """ Convert an array with shape of (B, C, H, W) into a tiled image. Args: data (~numpy.ndarray): An array with shape of (B, C, H, W). padsize (int): Each tile has padding with this size. padval (float): Padding pixels are filled with this ...
[ "def", "tile_images", "(", "data", ",", "padsize", "=", "1", ",", "padval", "=", "0", ")", ":", "assert", "(", "data", ".", "ndim", "==", "4", ")", "data", "=", "data", ".", "transpose", "(", "0", ",", "2", ",", "3", ",", "1", ")", "# force the...
30.885714
18.942857
def protoc_command(lang, output_dir, proto_path, refactored_dir): """Runs the "protoc" command on the refactored Protobuf files to generate the source python/python3 files. Args: lang (str): the language to compile with "protoc" (i.e. python, python3) output_dir (str): t...
[ "def", "protoc_command", "(", "lang", ",", "output_dir", ",", "proto_path", ",", "refactored_dir", ")", ":", "proto_files", "=", "glob", ".", "glob", "(", "os", ".", "path", ".", "join", "(", "refactored_dir", ",", "'*.proto'", ")", ")", "cmd", "=", "[",...
44.631579
20.947368
def _load_resource(self, source_r, abs_path=False): """The CSV package has no reseources, so we just need to resolve the URLs to them. Usually, the CSV package is built from a file system ackage on a publically acessible server. """ r = self.doc.resource(source_r.name) r.url = self...
[ "def", "_load_resource", "(", "self", ",", "source_r", ",", "abs_path", "=", "False", ")", ":", "r", "=", "self", ".", "doc", ".", "resource", "(", "source_r", ".", "name", ")", "r", ".", "url", "=", "self", ".", "resource_root", ".", "join", "(", ...
49.428571
15.285714
def _submit_resource_request(self): """ **Purpose**: Create and submits a RADICAL Pilot Job as per the user provided resource description """ try: self._prof.prof('creating rreq', uid=self._uid) def _pilot_state_cb(pilot, state): ...
[ "def", "_submit_resource_request", "(", "self", ")", ":", "try", ":", "self", ".", "_prof", ".", "prof", "(", "'creating rreq'", ",", "uid", "=", "self", ".", "_uid", ")", "def", "_pilot_state_cb", "(", "pilot", ",", "state", ")", ":", "self", ".", "_l...
33.819277
23.216867
def Parse(self): """Iterator returning dict for each entry in history.""" for data in self.Query(self.EVENTS_QUERY): (timestamp, agent_bundle_identifier, agent_name, url, sender, sender_address, type_number, title, referrer, referrer_alias) = data yield [ timestamp, "OSX_QUARANTINE"...
[ "def", "Parse", "(", "self", ")", ":", "for", "data", "in", "self", ".", "Query", "(", "self", ".", "EVENTS_QUERY", ")", ":", "(", "timestamp", ",", "agent_bundle_identifier", ",", "agent_name", ",", "url", ",", "sender", ",", "sender_address", ",", "typ...
45.1
23.1
def _kp2(A, B): """Special case Kronecker tensor product of A[i] and B[i] at each time interval i for i = 0 .. N-1 Specialized for the case A and B rank 3 with A.shape[0]==B.shape[0] """ N = A.shape[0] if B.shape[0] != N: raise(ValueError) newshape1 = A.shape[1]*B.shape[1] return...
[ "def", "_kp2", "(", "A", ",", "B", ")", ":", "N", "=", "A", ".", "shape", "[", "0", "]", "if", "B", ".", "shape", "[", "0", "]", "!=", "N", ":", "raise", "(", "ValueError", ")", "newshape1", "=", "A", ".", "shape", "[", "1", "]", "*", "B"...
37.1
14.7
def transform(self, col): """Prepare the transformer to convert data and return the processed table. Args: col(pandas.DataFrame): Data to transform. Returns: pandas.DataFrame """ out = pd.DataFrame() out[self.col_name] = self.safe_datetime_cast(c...
[ "def", "transform", "(", "self", ",", "col", ")", ":", "out", "=", "pd", ".", "DataFrame", "(", ")", "out", "[", "self", ".", "col_name", "]", "=", "self", ".", "safe_datetime_cast", "(", "col", ")", "out", "[", "self", ".", "col_name", "]", "=", ...
27.285714
19.5
def create_menu(self, menu_data): """ 创建自定义菜单 :: # -*- coding: utf-8 -*- wechat = WechatBasic(appid='appid', appsecret='appsecret') wechat.create_menu({ 'button':[ { 'type': 'click', ...
[ "def", "create_menu", "(", "self", ",", "menu_data", ")", ":", "menu_data", "=", "self", ".", "_transcoding_dict", "(", "menu_data", ")", "return", "self", ".", "request", ".", "post", "(", "url", "=", "'https://api.weixin.qq.com/cgi-bin/menu/create'", ",", "dat...
34.693878
13.102041
def compute_lower_upper_errors(sample, num_sigma=1): """ computes the upper and lower sigma from the median value. This functions gives good error estimates for skewed pdf's :param sample: 1-D sample :return: median, lower_sigma, upper_sigma """ if num_sigma > 3: raise ValueError("Nu...
[ "def", "compute_lower_upper_errors", "(", "sample", ",", "num_sigma", "=", "1", ")", ":", "if", "num_sigma", ">", "3", ":", "raise", "ValueError", "(", "\"Number of sigma-constraints restircted to three. %s not valid\"", "%", "num_sigma", ")", "num", "=", "len", "("...
43.272727
21.454545