text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def _annotate_somatic(data, retriever=None): """Annotate somatic calls if we have cosmic data installed. """ if is_human(data): paired = vcfutils.get_paired([data]) if paired: r = dd.get_variation_resources(data) if r.get("cosmic") and objectstore.file_exists_or_remot...
[ "def", "_annotate_somatic", "(", "data", ",", "retriever", "=", "None", ")", ":", "if", "is_human", "(", "data", ")", ":", "paired", "=", "vcfutils", ".", "get_paired", "(", "[", "data", "]", ")", "if", "paired", ":", "r", "=", "dd", ".", "get_variat...
37.1
13.5
def _consumeArgument(self, memberName, positionalArgumentKeyValueList, kwargs, defaultValue): """Returns member's value from kwargs if found or from positionalArgumentKeyValueList if found or default value otherw...
[ "def", "_consumeArgument", "(", "self", ",", "memberName", ",", "positionalArgumentKeyValueList", ",", "kwargs", ",", "defaultValue", ")", ":", "# Warning: we use this dict to simplify the usage of the key-value tuple list but be aware that this will", "# merge superfluous arguments as...
40.045455
17.727273
def get_feature_flag_by_name(self, name, check_feature_exists=None): """GetFeatureFlagByName. [Preview API] Retrieve information on a single feature flag and its current states :param str name: The name of the feature to retrieve :param bool check_feature_exists: Check if feature exists ...
[ "def", "get_feature_flag_by_name", "(", "self", ",", "name", ",", "check_feature_exists", "=", "None", ")", ":", "route_values", "=", "{", "}", "if", "name", "is", "not", "None", ":", "route_values", "[", "'name'", "]", "=", "self", ".", "_serialize", ".",...
58.578947
24.526316
def pagingRequestType2(MobileId_presence=0): """PAGING REQUEST TYPE 2 Section 9.1.23""" a = L2PseudoLength() b = TpPd(pd=0x6) c = MessageType(mesType=0x22) # 00100010 d = PageModeAndChannelNeeded() f = MobileId() g = MobileId() packet = a / b / c / d / f / g if MobileId_presence is...
[ "def", "pagingRequestType2", "(", "MobileId_presence", "=", "0", ")", ":", "a", "=", "L2PseudoLength", "(", ")", "b", "=", "TpPd", "(", "pd", "=", "0x6", ")", "c", "=", "MessageType", "(", "mesType", "=", "0x22", ")", "# 00100010", "d", "=", "PageModeA...
30.266667
12.866667
def generate(num, prompt_default=True): """Generates Python file for a problem.""" p = Problem(num) problem_text = p.text msg = "Generate file for problem %i?" % num click.confirm(msg, default=prompt_default, abort=True) # Allow skipped problem files to be recreated if p.glob: fil...
[ "def", "generate", "(", "num", ",", "prompt_default", "=", "True", ")", ":", "p", "=", "Problem", "(", "num", ")", "problem_text", "=", "p", ".", "text", "msg", "=", "\"Generate file for problem %i?\"", "%", "num", "click", ".", "confirm", "(", "msg", ",...
32.818182
19.030303
def _infer_fused_data_format(self, input_batch): """Infers the data format for the fused batch norm. It uses the axis option to infer this information. Specifically, the axis value (0, 1, 2) corresponds to data format NHWC and the axis value (0, 2, 3) to data format NCHW. Args: input_batch: ...
[ "def", "_infer_fused_data_format", "(", "self", ",", "input_batch", ")", ":", "input_shape", "=", "input_batch", ".", "get_shape", "(", ")", ".", "as_list", "(", ")", "input_shape_len", "=", "len", "(", "input_shape", ")", "if", "input_shape_len", "!=", "4", ...
39.942857
22.285714
def _srvc_extract_file_information(self, kwargs): """Extracts file information from kwargs. Note that `kwargs` is not passed as `**kwargs` in order to also `pop` the elements on the level of the function calling `_srvc_extract_file_information`. """ if 'filename' in kwargs: ...
[ "def", "_srvc_extract_file_information", "(", "self", ",", "kwargs", ")", ":", "if", "'filename'", "in", "kwargs", ":", "self", ".", "_filename", "=", "kwargs", ".", "pop", "(", "'filename'", ")", "if", "'file_title'", "in", "kwargs", ":", "self", ".", "_f...
36.666667
21.666667
def set_opcode(self, opcode): """Set the opcode. @param opcode: the opcode @type opcode: int """ self.flags &= 0x87FF self.flags |= dns.opcode.to_flags(opcode)
[ "def", "set_opcode", "(", "self", ",", "opcode", ")", ":", "self", ".", "flags", "&=", "0x87FF", "self", ".", "flags", "|=", "dns", ".", "opcode", ".", "to_flags", "(", "opcode", ")" ]
28.714286
7.714286
def fugacity_coefficients(self, Z, zs): r'''Literature formula for calculating fugacity coefficients for each species in a mixture. Verified numerically. Applicable to most derivatives of the SRK equation of state as well. Called by `fugacities` on initialization, or by a solver routine...
[ "def", "fugacity_coefficients", "(", "self", ",", "Z", ",", "zs", ")", ":", "A", "=", "self", ".", "a_alpha", "*", "self", ".", "P", "/", "R2", "/", "self", ".", "T", "**", "2", "B", "=", "self", ".", "b", "*", "self", ".", "P", "/", "R", "...
39.340426
21.255319
def human_to_seconds(string): """Convert internal string like 1M, 1Y3M, 3W to seconds. :type string: str :param string: Interval string like 1M, 1W, 1M3W4h2s... (s => seconds, m => minutes, h => hours, D => days, W => weeks, M => months, Y => Years). :rtype: int :return: The con...
[ "def", "human_to_seconds", "(", "string", ")", ":", "interval_exc", "=", "\"Bad interval format for {0}\"", ".", "format", "(", "string", ")", "interval_regex", "=", "re", ".", "compile", "(", "\"^(?P<value>[0-9]+)(?P<unit>[{0}])\"", ".", "format", "(", "\"\"", ".",...
35.566667
22.666667
def plot(self, data, height=1000, render_large_data=False): """ Plots a detail view of data. Args: data: a Pandas dataframe. height: the height of the output. """ import IPython if not isinstance(data, pd.DataFrame): raise ValueError('Expect a DataFrame.') if (len(data) > 1...
[ "def", "plot", "(", "self", ",", "data", ",", "height", "=", "1000", ",", "render_large_data", "=", "False", ")", ":", "import", "IPython", "if", "not", "isinstance", "(", "data", ",", "pd", ".", "DataFrame", ")", ":", "raise", "ValueError", "(", "'Exp...
36.5
20.285714
def scatter_blocks_2d(x, indices, shape): """scatters blocks from x into shape with indices.""" x_shape = common_layers.shape_list(x) # [length, batch, heads, dim] x_t = tf.transpose( tf.reshape(x, [x_shape[0], x_shape[1], -1, x_shape[-1]]), [2, 0, 1, 3]) x_t_shape = common_layers.shape_list(x_t) indi...
[ "def", "scatter_blocks_2d", "(", "x", ",", "indices", ",", "shape", ")", ":", "x_shape", "=", "common_layers", ".", "shape_list", "(", "x", ")", "# [length, batch, heads, dim]", "x_t", "=", "tf", ".", "transpose", "(", "tf", ".", "reshape", "(", "x", ",", ...
45
9.090909
def retinotopy_mesh_field(mesh, mdl, polar_angle=None, eccentricity=None, weight=None, weight_min=0, scale=1, sigma=None, shape=2, suffix=None, max_eccentricity=Ellipsis, max_polar_angle=180, ...
[ "def", "retinotopy_mesh_field", "(", "mesh", ",", "mdl", ",", "polar_angle", "=", "None", ",", "eccentricity", "=", "None", ",", "weight", "=", "None", ",", "weight_min", "=", "0", ",", "scale", "=", "1", ",", "sigma", "=", "None", ",", "shape", "=", ...
60.412903
27.690323
def _get_context_key(self, **kwargs): """ Get value of `self._resource.parent.id_name` from :kwargs: """ return str(kwargs.get(self._resource.parent.id_name))
[ "def", "_get_context_key", "(", "self", ",", "*", "*", "kwargs", ")", ":", "return", "str", "(", "kwargs", ".", "get", "(", "self", ".", "_resource", ".", "parent", ".", "id_name", ")", ")" ]
57.333333
8
def present(name, Name=None, ScheduleExpression=None, EventPattern=None, Description=None, RoleArn=None, State=None, Targets=None, region=None, key=None, keyid=None, profile=None): ''' Ensure trail exists. name The name of...
[ "def", "present", "(", "name", ",", "Name", "=", "None", ",", "ScheduleExpression", "=", "None", ",", "EventPattern", "=", "None", ",", "Description", "=", "None", ",", "RoleArn", "=", "None", ",", "State", "=", "None", ",", "Targets", "=", "None", ","...
37.088083
21.948187
def ip_rtm_config_route_static_bfd_bfd_static_route_bfd_interval_attributes_interval(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") ip = ET.SubElement(config, "ip", xmlns="urn:brocade.com:mgmt:brocade-common-def") rtm_config = ET.SubElement(ip, "rtm-con...
[ "def", "ip_rtm_config_route_static_bfd_bfd_static_route_bfd_interval_attributes_interval", "(", "self", ",", "*", "*", "kwargs", ")", ":", "config", "=", "ET", ".", "Element", "(", "\"config\"", ")", "ip", "=", "ET", ".", "SubElement", "(", "config", ",", "\"ip\""...
59.65
26.8
def get_base_kwargs(self): """Get base kwargs for API call.""" kwargs = { 'HostedZoneId': self.hosted_zone_id } if self.max_items is not None: kwargs.update({ 'MaxItems': str(self.max_items) }) return kwargs
[ "def", "get_base_kwargs", "(", "self", ")", ":", "kwargs", "=", "{", "'HostedZoneId'", ":", "self", ".", "hosted_zone_id", "}", "if", "self", ".", "max_items", "is", "not", "None", ":", "kwargs", ".", "update", "(", "{", "'MaxItems'", ":", "str", "(", ...
29
14.1
def pip_install_to_target(self, path, requirements="", local_package=None): """For a given active virtualenv, gather all installed pip packages then copy (re-install) them to the path provided. :param str path: Path to copy installed pip packages to. :param str requirements: ...
[ "def", "pip_install_to_target", "(", "self", ",", "path", ",", "requirements", "=", "\"\"", ",", "local_package", "=", "None", ")", ":", "packages", "=", "[", "]", "if", "not", "requirements", ":", "logger", ".", "debug", "(", "'Gathering pip packages'", ")"...
47.942857
19
def set_ugi(self, user_name, group_names): """ Parameters: - user_name - group_names """ self.send_set_ugi(user_name, group_names) return self.recv_set_ugi()
[ "def", "set_ugi", "(", "self", ",", "user_name", ",", "group_names", ")", ":", "self", ".", "send_set_ugi", "(", "user_name", ",", "group_names", ")", "return", "self", ".", "recv_set_ugi", "(", ")" ]
22.5
11
def save_checkpoint(prefix, epoch, symbol, arg_params, aux_params): """Checkpoint the model data into file. Parameters ---------- prefix : str Prefix of model name. epoch : int The epoch number of the model. symbol : Symbol The input Symbol. arg_params : dict of str ...
[ "def", "save_checkpoint", "(", "prefix", ",", "epoch", ",", "symbol", ",", "arg_params", ",", "aux_params", ")", ":", "if", "symbol", "is", "not", "None", ":", "symbol", ".", "save", "(", "'%s-symbol.json'", "%", "prefix", ")", "save_dict", "=", "{", "("...
36.928571
20.428571
def cursor_batch(self, table_name, start_timeperiod, end_timeperiod): """ method returns batched DB cursor """ raise NotImplementedError('method cursor_batch must be implemented by {0}'.format(self.__class__.__name__))
[ "def", "cursor_batch", "(", "self", ",", "table_name", ",", "start_timeperiod", ",", "end_timeperiod", ")", ":", "raise", "NotImplementedError", "(", "'method cursor_batch must be implemented by {0}'", ".", "format", "(", "self", ".", "__class__", ".", "__name__", ")"...
48.666667
17.666667
def variational_lower_bound(params, t, logprob, sampler, log_density, num_samples, rs): """Provides a stochastic estimate of the variational lower bound, for any variational family and model density.""" samples = sampler(params, num_samples, rs) log_qs = log_density(params...
[ "def", "variational_lower_bound", "(", "params", ",", "t", ",", "logprob", ",", "sampler", ",", "log_density", ",", "num_samples", ",", "rs", ")", ":", "samples", "=", "sampler", "(", "params", ",", "num_samples", ",", "rs", ")", "log_qs", "=", "log_densit...
49.2
7.4
def transform_text(input_txt): """Transforms text into :py:class:`~collections.deque`, pre-processes multiline strings. :param str or bytes input_txt: Input text. :return: Double-ended queue of single characters and multiline strings. :rtype: :py:class:`~collections.deque` """ if isinstance...
[ "def", "transform_text", "(", "input_txt", ")", ":", "if", "isinstance", "(", "input_txt", ",", "str", ")", ":", "text", "=", "u\"{}\"", ".", "format", "(", "input_txt", ")", "elif", "isinstance", "(", "input_txt", ",", "bytes", ")", ":", "text", "=", ...
28.982759
17.741379
def validate(self): """Validate / fix up the current config""" if not self.get('api_key'): raise ValueError("api_key not found in config. Please see documentation.") host = self.get('host') or DEFAULT_CLOUD_HOST if host: # remove extraneous slashes and force to by...
[ "def", "validate", "(", "self", ")", ":", "if", "not", "self", ".", "get", "(", "'api_key'", ")", ":", "raise", "ValueError", "(", "\"api_key not found in config. Please see documentation.\"", ")", "host", "=", "self", ".", "get", "(", "'host'", ")", "or", "...
48.631579
23.368421
def to_cloudformation(self, **kwargs): """Returns the Lambda layer to which this SAM Layer corresponds. :param dict kwargs: already-converted resources that may need to be modified when converting this \ macro to pure CloudFormation :returns: a list of vanilla CloudFormation Resources, ...
[ "def", "to_cloudformation", "(", "self", ",", "*", "*", "kwargs", ")", ":", "resources", "=", "[", "]", "# Append any CFN resources:", "intrinsics_resolver", "=", "kwargs", "[", "\"intrinsics_resolver\"", "]", "resources", ".", "append", "(", "self", ".", "_cons...
39.4
23.866667
def set_iscsi_initiator_info(self, initiator_iqn): """Set iSCSI initiator information in iLO. :param initiator_iqn: Initiator iqn for iLO. :raises: IloError, on an error from iLO. :raises: IloCommandNotSupportedInBiosError, if the system is in the BIOS boot mode. ...
[ "def", "set_iscsi_initiator_info", "(", "self", ",", "initiator_iqn", ")", ":", "sushy_system", "=", "self", ".", "_get_sushy_system", "(", "PROLIANT_SYSTEM_ID", ")", "if", "(", "self", ".", "_is_boot_mode_uefi", "(", ")", ")", ":", "iscsi_data", "=", "{", "'i...
47.130435
17
def fit(self, features, target, sample_weight=None, groups=None): """Fit an optimized machine learning pipeline. Uses genetic programming to optimize a machine learning pipeline that maximizes score on the provided features and target. Performs internal k-fold cross-validaton to avoid o...
[ "def", "fit", "(", "self", ",", "features", ",", "target", ",", "sample_weight", "=", "None", ",", "groups", "=", "None", ")", ":", "self", ".", "_fit_init", "(", ")", "features", ",", "target", "=", "self", ".", "_check_dataset", "(", "features", ",",...
45.66875
25.925
def _filter_packages(self): """ Run the package filtering plugins and remove any packages from the packages_to_sync that match any filters. - Logging of action will be done within the check_match methods """ global LOG_PLUGINS filter_plugins = filter_project_plug...
[ "def", "_filter_packages", "(", "self", ")", ":", "global", "LOG_PLUGINS", "filter_plugins", "=", "filter_project_plugins", "(", ")", "if", "not", "filter_plugins", ":", "if", "LOG_PLUGINS", ":", "logger", ".", "info", "(", "\"No project filters are enabled. Skipping ...
41.464286
17.321429
def _forbidden_attributes(obj): """Return the object without the forbidden attributes.""" for key in list(obj.data.keys()): if key in list(obj.reserved_keys.keys()): obj.data.pop(key) return obj
[ "def", "_forbidden_attributes", "(", "obj", ")", ":", "for", "key", "in", "list", "(", "obj", ".", "data", ".", "keys", "(", ")", ")", ":", "if", "key", "in", "list", "(", "obj", ".", "reserved_keys", ".", "keys", "(", ")", ")", ":", "obj", ".", ...
36.833333
9.666667
def _rapply(d, func, *args, **kwargs): """Apply a function to all values in a dictionary or list of dictionaries, recursively.""" if isinstance(d, (tuple, list)): return [_rapply(each, func, *args, **kwargs) for each in d] if isinstance(d, dict): return { key: _rapply(value, func...
[ "def", "_rapply", "(", "d", ",", "func", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "isinstance", "(", "d", ",", "(", "tuple", ",", "list", ")", ")", ":", "return", "[", "_rapply", "(", "each", ",", "func", ",", "*", "args", "...
42
17.8
def btc_is_p2wpkh_address( address ): """ Is the given address a p2wpkh address? """ wver, whash = segwit_addr_decode(address) if whash is None: return False if len(whash) != 20: return False return True
[ "def", "btc_is_p2wpkh_address", "(", "address", ")", ":", "wver", ",", "whash", "=", "segwit_addr_decode", "(", "address", ")", "if", "whash", "is", "None", ":", "return", "False", "if", "len", "(", "whash", ")", "!=", "20", ":", "return", "False", "retu...
19.833333
15.833333
def _handle_results(self): """ Call back function to be implemented by the CLI. """ # Only process if we get HTTP result of 200 if self._api_result.status_code == requests.codes.ok: payload = json.loads(self._api_result.text) out = json.dumps(payload, sor...
[ "def", "_handle_results", "(", "self", ")", ":", "# Only process if we get HTTP result of 200", "if", "self", ".", "_api_result", ".", "status_code", "==", "requests", ".", "codes", ".", "ok", ":", "payload", "=", "json", ".", "loads", "(", "self", ".", "_api_...
40
16.6
def _set_median_session_metrics(session_group, aggregation_metric): """Sets the metrics for session_group to those of its "median session". The median session is the session in session_group with the median value of the metric given by 'aggregation_metric'. The median is taken over the subset of sessions in th...
[ "def", "_set_median_session_metrics", "(", "session_group", ",", "aggregation_metric", ")", ":", "measurements", "=", "sorted", "(", "_measurements", "(", "session_group", ",", "aggregation_metric", ")", ",", "key", "=", "operator", ".", "attrgetter", "(", "'metric_...
49.166667
22.277778
def login(self, user, passwd, bank): """ Login """ logger.info("login...") if bank not in self.BANKS: logger.error("Can't find that bank.") return False self.useragent = self.BANKS[bank]["u-a"] self.bankid = self.BANKS[bank]["id"] login = json.dump...
[ "def", "login", "(", "self", ",", "user", ",", "passwd", ",", "bank", ")", ":", "logger", ".", "info", "(", "\"login...\"", ")", "if", "bank", "not", "in", "self", ".", "BANKS", ":", "logger", ".", "error", "(", "\"Can't find that bank.\"", ")", "retur...
39.146341
18.04878
def parse_table_schema(json, precise_float): """ Builds a DataFrame from a given schema Parameters ---------- json : A JSON table schema precise_float : boolean Flag controlling precision when decoding string to double values, as dictated by ``read_json`` Returns ...
[ "def", "parse_table_schema", "(", "json", ",", "precise_float", ")", ":", "table", "=", "loads", "(", "json", ",", "precise_float", "=", "precise_float", ")", "col_order", "=", "[", "field", "[", "'name'", "]", "for", "field", "in", "table", "[", "'schema'...
34.661538
24.2
def index(self, item, **kwargs): # type: (Any, dict) -> int """ Get index of the parameter. :param item: Item for which get the index. :return: Index of the parameter in the WeakList. """ return list.index(self, self.ref(item), **kwargs)
[ "def", "index", "(", "self", ",", "item", ",", "*", "*", "kwargs", ")", ":", "# type: (Any, dict) -> int", "return", "list", ".", "index", "(", "self", ",", "self", ".", "ref", "(", "item", ")", ",", "*", "*", "kwargs", ")" ]
35.75
7.75
def isEquilateral(self): ''' True if all sides of the triangle are the same length. All equilateral triangles are also isosceles. All equilateral triangles are also acute. ''' if not nearly_eq(self.a, self.b): return False if not nearly_eq(self.b, s...
[ "def", "isEquilateral", "(", "self", ")", ":", "if", "not", "nearly_eq", "(", "self", ".", "a", ",", "self", ".", "b", ")", ":", "return", "False", "if", "not", "nearly_eq", "(", "self", ".", "b", ",", "self", ".", "c", ")", ":", "return", "False...
25.333333
20.8
def success_response(field=None, data=None, request_type=""): """Return a generic success response.""" data_out = {} data_out["status"] = "success" if field: data_out[field] = data print("{} request successful.".format(request_type)) js = dumps(data_out, default=date_handler) return ...
[ "def", "success_response", "(", "field", "=", "None", ",", "data", "=", "None", ",", "request_type", "=", "\"\"", ")", ":", "data_out", "=", "{", "}", "data_out", "[", "\"status\"", "]", "=", "\"success\"", "if", "field", ":", "data_out", "[", "field", ...
40.555556
14.777778
def _qteFindAppletInSplitter(self, appletObj: QtmacsApplet, split: QtmacsSplitter): """ Return the splitter that holds ``appletObj``. This method recursively searches for ``appletObj`` in the nested splitter hierarchy of the window layout, starting at ...
[ "def", "_qteFindAppletInSplitter", "(", "self", ",", "appletObj", ":", "QtmacsApplet", ",", "split", ":", "QtmacsSplitter", ")", ":", "def", "splitterIter", "(", "split", ")", ":", "\"\"\"\n Iterator over all QtmacsSplitters.\n \"\"\"", "for", "idx",...
34.261905
20.928571
def item_id(response): """ Parse the item ids, will be available as ``item_0_name``, ``item_1_name``, ``item_2_name`` and so on """ dict_keys = ['item_0', 'item_1', 'item_2', 'item_3', 'item_4', 'item_5'] new_keys = ['item_0_name', 'item_1_name', 'item_2_name', '...
[ "def", "item_id", "(", "response", ")", ":", "dict_keys", "=", "[", "'item_0'", ",", "'item_1'", ",", "'item_2'", ",", "'item_3'", ",", "'item_4'", ",", "'item_5'", "]", "new_keys", "=", "[", "'item_0_name'", ",", "'item_1_name'", ",", "'item_2_name'", ",", ...
35.823529
15.352941
def _is_path(s): """Return whether an object is a path.""" if isinstance(s, string_types): try: return op.exists(s) except (OSError, ValueError): return False else: return False
[ "def", "_is_path", "(", "s", ")", ":", "if", "isinstance", "(", "s", ",", "string_types", ")", ":", "try", ":", "return", "op", ".", "exists", "(", "s", ")", "except", "(", "OSError", ",", "ValueError", ")", ":", "return", "False", "else", ":", "re...
25.444444
15.111111
def add_resolved_links(store, drop_defaults): """Adds the state of any link models between two models in store""" for widget_id, widget in Widget.widgets.items(): # go over all widgets if isinstance(widget, Link) and widget_id not in store: if widget.source[0].model_id in store and widget.ta...
[ "def", "add_resolved_links", "(", "store", ",", "drop_defaults", ")", ":", "for", "widget_id", ",", "widget", "in", "Widget", ".", "widgets", ".", "items", "(", ")", ":", "# go over all widgets", "if", "isinstance", "(", "widget", ",", "Link", ")", "and", ...
72.5
27.333333
def serveUpcoming(self, request): """Upcoming events list view.""" myurl = self.get_url(request) today = timezone.localdate() monthlyUrl = myurl + self.reverse_subpage('serveMonth', args=[today.year, today.month]) weekNum = gregor...
[ "def", "serveUpcoming", "(", "self", ",", "request", ")", ":", "myurl", "=", "self", ".", "get_url", "(", "request", ")", "today", "=", "timezone", ".", "localdate", "(", ")", "monthlyUrl", "=", "myurl", "+", "self", ".", "reverse_subpage", "(", "'serveM...
48.333333
15.333333
def main(): """Command line entry point.""" def help_exit(): raise SystemExit("usage: ddate [day] [month] [year]") if "--help" in sys.argv or "-h" in sys.argv: help_exit() if len(sys.argv) == 2: # allow for 23-2-2014 style, be lazy/sloppy with it for split_char in ".-/`,:;": ...
[ "def", "main", "(", ")", ":", "def", "help_exit", "(", ")", ":", "raise", "SystemExit", "(", "\"usage: ddate [day] [month] [year]\"", ")", "if", "\"--help\"", "in", "sys", ".", "argv", "or", "\"-h\"", "in", "sys", ".", "argv", ":", "help_exit", "(", ")", ...
27.565217
22.478261
def select_single_item(self, option_name, select_name): """ Select the named option from select with label (recommended), name or id. """ option_box = find_option(world.browser, select_name, option_name) assert option_box, "Cannot find option '{}'.".format(option_name) option_box.click()
[ "def", "select_single_item", "(", "self", ",", "option_name", ",", "select_name", ")", ":", "option_box", "=", "find_option", "(", "world", ".", "browser", ",", "select_name", ",", "option_name", ")", "assert", "option_box", ",", "\"Cannot find option '{}'.\"", "....
43.714286
18.285714
def set_options(pool_or_cursor,row_instance): "for connection-level options that need to be set on Row instances" # todo: move around an Options object instead for option in ('JSON_READ',): setattr(row_instance,option,getattr(pool_or_cursor,option,None)) return row_instance
[ "def", "set_options", "(", "pool_or_cursor", ",", "row_instance", ")", ":", "# todo: move around an Options object instead\r", "for", "option", "in", "(", "'JSON_READ'", ",", ")", ":", "setattr", "(", "row_instance", ",", "option", ",", "getattr", "(", "pool_or_curs...
56.4
24
def _init_object(self, catalog_id, proxy, runtime, cat_name, cat_class): """Initialize this object as an OsidObject....do we need this?? From the Mongo learning impl, but seems unnecessary for Handcar""" self._catalog_identifier = None self._init_proxy_and_runtime(proxy, runtime) ...
[ "def", "_init_object", "(", "self", ",", "catalog_id", ",", "proxy", ",", "runtime", ",", "cat_name", ",", "cat_class", ")", ":", "self", ".", "_catalog_identifier", "=", "None", "self", ".", "_init_proxy_and_runtime", "(", "proxy", ",", "runtime", ")", "sel...
58.333333
14
def new(cls): ''' a method to generate the current datetime as a labDT object :return: labDT object ''' dT = datetime.utcnow().replace(tzinfo=pytz.utc) dt_kwargs = { 'year': dT.year, 'month': dT.month, 'day': dT.day, ...
[ "def", "new", "(", "cls", ")", ":", "dT", "=", "datetime", ".", "utcnow", "(", ")", ".", "replace", "(", "tzinfo", "=", "pytz", ".", "utc", ")", "dt_kwargs", "=", "{", "'year'", ":", "dT", ".", "year", ",", "'month'", ":", "dT", ".", "month", "...
27.210526
18.157895
def tarzip_data(root_dir, output_file): """ Given a root directory, adds all its children to a tarball (compressed) :param root_dir: :param output_file: :return: """ if root_dir is None: raise ValueError('Must be a valid directory path', root_dir) t = tarfile.open(output_file, '...
[ "def", "tarzip_data", "(", "root_dir", ",", "output_file", ")", ":", "if", "root_dir", "is", "None", ":", "raise", "ValueError", "(", "'Must be a valid directory path'", ",", "root_dir", ")", "t", "=", "tarfile", ".", "open", "(", "output_file", ",", "'w:gz'",...
29.466667
17.066667
def bcesboot_backup(y1,y1err,y2,y2err,cerr,nsim=10000): """ Does the BCES with bootstrapping. Usage: >>> a,b,aerr,berr,covab=bcesboot(x,xerr,y,yerr,cov,nsim) :param x,y: data :param xerr,yerr: measurement errors affecting x and y :param cov: covariance between the measurement errors (all are arrays) :param nsim: n...
[ "def", "bcesboot_backup", "(", "y1", ",", "y1err", ",", "y2", ",", "y2err", ",", "cerr", ",", "nsim", "=", "10000", ")", ":", "import", "fish", "# Progress bar initialization", "peixe", "=", "fish", ".", "ProgressFish", "(", "total", "=", "nsim", ")", "p...
33.353846
25.107692
def weight(self): """ Current weight of the Node (with respect to the parent). """ if self.root.stale: self.root.update(self.root.now, None) return self._weight
[ "def", "weight", "(", "self", ")", ":", "if", "self", ".", "root", ".", "stale", ":", "self", ".", "root", ".", "update", "(", "self", ".", "root", ".", "now", ",", "None", ")", "return", "self", ".", "_weight" ]
29.428571
11.714286
def make_traceback(exc_info, source_hint=None): """Creates a processed traceback object from the exc_info.""" exc_type, exc_value, tb = exc_info if isinstance(exc_value, TemplateSyntaxError): exc_info = translate_syntax_error(exc_value, source_hint) initial_skip = 0 else: initial...
[ "def", "make_traceback", "(", "exc_info", ",", "source_hint", "=", "None", ")", ":", "exc_type", ",", "exc_value", ",", "tb", "=", "exc_info", "if", "isinstance", "(", "exc_value", ",", "TemplateSyntaxError", ")", ":", "exc_info", "=", "translate_syntax_error", ...
41.777778
13.444444
async def get_tracks(self, *, limit=20, offset=0) -> List[Track]: """Get a list of the songs saved in the current Spotify user’s ‘Your Music’ library. Parameters ---------- limit : Optional[int] The maximum number of items to return. Default: 20. Minimum: 1. Maximum: 50. ...
[ "async", "def", "get_tracks", "(", "self", ",", "*", ",", "limit", "=", "20", ",", "offset", "=", "0", ")", "->", "List", "[", "Track", "]", ":", "data", "=", "await", "self", ".", "user", ".", "http", ".", "saved_tracks", "(", "limit", "=", "lim...
43.538462
24.076923
def create_server(self, server): """ Create a server and its storages based on a (locally created) Server object. Populates the given Server instance with the API response. 0.3.0: also supports giving the entire POST body as a dict that is directly serialised into JSON. Refer t...
[ "def", "create_server", "(", "self", ",", "server", ")", ":", "if", "isinstance", "(", "server", ",", "Server", ")", ":", "body", "=", "server", ".", "prepare_post_body", "(", ")", "else", ":", "server", "=", "Server", ".", "_create_server_obj", "(", "se...
35.916667
18.041667
def remove_ancestors_of(self, node): """Remove all of the ancestor operation nodes of node.""" if isinstance(node, int): warnings.warn('Calling remove_ancestors_of() with a node id is deprecated,' ' use a DAGNode instead', DeprecationWarnin...
[ "def", "remove_ancestors_of", "(", "self", ",", "node", ")", ":", "if", "isinstance", "(", "node", ",", "int", ")", ":", "warnings", ".", "warn", "(", "'Calling remove_ancestors_of() with a node id is deprecated,'", "' use a DAGNode instead'", ",", "DeprecationWarning",...
46.285714
13.928571
def cublasZsyr(handle, uplo, n, alpha, x, incx, A, lda): """ Rank-1 operation on complex symmetric matrix. """ status = _libcublas.cublasZsyr_v2(handle, _CUBLAS_FILL_MODE[uplo], n, ctypes.byref(cuda.cuDoubleComplex(alpha....
[ "def", "cublasZsyr", "(", "handle", ",", "uplo", ",", "n", ",", "alpha", ",", "x", ",", "incx", ",", "A", ",", "lda", ")", ":", "status", "=", "_libcublas", ".", "cublasZsyr_v2", "(", "handle", ",", "_CUBLAS_FILL_MODE", "[", "uplo", "]", ",", "n", ...
41.416667
22.083333
def run(data, samples, force, ipyclient): """ Check all samples requested have been clustered (state=6), make output directory, then create the requested outfiles. Excluded samples are already removed from samples. """ ## prepare dirs data.dirs.outfiles = os.path.join(data.dirs.project, dat...
[ "def", "run", "(", "data", ",", "samples", ",", "force", ",", "ipyclient", ")", ":", "## prepare dirs", "data", ".", "dirs", ".", "outfiles", "=", "os", ".", "path", ".", "join", "(", "data", ".", "dirs", ".", "project", ",", "data", ".", "name", "...
43.183673
23.061224
def data2schemacls(_data, **kwargs): """Convert a data to a schema cls. :param data: object or dictionary from where get a schema cls. :return: schema class. :rtype: type """ content = {} for key in list(kwargs): # fill kwargs kwargs[key] = data2schema(kwargs[key]) if isinsta...
[ "def", "data2schemacls", "(", "_data", ",", "*", "*", "kwargs", ")", ":", "content", "=", "{", "}", "for", "key", "in", "list", "(", "kwargs", ")", ":", "# fill kwargs", "kwargs", "[", "key", "]", "=", "data2schema", "(", "kwargs", "[", "key", "]", ...
21.388889
20.916667
def scan_threads(self): """ Populates the snapshot with running threads. """ # Ignore special process IDs. # PID 0: System Idle Process. Also has a special meaning to the # toolhelp APIs (current process). # PID 4: System Integrity Group. See this forum po...
[ "def", "scan_threads", "(", "self", ")", ":", "# Ignore special process IDs.", "# PID 0: System Idle Process. Also has a special meaning to the", "# toolhelp APIs (current process).", "# PID 4: System Integrity Group. See this forum post for more info:", "# http://tinyurl.com/ycza8...
43.897436
16.358974
def _set_id_field(new_class): """Lookup the id field for this entity and assign""" # FIXME What does it mean when there are no declared fields? # Does it translate to an abstract entity? if new_class.meta_.declared_fields: try: new_class.meta_.id_field = nex...
[ "def", "_set_id_field", "(", "new_class", ")", ":", "# FIXME What does it mean when there are no declared fields?", "# Does it translate to an abstract entity?", "if", "new_class", ".", "meta_", ".", "declared_fields", ":", "try", ":", "new_class", ".", "meta_", ".", "id_...
47.833333
13.166667
def snapshots(self): """ Provides access to snapshot management methods for the given content type. API reference: https://www.contentful.com/developers/docs/references/content-management-api/#/reference/snapshots/content-type-snapshots-collection :return: :class:`ContentTypeSnapshotsP...
[ "def", "snapshots", "(", "self", ")", ":", "return", "ContentTypeSnapshotsProxy", "(", "self", ".", "_client", ",", "self", ".", "space", ".", "id", ",", "self", ".", "_environment_id", ",", "self", ".", "id", ")" ]
52.666667
44
def update_workspace(self, workspace_id, name=None, description=None, language=None, metadata=None, learning_opt_out=None, system_settings=None, ...
[ "def", "update_workspace", "(", "self", ",", "workspace_id", ",", "name", "=", "None", ",", "description", "=", "None", ",", "language", "=", "None", ",", "metadata", "=", "None", ",", "learning_opt_out", "=", "None", ",", "system_settings", "=", "None", "...
46.769231
22.807692
def get_image_performance_info(self, userid): """Get CPU and memory usage information. :userid: the zvm userid to be queried """ pi_dict = self.image_performance_query([userid]) return pi_dict.get(userid, None)
[ "def", "get_image_performance_info", "(", "self", ",", "userid", ")", ":", "pi_dict", "=", "self", ".", "image_performance_query", "(", "[", "userid", "]", ")", "return", "pi_dict", ".", "get", "(", "userid", ",", "None", ")" ]
35
9.428571
def _remove_sig(signature, idempotent=False): """ Remove the signature node from its parent, keeping any tail element. This is needed for eneveloped signatures. :param signature: Signature to remove from payload :type signature: XML ElementTree Element :param idempotent: If True, don't ...
[ "def", "_remove_sig", "(", "signature", ",", "idempotent", "=", "False", ")", ":", "try", ":", "signaturep", "=", "next", "(", "signature", ".", "iterancestors", "(", ")", ")", "except", "StopIteration", ":", "if", "idempotent", ":", "return", "raise", "Va...
36.580645
16.903226
def free_chunks(self): """ Returns an iterator over all the free chunks in the heap. """ raise NotImplementedError("%s not implemented for %s" % (self.free_chunks.__func__.__name__, self.__class__.__name__))
[ "def", "free_chunks", "(", "self", ")", ":", "raise", "NotImplementedError", "(", "\"%s not implemented for %s\"", "%", "(", "self", ".", "free_chunks", ".", "__func__", ".", "__name__", ",", "self", ".", "__class__", ".", "__name__", ")", ")" ]
49.833333
25.5
def verify_path(self, mold_id_path): """ Lookup and verify path. """ try: path = self.lookup_path(mold_id_path) if not exists(path): raise KeyError except KeyError: raise_os_error(ENOENT) return path
[ "def", "verify_path", "(", "self", ",", "mold_id_path", ")", ":", "try", ":", "path", "=", "self", ".", "lookup_path", "(", "mold_id_path", ")", "if", "not", "exists", "(", "path", ")", ":", "raise", "KeyError", "except", "KeyError", ":", "raise_os_error",...
24.083333
12.583333
def fit_predict(self, X, y=None, **kwargs): """Compute cluster centroids and predict cluster index for each sample. Convenience method; equivalent to calling fit(X) followed by predict(X). """ return self.fit(X, **kwargs).predict(X, **kwargs)
[ "def", "fit_predict", "(", "self", ",", "X", ",", "y", "=", "None", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "fit", "(", "X", ",", "*", "*", "kwargs", ")", ".", "predict", "(", "X", ",", "*", "*", "kwargs", ")" ]
39.571429
15.571429
def extract_current_routine(page, stations): '''Extract current routine information from page. :param page: crawled page. :param stations: bus stations list. See `~extract_stations`. ''' current_routines = CURRENT_ROUTINE_PATTERN.findall(page.text()) if not current_routines: return ...
[ "def", "extract_current_routine", "(", "page", ",", "stations", ")", ":", "current_routines", "=", "CURRENT_ROUTINE_PATTERN", ".", "findall", "(", "page", ".", "text", "(", ")", ")", "if", "not", "current_routines", ":", "return", "terminal_station", "=", "stati...
33.538462
18.692308
def remove_observer(self, observer, callble=None): """ Either (if callble is None) remove all callables, which were added alongside observer, or remove callable `callble` which was added alongside the observer `observer`. """ to_remove = [] for poc in self...
[ "def", "remove_observer", "(", "self", ",", "observer", ",", "callble", "=", "None", ")", ":", "to_remove", "=", "[", "]", "for", "poc", "in", "self", ".", "observers", ":", "_", ",", "obs", ",", "clble", "=", "poc", "if", "callble", "is", "not", "...
35.944444
9.166667
def update_all(self): """ 在绘制之前,针对形变进行计算,通过设置openGL的属性来达到绘制出变形的图形 """ self.update_points() self.update_vertex_list() self.update_anchor() pyglet.gl.glLoadIdentity() # reset gl pyglet.gl.glLineWidth(self.line_width) pyglet.gl.glPointSize(self.point_size) ...
[ "def", "update_all", "(", "self", ")", ":", "self", ".", "update_points", "(", ")", "self", ".", "update_vertex_list", "(", ")", "self", ".", "update_anchor", "(", ")", "pyglet", ".", "gl", ".", "glLoadIdentity", "(", ")", "# reset gl", "pyglet", ".", "g...
31.266667
12.133333
def action(cls, action, game, rosters, inning_number, inning_id): """ action data :param action: action object(type:Beautifulsoup) :param game: MLBAM Game object :param rosters: Game Rosters :param inning_number: Inning Number :param inning_id: Inning Id(0:home 1:...
[ "def", "action", "(", "cls", ",", "action", ",", "game", ",", "rosters", ",", "inning_number", ",", "inning_id", ")", ":", "player_mlbid", "=", "MlbamUtil", ".", "get_attribute_stats", "(", "action", ",", "'player'", ",", "str", ",", "MlbamConst", ".", "UN...
48.711111
15.2
def experimental_designs(df, filepath=None): """ For each experimental design it plot all the corresponding experimental conditions in a different plot Parameters ---------- df: `pandas.DataFrame`_ DataFrame with columns `id` and starting with `TR:` filepath: str Absolute p...
[ "def", "experimental_designs", "(", "df", ",", "filepath", "=", "None", ")", ":", "axes", "=", "[", "]", "bw", "=", "matplotlib", ".", "colors", ".", "ListedColormap", "(", "[", "'white'", ",", "'black'", "]", ")", "cols", "=", "df", ".", "columns", ...
29.755556
28.688889
def get_banks_by_assessment_part(self, assessment_part_id): """Gets the ``Banks`` mapped to an ``AssessmentPart``. arg: assessment_part_id (osid.id.Id): ``Id`` of an ``AssessmentPart`` return: (osid.assessment.BankList) - list of banks raise: NotFound - ``assessment_...
[ "def", "get_banks_by_assessment_part", "(", "self", ",", "assessment_part_id", ")", ":", "mgr", "=", "self", ".", "_get_provider_manager", "(", "'ASSESSMENT'", ",", "local", "=", "True", ")", "lookup_session", "=", "mgr", ".", "get_bank_lookup_session", "(", "prox...
49.882353
20.411765
def _get_pkg_install_time(pkg, arch=None): ''' Return package install time, based on the /var/lib/dpkg/info/<package>.list :return: ''' iso_time = iso_time_t = None loc_root = '/var/lib/dpkg/info' if pkg is not None: locations = [] if arch is not None and arch != 'all': ...
[ "def", "_get_pkg_install_time", "(", "pkg", ",", "arch", "=", "None", ")", ":", "iso_time", "=", "iso_time_t", "=", "None", "loc_root", "=", "'/var/lib/dpkg/info'", "if", "pkg", "is", "not", "None", ":", "locations", "=", "[", "]", "if", "arch", "is", "n...
33.769231
24.923077
def spherical_galaxy_orbit( orbit_x, orbit_y, orbit_z, N_stars=100, sigma_r=1, orbit_visible=False, orbit_line_interpolate=5, N_star_orbits=10, color=[255, 220, 200], size_star=1, scatter_kwargs={}, ): """Create a fake galaxy around the points orbit_x/y/z with N_stars aro...
[ "def", "spherical_galaxy_orbit", "(", "orbit_x", ",", "orbit_y", ",", "orbit_z", ",", "N_stars", "=", "100", ",", "sigma_r", "=", "1", ",", "orbit_visible", "=", "False", ",", "orbit_line_interpolate", "=", "5", ",", "N_star_orbits", "=", "10", ",", "color",...
40
22.4
def _format_strings(self): """ we by definition have DO NOT have a TZ """ values = self.values if not isinstance(values, DatetimeIndex): values = DatetimeIndex(values) if self.formatter is not None and callable(self.formatter): return [self.formatter(x) for x i...
[ "def", "_format_strings", "(", "self", ")", ":", "values", "=", "self", ".", "values", "if", "not", "isinstance", "(", "values", ",", "DatetimeIndex", ")", ":", "values", "=", "DatetimeIndex", "(", "values", ")", "if", "self", ".", "formatter", "is", "no...
36.529412
19.235294
def assets(self, asset_type=None): """ Gets the assets of a Victim Args: asset_type: Yields: asset json """ if not self.can_update(): self._tcex.handle_error(910, [self.type]) if not asset_type: for a in self.tc_requests.vic...
[ "def", "assets", "(", "self", ",", "asset_type", "=", "None", ")", ":", "if", "not", "self", ".", "can_update", "(", ")", ":", "self", ".", "_tcex", ".", "handle_error", "(", "910", ",", "[", "self", ".", "type", "]", ")", "if", "not", "asset_type"...
31.957447
19.617021
def _record_offset(self): """Stores the current file pointer position""" offset = self.blob_file.tell() self.event_offsets.append(offset)
[ "def", "_record_offset", "(", "self", ")", ":", "offset", "=", "self", ".", "blob_file", ".", "tell", "(", ")", "self", ".", "event_offsets", ".", "append", "(", "offset", ")" ]
39.5
4.5
def _create_ring(self, nodes): """Generate a ketama compatible continuum/ring. """ for node_name, node_conf in nodes: for w in range(0, node_conf['vnodes'] * node_conf['weight']): self._distribution[node_name] += 1 self._ring[self.hashi('%s-%s' % (node...
[ "def", "_create_ring", "(", "self", ",", "nodes", ")", ":", "for", "node_name", ",", "node_conf", "in", "nodes", ":", "for", "w", "in", "range", "(", "0", ",", "node_conf", "[", "'vnodes'", "]", "*", "node_conf", "[", "'weight'", "]", ")", ":", "self...
47.875
12.125
def disable(self): """ Disable the plugin. Raises: :py:class:`docker.errors.APIError` If the server returns an error. """ self.client.api.disable_plugin(self.name) self.reload()
[ "def", "disable", "(", "self", ")", ":", "self", ".", "client", ".", "api", ".", "disable_plugin", "(", "self", ".", "name", ")", "self", ".", "reload", "(", ")" ]
23.727273
16.454545
def add_text_item(self, collection_uri, name, metadata, text, title=None): """Add a new item to a collection containing a single text document. The full text of the text document is specified as the text argument and will be stored with the same name as the item and a .txt exten...
[ "def", "add_text_item", "(", "self", ",", "collection_uri", ",", "name", ",", "metadata", ",", "text", ",", "title", "=", "None", ")", ":", "docname", "=", "name", "+", "\".txt\"", "if", "title", "is", "None", ":", "title", "=", "name", "metadata", "["...
36.333333
25.47619
def get_date_type(calendar): """Return the cftime date type for a given calendar name.""" try: import cftime except ImportError: raise ImportError( 'cftime is required for dates with non-standard calendars') else: calendars = { 'noleap': cftime.DatetimeNoL...
[ "def", "get_date_type", "(", "calendar", ")", ":", "try", ":", "import", "cftime", "except", "ImportError", ":", "raise", "ImportError", "(", "'cftime is required for dates with non-standard calendars'", ")", "else", ":", "calendars", "=", "{", "'noleap'", ":", "cft...
37.6
14.5
def display_hook(prompt, session, context, matches, longest_match_len): # type: (str, ShellSession, BundleContext, List[str], int) -> None """ Displays the available services matches and the service details :param prompt: Shell prompt string :param session: Current shell session...
[ "def", "display_hook", "(", "prompt", ",", "session", ",", "context", ",", "matches", ",", "longest_match_len", ")", ":", "# type: (str, ShellSession, BundleContext, List[str], int) -> None", "# Prepare a line pattern for each match (-1 for the trailing space)", "match_pattern", "=...
42.59375
19.03125
def osx_clipboard_get(): """ Get the clipboard's text on OS X. """ p = subprocess.Popen(['pbpaste', '-Prefer', 'ascii'], stdout=subprocess.PIPE) text, stderr = p.communicate() # Text comes in with old Mac \r line endings. Change them to \n. text = text.replace('\r', '\n') return text
[ "def", "osx_clipboard_get", "(", ")", ":", "p", "=", "subprocess", ".", "Popen", "(", "[", "'pbpaste'", ",", "'-Prefer'", ",", "'ascii'", "]", ",", "stdout", "=", "subprocess", ".", "PIPE", ")", "text", ",", "stderr", "=", "p", ".", "communicate", "(",...
34.666667
11.777778
def can_cast_to(v: Literal, dt: str) -> bool: """ 5.4.3 Datatype Constraints Determine whether "a value of the lexical form of n can be cast to the target type v per XPath Functions 3.1 section 19 Casting[xpath-functions]." """ # TODO: rdflib doesn't appear to pay any attention to lengths (e.g. 257...
[ "def", "can_cast_to", "(", "v", ":", "Literal", ",", "dt", ":", "str", ")", "->", "bool", ":", "# TODO: rdflib doesn't appear to pay any attention to lengths (e.g. 257 is a valid XSD.byte)", "return", "v", ".", "value", "is", "not", "None", "and", "Literal", "(", "s...
52
26.875
def private_key(self, s): """ Parse text as some kind of private key. Return a subclass of :class:`Key <pycoin.key.Key>`, or None. """ s = parseable_str(s) for f in [self.wif, self.secret_exponent]: v = f(s) if v: return v
[ "def", "private_key", "(", "self", ",", "s", ")", ":", "s", "=", "parseable_str", "(", "s", ")", "for", "f", "in", "[", "self", ".", "wif", ",", "self", ".", "secret_exponent", "]", ":", "v", "=", "f", "(", "s", ")", "if", "v", ":", "return", ...
30.1
13.1
def file_handles(self) -> Iterable[IO[str]]: """Generates all file handles represented by the analysis. Callee owns file handle and closes it when the next is yielded or the generator ends. """ if self.file_handle: yield self.file_handle self.file_handle.c...
[ "def", "file_handles", "(", "self", ")", "->", "Iterable", "[", "IO", "[", "str", "]", "]", ":", "if", "self", ".", "file_handle", ":", "yield", "self", ".", "file_handle", "self", ".", "file_handle", ".", "close", "(", ")", "self", ".", "file_handle",...
36.769231
9.923077
def random_markov_chain(n, k=None, sparse=False, random_state=None): """ Return a randomly sampled MarkovChain instance with n states, where each state has k states with positive transition probability. Parameters ---------- n : scalar(int) Number of states. k : scalar(int), option...
[ "def", "random_markov_chain", "(", "n", ",", "k", "=", "None", ",", "sparse", "=", "False", ",", "random_state", "=", "None", ")", ":", "P", "=", "random_stochastic_matrix", "(", "n", ",", "k", ",", "sparse", ",", "format", "=", "'csr'", ",", "random_s...
33.5
23.152174
def ec2_vpc_subnets(self, lookup, default=None): """ Args: lookup - the friendly name of the VPC whose subnets we want Returns: A comma-separated list of all subnets in use in the named VPC or default/None if no match found """ vpc_id = self.ec2_vpc_vpc_id(lookup) if vpc_id is None: ...
[ "def", "ec2_vpc_subnets", "(", "self", ",", "lookup", ",", "default", "=", "None", ")", ":", "vpc_id", "=", "self", ".", "ec2_vpc_vpc_id", "(", "lookup", ")", "if", "vpc_id", "is", "None", ":", "return", "default", "subnets", "=", "EFAwsResolver", ".", "...
37.095238
21.190476
def _extract_header_number(lines): """ Extracts the number of header lines from the second line of the ODF file """ pair = _extract_header_value(lines[1]) value_list = list(pair.values()) return int(value_list[0])
[ "def", "_extract_header_number", "(", "lines", ")", ":", "pair", "=", "_extract_header_value", "(", "lines", "[", "1", "]", ")", "value_list", "=", "list", "(", "pair", ".", "values", "(", ")", ")", "return", "int", "(", "value_list", "[", "0", "]", ")...
33
8.428571
def srfnrm(method, target, et, fixref, srfpts): """ Map array of surface points on a specified target body to the corresponding unit length outward surface normal vectors. The surface of the target body may be represented by a triaxial ellipsoid or by topographic data provided by DSK files. ...
[ "def", "srfnrm", "(", "method", ",", "target", ",", "et", ",", "fixref", ",", "srfpts", ")", ":", "method", "=", "stypes", ".", "stringToCharP", "(", "method", ")", "target", "=", "stypes", ".", "stringToCharP", "(", "target", ")", "et", "=", "ctypes",...
39.34375
14.03125
def update_appt(self, complex: str, house: str, price: str, square: str, id: str, **kwargs): """ Update existing appartment """ self.check_house(complex, house) kwargs['price'] = self._format_decimal(price) kwargs['square'] = self._format_decimal(square) self.pu...
[ "def", "update_appt", "(", "self", ",", "complex", ":", "str", ",", "house", ":", "str", ",", "price", ":", "str", ",", "square", ":", "str", ",", "id", ":", "str", ",", "*", "*", "kwargs", ")", ":", "self", ".", "check_house", "(", "complex", ",...
35.4375
18.5625
def flatten_nested_hash(hash_table): """ Flatten nested dictionary for GET / POST / DELETE API request """ def flatten(hash_table, brackets=True): f = {} for key, value in hash_table.items(): _key = '[' + str(key) + ']' if brackets else str(key) if isinstance(valu...
[ "def", "flatten_nested_hash", "(", "hash_table", ")", ":", "def", "flatten", "(", "hash_table", ",", "brackets", "=", "True", ")", ":", "f", "=", "{", "}", "for", "key", ",", "value", "in", "hash_table", ".", "items", "(", ")", ":", "_key", "=", "'['...
35.952381
9.571429
def report_exception(self, filename, exc): """ This method is used when self.parser raises an Exception so that we can report a customized :class:`EventReport` object with info the exception. """ # Build fake event. event = AbinitError(src_file="Unknown", src_line=0, mess...
[ "def", "report_exception", "(", "self", ",", "filename", ",", "exc", ")", ":", "# Build fake event.", "event", "=", "AbinitError", "(", "src_file", "=", "\"Unknown\"", ",", "src_line", "=", "0", ",", "message", "=", "str", "(", "exc", ")", ")", "return", ...
47.375
17.875
def safe_listdir(path): """ Attempt to list contents of path, but suppress some exceptions. """ try: return os.listdir(path) except (PermissionError, NotADirectoryError): pass except OSError as e: # Ignore the directory if does not exist, not a directory or # perm...
[ "def", "safe_listdir", "(", "path", ")", ":", "try", ":", "return", "os", ".", "listdir", "(", "path", ")", "except", "(", "PermissionError", ",", "NotADirectoryError", ")", ":", "pass", "except", "OSError", "as", "e", ":", "# Ignore the directory if does not ...
31
18.684211
def parse_headers(content_disposition, location=None, relaxed=False): """Build a ContentDisposition from header values. """ LOGGER.debug( 'Content-Disposition %r, Location %r', content_disposition, location) if content_disposition is None: return ContentDisposition(location=location) ...
[ "def", "parse_headers", "(", "content_disposition", ",", "location", "=", "None", ",", "relaxed", "=", "False", ")", ":", "LOGGER", ".", "debug", "(", "'Content-Disposition %r, Location %r'", ",", "content_disposition", ",", "location", ")", "if", "content_dispositi...
44.517241
22.517241
def _get_bounds(self): ''' Return cached bounds of this Grob. If bounds are not cached, render to a meta surface, and keep the meta surface and bounds cached. ''' if self._bounds: return self._bounds record_surface = cairo.RecordingSurface(cairo.CONTE...
[ "def", "_get_bounds", "(", "self", ")", ":", "if", "self", ".", "_bounds", ":", "return", "self", ".", "_bounds", "record_surface", "=", "cairo", ".", "RecordingSurface", "(", "cairo", ".", "CONTENT_COLOR_ALPHA", ",", "(", "-", "1", ",", "-", "1", ",", ...
33.2
20
def _collect_data(directory, input_ext, target_ext): """Traverses directory collecting input and target files.""" # Directory from string to tuple pair of strings # key: the filepath to a datafile including the datafile's basename. Example, # if the datafile was "/path/to/datafile.wav" then the key would be ...
[ "def", "_collect_data", "(", "directory", ",", "input_ext", ",", "target_ext", ")", ":", "# Directory from string to tuple pair of strings", "# key: the filepath to a datafile including the datafile's basename. Example,", "# if the datafile was \"/path/to/datafile.wav\" then the key would ...
48.736842
14.631579
def fw_hex_to_int(hex_str, words): """Unpack hex string into integers. Use little-endian and unsigned int format. Specify number of words to unpack with argument words. """ return struct.unpack('<{}H'.format(words), binascii.unhexlify(hex_str))
[ "def", "fw_hex_to_int", "(", "hex_str", ",", "words", ")", ":", "return", "struct", ".", "unpack", "(", "'<{}H'", ".", "format", "(", "words", ")", ",", "binascii", ".", "unhexlify", "(", "hex_str", ")", ")" ]
37
17.571429
def fit_multinest(self, n_live_points=1000, basename='chains/single-', verbose=True, refit=False, overwrite=False, **kwargs): """ Fits model using MultiNest, via pymultinest. :param n_live_points: Number of live points to use for MultiNe...
[ "def", "fit_multinest", "(", "self", ",", "n_live_points", "=", "1000", ",", "basename", "=", "'chains/single-'", ",", "verbose", "=", "True", ",", "refit", "=", "False", ",", "overwrite", "=", "False", ",", "*", "*", "kwargs", ")", ":", "folder", "=", ...
36.342466
18.479452