text
stringlengths
75
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
0.18
def sample_from_data(self, model, data): """Convert incoming sample *data* into a numpy array. :param model: The :class:`~Model` instance to use for making predictions. :param data: A dict-like with the sample's data, typically retrieved from ``request.args`` or si...
[ "def", "sample_from_data", "(", "self", ",", "model", ",", "data", ")", ":", "values", "=", "[", "]", "for", "key", ",", "type_name", "in", "self", ".", "mapping", ":", "value_type", "=", "self", ".", "types", "[", "type_name", "]", "values", ".", "a...
36.166667
0.002994
def _set_load_balance_type(self, v, load=False): """ Setter method for load_balance_type, mapped from YANG variable /interface/port_channel/load_balance_type (enumeration) If this variable is read-only (config: false) in the source YANG file, then _set_load_balance_type is considered as a private me...
[ "def", "_set_load_balance_type", "(", "self", ",", "v", ",", "load", "=", "False", ")", ":", "if", "hasattr", "(", "v", ",", "\"_utype\"", ")", ":", "v", "=", "v", ".", "_utype", "(", "v", ")", "try", ":", "t", "=", "YANGDynClass", "(", "v", ",",...
94.363636
0.004769
def vrrpe_spf_basic(self, **kwargs): """Set vrrpe short path forwarding to default. Args: int_type (str): Type of interface. (gigabitethernet, tengigabitethernet, etc). name (str): Name of interface. (1/0/5, 1/0/10, etc). enable (bool): If vrrpe short...
[ "def", "vrrpe_spf_basic", "(", "self", ",", "*", "*", "kwargs", ")", ":", "int_type", "=", "kwargs", ".", "pop", "(", "'int_type'", ")", ".", "lower", "(", ")", "name", "=", "kwargs", ".", "pop", "(", "'name'", ")", "vrid", "=", "kwargs", ".", "pop...
47.4625
0.000516
def _new_stream(self): '''Grab the next stream from the input streamers, and start it. Raises ------ StopIteration When the input list or generator of streamers is complete, will raise a StopIteration. If `mode == cycle`, it will instead restart itera...
[ "def", "_new_stream", "(", "self", ")", ":", "try", ":", "# Advance the stream_generator_ to get the next available stream.", "# If successful, this will make self.chain_streamer_.active True", "next_stream", "=", "six", ".", "advance_iterator", "(", "self", ".", "stream_generato...
39.243902
0.001213
def get_properties_of_kind(kind, start=None, end=None): """Return all properties of kind in the specified range. NOTE: This function does not return unindexed properties. Args: kind: name of kind whose properties you want. start: only return properties >= start if start is not None. end: only return...
[ "def", "get_properties_of_kind", "(", "kind", ",", "start", "=", "None", ",", "end", "=", "None", ")", ":", "q", "=", "Property", ".", "query", "(", "ancestor", "=", "Property", ".", "key_for_kind", "(", "kind", ")", ")", "if", "start", "is", "not", ...
35.173913
0.008424
def get_week_avg_cycletime(self): """ Gets the average cycletime of the current user for the past week. This includes any ticket that was marked "In Progress" but not reopened. """ def moving_average(new_val, old_avg, prev_n): return (new_val + old_avg) / (prev_n + 1)...
[ "def", "get_week_avg_cycletime", "(", "self", ")", ":", "def", "moving_average", "(", "new_val", ",", "old_avg", ",", "prev_n", ")", ":", "return", "(", "new_val", "+", "old_avg", ")", "/", "(", "prev_n", "+", "1", ")", "active_tickets_jql", "=", "'assigne...
42.75
0.004577
def get_blog_context(context): """ Get context data useful on all blog related pages """ context['authors'] = get_user_model().objects.filter( owned_pages__live=True, owned_pages__content_type__model='blogpage' ).annotate(Count('owned_pages')).order_by('-owned_pages__count') context['all...
[ "def", "get_blog_context", "(", "context", ")", ":", "context", "[", "'authors'", "]", "=", "get_user_model", "(", ")", ".", "objects", ".", "filter", "(", "owned_pages__live", "=", "True", ",", "owned_pages__content_type__model", "=", "'blogpage'", ")", ".", ...
36.933333
0.001761
def set_magic(self, magic): '''Set magic (prefix)''' if magic is None or isinstance(magic, str): self.magic = magic else: raise TypeError('Invalid value for magic')
[ "def", "set_magic", "(", "self", ",", "magic", ")", ":", "if", "magic", "is", "None", "or", "isinstance", "(", "magic", ",", "str", ")", ":", "self", ".", "magic", "=", "magic", "else", ":", "raise", "TypeError", "(", "'Invalid value for magic'", ")" ]
34.5
0.009434
def handle_anonymous_user(self, response): """ Handles the ULogin response if user is not authenticated (anonymous) """ try: ulogin = ULoginUser.objects.get(network=response['network'], uid=response['uid']) except ULoginUser...
[ "def", "handle_anonymous_user", "(", "self", ",", "response", ")", ":", "try", ":", "ulogin", "=", "ULoginUser", ".", "objects", ".", "get", "(", "network", "=", "response", "[", "'network'", "]", ",", "uid", "=", "response", "[", "'uid'", "]", ")", "e...
40.4
0.001934
def ngrams(string, n=3, punctuation=PUNCTUATION, continuous=False): """ Returns a list of n-grams (tuples of n successive words) from the given string. Alternatively, you can supply a Text or Sentence object. With continuous=False, n-grams will not run over sentence markers (i.e., .!?). Punc...
[ "def", "ngrams", "(", "string", ",", "n", "=", "3", ",", "punctuation", "=", "PUNCTUATION", ",", "continuous", "=", "False", ")", ":", "def", "strip_punctuation", "(", "s", ",", "punctuation", "=", "set", "(", "punctuation", ")", ")", ":", "return", "[...
42.652174
0.004985
def get_file_contents_text( filename: str = None, blob: bytes = None, config: TextProcessingConfig = _DEFAULT_CONFIG) -> str: """ Returns the string contents of a file, or of a BLOB. """ binary_contents = get_file_contents(filename=filename, blob=blob) # 1. Try the encoding the user ...
[ "def", "get_file_contents_text", "(", "filename", ":", "str", "=", "None", ",", "blob", ":", "bytes", "=", "None", ",", "config", ":", "TextProcessingConfig", "=", "_DEFAULT_CONFIG", ")", "->", "str", ":", "binary_contents", "=", "get_file_contents", "(", "fil...
39.482759
0.000853
def parse_remote_port(self, reply): """ Parses a remote port from a Rendezvous Server's response. """ remote_port = re.findall("^REMOTE (TCP|UDP) ([0-9]+)$", reply) if not len(remote_port): remote_port = 0 else: remote_port = int...
[ "def", "parse_remote_port", "(", "self", ",", "reply", ")", ":", "remote_port", "=", "re", ".", "findall", "(", "\"^REMOTE (TCP|UDP) ([0-9]+)$\"", ",", "reply", ")", "if", "not", "len", "(", "remote_port", ")", ":", "remote_port", "=", "0", "else", ":", "r...
31.642857
0.004386
def get_unique_named_object(root, name): """ retrieves a unique named object (no fully qualified name) Args: root: start of search name: name of object Returns: the object (if not unique, raises an error) """ a = get_children(lambda x: hasattr(x, 'name') and x.name == n...
[ "def", "get_unique_named_object", "(", "root", ",", "name", ")", ":", "a", "=", "get_children", "(", "lambda", "x", ":", "hasattr", "(", "x", ",", "'name'", ")", "and", "x", ".", "name", "==", "name", ",", "root", ")", "assert", "len", "(", "a", ")...
25.428571
0.00271
def get_chunk(self,x,z): """ Return a chunk specified by the chunk coordinates x,z. Raise InconceivedChunk if the chunk is not yet generated. To get the raw NBT data, use get_nbt. """ return self.chunkclass(self.get_nbt(x, z))
[ "def", "get_chunk", "(", "self", ",", "x", ",", "z", ")", ":", "return", "self", ".", "chunkclass", "(", "self", ".", "get_nbt", "(", "x", ",", "z", ")", ")" ]
43.5
0.022556
def Yu_Lu(self, T, full=True, quick=True): r'''Method to calculate `a_alpha` and its first and second derivatives according to Yu and Lu (1987) [1]_. Returns `a_alpha`, `da_alpha_dT`, and `d2a_alpha_dT2`. See `GCEOS.a_alpha_and_derivatives` for more documentation. Four coefficients ne...
[ "def", "Yu_Lu", "(", "self", ",", "T", ",", "full", "=", "True", ",", "quick", "=", "True", ")", ":", "c1", ",", "c2", ",", "c3", ",", "c4", "=", "self", ".", "alpha_function_coeffs", "T", ",", "Tc", ",", "a", "=", "self", ".", "T", ",", "sel...
56.269231
0.007392
def individuals(self, ind_ids=None): """Return information about individuals Args: ind_ids (list(str)): List of individual ids Returns: individuals (Iterable): Iterable with Individuals """ if ind_ids: for ...
[ "def", "individuals", "(", "self", ",", "ind_ids", "=", "None", ")", ":", "if", "ind_ids", ":", "for", "ind_id", "in", "ind_ids", ":", "for", "ind", "in", "self", ".", "individual_objs", ":", "if", "ind", ".", "ind_id", "==", "ind_id", ":", "yield", ...
31.470588
0.00726
def sigma_sq(self, sample): """returns the value of sigma square, given the weight's sample Parameters ---------- sample: list sample is a (1 * NUM_OF_FUNCTIONS) matrix, representing{w1, w2, ... wk} Returns ------- float the value...
[ "def", "sigma_sq", "(", "self", ",", "sample", ")", ":", "ret", "=", "0", "for", "i", "in", "range", "(", "1", ",", "self", ".", "point_num", "+", "1", ")", ":", "temp", "=", "self", ".", "trial_history", "[", "i", "-", "1", "]", "-", "self", ...
31.333333
0.006885
def save_yaml(dictionary, path, pretty=False, sortkeys=False): # type: (Dict, str, bool, bool) -> None """Save dictionary to YAML file preserving order if it is an OrderedDict Args: dictionary (Dict): Python dictionary to save path (str): Path to YAML file pretty (bool): Whether to ...
[ "def", "save_yaml", "(", "dictionary", ",", "path", ",", "pretty", "=", "False", ",", "sortkeys", "=", "False", ")", ":", "# type: (Dict, str, bool, bool) -> None", "if", "sortkeys", ":", "dictionary", "=", "dict", "(", "dictionary", ")", "with", "open", "(", ...
35.15
0.00277
def initialize_from_ckpt(ckpt_dir, hparams): """Initialize variables from given directory.""" model_dir = hparams.get("model_dir", None) already_has_ckpt = ( model_dir and tf.train.latest_checkpoint(model_dir) is not None) if already_has_ckpt: return tf.logging.info("Checkpoint dir: %s", ckpt_dir) ...
[ "def", "initialize_from_ckpt", "(", "ckpt_dir", ",", "hparams", ")", ":", "model_dir", "=", "hparams", ".", "get", "(", "\"model_dir\"", ",", "None", ")", "already_has_ckpt", "=", "(", "model_dir", "and", "tf", ".", "train", ".", "latest_checkpoint", "(", "m...
39.6
0.01603
def update_metric(self, metric, labels, pre_sliced=False): """Update evaluation metric with label and current outputs.""" for current_exec, (texec, islice) in enumerate(zip(self.train_execs, self.slices)): if not pre_sliced: labels_slice = [label[islice] for label in labels] ...
[ "def", "update_metric", "(", "self", ",", "metric", ",", "labels", ",", "pre_sliced", "=", "False", ")", ":", "for", "current_exec", ",", "(", "texec", ",", "islice", ")", "in", "enumerate", "(", "zip", "(", "self", ".", "train_execs", ",", "self", "."...
54.625
0.006757
def arg_props(self): """Return the value and scalar properties as a dictionary. Returns only argumnet properties, properties declared on the same row as a term. It will return an entry for all of the args declared by the term's section. Use props to get values of all children and arg pr...
[ "def", "arg_props", "(", "self", ")", ":", "d", "=", "dict", "(", "zip", "(", "[", "str", "(", "e", ")", ".", "lower", "(", ")", "for", "e", "in", "self", ".", "section", ".", "property_names", "]", ",", "self", ".", "args", ")", ")", "# print(...
46.083333
0.008865
def breadcrumbs(self, tree_alias, context): """Builds and returns breadcrumb trail structure for 'sitetree_breadcrumbs' tag. :param str|unicode tree_alias: :param Context context: :rtype: list|str """ tree_alias, sitetree_items = self.init_tree(tree_alias, context) ...
[ "def", "breadcrumbs", "(", "self", ",", "tree_alias", ",", "context", ")", ":", "tree_alias", ",", "sitetree_items", "=", "self", ".", "init_tree", "(", "tree_alias", ",", "context", ")", "if", "not", "sitetree_items", ":", "return", "''", "current_item", "=...
32.6
0.003723
def value(self, value): """ set the value """ # for the indep direction we also allow a string which points to one # of the other available dimensions # TODO: support c, fc, ec? if isinstance(value, common.basestring) and value in ['x', 'y', 'z']: # we...
[ "def", "value", "(", "self", ",", "value", ")", ":", "# for the indep direction we also allow a string which points to one", "# of the other available dimensions", "# TODO: support c, fc, ec?", "if", "isinstance", "(", "value", ",", "common", ".", "basestring", ")", "and", ...
42.5
0.003836
def eval(self, valuation=None, trace=None): """ This method should be override to return some value :param valuation :param trace :return: """ return super().eval(valuation=valuation, trace=trace)
[ "def", "eval", "(", "self", ",", "valuation", "=", "None", ",", "trace", "=", "None", ")", ":", "return", "super", "(", ")", ".", "eval", "(", "valuation", "=", "valuation", ",", "trace", "=", "trace", ")" ]
30.625
0.007937
def dumb_relative_half_prime(n, divisor = None): '''A dumb brute-force algorithm to find a relative prime for n which is approximately n/2 through n/5. It is used for generating spaced colors. Written on a Friday evening. Do not judge! ''' if n < 1 or not isinstance(n, int): raise Exce...
[ "def", "dumb_relative_half_prime", "(", "n", ",", "divisor", "=", "None", ")", ":", "if", "n", "<", "1", "or", "not", "isinstance", "(", "n", ",", "int", ")", ":", "raise", "Exception", "(", "'n must be a positive non-zero integer.'", ")", "elif", "n", "<"...
31.64
0.004908
def validate_json(self): """ Ensure that the checksum matches. """ if not hasattr(self, 'guidance_json'): return False checksum = self.guidance_json.get('checksum') contents = self.guidance_json.get('db') hash_key = ("{}{}".format(json.dumps(contents, sort_keys=True...
[ "def", "validate_json", "(", "self", ")", ":", "if", "not", "hasattr", "(", "self", ",", "'guidance_json'", ")", ":", "return", "False", "checksum", "=", "self", ".", "guidance_json", ".", "get", "(", "'checksum'", ")", "contents", "=", "self", ".", "gui...
35.85
0.004076
def get_activity_streams(self, activity_id, types=None, resolution=None, series_type=None): """ Returns an streams for an activity. http://strava.github.io/api/v3/streams/#activity Streams represent the raw data of the uploaded file. External applic...
[ "def", "get_activity_streams", "(", "self", ",", "activity_id", ",", "types", "=", "None", ",", "resolution", "=", "None", ",", "series_type", "=", "None", ")", ":", "# stream are comma seperated list", "if", "types", "is", "not", "None", ":", "types", "=", ...
38.676923
0.002715
def integrate(self, coord, datetime_unit=None): """ integrate the array with the trapezoidal rule. .. note:: This feature is limited to simple cartesian geometry, i.e. coord must be one dimensional. Parameters ---------- dim: str, or a sequence of str ...
[ "def", "integrate", "(", "self", ",", "coord", ",", "datetime_unit", "=", "None", ")", ":", "if", "not", "isinstance", "(", "coord", ",", "(", "list", ",", "tuple", ")", ")", ":", "coord", "=", "(", "coord", ",", ")", "result", "=", "self", "for", ...
30.354839
0.00206
def backward_sampling(self, M, linear_cost=False, return_ar=False): """Generate trajectories using the FFBS (forward filtering backward sampling) algorithm. Arguments --------- M: int number of trajectories we want to generate linear_cost: bool ...
[ "def", "backward_sampling", "(", "self", ",", "M", ",", "linear_cost", "=", "False", ",", "return_ar", "=", "False", ")", ":", "idx", "=", "np", ".", "empty", "(", "(", "self", ".", "T", ",", "M", ")", ",", "dtype", "=", "int", ")", "idx", "[", ...
37.698113
0.007317
def _compute_metric_names(self): """Computes the list of metric names from all the scalar (run, tag) pairs. The return value is a list of (tag, group) pairs representing the metric names. The list is sorted in Python tuple-order (lexicographical). For example, if the scalar (run, tag) pairs are: (...
[ "def", "_compute_metric_names", "(", "self", ")", ":", "session_runs", "=", "self", ".", "_build_session_runs_set", "(", ")", "metric_names_set", "=", "set", "(", ")", "run_to_tag_to_content", "=", "self", ".", "multiplexer", ".", "PluginRunToTagToContent", "(", "...
41.325581
0.004398
def from_gene_ids(cls, gene_ids: List[str]): """Initialize instance from gene IDs.""" genes = [ExpGene(id_) for id_ in gene_ids] return cls.from_genes(genes)
[ "def", "from_gene_ids", "(", "cls", ",", "gene_ids", ":", "List", "[", "str", "]", ")", ":", "genes", "=", "[", "ExpGene", "(", "id_", ")", "for", "id_", "in", "gene_ids", "]", "return", "cls", ".", "from_genes", "(", "genes", ")" ]
44.5
0.01105
def north_arrow(self, north_arrow_path): """Set image that will be used as north arrow in reports. :param north_arrow_path: Path to the north arrow image. :type north_arrow_path: str """ if isinstance(north_arrow_path, str) and os.path.exists( north_arrow_path): ...
[ "def", "north_arrow", "(", "self", ",", "north_arrow_path", ")", ":", "if", "isinstance", "(", "north_arrow_path", ",", "str", ")", "and", "os", ".", "path", ".", "exists", "(", "north_arrow_path", ")", ":", "self", ".", "_north_arrow", "=", "north_arrow_pat...
39.181818
0.004535
def _create_resource_group(self, region, resource_group_name): """ Create resource group if it does not exist. """ resource_group_config = {'location': region} try: self.resource.resource_groups.create_or_update( resource_group_name, resource_group_co...
[ "def", "_create_resource_group", "(", "self", ",", "region", ",", "resource_group_name", ")", ":", "resource_group_config", "=", "{", "'location'", ":", "region", "}", "try", ":", "self", ".", "resource", ".", "resource_groups", ".", "create_or_update", "(", "re...
34.5
0.004032
def CompileReport(self, mediator): """Compiles an analysis report. Args: mediator (AnalysisMediator): mediates interactions between analysis plugins and other components, such as storage and dfvfs. Returns: AnalysisReport: analysis report. """ report_text = [ 'Session...
[ "def", "CompileReport", "(", "self", ",", "mediator", ")", ":", "report_text", "=", "[", "'Sessionize plugin identified {0:d} sessions and '", "'applied {1:d} tags.'", ".", "format", "(", "len", "(", "self", ".", "_events_per_session", ")", ",", "self", ".", "_numbe...
38.789474
0.002649
def phantomjs_get(url): """ Perform the request via PhantomJS. """ from selenium import webdriver from selenium.webdriver.common.desired_capabilities import DesiredCapabilities dcap = dict(DesiredCapabilities.PHANTOMJS) dcap["phantomjs.page.settings.userAgent"] = config.USER_AGENT dcap[...
[ "def", "phantomjs_get", "(", "url", ")", ":", "from", "selenium", "import", "webdriver", "from", "selenium", ".", "webdriver", ".", "common", ".", "desired_capabilities", "import", "DesiredCapabilities", "dcap", "=", "dict", "(", "DesiredCapabilities", ".", "PHANT...
32.789474
0.00624
def calc_humidity(temp, dewpoint): ''' calculates the humidity via the formula from weatherwise.org return the relative humidity ''' t = fahrenheit_to_celsius(temp) td = fahrenheit_to_celsius(dewpoint) num = 112 - (0.1 * t) + td denom = 112 + (0.9 * t) rh = math.pow((num / denom),...
[ "def", "calc_humidity", "(", "temp", ",", "dewpoint", ")", ":", "t", "=", "fahrenheit_to_celsius", "(", "temp", ")", "td", "=", "fahrenheit_to_celsius", "(", "dewpoint", ")", "num", "=", "112", "-", "(", "0.1", "*", "t", ")", "+", "td", "denom", "=", ...
21.866667
0.005848
def _verify_attachments(self): '''Verify that attachment values match the format expected by the Postmark API. ''' if self.attachments is None: return keys = ('Name', 'Content', 'ContentType') self._verify_dict_list(self.attachments, keys, 'Attachment')
[ "def", "_verify_attachments", "(", "self", ")", ":", "if", "self", ".", "attachments", "is", "None", ":", "return", "keys", "=", "(", "'Name'", ",", "'Content'", ",", "'ContentType'", ")", "self", ".", "_verify_dict_list", "(", "self", ".", "attachments", ...
38.25
0.00639
def token(cls: Type[SIGType], pubkey: str) -> SIGType: """ Return SIG instance from pubkey :param pubkey: Public key of the signature issuer :return: """ sig = cls() sig.pubkey = pubkey return sig
[ "def", "token", "(", "cls", ":", "Type", "[", "SIGType", "]", ",", "pubkey", ":", "str", ")", "->", "SIGType", ":", "sig", "=", "cls", "(", ")", "sig", ".", "pubkey", "=", "pubkey", "return", "sig" ]
25.2
0.007663
def get_subreddit_image(self, subreddit, id): """ Return the Gallery_image with the id submitted to subreddit gallery :param subreddit: The subreddit the image has been submitted to. :param id: The id of the image we want. """ url = self._base_url + "/3/gallery/r/{0}/{1}...
[ "def", "get_subreddit_image", "(", "self", ",", "subreddit", ",", "id", ")", ":", "url", "=", "self", ".", "_base_url", "+", "\"/3/gallery/r/{0}/{1}\"", ".", "format", "(", "subreddit", ",", "id", ")", "resp", "=", "self", ".", "_send_request", "(", "url",...
41.4
0.004728
def clone(self, _, scene): """ Create a clone of this Frame into a new Screen. :param _: ignored. :param scene: The new Scene object to clone into. """ # Assume that the application creates a new set of Frames and so we need to match up the # data from the old ob...
[ "def", "clone", "(", "self", ",", "_", ",", "scene", ")", ":", "# Assume that the application creates a new set of Frames and so we need to match up the", "# data from the old object to the new (using the name).", "if", "self", ".", "_name", "is", "not", "None", ":", "for", ...
42.5
0.004317
def recv_callback(self, callback, **kwargs): """receive messages and validate them with the callback, if the callback returns True then the message is valid and will be returned, if False then this will try and receive another message until timeout is 0""" payload = None timeout...
[ "def", "recv_callback", "(", "self", ",", "callback", ",", "*", "*", "kwargs", ")", ":", "payload", "=", "None", "timeout", "=", "self", ".", "get_timeout", "(", "*", "*", "kwargs", ")", "full_timeout", "=", "timeout", "while", "timeout", ">", "0.0", "...
36.863636
0.00601
def Popen(*args, **kwargs): """ Executes a command using subprocess.Popen and redirects output to AETROS and stdout. Parses stdout as well for stdout API calls. Use read_line argument to read stdout of command's stdout line by line. Use returned process stdin to communicate with the command. :...
[ "def", "Popen", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "read_line", "=", "None", "if", "'read_line'", "in", "kwargs", ":", "read_line", "=", "kwargs", "[", "'read_line'", "]", "del", "kwargs", "[", "'read_line'", "]", "p", "=", "subproces...
23.972973
0.00325
def toggle_state(self, state, active=TOGGLE): """ Toggle the given state for this conversation. The state will be set ``active`` is ``True``, otherwise the state will be removed. If ``active`` is not given, it will default to the inverse of the current state (i.e., ``False`` if...
[ "def", "toggle_state", "(", "self", ",", "state", ",", "active", "=", "TOGGLE", ")", ":", "if", "active", "is", "TOGGLE", ":", "active", "=", "not", "self", ".", "is_state", "(", "state", ")", "if", "active", ":", "self", ".", "set_state", "(", "stat...
33.636364
0.00657
def ask_pascal_16(self, next_rva_ptr): """The next RVA is taken to be the one immediately following this one. Such RVA could indicate the natural end of the string and will be checked with the possible length contained in the first word. """ length = self.__get_...
[ "def", "ask_pascal_16", "(", "self", ",", "next_rva_ptr", ")", ":", "length", "=", "self", ".", "__get_pascal_16_length", "(", ")", "if", "length", "==", "(", "next_rva_ptr", "-", "(", "self", ".", "rva_ptr", "+", "2", ")", ")", "/", "2", ":", "self", ...
34.357143
0.01417
def download(url, retry=5): """ Proxy function to be used with `enable_requests_cache()` to have the requests cached >>> import timeit >>> clean_cache() >>> enable_requests_cache() >>> url = "https://regardscitoyens.org/" >>> timeit.timeit(lambda: download(url), number=1) < 0.01 Fal...
[ "def", "download", "(", "url", ",", "retry", "=", "5", ")", ":", "try", ":", "if", "CACHE_ENABLED", ":", "file", "=", "os", ".", "path", ".", "join", "(", "cache_directory", "(", ")", ",", "hashlib", ".", "sha224", "(", "url", ".", "encode", "(", ...
35.714286
0.003337
def get_stop_times(feed: "Feed", date: Optional[str] = None) -> DataFrame: """ Return a subset of ``feed.stop_times``. Parameters ---------- feed : Feed date : string YYYYMMDD date string restricting the output to trips active on the date Returns ------- DataFrame ...
[ "def", "get_stop_times", "(", "feed", ":", "\"Feed\"", ",", "date", ":", "Optional", "[", "str", "]", "=", "None", ")", "->", "DataFrame", ":", "f", "=", "feed", ".", "stop_times", ".", "copy", "(", ")", "if", "date", "is", "None", ":", "return", "...
21.1
0.001511
def _query_for_reverse_geocoding(lat, lng): """ Given a lat & lng, what's the string search query. If the API changes, change this function. Only for internal use. """ # have to do some stupid f/Decimal/str stuff to (a) ensure we get as much # decimal places as the user already specified and (b...
[ "def", "_query_for_reverse_geocoding", "(", "lat", ",", "lng", ")", ":", "# have to do some stupid f/Decimal/str stuff to (a) ensure we get as much", "# decimal places as the user already specified and (b) to ensure we don't", "# get e-5 stuff", "return", "\"{0:f},{1:f}\"", ".", "format"...
42.1
0.002326
def export_yaml(obj, file_name): """ Exports curves and surfaces in YAML format. .. note:: Requires `ruamel.yaml <https://pypi.org/project/ruamel.yaml/>`_ package. YAML format is also used by the `geomdl command-line application <https://github.com/orbingol/geomdl-cli>`_ as a way to input sha...
[ "def", "export_yaml", "(", "obj", ",", "file_name", ")", ":", "def", "callback", "(", "data", ")", ":", "# Ref: https://yaml.readthedocs.io/en/latest/example.html#output-of-dump-as-a-string", "stream", "=", "StringIO", "(", ")", "yaml", "=", "YAML", "(", ")", "yaml"...
35.117647
0.004075
def execute(self, query, vars=None, result=False): """.. :py:method:: :param bool result: whether query return result :rtype: bool .. note:: True for `select`, False for `insert` and `update` """ with self.connection() as cur: if self.debug: ...
[ "def", "execute", "(", "self", ",", "query", ",", "vars", "=", "None", ",", "result", "=", "False", ")", ":", "with", "self", ".", "connection", "(", ")", "as", "cur", ":", "if", "self", ".", "debug", ":", "print", "(", "cur", ".", "mogrify", "("...
28.136364
0.004688
def contacts(self,*args,**kwargs): """ Use assess the cell-to-cell contacts recorded in the celldataframe Returns: Contacts: returns a class that holds cell-to-cell contact information for whatever phenotypes were in the CellDataFrame before execution. """ n = Cont...
[ "def", "contacts", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "n", "=", "Contacts", ".", "read_cellframe", "(", "self", ",", "prune_neighbors", "=", "True", ")", "if", "'measured_regions'", "in", "kwargs", ":", "n", ".", "measure...
51.928571
0.017568
def do_login(self, user): """Login a user.""" this.user_id = user.pk this.user_ddp_id = get_meteor_id(user) # silent subscription (sans sub/nosub msg) to LoggedInUser pub this.user_sub_id = meteor_random_id() API.do_sub(this.user_sub_id, 'LoggedInUser', silent=True) ...
[ "def", "do_login", "(", "self", ",", "user", ")", ":", "this", ".", "user_id", "=", "user", ".", "pk", "this", ".", "user_ddp_id", "=", "get_meteor_id", "(", "user", ")", "# silent subscription (sans sub/nosub msg) to LoggedInUser pub", "this", ".", "user_sub_id",...
40.454545
0.004396
def searchExpressionLevelsInDb( self, rnaQuantId, names=[], threshold=0.0, startIndex=0, maxResults=0): """ :param rnaQuantId: string restrict search by quantification id :param threshold: float minimum expression values to return :return an array of dictionaries,...
[ "def", "searchExpressionLevelsInDb", "(", "self", ",", "rnaQuantId", ",", "names", "=", "[", "]", ",", "threshold", "=", "0.0", ",", "startIndex", "=", "0", ",", "maxResults", "=", "0", ")", ":", "sql", "=", "(", "\"SELECT * FROM Expression WHERE \"", "\"rna...
42.090909
0.002112
def isel(self, indexers=None, drop=False, **indexers_kwargs): """Return a new DataArray whose dataset is given by integer indexing along the specified dimension(s). See Also -------- Dataset.isel DataArray.sel """ indexers = either_dict_or_kwargs(indexers...
[ "def", "isel", "(", "self", ",", "indexers", "=", "None", ",", "drop", "=", "False", ",", "*", "*", "indexers_kwargs", ")", ":", "indexers", "=", "either_dict_or_kwargs", "(", "indexers", ",", "indexers_kwargs", ",", "'isel'", ")", "ds", "=", "self", "."...
37.5
0.004338
def leave_chat( self, chat_id: Union[int, str], delete: bool = False ): """Use this method to leave a group chat or channel. Args: chat_id (``int`` | ``str``): Unique identifier for the target chat or username of the target channel/supergroup ...
[ "def", "leave_chat", "(", "self", ",", "chat_id", ":", "Union", "[", "int", ",", "str", "]", ",", "delete", ":", "bool", "=", "False", ")", ":", "peer", "=", "self", ".", "resolve_peer", "(", "chat_id", ")", "if", "isinstance", "(", "peer", ",", "t...
30.837209
0.004386
def converged_ionic(self): """ Checks that ionic step convergence has been reached, i.e. that vasp exited before reaching the max ionic steps for a relaxation run """ nsw = self.parameters.get("NSW", 0) return nsw <= 1 or len(self.ionic_steps) < nsw
[ "def", "converged_ionic", "(", "self", ")", ":", "nsw", "=", "self", ".", "parameters", ".", "get", "(", "\"NSW\"", ",", "0", ")", "return", "nsw", "<=", "1", "or", "len", "(", "self", ".", "ionic_steps", ")", "<", "nsw" ]
41.571429
0.006734
def create(dataset, num_clusters=None, features=None, label=None, initial_centers=None, max_iterations=10, batch_size=None, verbose=True): """ Create a k-means clustering model. The KmeansModel object contains the computed cluster centers and the cluster assignment for each instance in...
[ "def", "create", "(", "dataset", ",", "num_clusters", "=", "None", ",", "features", "=", "None", ",", "label", "=", "None", ",", "initial_centers", "=", "None", ",", "max_iterations", "=", "10", ",", "batch_size", "=", "None", ",", "verbose", "=", "True"...
37.880829
0.001333
def _put_data(self, sd, ase, offsets, data): # type: (SyncCopy, blobxfer.models.synccopy.Descriptor, # blobxfer.models.azure.StorageEntity, # blobxfer.models.upload.Offsets, bytes) -> None """Put data in Azure :param SyncCopy self: this :param blobxfer.model...
[ "def", "_put_data", "(", "self", ",", "sd", ",", "ase", ",", "offsets", ",", "data", ")", ":", "# type: (SyncCopy, blobxfer.models.synccopy.Descriptor,", "# blobxfer.models.azure.StorageEntity,", "# blobxfer.models.upload.Offsets, bytes) -> None", "if", "ase", "."...
46.8125
0.00218
def _unicode(value): """Converts a string argument to a unicode string. If the argument is already a unicode string or None, it is returned unchanged. Otherwise it must be a byte string and is decoded as utf8. """ if isinstance(value, _TO_UNICODE_TYPES): return value if not isinstance(...
[ "def", "_unicode", "(", "value", ")", ":", "if", "isinstance", "(", "value", ",", "_TO_UNICODE_TYPES", ")", ":", "return", "value", "if", "not", "isinstance", "(", "value", ",", "bytes_type", ")", ":", "raise", "TypeError", "(", "\"Expected bytes, unicode, or ...
35.692308
0.002101
def channel_names(self) -> tuple: """Channel names.""" if "channel_names" not in self.attrs.keys(): self.attrs["channel_names"] = np.array([], dtype="S") return tuple(s.decode() for s in self.attrs["channel_names"])
[ "def", "channel_names", "(", "self", ")", "->", "tuple", ":", "if", "\"channel_names\"", "not", "in", "self", ".", "attrs", ".", "keys", "(", ")", ":", "self", ".", "attrs", "[", "\"channel_names\"", "]", "=", "np", ".", "array", "(", "[", "]", ",", ...
49.4
0.007968
def get_criteria(self, sess, model, advx, y, batch_size=BATCH_SIZE): """ Returns a dictionary mapping the name of each criterion to a NumPy array containing the value of that criterion for each adversarial example. Subclasses can add extra criteria by implementing the `extra_criteria` method. ...
[ "def", "get_criteria", "(", "self", ",", "sess", ",", "model", ",", "advx", ",", "y", ",", "batch_size", "=", "BATCH_SIZE", ")", ":", "names", ",", "factory", "=", "self", ".", "extra_criteria", "(", ")", "factory", "=", "_CriteriaFactory", "(", "model",...
40.521739
0.001048
def get_bordercolor(self): """Get bordercolor based on hdrgos and usergos.""" hdrgos_all = self.grprobj.hdrobj.get_hdrgos() hdrgos_unused = hdrgos_all.difference(self.hdrgos_actual) go2bordercolor = {} # hdrgos that went unused for hdrgo in hdrgos_unused: go2b...
[ "def", "get_bordercolor", "(", "self", ")", ":", "hdrgos_all", "=", "self", ".", "grprobj", ".", "hdrobj", ".", "get_hdrgos", "(", ")", "hdrgos_unused", "=", "hdrgos_all", ".", "difference", "(", "self", ".", "hdrgos_actual", ")", "go2bordercolor", "=", "{",...
53.6
0.003666
def t_UFIXEDMN(t): r"ufixed(?P<M>256|248|240|232|224|216|208|200|192|184|176|168|160|152|144|136|128|120|112|104|96|88|80|72|64|56|48|40|32|24|16|8)x(?P<N>80|79|78|77|76|75|74|73|72|71|70|69|68|67|66|65|64|63|62|61|60|59|58|57|56|55|54|53|52|51|50|49|48|47|46|45|44|43|42|41|40|39|38|37|36|35|34|33|32|31|30|29|28|27...
[ "def", "t_UFIXEDMN", "(", "t", ")", ":", "M", "=", "int", "(", "t", ".", "lexer", ".", "lexmatch", ".", "group", "(", "'M'", ")", ")", "N", "=", "int", "(", "t", ".", "lexer", ".", "lexmatch", ".", "group", "(", "'N'", ")", ")", "t", ".", "...
85.333333
0.003868
def get_feature_variable_string(self, feature_key, variable_key, user_id, attributes=None): """ Returns value for a certain string variable attached to a feature. Args: feature_key: Key of the feature whose variable's value is being accessed. variable_key: Key of the variable whose value is to be a...
[ "def", "get_feature_variable_string", "(", "self", ",", "feature_key", ",", "variable_key", ",", "user_id", ",", "attributes", "=", "None", ")", ":", "variable_type", "=", "entities", ".", "Variable", ".", "Type", ".", "STRING", "return", "self", ".", "_get_fe...
40.277778
0.004043
def get_model(self): """ Get a model if the formula was previously satisfied. """ if self.minicard and self.status == True: model = pysolvers.minicard_model(self.minicard) return model if model != None else []
[ "def", "get_model", "(", "self", ")", ":", "if", "self", ".", "minicard", "and", "self", ".", "status", "==", "True", ":", "model", "=", "pysolvers", ".", "minicard_model", "(", "self", ".", "minicard", ")", "return", "model", "if", "model", "!=", "Non...
32.875
0.014815
def get_netconf_client_capabilities_output_session_version(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") get_netconf_client_capabilities = ET.Element("get_netconf_client_capabilities") config = get_netconf_client_capabilities output = ET.SubEle...
[ "def", "get_netconf_client_capabilities_output_session_version", "(", "self", ",", "*", "*", "kwargs", ")", ":", "config", "=", "ET", ".", "Element", "(", "\"config\"", ")", "get_netconf_client_capabilities", "=", "ET", ".", "Element", "(", "\"get_netconf_client_capab...
45.692308
0.00495
def stage_all(self): """ Stages all changed and untracked files """ LOGGER.info('Staging all files') self.repo.git.add(A=True)
[ "def", "stage_all", "(", "self", ")", ":", "LOGGER", ".", "info", "(", "'Staging all files'", ")", "self", ".", "repo", ".", "git", ".", "add", "(", "A", "=", "True", ")" ]
26.833333
0.012048
def refresh(self, access_token=None, **kwargs): """Refresh access and refresh tokens. Args: access_token (str): Access token to refresh. Defaults to ``None``. Returns: str: Refreshed access token. """ if not self.token_lock.locked(): with se...
[ "def", "refresh", "(", "self", ",", "access_token", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "not", "self", ".", "token_lock", ".", "locked", "(", ")", ":", "with", "self", ".", "token_lock", ":", "if", "access_token", "==", "self", ".",...
41.481013
0.000894
def lanczos_op(f, s, order=30): r""" Perform the lanczos approximation of the signal s. Parameters ---------- f: Filter s : ndarray Signal to approximate. order : int Degree of the lanczos approximation. (default = 30) Returns ------- L : ndarray lanczos...
[ "def", "lanczos_op", "(", "f", ",", "s", ",", "order", "=", "30", ")", ":", "G", "=", "f", ".", "G", "Nf", "=", "len", "(", "f", ".", "g", ")", "# To have the right shape for the output array depending on the signal dim", "try", ":", "Nv", "=", "np", "."...
22.45098
0.000837
def tearDown(self): """Clean up after each case. Stop harness service, close browser and close DUT. """ if self.__class__ is HarnessCase: return logger.info('Tearing down') self._destroy_harness() self._destroy_browser() self._destroy_dut() ...
[ "def", "tearDown", "(", "self", ")", ":", "if", "self", ".", "__class__", "is", "HarnessCase", ":", "return", "logger", ".", "info", "(", "'Tearing down'", ")", "self", ".", "_destroy_harness", "(", ")", "self", ".", "_destroy_browser", "(", ")", "self", ...
26.153846
0.005682
def linkage_group_ordering(linkage_records): """Convert degenerate linkage records into ordered info_frags-like records for comparison purposes. Simple example: >>> linkage_records = [ ... ['linkage_group_1', 31842, 94039, 'sctg_207'], ... ['linkage_group_1', 95303, 95303, 'sctg_20...
[ "def", "linkage_group_ordering", "(", "linkage_records", ")", ":", "new_records", "=", "dict", "(", ")", "for", "lg_name", ",", "linkage_group", "in", "itertools", ".", "groupby", "(", "linkage_records", ",", "operator", ".", "itemgetter", "(", "0", ")", ")", ...
34.254545
0.000516
def show( self, *actors, **options # at=None, # axes=None, # c=None, # alpha=None, # wire=False, # bc=None, # resetcam=True, # zoom=False, # interactive=None, # rate=None, # viewup="", # azimuth=0, # elevation=0, ...
[ "def", "show", "(", "self", ",", "*", "actors", ",", "*", "*", "options", "# at=None,", "# axes=None,", "# c=None,", "# alpha=None,", "# wire=False,", "# bc=None,", "# resetcam=True,", "# zoom=False,", "# interactiv...
38.828488
0.002993
def _build_native_function_call(fn): """ If fn can be interpreted and handled as a native function: i.e. fn is one of the extensions, or fn is a simple lambda closure using one of the extensions. fn = tc.extensions.add fn = lambda x: tc.extensions.add(5) Then, this returns a closure ...
[ "def", "_build_native_function_call", "(", "fn", ")", ":", "# See if fn is the native function itself", "native_function_name", "=", "_get_toolkit_function_name_from_function", "(", "fn", ")", "if", "native_function_name", "!=", "\"\"", ":", "# yup!", "# generate an \"identity\...
39.037037
0.002159
def init(opts): ''' This function gets called when the proxy starts up. For panos devices, a determination is made on the connection type and the appropriate connection details that must be cached. ''' if 'host' not in opts['proxy']: log.critical('No \'host\' key found in pillar for this...
[ "def", "init", "(", "opts", ")", ":", "if", "'host'", "not", "in", "opts", "[", "'proxy'", "]", ":", "log", ".", "critical", "(", "'No \\'host\\' key found in pillar for this proxy.'", ")", "return", "False", "if", "'apikey'", "not", "in", "opts", "[", "'pro...
43.215686
0.001775
def remove_capacity_from_diskgroup(service_instance, host_ref, diskgroup, capacity_disks, data_evacuation=True, hostname=None, host_vsan_system=None): ''' Removes capacity disk(s) from a disk group. ser...
[ "def", "remove_capacity_from_diskgroup", "(", "service_instance", ",", "host_ref", ",", "diskgroup", ",", "capacity_disks", ",", "data_evacuation", "=", "True", ",", "hostname", "=", "None", ",", "host_vsan_system", "=", "None", ")", ":", "if", "not", "hostname", ...
37.888889
0.000715
def set_in_bounds(self,obj,val): """ Set to the given value, but cropped to be within the legal bounds. All objects are accepted, and no exceptions will be raised. See crop_to_bounds for details on how cropping is done. """ if not callable(val): bounded_val =...
[ "def", "set_in_bounds", "(", "self", ",", "obj", ",", "val", ")", ":", "if", "not", "callable", "(", "val", ")", ":", "bounded_val", "=", "self", ".", "crop_to_bounds", "(", "val", ")", "else", ":", "bounded_val", "=", "val", "super", "(", "Number", ...
39.181818
0.013605
def get(self, url, params=None, cache_cb=None, **kwargs): """ Make http get request. :param url: :param params: :param cache_cb: (optional) a function that taking requests.Response as input, and returns a bool flag, ind...
[ "def", "get", "(", "self", ",", "url", ",", "params", "=", "None", ",", "cache_cb", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "self", ".", "use_random_user_agent", ":", "headers", "=", "kwargs", ".", "get", "(", "\"headers\"", ",", "dict"...
32.861111
0.005747
def compare_content(self, other): ''' Compare only the content of the documents (ignoring the meta fields). ''' if type(self) is not type(other): return False s1 = self.snapshot() s2 = other.snapshot() for snapshot in (s1, s2): for key in s...
[ "def", "compare_content", "(", "self", ",", "other", ")", ":", "if", "type", "(", "self", ")", "is", "not", "type", "(", "other", ")", ":", "return", "False", "s1", "=", "self", ".", "snapshot", "(", ")", "s2", "=", "other", ".", "snapshot", "(", ...
32.769231
0.004566
def command(self, *args, **kwargs): """Usage:: @cli.command(aliases=['ci']) def commit(): ... """ aliases = kwargs.pop('aliases', None) decorator = super(ProfilingCLI, self).command(*args, **kwargs) if aliases is None: return dec...
[ "def", "command", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "aliases", "=", "kwargs", ".", "pop", "(", "'aliases'", ",", "None", ")", "decorator", "=", "super", "(", "ProfilingCLI", ",", "self", ")", ".", "command", "(", "*"...
28.333333
0.005693
def get_input_chat_photo(photo): """Similar to :meth:`get_input_peer`, but for chat photos""" try: if photo.SUBCLASS_OF_ID == 0xd4eb2d74: # crc32(b'InputChatPhoto') return photo elif photo.SUBCLASS_OF_ID == 0xe7655f1f: # crc32(b'InputFile'): return types.InputChatUpload...
[ "def", "get_input_chat_photo", "(", "photo", ")", ":", "try", ":", "if", "photo", ".", "SUBCLASS_OF_ID", "==", "0xd4eb2d74", ":", "# crc32(b'InputChatPhoto')", "return", "photo", "elif", "photo", ".", "SUBCLASS_OF_ID", "==", "0xe7655f1f", ":", "# crc32(b'InputFile')...
38.764706
0.001481
def _set_enhanced_voq_max_queue_depth(self, v, load=False): """ Setter method for enhanced_voq_max_queue_depth, mapped from YANG variable /telemetry/profile/enhanced_voq_max_queue_depth (list) If this variable is read-only (config: false) in the source YANG file, then _set_enhanced_voq_max_queue_depth i...
[ "def", "_set_enhanced_voq_max_queue_depth", "(", "self", ",", "v", ",", "load", "=", "False", ")", ":", "if", "hasattr", "(", "v", ",", "\"_utype\"", ")", ":", "v", "=", "v", ".", "_utype", "(", "v", ")", "try", ":", "t", "=", "YANGDynClass", "(", ...
128.136364
0.004225
def setModel(self, model): """ Sets the model. Checks that the model is a """ check_class(model, BaseTreeModel) super(ArgosTreeView, self).setModel(model)
[ "def", "setModel", "(", "self", ",", "model", ")", ":", "check_class", "(", "model", ",", "BaseTreeModel", ")", "super", "(", "ArgosTreeView", ",", "self", ")", ".", "setModel", "(", "model", ")" ]
32.166667
0.010101
def _all_number_groups_are_exactly_present(numobj, normalized_candidate, formatted_number_groups): """Returns True if the groups of digits found in our candidate phone number match our expectations. Arguments: numobj -- the original number we found when parsing normalized_candidate -- the candidate...
[ "def", "_all_number_groups_are_exactly_present", "(", "numobj", ",", "normalized_candidate", ",", "formatted_number_groups", ")", ":", "candidate_groups", "=", "re", ".", "split", "(", "NON_DIGITS_PATTERN", ",", "normalized_candidate", ")", "# Set this to the last group, skip...
56.5
0.005037
def process_service_check_result(self, service, return_code, plugin_output): """Process service check result Format of the line that triggers function call:: PROCESS_SERVICE_CHECK_RESULT;<host_name>;<service_description>;<return_code>;<plugin_output> :param service: service to process ...
[ "def", "process_service_check_result", "(", "self", ",", "service", ",", "return_code", ",", "plugin_output", ")", ":", "now", "=", "time", ".", "time", "(", ")", "cls", "=", "service", ".", "__class__", "# If globally disabled OR service disabled, do not launch..", ...
44.263158
0.002035
def setWebView( self, webView ): """ Sets the web view edit that this find widget will use to search. :param webView | <QWebView> """ if ( self._webView ): self._webView.removeAction(self._findAction) self._webView = webView ...
[ "def", "setWebView", "(", "self", ",", "webView", ")", ":", "if", "(", "self", ".", "_webView", ")", ":", "self", ".", "_webView", ".", "removeAction", "(", "self", ".", "_findAction", ")", "self", ".", "_webView", "=", "webView", "if", "(", "webView",...
31.583333
0.025641
def stop_broadcast(self, broadcast_id): """ Use this method to stop a live broadcast of an OpenTok session :param String broadcast_id: The ID of the broadcast you want to stop :rtype A Broadcast object, which contains information of the broadcast: id, sessionId projectId, creat...
[ "def", "stop_broadcast", "(", "self", ",", "broadcast_id", ")", ":", "endpoint", "=", "self", ".", "endpoints", ".", "broadcast_url", "(", "broadcast_id", ",", "stop", "=", "True", ")", "response", "=", "requests", ".", "post", "(", "endpoint", ",", "heade...
40.387097
0.0039
def check(branch: str = 'master'): """ Detects the current CI environment, if any, and performs necessary environment checks. :param branch: The branch that should be the current branch. """ if os.environ.get('TRAVIS') == 'true': travis(branch) elif os.environ.get('SEMAPHORE') == 't...
[ "def", "check", "(", "branch", ":", "str", "=", "'master'", ")", ":", "if", "os", ".", "environ", ".", "get", "(", "'TRAVIS'", ")", "==", "'true'", ":", "travis", "(", "branch", ")", "elif", "os", ".", "environ", ".", "get", "(", "'SEMAPHORE'", ")"...
32.368421
0.00158
def state_blank(self, flag_page=None, **kwargs): """ :param flag_page: Flag page content, either a string or a list of BV8s """ s = super(SimCGC, self).state_blank(**kwargs) # pylint:disable=invalid-name # Special stack base for CGC binaries to work with Shellphish CRS ...
[ "def", "state_blank", "(", "self", ",", "flag_page", "=", "None", ",", "*", "*", "kwargs", ")", ":", "s", "=", "super", "(", "SimCGC", ",", "self", ")", ".", "state_blank", "(", "*", "*", "kwargs", ")", "# pylint:disable=invalid-name", "# Special stack bas...
37.85
0.005151
def removeFixedEffect(self, index=None): """ set sample and trait designs F: NxK sample design A: LxP sample design REML: REML for this term? index: index of which fixed effect to replace. If None, remove last term. """ if self._n_terms==0: ...
[ "def", "removeFixedEffect", "(", "self", ",", "index", "=", "None", ")", ":", "if", "self", ".", "_n_terms", "==", "0", ":", "pass", "if", "index", "is", "None", "or", "index", "==", "(", "self", ".", "_n_terms", "-", "1", ")", ":", "self", ".", ...
40.272727
0.022043
def _parse_integrator(int_method): """parse the integrator method to pass to C""" #Pick integrator if int_method.lower() == 'rk4_c': int_method_c= 1 elif int_method.lower() == 'rk6_c': int_method_c= 2 elif int_method.lower() == 'symplec4_c': int_method_c= 3 elif int_metho...
[ "def", "_parse_integrator", "(", "int_method", ")", ":", "#Pick integrator", "if", "int_method", ".", "lower", "(", ")", "==", "'rk4_c'", ":", "int_method_c", "=", "1", "elif", "int_method", ".", "lower", "(", ")", "==", "'rk6_c'", ":", "int_method_c", "=", ...
30.277778
0.016014
def with_context(cls, setup_phases, teardown_phases): """Create PhaseGroup creator function with setup and teardown phases. Args: setup_phases: list of phase_descriptor.PhaseDescriptors/PhaseGroups/ callables/iterables, phases to run during the setup for the PhaseGroup returned from t...
[ "def", "with_context", "(", "cls", ",", "setup_phases", ",", "teardown_phases", ")", ":", "setup", "=", "flatten_phases_and_groups", "(", "setup_phases", ")", "teardown", "=", "flatten_phases_and_groups", "(", "teardown_phases", ")", "def", "_context_wrapper", "(", ...
43.043478
0.002964
def confirm_iam_role(self, account): """Return the ARN of the IAM Role on the provided account as a string. Returns an `IAMRole` object from boto3 Args: account (:obj:`Account`): Account where to locate the role Returns: :obj:`IAMRole` """ try: ...
[ "def", "confirm_iam_role", "(", "self", ",", "account", ")", ":", "try", ":", "iam", "=", "self", ".", "session", ".", "client", "(", "'iam'", ")", "rolearn", "=", "iam", ".", "get_role", "(", "RoleName", "=", "self", ".", "role_name", ")", "[", "'Ro...
34.272727
0.005161
def new_output(output_type=None, output_text=None, output_png=None, output_html=None, output_svg=None, output_latex=None, output_json=None, output_javascript=None, output_jpeg=None, prompt_number=None, etype=None, evalue=None, traceback=None): """Create a new code cell with input and output""" outpu...
[ "def", "new_output", "(", "output_type", "=", "None", ",", "output_text", "=", "None", ",", "output_png", "=", "None", ",", "output_html", "=", "None", ",", "output_svg", "=", "None", ",", "output_latex", "=", "None", ",", "output_json", "=", "None", ",", ...
38.075
0.003201
def main_module_name() -> str: """Returns main module and module name pair.""" if not hasattr(main_module, '__file__'): # running from interactive shell return None main_filename = os.path.basename(main_module.__file__) module_name, ext = os.path.splitext(main_filename) return modul...
[ "def", "main_module_name", "(", ")", "->", "str", ":", "if", "not", "hasattr", "(", "main_module", ",", "'__file__'", ")", ":", "# running from interactive shell", "return", "None", "main_filename", "=", "os", ".", "path", ".", "basename", "(", "main_module", ...
35.333333
0.003067
def copyFile(input, output, replace=None): """Copy a file whole from input to output.""" _found = findFile(output) if not _found or (_found and replace): shutil.copy2(input, output)
[ "def", "copyFile", "(", "input", ",", "output", ",", "replace", "=", "None", ")", ":", "_found", "=", "findFile", "(", "output", ")", "if", "not", "_found", "or", "(", "_found", "and", "replace", ")", ":", "shutil", ".", "copy2", "(", "input", ",", ...
32.833333
0.00495
def _create_m_objective(w, X): """ Creates an objective function and its derivative for M, given W and X Args: w (array): clusters x cells X (array): genes x cells """ clusters, cells = w.shape genes = X.shape[0] w_sum = w.sum(1) def objective(m): m = m.reshape((...
[ "def", "_create_m_objective", "(", "w", ",", "X", ")", ":", "clusters", ",", "cells", "=", "w", ".", "shape", "genes", "=", "X", ".", "shape", "[", "0", "]", "w_sum", "=", "w", ".", "sum", "(", "1", ")", "def", "objective", "(", "m", ")", ":", ...
27.105263
0.003752
def __descendants(self): """Implementation for descendants, hacky workaround for __getattr__ issues. """ return itertools.chain(self.contents, *[c.descendants for c in self.children])
[ "def", "__descendants", "(", "self", ")", ":", "return", "itertools", ".", "chain", "(", "self", ".", "contents", ",", "*", "[", "c", ".", "descendants", "for", "c", "in", "self", ".", "children", "]", ")" ]
40.166667
0.00813
def get_item_sh(self, item): """ Add sorting hat enrichment fields """ sh_fields = {} # Not shared common get_item_sh because it is pretty specific if 'member' in item: # comment and rsvp identity = self.get_sh_identity(item['member']) elif 'event_hosts...
[ "def", "get_item_sh", "(", "self", ",", "item", ")", ":", "sh_fields", "=", "{", "}", "# Not shared common get_item_sh because it is pretty specific", "if", "'member'", "in", "item", ":", "# comment and rsvp", "identity", "=", "self", ".", "get_sh_identity", "(", "i...
31.736842
0.003221
def list_datacenters(kwargs=None, call=None): ''' List all the data centers for this VMware environment CLI Example: .. code-block:: bash salt-cloud -f list_datacenters my-vmware-config ''' if call != 'function': raise SaltCloudSystemExit( 'The list_datacenters fun...
[ "def", "list_datacenters", "(", "kwargs", "=", "None", ",", "call", "=", "None", ")", ":", "if", "call", "!=", "'function'", ":", "raise", "SaltCloudSystemExit", "(", "'The list_datacenters function must be called with '", "'-f or --function.'", ")", "return", "{", ...
26.352941
0.002155
def clone_fluent_contentitems_m2m_relationships(self, dst_obj): """ Find all MTM relationships on related ContentItem's and ensure the published M2M relationships directed back to the draft (src) content items are maintained for the published (dst) page's content items. "...
[ "def", "clone_fluent_contentitems_m2m_relationships", "(", "self", ",", "dst_obj", ")", ":", "if", "not", "hasattr", "(", "self", ",", "'contentitem_set'", ")", ":", "return", "# We must explicitly and reliably order both the src and dst content", "# items here to ensure that w...
50.25
0.001085
def _set_dacl_inheritance(path, objectType, inheritance=True, copy=True, clear=False): ''' helper function to set the inheritance Args: path (str): The path to the object objectType (str): The type of object inheritance (bool): True enables inheritance, False disables cop...
[ "def", "_set_dacl_inheritance", "(", "path", ",", "objectType", ",", "inheritance", "=", "True", ",", "copy", "=", "True", ",", "clear", "=", "False", ")", ":", "ret", "=", "{", "'result'", ":", "False", ",", "'comment'", ":", "''", ",", "'changes'", "...
43.457143
0.003214