text
stringlengths
75
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
0.18
def edit_permissions(self): """Creates the view used to edit permissions. To create the view, data in the following format is passed to the UI in the objects field: .. code-block:: python { "type": "tree-toggle", "action": "set_permission", ...
[ "def", "edit_permissions", "(", "self", ")", ":", "# Get the role that was selected in the CRUD view", "key", "=", "self", ".", "current", ".", "input", "[", "'object_id'", "]", "self", ".", "current", ".", "task_data", "[", "'role_id'", "]", "=", "key", "role",...
43.068966
0.001565
def add(self, address, topics=None): """Add *address* to the subscribing list for *topics*. It topics is None we will subscibe to already specified topics. """ with self._lock: if address in self.addresses: return False topics = self._magickfy_to...
[ "def", "add", "(", "self", ",", "address", ",", "topics", "=", "None", ")", ":", "with", "self", ".", "_lock", ":", "if", "address", "in", "self", ".", "addresses", ":", "return", "False", "topics", "=", "self", ".", "_magickfy_topics", "(", "topics", ...
40.619048
0.002291
def unique(seq, idfunc=None): """ Unique a list or tuple and preserve the order @type idfunc: Function or None @param idfunc: If idfunc is provided it will be called during the comparison process. """ if idfunc is None: idfunc = lambda x: x preserved_type = type(seq) seen = {} result = [] for item in seq:...
[ "def", "unique", "(", "seq", ",", "idfunc", "=", "None", ")", ":", "if", "idfunc", "is", "None", ":", "idfunc", "=", "lambda", "x", ":", "x", "preserved_type", "=", "type", "(", "seq", ")", "seen", "=", "{", "}", "result", "=", "[", "]", "for", ...
21.5
0.044543
def resettable(f): """A decorator to simplify the context management of simple object attributes. Gets the value of the attribute prior to setting it, and stores a function to set the value to the old value in the HistoryManager. """ def wrapper(self, new_value): context = get_context(self)...
[ "def", "resettable", "(", "f", ")", ":", "def", "wrapper", "(", "self", ",", "new_value", ")", ":", "context", "=", "get_context", "(", "self", ")", "if", "context", ":", "old_value", "=", "getattr", "(", "self", ",", "f", ".", "__name__", ")", "# Do...
33.166667
0.001629
def get_drafts(self, **kwargs): """Same as Session.get_messages, but where ``statuses=["draft"]``.""" default_kwargs = { "order": "updated_at desc" } default_kwargs.update(kwargs) return self.get_messages(statuses=["draft"], **default_kwargs)
[ "def", "get_drafts", "(", "self", ",", "*", "*", "kwargs", ")", ":", "default_kwargs", "=", "{", "\"order\"", ":", "\"updated_at desc\"", "}", "default_kwargs", ".", "update", "(", "kwargs", ")", "return", "self", ".", "get_messages", "(", "statuses", "=", ...
54
0.014599
def _wifi_connect(): """Connects to WIFI""" if not wlan.isconnected(): wlan.active(True) print("NETWORK: connecting to network %s..." % settings.WIFI_SSID) wlan.connect(settings.WIFI_SSID, secret) while not wlan.isconnected(): print("NETWORK: waiting for connection......
[ "def", "_wifi_connect", "(", ")", ":", "if", "not", "wlan", ".", "isconnected", "(", ")", ":", "wlan", ".", "active", "(", "True", ")", "print", "(", "\"NETWORK: connecting to network %s...\"", "%", "settings", ".", "WIFI_SSID", ")", "wlan", ".", "connect", ...
42
0.002331
def cafferesnet101(num_classes=1000, pretrained='imagenet'): """Constructs a ResNet-101 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet """ model = ResNet(Bottleneck, [3, 4, 23, 3], num_classes=num_classes) if pretrained is not None: settings = pretrained...
[ "def", "cafferesnet101", "(", "num_classes", "=", "1000", ",", "pretrained", "=", "'imagenet'", ")", ":", "model", "=", "ResNet", "(", "Bottleneck", ",", "[", "3", ",", "4", ",", "23", ",", "3", "]", ",", "num_classes", "=", "num_classes", ")", "if", ...
47.470588
0.00243
def action(route, template='', methods=['GET']): """Decorator to create an action""" def real_decorator(function): function.pi_api_action = True function.pi_api_route = route function.pi_api_template = template function.pi_api_methods = methods if hasattr(function, 'pi_a...
[ "def", "action", "(", "route", ",", "template", "=", "''", ",", "methods", "=", "[", "'GET'", "]", ")", ":", "def", "real_decorator", "(", "function", ")", ":", "function", ".", "pi_api_action", "=", "True", "function", ".", "pi_api_route", "=", "route",...
36.411765
0.001575
def haversine(lat1, lon1, lat2, lon2): """ Calculate the great circle distance between two points on the earth (specified in decimal degrees) Thanks to a answer on stackoverflow by Michael Dunn. http://stackoverflow.com/questions/4913349/haversine-formula-in-python-bearing-and-distance-between-...
[ "def", "haversine", "(", "lat1", ",", "lon1", ",", "lat2", ",", "lon2", ")", ":", "if", "abs", "(", "lat1", ")", ">", "90", "or", "abs", "(", "lat2", ")", ">", "90", ":", "raise", "InvalidCoordinate", "(", "'invalid latitude'", ")", "if", "abs", "(...
41.75
0.001171
def get_hyperedge_attributes(self, hyperedge_id): """Given a hyperedge ID, get a dictionary of copies of that hyperedge's attributes. :param hyperedge_id: ID of the hyperedge to retrieve the attributes of. :returns: dict -- copy of each attribute of the specified hyperedge_id ...
[ "def", "get_hyperedge_attributes", "(", "self", ",", "hyperedge_id", ")", ":", "if", "not", "self", ".", "has_hyperedge_id", "(", "hyperedge_id", ")", ":", "raise", "ValueError", "(", "\"No such hyperedge exists.\"", ")", "dict_to_copy", "=", "self", ".", "_hypere...
45.111111
0.002413
def Yu_France(m, x, rhol, rhog, mul, mug, D, roughness=0, L=1): r'''Calculates two-phase pressure drop with the Yu, France, Wambsganss, and Hull (2002) correlation given in [1]_ and reviewed in [2]_ and [3]_. .. math:: \Delta P = \Delta P_{l} \phi_{l}^2 .. math:: \phi_l^2 = X^{-1.9} ...
[ "def", "Yu_France", "(", "m", ",", "x", ",", "rhol", ",", "rhog", ",", "mul", ",", "mug", ",", "D", ",", "roughness", "=", "0", ",", "L", "=", "1", ")", ":", "# Actual Liquid flow", "v_l", "=", "m", "*", "(", "1", "-", "x", ")", "/", "rhol", ...
32.75641
0.00038
def _deep_tuple(self, x): """Converts nested `tuple`, `list`, or `dict` to nested `tuple`.""" if isinstance(x, dict): return self._deep_tuple(tuple(sorted(x.items()))) elif isinstance(x, (list, tuple)): return tuple(map(self._deep_tuple, x)) return x
[ "def", "_deep_tuple", "(", "self", ",", "x", ")", ":", "if", "isinstance", "(", "x", ",", "dict", ")", ":", "return", "self", ".", "_deep_tuple", "(", "tuple", "(", "sorted", "(", "x", ".", "items", "(", ")", ")", ")", ")", "elif", "isinstance", ...
34
0.010753
def token_count_pandas(self): """ See token counts as pandas dataframe""" freq_df = pd.DataFrame.from_dict(self.indexer.word_counts, orient='index') freq_df.columns = ['count'] return freq_df.sort_values('count', ascending=False)
[ "def", "token_count_pandas", "(", "self", ")", ":", "freq_df", "=", "pd", ".", "DataFrame", ".", "from_dict", "(", "self", ".", "indexer", ".", "word_counts", ",", "orient", "=", "'index'", ")", "freq_df", ".", "columns", "=", "[", "'count'", "]", "retur...
51.4
0.011494
def comment(self, nme, desc): """ Adds a comment to the existing program in the list, logs the reference and TODO - adds core link to processes """ if nme != '': program_exists = False for i in self.lstPrograms: print(i) ...
[ "def", "comment", "(", "self", ",", "nme", ",", "desc", ")", ":", "if", "nme", "!=", "''", ":", "program_exists", "=", "False", "for", "i", "in", "self", ".", "lstPrograms", ":", "print", "(", "i", ")", "if", "nme", "in", "i", "[", "0", "]", ":...
35.055556
0.013889
def make_img_widget(cls, img, layout=Layout(), format='jpg'): "Returns an image widget for specified file name `img`." return widgets.Image(value=img, format=format, layout=layout)
[ "def", "make_img_widget", "(", "cls", ",", "img", ",", "layout", "=", "Layout", "(", ")", ",", "format", "=", "'jpg'", ")", ":", "return", "widgets", ".", "Image", "(", "value", "=", "img", ",", "format", "=", "format", ",", "layout", "=", "layout", ...
64.666667
0.010204
def update_floatingip(context, id, content): """Update an existing floating IP. :param context: neutron api request context. :param id: id of the floating ip :param content: dictionary with keys indicating fields to update. valid keys are those that have a value of True for 'allow_put' ...
[ "def", "update_floatingip", "(", "context", ",", "id", ",", "content", ")", ":", "LOG", ".", "info", "(", "'update_floatingip %s for tenant %s and body %s'", "%", "(", "id", ",", "context", ".", "tenant_id", ",", "content", ")", ")", "if", "'port_id'", "not", ...
39.185185
0.000923
def _getTransformation(self): """_getTransformation(self) -> PyObject *""" CheckParent(self) val = _fitz.Page__getTransformation(self) val = Matrix(val) return val
[ "def", "_getTransformation", "(", "self", ")", ":", "CheckParent", "(", "self", ")", "val", "=", "_fitz", ".", "Page__getTransformation", "(", "self", ")", "val", "=", "Matrix", "(", "val", ")", "return", "val" ]
24.75
0.009756
def approve(self, peer_jid): """ (Pre-)approve a subscription request from `peer_jid`. :param peer_jid: The peer to (pre-)approve. This sends a ``"subscribed"`` presence to the peer; if the peer has previously asked for a subscription, this will seal the deal and create ...
[ "def", "approve", "(", "self", ",", "peer_jid", ")", ":", "self", ".", "client", ".", "enqueue", "(", "stanza", ".", "Presence", "(", "type_", "=", "structs", ".", "PresenceType", ".", "SUBSCRIBED", ",", "to", "=", "peer_jid", ")", ")" ]
35.782609
0.002367
def replay(self, event, ts=0, end_ts=None, with_ts=False): """Replay events based on timestamp. If you split namespace with ts, the replay will only return events within the same namespace. :param event: event name :param ts: replay events after ts, default from 0. :par...
[ "def", "replay", "(", "self", ",", "event", ",", "ts", "=", "0", ",", "end_ts", "=", "None", ",", "with_ts", "=", "False", ")", ":", "key", "=", "self", ".", "_keygen", "(", "event", ",", "ts", ")", "end_ts", "=", "end_ts", "if", "end_ts", "else"...
40.428571
0.002301
def add_require(self, require): """ Add a require object if it does not already exist """ for p in self.requires: if p.value == require.value: return self.requires.append(require)
[ "def", "add_require", "(", "self", ",", "require", ")", ":", "for", "p", "in", "self", ".", "requires", ":", "if", "p", ".", "value", "==", "require", ".", "value", ":", "return", "self", ".", "requires", ".", "append", "(", "require", ")" ]
37.666667
0.008658
def liftover(self, intersecting_region): """ Lift a region that overlaps the genomic occurrence of the retrotransposon to consensus sequence co-ordinates. This method will behave differently depending on whether this retrotransposon occurrance contains a full alignment or not. If it does, the alignm...
[ "def", "liftover", "(", "self", ",", "intersecting_region", ")", ":", "# a little sanity check here to make sure intersecting_region really does..", "if", "not", "self", ".", "intersects", "(", "intersecting_region", ")", ":", "raise", "RetrotransposonError", "(", "\"trying...
55.7
0.001765
def _train_and_eval_dataset_v1(problem_name, data_dir): """Return train and evaluation datasets, feature info and supervised keys.""" assert not tf.executing_eagerly(), "tf.eager mode must be turned off." problem = t2t_problems.problem(problem_name) train_dataset = problem.dataset(tf.estimator.ModeKeys.TRAIN, d...
[ "def", "_train_and_eval_dataset_v1", "(", "problem_name", ",", "data_dir", ")", ":", "assert", "not", "tf", ".", "executing_eagerly", "(", ")", ",", "\"tf.eager mode must be turned off.\"", "problem", "=", "t2t_problems", ".", "problem", "(", "problem_name", ")", "t...
53.62069
0.017056
def acquaint_and_shift(parts: Tuple[List[ops.Qid], List[ops.Qid]], layers: Layers, acquaintance_size: Optional[int], swap_gate: ops.Gate, mapping: Dict[ops.Qid, int]): """Acquaints and shifts a pair of lists of qubits. The f...
[ "def", "acquaint_and_shift", "(", "parts", ":", "Tuple", "[", "List", "[", "ops", ".", "Qid", "]", ",", "List", "[", "ops", ".", "Qid", "]", "]", ",", "layers", ":", "Layers", ",", "acquaintance_size", ":", "Optional", "[", "int", "]", ",", "swap_gat...
41.121212
0.00072
def check_download(obj, *args, **kwargs): """Verify a download""" version = args[0] workdir = args[1] signame = args[2] if version: local_version = get_local_version(workdir, signame) if not verify_sigfile(workdir, signame) or version != local_version: error("[-] \033[91m...
[ "def", "check_download", "(", "obj", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "version", "=", "args", "[", "0", "]", "workdir", "=", "args", "[", "1", "]", "signame", "=", "args", "[", "2", "]", "if", "version", ":", "local_version", ...
42.727273
0.002083
def _get_region(self, ipnum): """ Seek and return the region information. Returns dict containing country_code and region_code. :arg ipnum: Result of ip2long conversion """ region_code = None country_code = None seek_country = self._seek_country(ipnum) ...
[ "def", "_get_region", "(", "self", ",", "ipnum", ")", ":", "region_code", "=", "None", "country_code", "=", "None", "seek_country", "=", "self", ".", "_seek_country", "(", "ipnum", ")", "def", "get_region_code", "(", "offset", ")", ":", "region1", "=", "ch...
41.976744
0.001624
def _build_doc(func_name, desc, arg_names, arg_types, arg_desc, key_var_num_args=None, ret_type=None): """Build docstring for symbolic functions.""" param_str = _build_param_doc(arg_names, arg_types, arg_desc) if key_v...
[ "def", "_build_doc", "(", "func_name", ",", "desc", ",", "arg_names", ",", "arg_types", ",", "arg_desc", ",", "key_var_num_args", "=", "None", ",", "ret_type", "=", "None", ")", ":", "param_str", "=", "_build_param_doc", "(", "arg_names", ",", "arg_types", "...
40.24
0.001942
def ApplyPluginToTypedCollection(plugin, type_names, fetch_fn): """Applies instant output plugin to a collection of results. Args: plugin: InstantOutputPlugin instance. type_names: List of type names (strings) to be processed. fetch_fn: Function that takes a type name as an argument and returns a...
[ "def", "ApplyPluginToTypedCollection", "(", "plugin", ",", "type_names", ",", "fetch_fn", ")", ":", "for", "chunk", "in", "plugin", ".", "Start", "(", ")", ":", "yield", "chunk", "def", "GetValues", "(", "tn", ")", ":", "for", "v", "in", "fetch_fn", "(",...
29.37931
0.009091
def print_info(*messages, **kwargs): """Simple print use logger, print with time / file / line_no. :param sep: sep of messages, " " by default. Basic Usage:: print_info(1, 2, 3) print_info(1, 2, 3) print_info(1, 2, 3) # [2018-10-24 19:12:16] temp_code.py(7): 1 2 3 ...
[ "def", "print_info", "(", "*", "messages", ",", "*", "*", "kwargs", ")", ":", "sep", "=", "kwargs", ".", "pop", "(", "\"sep\"", ",", "\" \"", ")", "frame", "=", "sys", ".", "_getframe", "(", "1", ")", "ln", "=", "frame", ".", "f_lineno", "_file", ...
31.136364
0.001416
def _get_body_instance(self): """Return the body instance.""" simple_body = { MultipartType.OFPMP_FLOW: FlowStatsRequest, MultipartType.OFPMP_AGGREGATE: AggregateStatsRequest, MultipartType.OFPMP_PORT_STATS: PortStatsRequest, MultipartType.OFPMP_QUEUE: Que...
[ "def", "_get_body_instance", "(", "self", ")", ":", "simple_body", "=", "{", "MultipartType", ".", "OFPMP_FLOW", ":", "FlowStatsRequest", ",", "MultipartType", ".", "OFPMP_AGGREGATE", ":", "AggregateStatsRequest", ",", "MultipartType", ".", "OFPMP_PORT_STATS", ":", ...
39.444444
0.001833
def _optimize(self, context, argspec): """Inject speedup shortcut bindings into the argument specification for a function. This assigns these labels to the local scope, avoiding a cascade through to globals(), saving time. This also has some unfortunate side-effects for using these sentinels in argument def...
[ "def", "_optimize", "(", "self", ",", "context", ",", "argspec", ")", ":", "argspec", "=", "argspec", ".", "strip", "(", ")", "optimization", "=", "\", \"", ".", "join", "(", "i", "+", "\"=\"", "+", "i", "for", "i", "in", "self", ".", "OPTIMIZE", "...
30.068182
0.043924
def getPluginDescriptor(self, dir): """ Detects the .uplugin descriptor file for the Unreal plugin in the specified directory """ for plugin in glob.glob(os.path.join(dir, '*.uplugin')): return os.path.realpath(plugin) # No plugin detected raise UnrealManagerException('could not detect an Unreal plugi...
[ "def", "getPluginDescriptor", "(", "self", ",", "dir", ")", ":", "for", "plugin", "in", "glob", ".", "glob", "(", "os", ".", "path", ".", "join", "(", "dir", ",", "'*.uplugin'", ")", ")", ":", "return", "os", ".", "path", ".", "realpath", "(", "plu...
37.777778
0.037356
def AddDescriptorFromSchema(self, schema_name, schema): """Add a new MessageDescriptor named schema_name based on schema.""" # TODO(craigcitro): Is schema_name redundant? if self.__GetDescriptor(schema_name): return if schema.get('enum'): self.__DeclareEnum(schema...
[ "def", "AddDescriptorFromSchema", "(", "self", ",", "schema_name", ",", "schema", ")", ":", "# TODO(craigcitro): Is schema_name redundant?", "if", "self", ".", "__GetDescriptor", "(", "schema_name", ")", ":", "return", "if", "schema", ".", "get", "(", "'enum'", ")...
51.352941
0.001124
def list(self, **params): """ Retrieve all deal unqualified reasons Returns all deal unqualified reasons available to the user according to the parameters provided :calls: ``get /deal_unqualified_reasons`` :param dict params: (optional) Search options. :return: List of ...
[ "def", "list", "(", "self", ",", "*", "*", "params", ")", ":", "_", ",", "_", ",", "deal_unqualified_reasons", "=", "self", ".", "http_client", ".", "get", "(", "\"/deal_unqualified_reasons\"", ",", "params", "=", "params", ")", "return", "deal_unqualified_r...
42.142857
0.008292
def _update_metadata(self, archive_name, archive_metadata): """ Appends the updated_metada dict to the Metadata Attribute list Parameters ---------- archive_name: str ID of archive to update updated_metadata: dict dictionary of metadata keys an...
[ "def", "_update_metadata", "(", "self", ",", "archive_name", ",", "archive_metadata", ")", ":", "archive_metadata_current", "=", "self", ".", "_get_archive_metadata", "(", "archive_name", ")", "archive_metadata_current", ".", "update", "(", "archive_metadata", ")", "f...
33.206897
0.002018
def runExperiment4B(dirName): """ This runs the second experiment in the section "Simulations with Pure Temporal Sequences". Here we check accuracy of the L2/L4 networks in classifying the sequences. This experiment averages over many parameter combinations and could take several minutes. """ # Results ar...
[ "def", "runExperiment4B", "(", "dirName", ")", ":", "# Results are put into a pkl file which can be used to generate the plots.", "# dirName is the absolute path where the pkl file will be placed.", "resultsName", "=", "os", ".", "path", ".", "join", "(", "dirName", ",", "\"seque...
34.807692
0.013978
def update_brand(self) -> None: """Update brand group of parameters.""" self.update(path=URL_GET + GROUP.format(group=BRAND))
[ "def", "update_brand", "(", "self", ")", "->", "None", ":", "self", ".", "update", "(", "path", "=", "URL_GET", "+", "GROUP", ".", "format", "(", "group", "=", "BRAND", ")", ")" ]
46.333333
0.014184
def dist(self, src, tar, cost=(0, 1, 2), local=False): """Return the normalized Editex distance between two strings. The Editex distance is normalized by dividing the Editex distance (calculated by any of the three supported methods) by the greater of the number of characters in src tim...
[ "def", "dist", "(", "self", ",", "src", ",", "tar", ",", "cost", "=", "(", "0", ",", "1", ",", "2", ")", ",", "local", "=", "False", ")", ":", "if", "src", "==", "tar", ":", "return", "0.0", "mismatch_cost", "=", "cost", "[", "2", "]", "retur...
33.521739
0.00126
def decode_iter(data, codec_options=DEFAULT_CODEC_OPTIONS): """Decode BSON data to multiple documents as a generator. Works similarly to the decode_all function, but yields one document at a time. `data` must be a string of concatenated, valid, BSON-encoded documents. :Parameters: - `da...
[ "def", "decode_iter", "(", "data", ",", "codec_options", "=", "DEFAULT_CODEC_OPTIONS", ")", ":", "if", "not", "isinstance", "(", "codec_options", ",", "CodecOptions", ")", ":", "raise", "_CODEC_OPTIONS_TYPE_ERROR", "position", "=", "0", "end", "=", "len", "(", ...
29.870968
0.001046
def y(self): """ Returns the scaled y positions of the points as doubles """ return scale_dimension(self.Y, self.header.y_scale, self.header.y_offset)
[ "def", "y", "(", "self", ")", ":", "return", "scale_dimension", "(", "self", ".", "Y", ",", "self", ".", "header", ".", "y_scale", ",", "self", ".", "header", ".", "y_offset", ")" ]
42.75
0.017241
def new_sender(project_id): """Add sender.""" project = get_data_or_404('project', project_id) if project['owner_id'] != get_current_user_id(): return jsonify(message='forbidden'), 403 form = NewSenderForm() if not form.validate_on_submit(): return jsonify(errors=form.errors), 400...
[ "def", "new_sender", "(", "project_id", ")", ":", "project", "=", "get_data_or_404", "(", "'project'", ",", "project_id", ")", "if", "project", "[", "'owner_id'", "]", "!=", "get_current_user_id", "(", ")", ":", "return", "jsonify", "(", "message", "=", "'fo...
25.375
0.001582
def _get_event(self, event, find_str): """Get a concept referred from the event by the given string.""" # Get the term with the given element id element = event.find(find_str) if element is None: return None element_id = element.attrib.get('id') element_term =...
[ "def", "_get_event", "(", "self", ",", "event", ",", "find_str", ")", ":", "# Get the term with the given element id", "element", "=", "event", ".", "find", "(", "find_str", ")", "if", "element", "is", "None", ":", "return", "None", "element_id", "=", "element...
41.131579
0.00125
def _response_value(self, response, json=True): """Parses the HTTP response as a the cloudstack value. It throws an exception if the server didn't answer with a 200. """ if json: contentType = response.headers.get("Content-Type", "") if not contentType.startswith...
[ "def", "_response_value", "(", "self", ",", "response", ",", "json", "=", "True", ")", ":", "if", "json", ":", "contentType", "=", "response", ".", "headers", ".", "get", "(", "\"Content-Type\"", ",", "\"\"", ")", "if", "not", "contentType", ".", "starts...
36.431818
0.001215
def gatk_rnaseq_calling(data): """Use GATK to perform gVCF variant calling on RNA-seq data """ from bcbio.bam import callable data = utils.deepish_copy(data) tools_on = dd.get_tools_on(data) if not tools_on: tools_on = [] tools_on.append("gvcf") data = dd.set_tools_on(data, tools...
[ "def", "gatk_rnaseq_calling", "(", "data", ")", ":", "from", "bcbio", ".", "bam", "import", "callable", "data", "=", "utils", ".", "deepish_copy", "(", "data", ")", "tools_on", "=", "dd", ".", "get_tools_on", "(", "data", ")", "if", "not", "tools_on", ":...
58.387097
0.008696
def handle_channel_message(db, queues, b64decode, notification_object): """Handler for notification channels Given a NotificationMessage object, update internal state, notify any subscribers and resolve async deferred tasks. :param db: :param queues: :param b64decode: :param notification_o...
[ "def", "handle_channel_message", "(", "db", ",", "queues", ",", "b64decode", ",", "notification_object", ")", ":", "for", "notification", "in", "getattr", "(", "notification_object", ",", "'notifications'", ")", "or", "[", "]", ":", "# Ensure we have subscribed for ...
33.073171
0.001433
def get_edges_with_citations(self, citations: Iterable[Citation]) -> List[Edge]: """Get edges with one of the given citations.""" return self.session.query(Edge).join(Evidence).filter(Evidence.citation.in_(citations)).all()
[ "def", "get_edges_with_citations", "(", "self", ",", "citations", ":", "Iterable", "[", "Citation", "]", ")", "->", "List", "[", "Edge", "]", ":", "return", "self", ".", "session", ".", "query", "(", "Edge", ")", ".", "join", "(", "Evidence", ")", ".",...
79
0.016736
def start(self, zone_id, duration): """Start a zone.""" path = 'zone/start' payload = {'id': zone_id, 'duration': duration} return self.rachio.put(path, payload)
[ "def", "start", "(", "self", ",", "zone_id", ",", "duration", ")", ":", "path", "=", "'zone/start'", "payload", "=", "{", "'id'", ":", "zone_id", ",", "'duration'", ":", "duration", "}", "return", "self", ".", "rachio", ".", "put", "(", "path", ",", ...
37.8
0.010363
def request_sensor_sampling(self, req, msg): """Configure or query the way a sensor is sampled. Sampled values are reported asynchronously using the #sensor-status message. Parameters ---------- name : str Name of the sensor whose sampling strategy to query ...
[ "def", "request_sensor_sampling", "(", "self", ",", "req", ",", "msg", ")", ":", "f", "=", "Future", "(", ")", "self", ".", "ioloop", ".", "add_callback", "(", "lambda", ":", "chain_future", "(", "self", ".", "_handle_sensor_sampling", "(", "req", ",", "...
43.140351
0.001193
def create_gzip_message(message_set): """ Construct a gzip-compressed message containing multiple messages The given messages will be encoded, compressed, and sent as a single atomic message to Kafka. :param list message_set: a list of :class:`Message` instances """ encoded_message_set = K...
[ "def", "create_gzip_message", "(", "message_set", ")", ":", "encoded_message_set", "=", "KafkaCodec", ".", "_encode_message_set", "(", "message_set", ")", "gzipped", "=", "gzip_encode", "(", "encoded_message_set", ")", "return", "Message", "(", "0", ",", "CODEC_GZIP...
34.384615
0.002179
def save_popset(self,filename='popset.h5',**kwargs): """Saves the PopulationSet Calls :func:`PopulationSet.save_hdf`. """ self.popset.save_hdf(os.path.join(self.folder,filename))
[ "def", "save_popset", "(", "self", ",", "filename", "=", "'popset.h5'", ",", "*", "*", "kwargs", ")", ":", "self", ".", "popset", ".", "save_hdf", "(", "os", ".", "path", ".", "join", "(", "self", ".", "folder", ",", "filename", ")", ")" ]
34.333333
0.023697
def expand(string, vars, local_vars={}): """Expand a string containing $vars as Ninja would. Note: doesn't handle the full Ninja variable syntax, but it's enough to make configure.py's use of it work. """ def exp(m): var = m.group(1) if var == '$': return '$' ret...
[ "def", "expand", "(", "string", ",", "vars", ",", "local_vars", "=", "{", "}", ")", ":", "def", "exp", "(", "m", ")", ":", "var", "=", "m", ".", "group", "(", "1", ")", "if", "var", "==", "'$'", ":", "return", "'$'", "return", "local_vars", "."...
33.083333
0.002451
def _handle_indent_between_paren(self, column, line, parent_impl, tc): """ Handle indent between symbols such as parenthesis, braces,... """ pre, post = parent_impl next_char = self._get_next_char(tc) prev_char = self._get_prev_char(tc) prev_open = prev_char in ['...
[ "def", "_handle_indent_between_paren", "(", "self", ",", "column", ",", "line", ",", "parent_impl", ",", "tc", ")", ":", "pre", ",", "post", "=", "parent_impl", "next_char", "=", "self", ".", "_get_next_char", "(", "tc", ")", "prev_char", "=", "self", ".",...
42.38
0.000923
def process_tessellate(elem, update_delta, delta, **kwargs): """ Tessellates surfaces. .. note:: Helper function required for ``multiprocessing`` :param elem: surface :type elem: abstract.Surface :param update_delta: flag to control evaluation delta updates :type update_delta: bool :param ...
[ "def", "process_tessellate", "(", "elem", ",", "update_delta", ",", "delta", ",", "*", "*", "kwargs", ")", ":", "if", "update_delta", ":", "elem", ".", "delta", "=", "delta", "elem", ".", "evaluate", "(", ")", "elem", ".", "tessellate", "(", "*", "*", ...
28.315789
0.001799
def output_image_link(self, m): """Pass through rest role.""" return self.renderer.image_link( m.group('url'), m.group('target'), m.group('alt'))
[ "def", "output_image_link", "(", "self", ",", "m", ")", ":", "return", "self", ".", "renderer", ".", "image_link", "(", "m", ".", "group", "(", "'url'", ")", ",", "m", ".", "group", "(", "'target'", ")", ",", "m", ".", "group", "(", "'alt'", ")", ...
42.5
0.011561
def max_width(self): """Get maximum width of progress bar :rtype: int :returns: Maximum column width of progress bar """ value, unit = float(self._width_str[:-1]), self._width_str[-1] ensure(unit in ["c", "%"], ValueError, "Width unit must be either 'c' o...
[ "def", "max_width", "(", "self", ")", ":", "value", ",", "unit", "=", "float", "(", "self", ".", "_width_str", "[", ":", "-", "1", "]", ")", ",", "self", ".", "_width_str", "[", "-", "1", "]", "ensure", "(", "unit", "in", "[", "\"c\"", ",", "\"...
34.73913
0.002436
def editor(self, value): """ Setter for **self.__editor** attribute. :param value: Attribute value. :type value: Editor """ if value is not None: assert type(value) is Editor, "'{0}' attribute: '{1}' type is not 'Editor'!".format("editor", value) sel...
[ "def", "editor", "(", "self", ",", "value", ")", ":", "if", "value", "is", "not", "None", ":", "assert", "type", "(", "value", ")", "is", "Editor", ",", "\"'{0}' attribute: '{1}' type is not 'Editor'!\"", ".", "format", "(", "\"editor\"", ",", "value", ")", ...
29.818182
0.008876
def parse_subcommands(parser, subcommands, argv): """ Setup all sub-commands """ subparsers = parser.add_subparsers(dest='subparser_name') # add help sub-command parser_help = subparsers.add_parser( 'help', help='Detailed help for actions using `help <action>`') parser_help.add_arg...
[ "def", "parse_subcommands", "(", "parser", ",", "subcommands", ",", "argv", ")", ":", "subparsers", "=", "parser", ".", "add_subparsers", "(", "dest", "=", "'subparser_name'", ")", "# add help sub-command", "parser_help", "=", "subparsers", ".", "add_parser", "(",...
34.215686
0.000557
def _islinklike(dir_path): ''' Parameters ---------- dir_path : str Directory path. Returns ------- bool ``True`` if :data:`dir_path` is a link *or* junction. ''' dir_path = ph.path(dir_path) if platform.system() == 'Windows': if dir_path.isjunction(): ...
[ "def", "_islinklike", "(", "dir_path", ")", ":", "dir_path", "=", "ph", ".", "path", "(", "dir_path", ")", "if", "platform", ".", "system", "(", ")", "==", "'Windows'", ":", "if", "dir_path", ".", "isjunction", "(", ")", ":", "return", "True", "elif", ...
20.421053
0.002463
def Lomb_Scargle(data, precision, min_period, max_period, period_jobs=1): """ Returns the period of *data* according to the `Lomb-Scargle periodogram <https://en.wikipedia.org/wiki/Least-squares_spectral_analysis#The_Lomb.E2.80.93Scargle_periodogram>`_. **Parameters** data : array-like, shape = [n...
[ "def", "Lomb_Scargle", "(", "data", ",", "precision", ",", "min_period", ",", "max_period", ",", "period_jobs", "=", "1", ")", ":", "time", ",", "mags", ",", "", "*", "err", "=", "data", ".", "T", "scaled_mags", "=", "(", "mags", "-", "mags", ".", ...
37.625
0.001619
def get_subgraphs_by_citation(graph): """Stratify the graph based on citations. :type graph: pybel.BELGraph :rtype: dict[tuple[str,str],pybel.BELGraph] """ rv = defaultdict(graph.fresh_copy) for u, v, key, data in graph.edges(keys=True, data=True): if CITATION not in data: ...
[ "def", "get_subgraphs_by_citation", "(", "graph", ")", ":", "rv", "=", "defaultdict", "(", "graph", ".", "fresh_copy", ")", "for", "u", ",", "v", ",", "key", ",", "data", "in", "graph", ".", "edges", "(", "keys", "=", "True", ",", "data", "=", "True"...
26.833333
0.002
def _timeseries_component(self, series): """ Internal function for creating a timeseries model element """ # this is only called if the set_component function recognizes a pandas series # Todo: raise a warning if extrapolating from the end of the series. return lambda: np.interp(self.tim...
[ "def", "_timeseries_component", "(", "self", ",", "series", ")", ":", "# this is only called if the set_component function recognizes a pandas series", "# Todo: raise a warning if extrapolating from the end of the series.", "return", "lambda", ":", "np", ".", "interp", "(", "self",...
69.8
0.008499
def cnvlGauss2D(idxPrc, aryBoxCar, aryMdlParamsChnk, tplPngSize, varNumVol, queOut): """Spatially convolve boxcar functions with 2D Gaussian. Parameters ---------- idxPrc : 2d numpy array, shape [n_samples, n_measurements] Description of input 1. aryBoxCar : float, positive ...
[ "def", "cnvlGauss2D", "(", "idxPrc", ",", "aryBoxCar", ",", "aryMdlParamsChnk", ",", "tplPngSize", ",", "varNumVol", ",", "queOut", ")", ":", "# Number of combinations of model parameters in the current chunk:", "varChnkSze", "=", "np", ".", "size", "(", "aryMdlParamsCh...
36.753425
0.000363
def proto_0304(theABF): """protocol: repeated IC steps.""" abf=ABF(theABF) abf.log.info("analyzing as repeated current-clamp step") # prepare for AP analysis ap=AP(abf) # calculate rest potential avgVoltagePerSweep = []; times = [] for sweep in abf.setsweeps(): avgVoltageP...
[ "def", "proto_0304", "(", "theABF", ")", ":", "abf", "=", "ABF", "(", "theABF", ")", "abf", ".", "log", ".", "info", "(", "\"analyzing as repeated current-clamp step\"", ")", "# prepare for AP analysis", "ap", "=", "AP", "(", "abf", ")", "# calculate rest potent...
23.830189
0.019772
def plot_acf(series, ax=None, lags=None, alpha=None, use_vlines=True, unbiased=False, fft=True, title='Autocorrelation', zero=True, vlines_kwargs=None, show=True, **kwargs): """Plot a series' auto-correlation as a line plot. A wrapper method for the statsmodels ``plot_acf`` method. ...
[ "def", "plot_acf", "(", "series", ",", "ax", "=", "None", ",", "lags", "=", "None", ",", "alpha", "=", "None", ",", "use_vlines", "=", "True", ",", "unbiased", "=", "False", ",", "fft", "=", "True", ",", "title", "=", "'Autocorrelation'", ",", "zero"...
38.088608
0.000324
def delete_endpoint_config(self, endpoint_config_name): """Delete an Amazon SageMaker endpoint configuration. Args: endpoint_config_name (str): Name of the Amazon SageMaker endpoint configuration to delete. """ LOGGER.info('Deleting endpoint configuration with name: {}'.form...
[ "def", "delete_endpoint_config", "(", "self", ",", "endpoint_config_name", ")", ":", "LOGGER", ".", "info", "(", "'Deleting endpoint configuration with name: {}'", ".", "format", "(", "endpoint_config_name", ")", ")", "self", ".", "sagemaker_client", ".", "delete_endpoi...
54
0.01139
def from_iterable(cls, target_types, address_mapper, adaptor_iter): """Create a new DependentGraph from an iterable of TargetAdaptor subclasses.""" inst = cls(target_types, address_mapper) all_valid_addresses = set() for target_adaptor in adaptor_iter: inst._inject_target(target_adaptor) all...
[ "def", "from_iterable", "(", "cls", ",", "target_types", ",", "address_mapper", ",", "adaptor_iter", ")", ":", "inst", "=", "cls", "(", "target_types", ",", "address_mapper", ")", "all_valid_addresses", "=", "set", "(", ")", "for", "target_adaptor", "in", "ada...
45.777778
0.009524
def link_add(self, rel, href, **atts): """Create an link with specified rel. Will add a link even if one with that rel already exists. """ self.link_set(rel, href, allow_duplicates=True, **atts)
[ "def", "link_add", "(", "self", ",", "rel", ",", "href", ",", "*", "*", "atts", ")", ":", "self", ".", "link_set", "(", "rel", ",", "href", ",", "allow_duplicates", "=", "True", ",", "*", "*", "atts", ")" ]
37
0.008811
def to_entity(entity_type, value, fields): """ Internal API: Returns an instance of an entity of type entity_type with the specified value and fields (stored in dict). This is only used by the local transform runner as a helper function. """ e = entity_type(value) for k, v in fields.items(): ...
[ "def", "to_entity", "(", "entity_type", ",", "value", ",", "fields", ")", ":", "e", "=", "entity_type", "(", "value", ")", "for", "k", ",", "v", "in", "fields", ".", "items", "(", ")", ":", "e", ".", "fields", "[", "k", "]", "=", "Field", "(", ...
39.444444
0.008264
def register_parser(parser, subparsers_action=None, categories=('other', ), add_help=True): """Attaches `parser` to the global ``parser_map``. If `add_help` is truthy, then adds the helpstring of `parser` into the output of ``dx help...``, for each category in `categories`. :param subparsers_action: A ...
[ "def", "register_parser", "(", "parser", ",", "subparsers_action", "=", "None", ",", "categories", "=", "(", "'other'", ",", ")", ",", "add_help", "=", "True", ")", ":", "name", "=", "re", ".", "sub", "(", "'^dx '", ",", "''", ",", "parser", ".", "pr...
44.761905
0.002083
def need_check(self): '''Does the resource needs to be checked against its linkchecker? We check unavailable resources often, unless they go over the threshold. Available resources are checked less and less frequently based on their historical availability. ''' min_cache...
[ "def", "need_check", "(", "self", ")", ":", "min_cache_duration", ",", "max_cache_duration", ",", "ko_threshold", "=", "[", "current_app", ".", "config", ".", "get", "(", "k", ")", "for", "k", "in", "(", "'LINKCHECKING_MIN_CACHE_DURATION'", ",", "'LINKCHECKING_M...
42.176471
0.001363
def radec_to_custom(ra,dec,T=None,degree=False): """ NAME: radec_to_custom PURPOSE: transform from equatorial coordinates to a custom set of sky coordinates INPUT: ra - right ascension dec - declination T= matrix defining the transformation: new_rect= T dot old_...
[ "def", "radec_to_custom", "(", "ra", ",", "dec", ",", "T", "=", "None", ",", "degree", "=", "False", ")", ":", "if", "T", "is", "None", ":", "raise", "ValueError", "(", "\"Must set T= for radec_to_custom\"", ")", "#Whether to use degrees and scalar input is handle...
27.5
0.01374
def precmd(self, line): """ Allow commands to have a last parameter of 'cookie=somevalue' TODO somevalue will be prepended onto any output lines so that editors can distinguish output from certain kinds of events they have sent. :param line: :return: """...
[ "def", "precmd", "(", "self", ",", "line", ")", ":", "args", "=", "shlex", ".", "split", "(", "line", "or", "\"\"", ")", "if", "args", "and", "'cookie='", "in", "args", "[", "-", "1", "]", ":", "cookie_index", "=", "line", ".", "index", "(", "'co...
32.342857
0.001715
def _convert_schemas(mapping, schemas): """Convert schemas to be compatible with storage schemas. Foreign keys related operations. Args: mapping (dict): mapping between resource name and table name schemas (list): schemas Raises: ValueError: if there is no resource ...
[ "def", "_convert_schemas", "(", "mapping", ",", "schemas", ")", ":", "schemas", "=", "deepcopy", "(", "schemas", ")", "for", "schema", "in", "schemas", ":", "for", "fk", "in", "schema", ".", "get", "(", "'foreignKeys'", ",", "[", "]", ")", ":", "resour...
31.392857
0.001104
def Vml_STP(self): r'''Liquid-phase molar volume of the mixture at 298.15 K and 101.325 kPa, and the current composition in units of [m^3/mol]. Examples -------- >>> Mixture(['cyclobutane'], ws=[1]).Vml_STP 8.143327329133706e-05 ''' return self.VolumeLiqu...
[ "def", "Vml_STP", "(", "self", ")", ":", "return", "self", ".", "VolumeLiquidMixture", "(", "T", "=", "298.15", ",", "P", "=", "101325", ",", "zs", "=", "self", ".", "zs", ",", "ws", "=", "self", ".", "ws", ")" ]
36.4
0.010724
def parse_zone_details(zone_contents): """Parses a zone file into python data-structures.""" records = [] bad_lines = [] zone_lines = [line.strip() for line in zone_contents.split('\n')] zone_search = re.search(r'^\$ORIGIN (?P<zone>.*)\.', zone_lines[0]) zone = zone_search.group('zone') fo...
[ "def", "parse_zone_details", "(", "zone_contents", ")", ":", "records", "=", "[", "]", "bad_lines", "=", "[", "]", "zone_lines", "=", "[", "line", ".", "strip", "(", ")", "for", "line", "in", "zone_contents", ".", "split", "(", "'\\n'", ")", "]", "zone...
32.468085
0.000636
def _get_index_mapred_emu(self, bucket, index, startkey, endkey=None): """ Emulates a secondary index request via MapReduce. Used in the case where the transport supports MapReduce but has no native secondary index query capability. """ phases = [] if not self.pha...
[ "def", "_get_index_mapred_emu", "(", "self", ",", "bucket", ",", "index", ",", "startkey", ",", "endkey", "=", "None", ")", ":", "phases", "=", "[", "]", "if", "not", "self", ".", "phaseless_mapred", "(", ")", ":", "phases", ".", "append", "(", "{", ...
43.625
0.001869
def d3flare_json(metadata, file=None, **options): """ Converts the *metadata* dictionary of a container or field into a ``flare.json`` formatted string or formatted stream written to the *file* The ``flare.json`` format is defined by the `d3.js <https://d3js.org/>`_ graphic library. The ``flare.js...
[ "def", "d3flare_json", "(", "metadata", ",", "file", "=", "None", ",", "*", "*", "options", ")", ":", "def", "convert", "(", "root", ")", ":", "dct", "=", "OrderedDict", "(", ")", "item_type", "=", "root", ".", "get", "(", "'type'", ")", "dct", "["...
35.065574
0.00091
def strip_prefix(string, strip): """ Strips a prefix from a string, if the string starts with the prefix. :param string: String that should have its prefix removed :param strip: Prefix to be removed :return: string with the prefix removed if it has the prefix, or else it just returns the or...
[ "def", "strip_prefix", "(", "string", ",", "strip", ")", ":", "import", "re", "strip_esc", "=", "re", ".", "escape", "(", "strip", ")", "if", "re", ".", "match", "(", "strip_esc", ",", "string", ")", ":", "return", "string", "[", "len", "(", "strip",...
31.8
0.002037
def _get_terminal(value, text): """Checks the beginning of text for a value. If it is found, a terminal ParseNode is returned filled out appropriately for the value it found. DeadEnd is raised if the value does not match. """ if text and text.startswith(value): return ParseNode(ParseNodeType.terminal, ...
[ "def", "_get_terminal", "(", "value", ",", "text", ")", ":", "if", "text", "and", "text", ".", "startswith", "(", "value", ")", ":", "return", "ParseNode", "(", "ParseNodeType", ".", "terminal", ",", "children", "=", "[", "value", "]", ",", "consumed", ...
41.636364
0.019231
def split(self, sep=TOKENS): """ Returns a list of sentences, where each sentence is a list of tokens, where each token is a list of word + tags. """ if sep != TOKENS: return unicode.split(self, sep) if len(self) == 0: return [] return [[[x.rep...
[ "def", "split", "(", "self", ",", "sep", "=", "TOKENS", ")", ":", "if", "sep", "!=", "TOKENS", ":", "return", "unicode", ".", "split", "(", "self", ",", "sep", ")", "if", "len", "(", "self", ")", "==", "0", ":", "return", "[", "]", "return", "[...
42
0.008475
def perform_permissions_check(self, user, obj, perms): """ Performs the permissions check. """ return self.request.forum_permission_handler.can_access_moderation_queue(user)
[ "def", "perform_permissions_check", "(", "self", ",", "user", ",", "obj", ",", "perms", ")", ":", "return", "self", ".", "request", ".", "forum_permission_handler", ".", "can_access_moderation_queue", "(", "user", ")" ]
62.333333
0.015873
def _createFuture(func, *args, **kwargs): """Helper function to create a future.""" assert callable(func), ( "The provided func parameter is not a callable." ) if scoop.IS_ORIGIN and "SCOOP_WORKER" not in sys.modules: sys.modules["SCOOP_WORKER"] = sys.modules["__main__"] # If funct...
[ "def", "_createFuture", "(", "func", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "assert", "callable", "(", "func", ")", ",", "(", "\"The provided func parameter is not a callable.\"", ")", "if", "scoop", ".", "IS_ORIGIN", "and", "\"SCOOP_WORKER\"", "...
41
0.001135
def send(query, address=DEFAULT_ADDRESS, port=DEFAULT_PORT, ttl=DEFAULT_TTL, local_only=False, timeout_s=2): """Sends a query to the given multicast socket and returns responses. Args: query: The string query to send. address: Multicast IP address component of t...
[ "def", "send", "(", "query", ",", "address", "=", "DEFAULT_ADDRESS", ",", "port", "=", "DEFAULT_PORT", ",", "ttl", "=", "DEFAULT_TTL", ",", "local_only", "=", "False", ",", "timeout_s", "=", "2", ")", ":", "# Set up the socket as a UDP Multicast socket with the gi...
35.092593
0.01078
def list_all_collections(cls, **kwargs): """List Collections Return a list of Collections This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.list_all_collections(async=True) >>> result = ...
[ "def", "list_all_collections", "(", "cls", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'async'", ")", ":", "return", "cls", ".", "_list_all_collections_with_http_info", "(", ...
37.086957
0.002286
def getbfs(coords, gbasis): """Convenience function for both wavefunction and density based on PyQuante Ints.py.""" sym2powerlist = { 'S' : [(0,0,0)], 'P' : [(1,0,0),(0,1,0),(0,0,1)], 'D' : [(2,0,0),(0,2,0),(0,0,2),(1,1,0),(0,1,1),(1,0,1)], 'F' : [(3,0,0),(2,1,0),(2,0,1),(1,2,0)...
[ "def", "getbfs", "(", "coords", ",", "gbasis", ")", ":", "sym2powerlist", "=", "{", "'S'", ":", "[", "(", "0", ",", "0", ",", "0", ")", "]", ",", "'P'", ":", "[", "(", "1", ",", "0", ",", "0", ")", ",", "(", "0", ",", "1", ",", "0", ")"...
31.913043
0.084656
def with_subprocess(cls): """a class decorator for Crontabber Apps. This decorator gives the CronApp a _run_proxy method that will execute the cron app as a single PG transaction. Commit and Rollback are automatic. The cron app should do no transaction management of its own. The cron app should be s...
[ "def", "with_subprocess", "(", "cls", ")", ":", "def", "run_process", "(", "self", ",", "command", ",", "input", "=", "None", ")", ":", "\"\"\"\n Run the command and return a tuple of three things.\n\n 1. exit code - an integer number\n 2. stdout - all output...
36.758621
0.000914
def get_template(template_file='', **kwargs): """Get the Jinja2 template and renders with dict _kwargs_. Args: template_file (str): name of the template file kwargs: Keywords to use for rendering the Jinja2 template. Returns: String of rendered JSON template. """ template ...
[ "def", "get_template", "(", "template_file", "=", "''", ",", "*", "*", "kwargs", ")", ":", "template", "=", "get_template_object", "(", "template_file", ")", "LOG", ".", "info", "(", "'Rendering template %s'", ",", "template", ".", "filename", ")", "for", "k...
28.47619
0.001618
def loadFeatureWriters(ufo, ignoreErrors=True): """Check UFO lib for key "com.github.googlei18n.ufo2ft.featureWriters", containing a list of dicts, each having the following key/value pairs: For example: { "module": "myTools.featureWriters", # default: ufo2ft.featureWriters "class": ...
[ "def", "loadFeatureWriters", "(", "ufo", ",", "ignoreErrors", "=", "True", ")", ":", "if", "FEATURE_WRITERS_KEY", "not", "in", "ufo", ".", "lib", ":", "return", "None", "writers", "=", "[", "]", "for", "wdict", "in", "ufo", ".", "lib", "[", "FEATURE_WRIT...
38.55814
0.000588
def setattr_context(obj, **kwargs): """ Context manager to temporarily change the values of object attributes while executing a function. Example ------- >>> class Foo: pass >>> f = Foo(); f.attr = 'hello' >>> with setattr_context(f, attr='goodbye'): ... print(f.attr) goodby...
[ "def", "setattr_context", "(", "obj", ",", "*", "*", "kwargs", ")", ":", "old_kwargs", "=", "dict", "(", "[", "(", "key", ",", "getattr", "(", "obj", ",", "key", ")", ")", "for", "key", "in", "kwargs", "]", ")", "[", "setattr", "(", "obj", ",", ...
27.285714
0.001686
def factorize(self, A): """ Factorizes A. Parameters ---------- A : matrix For symmetric systems, should contain only lower diagonal part. """ A = csc_matrix(A) if self.prop == self.SYMMETRIC: A = (A + A.T) - triu(A) ...
[ "def", "factorize", "(", "self", ",", "A", ")", ":", "A", "=", "csc_matrix", "(", "A", ")", "if", "self", ".", "prop", "==", "self", ".", "SYMMETRIC", ":", "A", "=", "(", "A", "+", "A", ".", "T", ")", "-", "triu", "(", "A", ")", "self", "."...
22.6
0.008499
async def _data_channel_flush(self): """ Try to flush buffered data to the SCTP layer. We wait until the association is established, as we need to know whether we are a client or a server to correctly assign an odd/even ID to the data channels. """ if self._assoc...
[ "async", "def", "_data_channel_flush", "(", "self", ")", ":", "if", "self", ".", "_association_state", "!=", "self", ".", "State", ".", "ESTABLISHED", ":", "return", "while", "self", ".", "_data_channel_queue", "and", "not", "self", ".", "_outbound_queue", ":"...
41.702703
0.001267
def screen(args): """ %prog screen anchorfile newanchorfile --qbed=qbedfile --sbed=sbedfile [options] Extract subset of blocks from anchorfile. Provide several options: 1. Option --ids: a file with IDs, 0-based, comma separated, all in one line. 2. Option --seqids: only allow seqids in this file. ...
[ "def", "screen", "(", "args", ")", ":", "p", "=", "OptionParser", "(", "screen", ".", "__doc__", ")", "p", ".", "set_beds", "(", ")", "p", ".", "add_option", "(", "\"--ids\"", ",", "help", "=", "\"File with block IDs (0-based) [default: %default]\"", ")", "p...
32.216981
0.002273
def delete(self, event): """Mark event as deleted.""" assert self.receiver_id == event.receiver_id event.response = {'status': 410, 'message': 'Gone.'} event.response_code = 410
[ "def", "delete", "(", "self", ",", "event", ")", ":", "assert", "self", ".", "receiver_id", "==", "event", ".", "receiver_id", "event", ".", "response", "=", "{", "'status'", ":", "410", ",", "'message'", ":", "'Gone.'", "}", "event", ".", "response_code...
41
0.009569
def merge_otus_and_trees(nexson_blob): """Takes a nexson object: 1. merges trees elements 2 - # trees into the first trees element., 2. merges otus elements 2 - # otus into the first otus element. 3. if there is no ot:originalLabel field for any otu, it sets that field based on @...
[ "def", "merge_otus_and_trees", "(", "nexson_blob", ")", ":", "id_to_replace_id", "=", "{", "}", "orig_version", "=", "detect_nexson_version", "(", "nexson_blob", ")", "convert_nexson_format", "(", "nexson_blob", ",", "BY_ID_HONEY_BADGERFISH", ")", "nexson", "=", "get_...
50.3
0.001532
def ensure_packages( packages, current_packages, present, install_command, uninstall_command, latest=False, upgrade_command=None, version_join=None, lower=True, ): ''' Handles this common scenario: + We have a list of packages(/versions) to ensure + We have a map of existing package -> ...
[ "def", "ensure_packages", "(", "packages", ",", "current_packages", ",", "present", ",", "install_command", ",", "uninstall_command", ",", "latest", "=", "False", ",", "upgrade_command", "=", "None", ",", "version_join", "=", "None", ",", "lower", "=", "True", ...
32.767241
0.001532
def GeneReader( fh, format='gff' ): """ yield chrom, strand, gene_exons, name """ known_formats = ( 'gff', 'gtf', 'bed') if format not in known_formats: print('%s format not in %s' % (format, ",".join( known_formats )), file=sys.stderr) raise Exception('?') if format == 'bed': ...
[ "def", "GeneReader", "(", "fh", ",", "format", "=", "'gff'", ")", ":", "known_formats", "=", "(", "'gff'", ",", "'gtf'", ",", "'bed'", ")", "if", "format", "not", "in", "known_formats", ":", "print", "(", "'%s format not in %s'", "%", "(", "format", ",",...
34.42623
0.021296
def render_to_response(self, template_name, __data, content_type="text/html"): '''Given a template name and template data. Renders a template and returns `webob.Response` object''' resp = self.render(template_name, __data) return Response(resp, ...
[ "def", "render_to_response", "(", "self", ",", "template_name", ",", "__data", ",", "content_type", "=", "\"text/html\"", ")", ":", "resp", "=", "self", ".", "render", "(", "template_name", ",", "__data", ")", "return", "Response", "(", "resp", ",", "content...
49.714286
0.008475
def print_bin_sizes(): """ Useful for debugging: how large is each bin, and what are the bin IDs? """ for i, offset in enumerate(OFFSETS): binstart = offset try: binstop = OFFSETS[i + 1] except IndexError: binstop = binstart bin_size = 2 ** (FIRST...
[ "def", "print_bin_sizes", "(", ")", ":", "for", "i", ",", "offset", "in", "enumerate", "(", "OFFSETS", ")", ":", "binstart", "=", "offset", "try", ":", "binstop", "=", "OFFSETS", "[", "i", "+", "1", "]", "except", "IndexError", ":", "binstop", "=", "...
32.96
0.001179
def _c_base_var(self): """Return the name of the module base variable.""" if self.opts.no_structs: return self.name return 'windll->{}.{}'.format( self.name, self.opts.base )
[ "def", "_c_base_var", "(", "self", ")", ":", "if", "self", ".", "opts", ".", "no_structs", ":", "return", "self", ".", "name", "return", "'windll->{}.{}'", ".", "format", "(", "self", ".", "name", ",", "self", ".", "opts", ".", "base", ")" ]
32
0.008696
def codon2weight(self, codon): """ Turn a codon of "000" to "999" to a number between -5.0 and 5.0. """ length = len(codon) retval = int(codon) return retval/(10 ** (length - 1)) - 5.0
[ "def", "codon2weight", "(", "self", ",", "codon", ")", ":", "length", "=", "len", "(", "codon", ")", "retval", "=", "int", "(", "codon", ")", "return", "retval", "/", "(", "10", "**", "(", "length", "-", "1", ")", ")", "-", "5.0" ]
29.125
0.008333
def _send_output(self, message_body=None): """Send the currently buffered request and clear the buffer. Appends an extra \\r\\n to the buffer. A message_body may be specified, to be appended to the request. """ self._buffer.extend((bytes(b""), bytes(b""))) msg = bytes(b"...
[ "def", "_send_output", "(", "self", ",", "message_body", "=", "None", ")", ":", "self", ".", "_buffer", ".", "extend", "(", "(", "bytes", "(", "b\"\"", ")", ",", "bytes", "(", "b\"\"", ")", ")", ")", "msg", "=", "bytes", "(", "b\"\\r\\n\"", ")", "....
43.3
0.00226