text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def ifft(self): """Compute the one-dimensional discrete inverse Fourier transform of this `FrequencySeries`. Returns ------- out : :class:`~gwpy.timeseries.TimeSeries` the normalised, real-valued `TimeSeries`. See Also -------- :mod:`scipy.ff...
[ "def", "ifft", "(", "self", ")", ":", "from", ".", ".", "timeseries", "import", "TimeSeries", "nout", "=", "(", "self", ".", "size", "-", "1", ")", "*", "2", "# Undo normalization from TimeSeries.fft", "# The DC component does not have the factor of two applied", "#...
33.870968
20.709677
def buscar_ambientep44_por_finalidade_cliente( self, finalidade_txt, cliente_txt): """Search ambiente_p44_txt environment vip :return: Dictionary with the following structure: :: {‘ambiente_p44_txt’: 'id':<'id_ambientevip'>, ...
[ "def", "buscar_ambientep44_por_finalidade_cliente", "(", "self", ",", "finalidade_txt", ",", "cliente_txt", ")", ":", "vip_map", "=", "dict", "(", ")", "vip_map", "[", "'finalidade_txt'", "]", "=", "finalidade_txt", "vip_map", "[", "'cliente_txt'", "]", "=", "clie...
31.633333
20.933333
def list_storage_accounts_sub(access_token, subscription_id): '''List the storage accounts in the specified subscription. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. Returns: HTTP response. JSON body list of storage ac...
[ "def", "list_storage_accounts_sub", "(", "access_token", ",", "subscription_id", ")", ":", "endpoint", "=", "''", ".", "join", "(", "[", "get_rm_endpoint", "(", ")", ",", "'/subscriptions/'", ",", "subscription_id", ",", "'/providers/Microsoft.Storage/storageAccounts'",...
39.533333
22.466667
def min_renewable_share(network, snapshots, share=0.72): """ Sets minimal renewable share of generation as extra functionality in LOPF Parameters ---------- share: float Minimal share of renewable generation in p.u. """ renewables = ['wind_onshore', 'wind_offshore', ...
[ "def", "min_renewable_share", "(", "network", ",", "snapshots", ",", "share", "=", "0.72", ")", ":", "renewables", "=", "[", "'wind_onshore'", ",", "'wind_offshore'", ",", "'biomass'", ",", "'solar'", ",", "'run_of_river'", "]", "res", "=", "list", "(", "net...
33.548387
17.290323
def build_command(self, config, **kwargs): """Builds the command to execute MIP.""" command = ['perl', self.script, CLI_OPTIONS['config']['option'], config] for key, value in kwargs.items(): # enable passing in flags as "False" - shouldn't add command if value: ...
[ "def", "build_command", "(", "self", ",", "config", ",", "*", "*", "kwargs", ")", ":", "command", "=", "[", "'perl'", ",", "self", ".", "script", ",", "CLI_OPTIONS", "[", "'config'", "]", "[", "'option'", "]", ",", "config", "]", "for", "key", ",", ...
45.916667
15.75
def _add_source(model): """ Go over all attributes in `model` and add :class:`SourceString` to them. Args: model (obj): :class:`Model` instance. Returns: obj: :class:`Model` instance with :class:`SourceString` descriptors. """ ignored_keys = {"author_tags", "original_xml", "add...
[ "def", "_add_source", "(", "model", ")", ":", "ignored_keys", "=", "{", "\"author_tags\"", ",", "\"original_xml\"", ",", "\"additional_info\"", "}", "# convert all values to source strings", "source", "=", "\"Aleph\"", "for", "key", ",", "val", "in", "model", ".", ...
26.448276
21.62069
def get_requirements_transform_cfme(config): """Return requirement transformation function for CFME.""" def requirement_transform(requirement): """Requirements transform for CFME.""" requirement = copy.deepcopy(requirement) if "id" in requirement: del requirement["id"] ...
[ "def", "get_requirements_transform_cfme", "(", "config", ")", ":", "def", "requirement_transform", "(", "requirement", ")", ":", "\"\"\"Requirements transform for CFME.\"\"\"", "requirement", "=", "copy", ".", "deepcopy", "(", "requirement", ")", "if", "\"id\"", "in", ...
28.076923
16.384615
def _publish_edited(self): """Publish the deposit after for editing.""" record_pid, record = self.fetch_published() if record.revision_id == self['_deposit']['pid']['revision_id']: data = dict(self.dumps()) else: data = self.merge_with_published() data['$...
[ "def", "_publish_edited", "(", "self", ")", ":", "record_pid", ",", "record", "=", "self", ".", "fetch_published", "(", ")", "if", "record", ".", "revision_id", "==", "self", "[", "'_deposit'", "]", "[", "'pid'", "]", "[", "'revision_id'", "]", ":", "dat...
38.666667
14.833333
def getroot(self): """Return the root element of the figure. The root element is a group of elements after stripping the toplevel ``<svg>`` tag. Returns ------- GroupElement All elements of the figure without the ``<svg>`` tag. """ if 'class'...
[ "def", "getroot", "(", "self", ")", ":", "if", "'class'", "in", "self", ".", "root", ".", "attrib", ":", "attrib", "=", "{", "'class'", ":", "self", ".", "root", ".", "attrib", "[", "'class'", "]", "}", "else", ":", "attrib", "=", "None", "return",...
30.75
21.125
def cast_to_a1_notation(method): """ Decorator function casts wrapped arguments to A1 notation in range method calls. """ @wraps(method) def wrapper(self, *args, **kwargs): try: if len(args): int(args[0]) # Convert to A1 notation range...
[ "def", "cast_to_a1_notation", "(", "method", ")", ":", "@", "wraps", "(", "method", ")", "def", "wrapper", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "try", ":", "if", "len", "(", "args", ")", ":", "int", "(", "args", "[", ...
25.826087
16.869565
def get_all_clusters(resource_root, view=None): """ Get all clusters @param resource_root: The root Resource object. @return: A list of ApiCluster objects. """ return call(resource_root.get, CLUSTERS_PATH, ApiCluster, True, params=view and dict(view=view) or None)
[ "def", "get_all_clusters", "(", "resource_root", ",", "view", "=", "None", ")", ":", "return", "call", "(", "resource_root", ".", "get", ",", "CLUSTERS_PATH", ",", "ApiCluster", ",", "True", ",", "params", "=", "view", "and", "dict", "(", "view", "=", "v...
34.375
8.625
def vocab_marking_definition(instance): """Ensure that the `definition_type` property of `marking-definition` objects is one of the values in the STIX 2.0 specification. """ if (instance['type'] == 'marking-definition' and 'definition_type' in instance and not instance['definitio...
[ "def", "vocab_marking_definition", "(", "instance", ")", ":", "if", "(", "instance", "[", "'type'", "]", "==", "'marking-definition'", "and", "'definition_type'", "in", "instance", "and", "not", "instance", "[", "'definition_type'", "]", "in", "enums", ".", "MAR...
52.909091
20.363636
def busy_connections(self): """Return a list of active/busy connections :rtype: list """ return [c for c in self.connections.values() if c.busy and not c.closed]
[ "def", "busy_connections", "(", "self", ")", ":", "return", "[", "c", "for", "c", "in", "self", ".", "connections", ".", "values", "(", ")", "if", "c", ".", "busy", "and", "not", "c", ".", "closed", "]" ]
25.5
16
def calcPosition(self,parent_circle): ''' Position the circle tangent to the parent circle with the line connecting the centers of the two circles meeting the x axis at angle theta. ''' if r not in self: raise AttributeError("radius must be calculated before position.") if theta not ...
[ "def", "calcPosition", "(", "self", ",", "parent_circle", ")", ":", "if", "r", "not", "in", "self", ":", "raise", "AttributeError", "(", "\"radius must be calculated before position.\"", ")", "if", "theta", "not", "in", "self", ":", "raise", "AttributeError", "(...
63.2
29
def get_tool_names(): """ Get tool names from all configured groups. :return: list of tool names """ names = [] for group in cfg.get('Gromacs', 'groups').split(): names.extend(cfg.get('Gromacs', group).split()) return names
[ "def", "get_tool_names", "(", ")", ":", "names", "=", "[", "]", "for", "group", "in", "cfg", ".", "get", "(", "'Gromacs'", ",", "'groups'", ")", ".", "split", "(", ")", ":", "names", ".", "extend", "(", "cfg", ".", "get", "(", "'Gromacs'", ",", "...
27.555556
16.333333
def reset(self, rg=None): ''' Enable all offline cpus, and reset max and min frequencies files rg: range or list of threads to reset ''' if type(rg) == int: rg= [rg] to_reset= rg if rg else self.__get_ranges("present") self.enable_cpu(to_reset) ...
[ "def", "reset", "(", "self", ",", "rg", "=", "None", ")", ":", "if", "type", "(", "rg", ")", "==", "int", ":", "rg", "=", "[", "rg", "]", "to_reset", "=", "rg", "if", "rg", "else", "self", ".", "__get_ranges", "(", "\"present\"", ")", "self", "...
41.7
22.2
def erase_up (self): # <ESC>[1J '''Erases the screen from the current line up to the top of the screen.''' self.erase_start_of_line () self.fill_region (self.cur_r-1, 1, 1, self.cols)
[ "def", "erase_up", "(", "self", ")", ":", "# <ESC>[1J", "self", ".", "erase_start_of_line", "(", ")", "self", ".", "fill_region", "(", "self", ".", "cur_r", "-", "1", ",", "1", ",", "1", ",", "self", ".", "cols", ")" ]
35.166667
20.5
def _construct_location_to_filter_list(match_query): """Return a dict mapping location -> list of filters applied at that location. Args: match_query: MatchQuery object from which to extract location -> filters dict Returns: dict mapping each location in match_query to a list of ...
[ "def", "_construct_location_to_filter_list", "(", "match_query", ")", ":", "# For each location, all filters for that location should be applied at the first instance.", "# This function collects a list of all filters corresponding to each location", "# present in the given MatchQuery.", "location...
43.347826
21.043478
def plot_errorbars_trainset(self, which_data_rows='all', which_data_ycols='all', fixed_inputs=None, plot_raw=False, apply_link=False, label=None, projection='2d', predict_kw=None, **plot_kwargs): """ Plot the errorbars of the GP likelihood on the training data. These are the errorbar...
[ "def", "plot_errorbars_trainset", "(", "self", ",", "which_data_rows", "=", "'all'", ",", "which_data_ycols", "=", "'all'", ",", "fixed_inputs", "=", "None", ",", "plot_raw", "=", "False", ",", "apply_link", "=", "False", ",", "label", "=", "None", ",", "pro...
56.92
29.16
def user_delete(users, **kwargs): ''' Delete zabbix users. .. versionadded:: 2016.3.0 :param users: array of users (userids) to delete :param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring) :param _connection_password: Optional - zabbix pass...
[ "def", "user_delete", "(", "users", ",", "*", "*", "kwargs", ")", ":", "conn_args", "=", "_login", "(", "*", "*", "kwargs", ")", "ret", "=", "{", "}", "try", ":", "if", "conn_args", ":", "method", "=", "'user.delete'", "if", "not", "isinstance", "(",...
31.352941
26.529412
def rmse(targets, predictions): r""" Compute the root mean squared error between two SArrays. Parameters ---------- targets : SArray[float or int] An Sarray of ground truth target values. predictions : SArray[float or int] The prediction that corresponds to each target value. ...
[ "def", "rmse", "(", "targets", ",", "predictions", ")", ":", "_supervised_evaluation_error_checking", "(", "targets", ",", "predictions", ")", "return", "_turicreate", ".", "extensions", ".", "_supervised_streaming_evaluator", "(", "targets", ",", "predictions", ",", ...
25.893617
25.148936
def quadraticSolver(a, b, c): """return solution(s) for x, to the quadratic equation a*x^2 + b*x + c when it equals zero using the quadratic formula""" if a == 0: if b == 0: return [] # attempting to solve an equation with infinite (0=0) or impossible (0=3) solutions for x else: retur...
[ "def", "quadraticSolver", "(", "a", ",", "b", ",", "c", ")", ":", "if", "a", "==", "0", ":", "if", "b", "==", "0", ":", "return", "[", "]", "# attempting to solve an equation with infinite (0=0) or impossible (0=3) solutions for x", "else", ":", "return", "[", ...
54
21.333333
def oauth_connect(self, provider, action): """ This endpoint doesn't check if user is logged in, because it has two functions 1. If the user is not logged in, it will try to signup the user - if the social info exist, it will login - not, it will create a new account and...
[ "def", "oauth_connect", "(", "self", ",", "provider", ",", "action", ")", ":", "valid_actions", "=", "[", "\"connect\"", ",", "\"authorized\"", ",", "\"test\"", "]", "_redirect", "=", "views", ".", "auth", ".", "Account", ".", "account_settings", "if", "is_a...
36.490741
17.601852
def _create_awards(self): """ Creates awards. """ users = User.objects.all() for user in users: everyone_badge = Badge.objects.last() badge = Badge.objects.order_by('?')[0] try: award = Award.objects.create(user=user, badge=bad...
[ "def", "_create_awards", "(", "self", ")", ":", "users", "=", "User", ".", "objects", ".", "all", "(", ")", "for", "user", "in", "users", ":", "everyone_badge", "=", "Badge", ".", "objects", ".", "last", "(", ")", "badge", "=", "Badge", ".", "objects...
34.4
17.2
def reqTickByTickData( self, contract: Contract, tickType: str, numberOfTicks: int = 0, ignoreSize: bool = False) -> Ticker: """ Subscribe to tick-by-tick data and return the Ticker that holds the ticks in ticker.tickByTicks. https://interactivebrokers.github.io/...
[ "def", "reqTickByTickData", "(", "self", ",", "contract", ":", "Contract", ",", "tickType", ":", "str", ",", "numberOfTicks", ":", "int", "=", "0", ",", "ignoreSize", ":", "bool", "=", "False", ")", "->", "Ticker", ":", "reqId", "=", "self", ".", "clie...
41.85
19.55
def _parse_networks(networks): ''' Common logic for parsing the networks ''' networks = salt.utils.args.split_input(networks or []) if not networks: networks = {} else: # We don't want to recurse the repack, as the values of the kwargs # being passed when connecting to th...
[ "def", "_parse_networks", "(", "networks", ")", ":", "networks", "=", "salt", ".", "utils", ".", "args", ".", "split_input", "(", "networks", "or", "[", "]", ")", "if", "not", "networks", ":", "networks", "=", "{", "}", "else", ":", "# We don't want to r...
38.246377
18.710145
def _analyze(self): """ works out the updates to be performed """ if self.value is None or self.value == self.previous: pass elif self._operation == "append": self._append = self.value elif self._operation == "prepend": self._prepend = self.value ...
[ "def", "_analyze", "(", "self", ")", ":", "if", "self", ".", "value", "is", "None", "or", "self", ".", "value", "==", "self", ".", "previous", ":", "pass", "elif", "self", ".", "_operation", "==", "\"append\"", ":", "self", ".", "_append", "=", "self...
35
17.319149
def getmembers(self): ''' Return the members of the archive as a list of RPMInfo objects. The list has the same order as the members in the archive. ''' if self._members is None: self._members = _members = [] g = self.data_file magic = g.read(2...
[ "def", "getmembers", "(", "self", ")", ":", "if", "self", ".", "_members", "is", "None", ":", "self", ".", "_members", "=", "_members", "=", "[", "]", "g", "=", "self", ".", "data_file", "magic", "=", "g", ".", "read", "(", "2", ")", "while", "ma...
31.130435
16.521739
def forward(self, # pylint: disable=arguments-differ embeddings: torch.FloatTensor, mask: torch.LongTensor, num_items_to_keep: Union[int, torch.LongTensor]) -> Tuple[torch.FloatTensor, torch.LongTensor, ...
[ "def", "forward", "(", "self", ",", "# pylint: disable=arguments-differ", "embeddings", ":", "torch", ".", "FloatTensor", ",", "mask", ":", "torch", ".", "LongTensor", ",", "num_items_to_keep", ":", "Union", "[", "int", ",", "torch", ".", "LongTensor", "]", ")...
52.691589
27.009346
def ping(self, endpoint=''): """ Ping the server to make sure that you can access the base URL. Arguments: None Returns: `boolean` Successful access of server (or status code) """ r = requests.get(self.url() + "/" + endpoint) return r.stat...
[ "def", "ping", "(", "self", ",", "endpoint", "=", "''", ")", ":", "r", "=", "requests", ".", "get", "(", "self", ".", "url", "(", ")", "+", "\"/\"", "+", "endpoint", ")", "return", "r", ".", "status_code" ]
28.818182
18.454545
def process_dimensions(kdims, vdims): """Converts kdims and vdims to Dimension objects. Args: kdims: List or single key dimension(s) specified as strings, tuples dicts or Dimension objects. vdims: List or single value dimension(s) specified as strings, tuples dicts or Di...
[ "def", "process_dimensions", "(", "kdims", ",", "vdims", ")", ":", "dimensions", "=", "{", "}", "for", "group", ",", "dims", "in", "[", "(", "'kdims'", ",", "kdims", ")", ",", "(", "'vdims'", ",", "vdims", ")", "]", ":", "if", "dims", "is", "None",...
45
24.575758
def upload_object(bucket_path, bucket, content='', metadata=None, acl=None, cache_control=None, content_type=None): """Upload an arbitrary object to an S3 bucket. Parameters ---------- bucket_path : `str` Destination path (also known as the key name) of the f...
[ "def", "upload_object", "(", "bucket_path", ",", "bucket", ",", "content", "=", "''", ",", "metadata", "=", "None", ",", "acl", "=", "None", ",", "cache_control", "=", "None", ",", "content_type", "=", "None", ")", ":", "obj", "=", "bucket", ".", "Obje...
37.833333
17.714286
def diff(self, path_a, path_b): """ Performs a deep comparison of path_a/ and path_b/ For each child, it yields (rv, child) where rv: -1 if doesn't exist in path_b (destination) 0 if they are different 1 if it doesn't exist in path_a (source) """ ...
[ "def", "diff", "(", "self", ",", "path_a", ",", "path_b", ")", ":", "path_a", "=", "path_a", ".", "rstrip", "(", "\"/\"", ")", "path_b", "=", "path_b", ".", "rstrip", "(", "\"/\"", ")", "if", "not", "self", ".", "exists", "(", "path_a", ")", "or", ...
30.7
16.7
def build_wheel(wheel_directory, config_settings, metadata_directory=None): """Invoke the mandatory build_wheel hook. If a wheel was already built in the prepare_metadata_for_build_wheel fallback, this will copy it rather than rebuilding the wheel. """ prebuilt_whl = _find_already_built_wheel(m...
[ "def", "build_wheel", "(", "wheel_directory", ",", "config_settings", ",", "metadata_directory", "=", "None", ")", ":", "prebuilt_whl", "=", "_find_already_built_wheel", "(", "metadata_directory", ")", "if", "prebuilt_whl", ":", "shutil", ".", "copy2", "(", "prebuil...
41.357143
17.785714
def intern(obj, timeout): """ Tell untwisted to process an extern event loop. """ core.gear.timeout = timeout core.gear.pool.append(obj)
[ "def", "intern", "(", "obj", ",", "timeout", ")", ":", "core", ".", "gear", ".", "timeout", "=", "timeout", "core", ".", "gear", ".", "pool", ".", "append", "(", "obj", ")" ]
19.25
13.75
def magspec(frames, NFFT): """Compute the magnitude spectrum of each frame in frames. If frames is an NxD matrix, output will be Nx(NFFT/2+1). :param frames: the array of frames. Each row is a frame. :param NFFT: the FFT length to use. If NFFT > frame_len, the frames are zero-padded. :returns: If frame...
[ "def", "magspec", "(", "frames", ",", "NFFT", ")", ":", "if", "numpy", ".", "shape", "(", "frames", ")", "[", "1", "]", ">", "NFFT", ":", "logging", ".", "warn", "(", "'frame length (%d) is greater than FFT size (%d), frame will be truncated. Increase NFFT to avoid....
56.538462
24.846154
def _read_annotations(self, graph): """ Find any non-defined elements at TopLevel and create annotations """ flipped_namespaces = {v: k for k, v in self._namespaces.items()} for triple in graph.triples((None, RDF.type, None)): namespace, obj = split_uri(triple[2]) ...
[ "def", "_read_annotations", "(", "self", ",", "graph", ")", ":", "flipped_namespaces", "=", "{", "v", ":", "k", "for", "k", ",", "v", "in", "self", ".", "_namespaces", ".", "items", "(", ")", "}", "for", "triple", "in", "graph", ".", "triples", "(", ...
50.235294
14.823529
def _spectrum(self, photon_energy): """ Compute differential spectrum from pp interactions using Eq.71 and Eq.58 of Kelner, S.R., Aharonian, F.A., and Bugayov, V.V., 2006 PhysRevD 74, 034018 (`arXiv:astro-ph/0606058 <http://www.arxiv.org/abs/astro-ph/0606058>`_). Paramet...
[ "def", "_spectrum", "(", "self", ",", "photon_energy", ")", ":", "outspecene", "=", "_validate_ene", "(", "photon_energy", ")", "with", "warnings", ".", "catch_warnings", "(", ")", ":", "warnings", ".", "simplefilter", "(", "\"ignore\"", ")", "self", ".", "n...
39.473684
21.157895
def export_kappa_cm(model, fname=None): """Return a networkx graph representing the model's Kappa contact map. Parameters ---------- model : pysb.core.Model A PySB model to be exported into a Kappa CM. fname : Optional[str] A file name, typically with .png or .pdf extension in which...
[ "def", "export_kappa_cm", "(", "model", ",", "fname", "=", "None", ")", ":", "from", ".", "kappa_util", "import", "cm_json_to_graph", "kappa", "=", "_prepare_kappa", "(", "model", ")", "cmap", "=", "kappa", ".", "analyses_contact_map", "(", ")", "cm", "=", ...
28.956522
16.217391
def batch_move_file(path, dest, in_name=None, copy=True): """将path目录下文件名中包含的in_name的文件移动到dest目录下 parameters ------------ path 需要转移文件的目录 dest 目标目录 in_name str, 默认是None。文件名过滤规则 example ------------ # 将path目录下的所有txt文件转移到dest目录 move_file(path, dest, in_name='.txt'...
[ "def", "batch_move_file", "(", "path", ",", "dest", ",", "in_name", "=", "None", ",", "copy", "=", "True", ")", ":", "assert", "os", ".", "path", ".", "exists", "(", "path", ")", ",", "'%s 文件夹不存在' % path", "", "", "assert", "os", ".", "path", ".", ...
25.473684
17.973684
def schedule_at(self, task: Schedulable, at: datetime, *args, **kwargs): """Schedule a job to be executed in the future. :arg task: the task or its name to execute in the background :arg at: date at which the job should start. It is advised to pass a timezone aware datetime to ...
[ "def", "schedule_at", "(", "self", ",", "task", ":", "Schedulable", ",", "at", ":", "datetime", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "task", "=", "self", ".", "_tasks", ".", "get", "(", "task", ")", "job", "=", "Job", "(", "task",...
52
20
def convert_duration(duration): ''' Convert the a duration string into XXhYYmZZs format duration Duration to convert Returns: duration_string String representation of duration in XXhYYmZZs format ''' # durations must be specified in days, weeks or hours if duration.endswi...
[ "def", "convert_duration", "(", "duration", ")", ":", "# durations must be specified in days, weeks or hours", "if", "duration", ".", "endswith", "(", "'h'", ")", ":", "hours", "=", "int", "(", "duration", ".", "split", "(", "'h'", ")", ")", "elif", "duration", ...
24.038462
20.038462
def _wrap_OCLArray(cls): """ WRAPPER """ def prepare(arr): return np.require(arr, None, "C") @classmethod def from_array(cls, arr, *args, **kwargs): queue = get_device().queue return cl_array.to_device(queue, prepare(arr), *args, **kwargs) @classmethod def empt...
[ "def", "_wrap_OCLArray", "(", "cls", ")", ":", "def", "prepare", "(", "arr", ")", ":", "return", "np", ".", "require", "(", "arr", ",", "None", ",", "\"C\"", ")", "@", "classmethod", "def", "from_array", "(", "cls", ",", "arr", ",", "*", "args", ",...
30.336842
19.578947
def start(self): """start command in background and does not wait for it. :rtype: self """ if self.is_started: raise EasyProcessError(self, 'process was started twice!') if self.use_temp_files: self._stdout_file = tempfile.TemporaryFile(prefix='stdout_'...
[ "def", "start", "(", "self", ")", ":", "if", "self", ".", "is_started", ":", "raise", "EasyProcessError", "(", "self", ",", "'process was started twice!'", ")", "if", "self", ".", "use_temp_files", ":", "self", ".", "_stdout_file", "=", "tempfile", ".", "Tem...
34.2
18.114286
async def health_check(cls) -> Iterator[HealthCheckFail]: """ Perform checks of the state itself. So far: - For each method of the class, check for the presence of a health_check() method. If the method is present then call it. This is used to allow the context decorator to ...
[ "async", "def", "health_check", "(", "cls", ")", "->", "Iterator", "[", "HealthCheckFail", "]", ":", "for", "k", ",", "v", "in", "cls", ".", "__dict__", ".", "items", "(", ")", ":", "if", "hasattr", "(", "v", ",", "'health_check'", ")", "and", "calla...
41.357143
19.214286
def register_prefix(self, nspair): """ Register with ElementTree a set of namespaces :param nspair: A dictionary of prefixes and uris to use when constructing the text representation. :return: """ for prefix, uri in nspair.items(): try: ...
[ "def", "register_prefix", "(", "self", ",", "nspair", ")", ":", "for", "prefix", ",", "uri", "in", "nspair", ".", "items", "(", ")", ":", "try", ":", "ElementTree", ".", "register_namespace", "(", "prefix", ",", "uri", ")", "except", "AttributeError", ":...
34.625
14.5
def update(self): """ In the case where you have accessed an existing health check on a load balancer, this method applies this instance's health check values to the load balancer it is attached to. .. note:: This method will not do anything if the :py:attr:`access_point` ...
[ "def", "update", "(", "self", ")", ":", "if", "not", "self", ".", "access_point", ":", "return", "new_hc", "=", "self", ".", "connection", ".", "configure_health_check", "(", "self", ".", "access_point", ",", "self", ")", "self", ".", "interval", "=", "n...
41.263158
19.894737
def parse_JSON(self, JSON_string): """ Parses a `pyowm.alertapi30.trigger.Trigger` instance out of raw JSON data. As per OWM documentation, start and end times are expressed with respect to the moment when you create/update the Trigger. By design, PyOWM will only allow users to s...
[ "def", "parse_JSON", "(", "self", ",", "JSON_string", ")", ":", "if", "JSON_string", "is", "None", ":", "raise", "parse_response_error", ".", "ParseResponseError", "(", "'JSON data is None'", ")", "d", "=", "json", ".", "loads", "(", "JSON_string", ")", "try",...
43.720588
24.720588
def find_file(path, tgt_env='base', **kwargs): # pylint: disable=W0613 ''' Find the first file to match the path and ref. This operates similarly to the roots file sever but with assumptions of the directory structure based on svn standard practices. ''' fnd = {'path': '', 'rel': ''}...
[ "def", "find_file", "(", "path", ",", "tgt_env", "=", "'base'", ",", "*", "*", "kwargs", ")", ":", "# pylint: disable=W0613", "fnd", "=", "{", "'path'", ":", "''", ",", "'rel'", ":", "''", "}", "if", "os", ".", "path", ".", "isabs", "(", "path", ")...
36.422222
17
def strlen(state, s): """ strlen symbolic model. Algorithm: Walks from end of string not including NULL building ITE tree when current byte is symbolic. :param State state: current program state :param int s: Address of string :return: Symbolic strlen result :rtype: Expression or int "...
[ "def", "strlen", "(", "state", ",", "s", ")", ":", "cpu", "=", "state", ".", "cpu", "if", "issymbolic", "(", "s", ")", ":", "raise", "ConcretizeArgument", "(", "state", ".", "cpu", ",", "1", ")", "zero_idx", "=", "_find_zero", "(", "cpu", ",", "sta...
24.592593
22.222222
def radialrange(self, origin, return_all_global_extrema=False): """returns the tuples (d_min, t_min) and (d_max, t_max) which minimize and maximize, respectively, the distance d = |self.point(t)-origin|.""" return bezier_radialrange(self, origin, return_all_global_extrema=return_...
[ "def", "radialrange", "(", "self", ",", "origin", ",", "return_all_global_extrema", "=", "False", ")", ":", "return", "bezier_radialrange", "(", "self", ",", "origin", ",", "return_all_global_extrema", "=", "return_all_global_extrema", ")" ]
67
11.6
def _add_data(self, plotter_cls, *args, **kwargs): """ Visualize this data array Parameters ---------- %(Plotter.parameters.no_data)s Returns ------- psyplot.plotter.Plotter The plotter that visualizes the data """ # this meth...
[ "def", "_add_data", "(", "self", ",", "plotter_cls", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# this method is just a shortcut to the :meth:`Project._add_data`", "# method but is reimplemented by subclasses as the", "# :class:`DatasetPlotter` or the :class:`DataArrayPl...
31.647059
17.647059
def get_object(self, **kwargs): """Sometimes preprocessing of a view need to happen before the object attribute has been set for a view. In this case, just return the object if it has already been set when it's called down the road since there's no need to make another query. ""...
[ "def", "get_object", "(", "self", ",", "*", "*", "kwargs", ")", ":", "if", "hasattr", "(", "self", ",", "'object'", ")", "and", "self", ".", "object", ":", "return", "self", ".", "object", "obj", "=", "super", "(", "CommonSingleObjectViewMixin", ",", "...
42.916667
18.25
def set_operation_voltage_level(self): """Set operation voltage level """ mv_station_v_level_operation = float(cfg_ding0.get('mv_routing_tech_constraints', 'mv_station_v_level_operation')) self.v_level_operation = mv_stati...
[ "def", "set_operation_voltage_level", "(", "self", ")", ":", "mv_station_v_level_operation", "=", "float", "(", "cfg_ding0", ".", "get", "(", "'mv_routing_tech_constraints'", ",", "'mv_station_v_level_operation'", ")", ")", "self", ".", "v_level_operation", "=", "mv_sta...
39.111111
28.777778
def update_or_create(cls, append_lists=True, with_status=False, **kwargs): """ Update or create an IPList. :param bool append_lists: append to existing IP List :param dict kwargs: provide at minimum the name attribute and optionally match the create constructor value...
[ "def", "update_or_create", "(", "cls", ",", "append_lists", "=", "True", ",", "with_status", "=", "False", ",", "*", "*", "kwargs", ")", ":", "was_created", ",", "was_modified", "=", "False", ",", "False", "element", "=", "None", "try", ":", "element", "...
35.333333
16.555556
def _check_collections(self): """Checks node local collection storage sizes""" self.collection_sizes = {} self.collection_total = 0 for col in self.db.collection_names(include_system_collections=False): self.collection_sizes[col] = self.db.command('collstats', col).get( ...
[ "def", "_check_collections", "(", "self", ")", ":", "self", ".", "collection_sizes", "=", "{", "}", "self", ".", "collection_total", "=", "0", "for", "col", "in", "self", ".", "db", ".", "collection_names", "(", "include_system_collections", "=", "False", ")...
41.4
21.5
def set(self, key, value, timeout=None): """ Cache the given ``value`` in the specified ``key``. If no timeout is specified, the default timeout will be used. """ key = self.make_key(key) if timeout is None: timeout = self.default_timeout if self.debu...
[ "def", "set", "(", "self", ",", "key", ",", "value", ",", "timeout", "=", "None", ")", ":", "key", "=", "self", ".", "make_key", "(", "key", ")", "if", "timeout", "is", "None", ":", "timeout", "=", "self", ".", "default_timeout", "if", "self", ".",...
31.888889
16.111111
def _colorformat(text): """ Parse/validate color format. Like in Pygments, but also support the ANSI color names. (These will map to the colors of the 16 color palette.) """ if text[0:1] == '#': col = text[1:] if col in ANSI_COLOR_NAMES: return col elif len(c...
[ "def", "_colorformat", "(", "text", ")", ":", "if", "text", "[", "0", ":", "1", "]", "==", "'#'", ":", "col", "=", "text", "[", "1", ":", "]", "if", "col", "in", "ANSI_COLOR_NAMES", ":", "return", "col", "elif", "len", "(", "col", ")", "==", "6...
26.684211
16.157895
def fit(self, X, y, sample_weight=None, eval_set=None, eval_metric=None, early_stopping_rounds=None, verbose=True): # pylint: disable = attribute-defined-outside-init,arguments-differ """ Fit gradient boosting classifier Parameters ---------- X : array_like ...
[ "def", "fit", "(", "self", ",", "X", ",", "y", ",", "sample_weight", "=", "None", ",", "eval_set", "=", "None", ",", "eval_metric", "=", "None", ",", "early_stopping_rounds", "=", "None", ",", "verbose", "=", "True", ")", ":", "# pylint: disable = attribut...
43.711111
20.844444
def ensureUtf(s, encoding='utf8'): """Converts input to unicode if necessary. If `s` is bytes, it will be decoded using the `encoding` parameters. This function is used for preprocessing /source/ and /filename/ arguments to the builtin function `compile`. """ # In Python2, str == bytes. # In...
[ "def", "ensureUtf", "(", "s", ",", "encoding", "=", "'utf8'", ")", ":", "# In Python2, str == bytes.", "# In Python3, bytes remains unchanged, but str means unicode", "# while unicode is not defined anymore", "if", "type", "(", "s", ")", "==", "bytes", ":", "return", "s",...
38.692308
14.307692
def from_json(buffer, auto_flatten=True, raise_for_index=True): """Parses a JSON string into either a view or an index. If auto flatten is enabled a sourcemap index that does not contain external references is automatically flattened into a view. By default if an index would be returned an `IndexedSou...
[ "def", "from_json", "(", "buffer", ",", "auto_flatten", "=", "True", ",", "raise_for_index", "=", "True", ")", ":", "buffer", "=", "to_bytes", "(", "buffer", ")", "view_out", "=", "_ffi", ".", "new", "(", "'lsm_view_t **'", ")", "index_out", "=", "_ffi", ...
38.071429
17.25
def call(self, iface_name, func_name, params): """ Implements the call() function with same signature as Client.call(). Raises a RpcException if send() has already been called on this batch. Otherwise appends the request to an internal list. This method is not commonly called ...
[ "def", "call", "(", "self", ",", "iface_name", ",", "func_name", ",", "params", ")", ":", "if", "self", ".", "sent", ":", "raise", "Exception", "(", "\"Batch already sent. Cannot add more calls.\"", ")", "else", ":", "req", "=", "self", ".", "client", ".", ...
42.230769
20.384615
def parseelement(elem): ''' Convert the content of an element into more ElementTree structures. We do this because sometimes we want to set xml as the content of an element. ''' xml = '<%(tag)s>%(content)s</%(tag)s>' % {'tag' : elem.tag, 'content' : elem.text} et = etree.fromstring(xml) repl...
[ "def", "parseelement", "(", "elem", ")", ":", "xml", "=", "'<%(tag)s>%(content)s</%(tag)s>'", "%", "{", "'tag'", ":", "elem", ".", "tag", ",", "'content'", ":", "elem", ".", "text", "}", "et", "=", "etree", ".", "fromstring", "(", "xml", ")", "replaceele...
41.625
27.875
def fetch_items(self, category, **kwargs): """Fetch the messages :param category: the category of items to fetch :param kwargs: backend arguments :returns: a generator of items """ from_date = kwargs['from_date'] logger.info("Looking for messages from '%s' on '...
[ "def", "fetch_items", "(", "self", ",", "category", ",", "*", "*", "kwargs", ")", ":", "from_date", "=", "kwargs", "[", "'from_date'", "]", "logger", ".", "info", "(", "\"Looking for messages from '%s' on '%s' since %s\"", ",", "self", ".", "uri", ",", "self",...
29.428571
20.47619
def detail( self, participant1: Address, participant2: Address, block_identifier: BlockSpecification, channel_identifier: ChannelID = None, ) -> ChannelDetails: """ Returns a ChannelDetails instance with all the details of the channel a...
[ "def", "detail", "(", "self", ",", "participant1", ":", "Address", ",", "participant2", ":", "Address", ",", "block_identifier", ":", "BlockSpecification", ",", "channel_identifier", ":", "ChannelID", "=", "None", ",", ")", "->", "ChannelDetails", ":", "if", "...
36.210526
16.631579
def http_error_default(self, url, fp, errcode, errmsg, headers): """Default error handler: close the connection and raise IOError.""" fp.close() raise HTTPError(url, errcode, errmsg, headers, None)
[ "def", "http_error_default", "(", "self", ",", "url", ",", "fp", ",", "errcode", ",", "errmsg", ",", "headers", ")", ":", "fp", ".", "close", "(", ")", "raise", "HTTPError", "(", "url", ",", "errcode", ",", "errmsg", ",", "headers", ",", "None", ")" ...
54.5
16.5
def read_targets(targets): """Reads generic key-value pairs from input files""" results = {} for target, regexer in regexer_for_targets(targets): with open(target) as fh: results.update(extract_keypairs(fh.readlines(), regexer)) return results
[ "def", "read_targets", "(", "targets", ")", ":", "results", "=", "{", "}", "for", "target", ",", "regexer", "in", "regexer_for_targets", "(", "targets", ")", ":", "with", "open", "(", "target", ")", "as", "fh", ":", "results", ".", "update", "(", "extr...
39
16.142857
def _wva(values, weights): """ Calculates a weighted average """ assert len(values) == len(weights) and len(weights) > 0 return sum([mul(*x) for x in zip(values, weights)]) / sum(weights)
[ "def", "_wva", "(", "values", ",", "weights", ")", ":", "assert", "len", "(", "values", ")", "==", "len", "(", "weights", ")", "and", "len", "(", "weights", ")", ">", "0", "return", "sum", "(", "[", "mul", "(", "*", "x", ")", "for", "x", "in", ...
43
14.2
def set_qs_value(self, qsid, val, success_cb): """Push state to QSUSB, retry with backoff.""" self.loop.create_task(self.async_set_qs_value(qsid, val, success_cb))
[ "def", "set_qs_value", "(", "self", ",", "qsid", ",", "val", ",", "success_cb", ")", ":", "self", ".", "loop", ".", "create_task", "(", "self", ".", "async_set_qs_value", "(", "qsid", ",", "val", ",", "success_cb", ")", ")" ]
59
14.333333
def get_open_files(self): """Return files opened by process.""" if self.pid == 0: return [] files = [] rawlist = _psutil_osx.get_process_open_files(self.pid) for path, fd in rawlist: if isfile_strict(path): ntuple = nt_openfile(path, fd) ...
[ "def", "get_open_files", "(", "self", ")", ":", "if", "self", ".", "pid", "==", "0", ":", "return", "[", "]", "files", "=", "[", "]", "rawlist", "=", "_psutil_osx", ".", "get_process_open_files", "(", "self", ".", "pid", ")", "for", "path", ",", "fd"...
33.181818
12.363636
def ifi_index(self, value): """Index setter.""" self.bytearray[self._get_slicers(3)] = bytearray(c_int(value or 0))
[ "def", "ifi_index", "(", "self", ",", "value", ")", ":", "self", ".", "bytearray", "[", "self", ".", "_get_slicers", "(", "3", ")", "]", "=", "bytearray", "(", "c_int", "(", "value", "or", "0", ")", ")" ]
43
16
def dependencies_of(self, address): """Returns the dependencies of the Target at `address`. This method asserts that the address given is actually in the BuildGraph. :API: public """ assert address in self._target_by_address, ( 'Cannot retrieve dependencies of {address} because it is not in ...
[ "def", "dependencies_of", "(", "self", ",", "address", ")", ":", "assert", "address", "in", "self", ".", "_target_by_address", ",", "(", "'Cannot retrieve dependencies of {address} because it is not in the BuildGraph.'", ".", "format", "(", "address", "=", "address", ")...
34.916667
21.75
def get_obj_subcmds(obj): """Fetch action in callable attributes which and commands Callable must have their attribute 'command' set to True to be recognised by this lookup. Please consider using the decorator ``@cmd`` to declare your subcommands in classes for instance. """ subcmds = [] ...
[ "def", "get_obj_subcmds", "(", "obj", ")", ":", "subcmds", "=", "[", "]", "for", "label", "in", "dir", "(", "obj", ".", "__class__", ")", ":", "if", "label", ".", "startswith", "(", "\"_\"", ")", ":", "continue", "if", "isinstance", "(", "getattr", "...
35.428571
16.214286
def simxAddStatusbarMessage(clientID, message, operationMode): ''' Please have a look at the function description/documentation in the V-REP user manual ''' if (sys.version_info[0] == 3) and (type(message) is str): message=message.encode('utf-8') return c_AddStatusbarMessage(clientID, messa...
[ "def", "simxAddStatusbarMessage", "(", "clientID", ",", "message", ",", "operationMode", ")", ":", "if", "(", "sys", ".", "version_info", "[", "0", "]", "==", "3", ")", "and", "(", "type", "(", "message", ")", "is", "str", ")", ":", "message", "=", "...
41.375
28.125
def _return_parsed_timezone_results(result, timezones, box, tz, name): """ Return results from array_strptime if a %z or %Z directive was passed. Parameters ---------- result : ndarray int64 date representations of the dates timezones : ndarray pytz timezone objects box : bo...
[ "def", "_return_parsed_timezone_results", "(", "result", ",", "timezones", ",", "box", ",", "tz", ",", "name", ")", ":", "if", "tz", "is", "not", "None", ":", "raise", "ValueError", "(", "\"Cannot pass a tz argument when \"", "\"parsing strings with timezone \"", "\...
30.055556
19.277778
def _add_mem_percent(self, cur_read): """Compute memory percent utilisation based on the mem_rss_bytes and mem_limit_bytes """ for executor_id, cur_data in cur_read.items(): stats = cur_data['statistics'] mem_rss_bytes = stats.get('mem_rss_bytes') mem_...
[ "def", "_add_mem_percent", "(", "self", ",", "cur_read", ")", ":", "for", "executor_id", ",", "cur_data", "in", "cur_read", ".", "items", "(", ")", ":", "stats", "=", "cur_data", "[", "'statistics'", "]", "mem_rss_bytes", "=", "stats", ".", "get", "(", "...
48.6
10.3
def event_date(self, event_date): """Set the Events "event date" value.""" self._group_data['eventDate'] = self._utils.format_datetime( event_date, date_format='%Y-%m-%dT%H:%M:%SZ' )
[ "def", "event_date", "(", "self", ",", "event_date", ")", ":", "self", ".", "_group_data", "[", "'eventDate'", "]", "=", "self", ".", "_utils", ".", "format_datetime", "(", "event_date", ",", "date_format", "=", "'%Y-%m-%dT%H:%M:%SZ'", ")" ]
42.8
16.4
def forward_backward(self, parameters): """ Run the forward backward algorithm with the given parameters. """ # If the features are sparse, we can use an optimization. # I'm not using scipy.sparse here because we want to avoid a scipy dependency and also scipy.sparse doesn't seem # to ha...
[ "def", "forward_backward", "(", "self", ",", "parameters", ")", ":", "# If the features are sparse, we can use an optimization.", "# I'm not using scipy.sparse here because we want to avoid a scipy dependency and also scipy.sparse doesn't seem", "# to handle arrays of shape higher than 2.", "i...
59.65625
27.8125
def from_header_str(cls, header): """ Create a TraceHeader object from a tracing header string extracted from a http request headers. """ if not header: return cls() try: params = header.strip().split(HEADER_DELIMITER) header_dict = {}...
[ "def", "from_header_str", "(", "cls", ",", "header", ")", ":", "if", "not", "header", ":", "return", "cls", "(", ")", "try", ":", "params", "=", "header", ".", "strip", "(", ")", ".", "split", "(", "HEADER_DELIMITER", ")", "header_dict", "=", "{", "}...
31.40625
16.59375
def vectors(self): """ :rtype: dict """ vectors = {} for anopheles in self.et.findall("anopheles"): vectors[anopheles.attrib["mosquito"]] = Vector(anopheles) return vectors
[ "def", "vectors", "(", "self", ")", ":", "vectors", "=", "{", "}", "for", "anopheles", "in", "self", ".", "et", ".", "findall", "(", "\"anopheles\"", ")", ":", "vectors", "[", "anopheles", ".", "attrib", "[", "\"mosquito\"", "]", "]", "=", "Vector", ...
28.125
15.375
def find(pattern, path=os.path.curdir, recursive=False): """ Find absolute file/folder paths with the given ``re`` pattern. Args: * pattern: search pattern, support both string (exact match) and `re` pattern. * path: root path to start searching, default is current working directory. ...
[ "def", "find", "(", "pattern", ",", "path", "=", "os", ".", "path", ".", "curdir", ",", "recursive", "=", "False", ")", ":", "root", "=", "realpath", "(", "path", ")", "Finder", "=", "lambda", "item", ":", "regex", ".", "is_regex", "(", "pattern", ...
37.92
26.8
def post(self, url, data, params=None, headers=None, connection=None): """ Synchronous POST request. ``data`` must be a JSONable value. """ params = params or {} headers = headers or {} endpoint = self._build_endpoint_url(url, None) self._authenticate(params, head...
[ "def", "post", "(", "self", ",", "url", ",", "data", ",", "params", "=", "None", ",", "headers", "=", "None", ",", "connection", "=", "None", ")", ":", "params", "=", "params", "or", "{", "}", "headers", "=", "headers", "or", "{", "}", "endpoint", ...
44.090909
13
def get_value(record, key, default=None): """Return item as `dict.__getitem__` but using 'smart queries'. .. note:: Accessing one value in a normal way, meaning d['a'], is almost as fast as accessing a regular dictionary. But using the special name convention is a bit slower than using...
[ "def", "get_value", "(", "record", ",", "key", ",", "default", "=", "None", ")", ":", "def", "getitem", "(", "k", ",", "v", ",", "default", ")", ":", "if", "isinstance", "(", "v", ",", "string_types", ")", ":", "raise", "KeyError", "elif", "isinstanc...
30.491525
16.084746
def connect_array(self, address, connection_key, connection_type, **kwargs): """Connect this array with another one. :param address: IP address or DNS name of other array. :type address: str :param connection_key: Connection key of other array. :type connection_key: str ...
[ "def", "connect_array", "(", "self", ",", "address", ",", "connection_key", ",", "connection_type", ",", "*", "*", "kwargs", ")", ":", "data", "=", "{", "\"management_address\"", ":", "address", ",", "\"connection_key\"", ":", "connection_key", ",", "\"type\"", ...
35.677419
21.096774
def vsearch_sort_by_abundance( fasta_filepath, output_filepath, working_dir=None, minsize=None, maxsize=None, log_name="abundance_sort.log", HALT_EXEC=False): """ Fasta entries are sorted by decreasing abundance (Fasta entries are assumed to be dereplicated with the patte...
[ "def", "vsearch_sort_by_abundance", "(", "fasta_filepath", ",", "output_filepath", ",", "working_dir", "=", "None", ",", "minsize", "=", "None", ",", "maxsize", "=", "None", ",", "log_name", "=", "\"abundance_sort.log\"", ",", "HALT_EXEC", "=", "False", ")", ":"...
29.169231
18.384615
def get_messages(self, page=0): """Get first 10 messages in account, across all folders. Keyword Args: page (int): Integer representing the 'page' of results to fetch Returns: List[:class:`Message <pyOutlook.core.message.Message>`] """ endpoint = 'https...
[ "def", "get_messages", "(", "self", ",", "page", "=", "0", ")", ":", "endpoint", "=", "'https://outlook.office.com/api/v2.0/me/messages'", "if", "page", ">", "0", ":", "endpoint", "=", "endpoint", "+", "'/?%24skip='", "+", "str", "(", "page", ")", "+", "'0'"...
32.333333
27.52381
def get_composition_assets(self, composition_id): """Gets the list of assets mapped to the given ``Composition``. arg: composition_id (osid.id.Id): ``Id`` of the ``Composition`` return: (osid.repository.AssetList) - list of assets raise: NotFound - ``composition_id``...
[ "def", "get_composition_assets", "(", "self", ",", "composition_id", ")", ":", "# Implemented from template for", "# osid.repository.AssetCompositionSession.get_composition_assets", "collection", "=", "JSONClientValidated", "(", "'repository'", ",", "collection", "=", "'Compositi...
49.666667
16.866667
def lm_amps_phases(**kwargs): """ Take input_params and return dictionaries with amplitudes and phases of each overtone of a specific lm mode, checking that all of them are given. """ l, m = kwargs['l'], kwargs['m'] amps, phis = {}, {} # amp220 is always required, because the amplitudes of subdo...
[ "def", "lm_amps_phases", "(", "*", "*", "kwargs", ")", ":", "l", ",", "m", "=", "kwargs", "[", "'l'", "]", ",", "kwargs", "[", "'m'", "]", "amps", ",", "phis", "=", "{", "}", ",", "{", "}", "# amp220 is always required, because the amplitudes of subdominan...
38.148148
18.481481
def _remove_from_index_operations(self, which, transforms): """ Helper preventing copy code. Remove given what (transform prior etc) from which param index ops. """ if len(transforms) == 0: transforms = which.properties() removed = np.empty((0,), dtype=int) ...
[ "def", "_remove_from_index_operations", "(", "self", ",", "which", ",", "transforms", ")", ":", "if", "len", "(", "transforms", ")", "==", "0", ":", "transforms", "=", "which", ".", "properties", "(", ")", "removed", "=", "np", ".", "empty", "(", "(", ...
39.266667
14.6
def _infer_tarball_url(): """Returns the tarball URL inferred from an app.json, if present.""" try: with click.open_file('app.json', 'r') as f: contents = f.read() app_json = json.loads(contents) except IOError: return None repository = app_json.get('repository') ...
[ "def", "_infer_tarball_url", "(", ")", ":", "try", ":", "with", "click", ".", "open_file", "(", "'app.json'", ",", "'r'", ")", "as", "f", ":", "contents", "=", "f", ".", "read", "(", ")", "app_json", "=", "json", ".", "loads", "(", "contents", ")", ...
26.1875
20.3125
def extended_cigar(aligned_template, aligned_query): ''' Convert mutation annotations to extended cigar format https://github.com/lh3/minimap2#the-cs-optional-tag USAGE: >>> template = 'CGATCGATAAATAGAGTAG---GAATAGCA' >>> query = 'CGATCG---AATAGAGTAGGTCGAATtGCA' >>> extended_cigar(tem...
[ "def", "extended_cigar", "(", "aligned_template", ",", "aligned_query", ")", ":", "# - Go through each position in the alignment", "insertion", "=", "[", "]", "deletion", "=", "[", "]", "matches", "=", "[", "]", "cigar", "=", "[", "]", "for", "r_aa", ",", "q...
27.285714
17.4
def delete(self, receiver_id=None, event_id=None): """Handle DELETE request.""" event = self._get_event(receiver_id, event_id) event.delete() db.session.commit() return make_response(event)
[ "def", "delete", "(", "self", ",", "receiver_id", "=", "None", ",", "event_id", "=", "None", ")", ":", "event", "=", "self", ".", "_get_event", "(", "receiver_id", ",", "event_id", ")", "event", ".", "delete", "(", ")", "db", ".", "session", ".", "co...
37.333333
10
def list_active_courses_in_account(self, account_id, by_subaccounts=None, by_teachers=None, completed=None, enrollment_term_id=None, enrollment_type=None, hide_enrollmentless_courses=None, include=None, published=None, search_term=None, state=None, with_enrollments=None): """ List active courses in an...
[ "def", "list_active_courses_in_account", "(", "self", ",", "account_id", ",", "by_subaccounts", "=", "None", ",", "by_teachers", "=", "None", ",", "completed", "=", "None", ",", "enrollment_term_id", "=", "None", ",", "enrollment_type", "=", "None", ",", "hide_e...
50.411765
19.588235
def list_mutable_configs(pipette_id: str) -> Dict[str, Any]: """ Returns dict of mutable configs only. """ cfg: Dict[str, Any] = {} if pipette_id in known_pipettes(): config = load_config_dict(pipette_id) else: log.info('Pipette id {} not found'.format(pipette_id)) retur...
[ "def", "list_mutable_configs", "(", "pipette_id", ":", "str", ")", "->", "Dict", "[", "str", ",", "Any", "]", ":", "cfg", ":", "Dict", "[", "str", ",", "Any", "]", "=", "{", "}", "if", "pipette_id", "in", "known_pipettes", "(", ")", ":", "config", ...
26.1875
15.6875
def delete_unique_identity(db, uuid): """Remove a unique identity from the registry. Function that removes from the registry, the unique identity that matches with uuid. Data related to this identity will be also removed. It checks first whether the unique identity is already on the registry. ...
[ "def", "delete_unique_identity", "(", "db", ",", "uuid", ")", ":", "with", "db", ".", "connect", "(", ")", "as", "session", ":", "uidentity", "=", "find_unique_identity", "(", "session", ",", "uuid", ")", "if", "not", "uidentity", ":", "raise", "NotFoundEr...
34.32
21.64
def toxml(self): """ Exports this object into a LEMS XML object """ xmlstr = '<Component id="{0}" type="{1}"'.format(self.id, self.type) for (k, v) in self.parameters.items(): xmlstr += ' {0}="{1}"'.format(k, v) if self.children: xmlstr += '>' ...
[ "def", "toxml", "(", "self", ")", ":", "xmlstr", "=", "'<Component id=\"{0}\" type=\"{1}\"'", ".", "format", "(", "self", ".", "id", ",", "self", ".", "type", ")", "for", "(", "k", ",", "v", ")", "in", "self", ".", "parameters", ".", "items", "(", ")...
25.315789
17.842105
def _solver(self): """ Creates or gets a Claripy solver, based on the state options. """ if self._stored_solver is not None: return self._stored_solver track = o.CONSTRAINT_TRACKING_IN_SOLVER in self.state.options approximate_first = o.APPROXIMATE_FIRST in se...
[ "def", "_solver", "(", "self", ")", ":", "if", "self", ".", "_stored_solver", "is", "not", "None", ":", "return", "self", ".", "_stored_solver", "track", "=", "o", ".", "CONSTRAINT_TRACKING_IN_SOLVER", "in", "self", ".", "state", ".", "options", "approximate...
56.365854
28.658537
def get_objectives_by_search(self, objective_query, objective_search): """Pass through to provider ObjectiveSearchSession.get_objectives_by_search""" # Implemented from azosid template for - # osid.resource.ResourceSearchSession.get_resources_by_search_template if not self._can('search')...
[ "def", "get_objectives_by_search", "(", "self", ",", "objective_query", ",", "objective_search", ")", ":", "# Implemented from azosid template for -", "# osid.resource.ResourceSearchSession.get_resources_by_search_template", "if", "not", "self", ".", "_can", "(", "'search'", ")...
64.285714
20.285714
def filter_edge_field_non_existence(edge_expression): """Return an Expression that is True iff the specified edge (edge_expression) does not exist.""" # When an edge does not exist at a given vertex, OrientDB represents that in one of two ways: # - the edge's field does not exist (is null) on the vertex d...
[ "def", "filter_edge_field_non_existence", "(", "edge_expression", ")", ":", "# When an edge does not exist at a given vertex, OrientDB represents that in one of two ways:", "# - the edge's field does not exist (is null) on the vertex document, or", "# - the edge's field does exist, but is an emp...
63.714286
32.285714
def get_ntp_peers(self): """Return the NTP peers configured on the device.""" ntp_table = junos_views.junos_ntp_peers_config_table(self.device) ntp_table.get() ntp_peers = ntp_table.items() if not ntp_peers: return {} return {napalm_base.helpers.ip(peer[0])...
[ "def", "get_ntp_peers", "(", "self", ")", ":", "ntp_table", "=", "junos_views", ".", "junos_ntp_peers_config_table", "(", "self", ".", "device", ")", "ntp_table", ".", "get", "(", ")", "ntp_peers", "=", "ntp_table", ".", "items", "(", ")", "if", "not", "nt...
30.636364
23.363636