text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def parallel_check(vec1, vec2): """Checks whether two vectors are parallel OR anti-parallel. Vectors must be of the same dimension. Parameters ---------- vec1 length-R |npfloat_| -- First vector to compare vec2 length-R |npfloat_| -- Second vector to compare ...
[ "def", "parallel_check", "(", "vec1", ",", "vec2", ")", ":", "# Imports", "from", ".", ".", "const", "import", "PRM", "import", "numpy", "as", "np", "# Initialize False", "par", "=", "False", "# Shape check", "for", "n", ",", "v", "in", "enumerate", "(", ...
22.1875
22.583333
def show_vpnservice(vpnservice, profile=None, **kwargs): ''' Fetches information of a specific VPN service CLI Example: .. code-block:: bash salt '*' neutron.show_vpnservice vpnservice-name :param vpnservice: ID or name of vpn service to look up :param profile: Profile to build on (O...
[ "def", "show_vpnservice", "(", "vpnservice", ",", "profile", "=", "None", ",", "*", "*", "kwargs", ")", ":", "conn", "=", "_auth", "(", "profile", ")", "return", "conn", ".", "show_vpnservice", "(", "vpnservice", ",", "*", "*", "kwargs", ")" ]
27.375
23
def maybedotted(name): """Resolve dotted names: .. code-block:: python >>> maybedotted('irc3.config') <module 'irc3.config' from '...'> >>> maybedotted('irc3.utils.IrcString') <class 'irc3.utils.IrcString'> .. """ if not name: raise LookupError( ...
[ "def", "maybedotted", "(", "name", ")", ":", "if", "not", "name", ":", "raise", "LookupError", "(", "'Not able to resolve %s'", "%", "name", ")", "if", "not", "hasattr", "(", "name", ",", "'__name__'", ")", ":", "try", ":", "mod", "=", "importlib", ".", ...
27.388889
14.25
def get_path(self, wd): """ Returns the path associated to WD, if WD is unknown it returns None. @param wd: Watch descriptor. @type wd: int @return: Path or None. @rtype: string or None """ watch_ = self._wmd.get(wd) if watch_ is not None: ...
[ "def", "get_path", "(", "self", ",", "wd", ")", ":", "watch_", "=", "self", ".", "_wmd", ".", "get", "(", "wd", ")", "if", "watch_", "is", "not", "None", ":", "return", "watch_", ".", "path" ]
27.666667
13.5
def b_getma(b): """Get masked array from input GDAL Band Parameters ---------- b : gdal.Band Input GDAL Band Returns ------- np.ma.array Masked array containing raster values """ b_ndv = get_ndv_b(b) #bma = np.ma.masked_equal(b.ReadAsArray(), b_ndv) ...
[ "def", "b_getma", "(", "b", ")", ":", "b_ndv", "=", "get_ndv_b", "(", "b", ")", "#bma = np.ma.masked_equal(b.ReadAsArray(), b_ndv)", "#This is more appropriate for float, handles precision issues", "bma", "=", "np", ".", "ma", ".", "masked_values", "(", "b", ".", "Rea...
24.166667
20.444444
def to_clipboard(self, excel=True, sep=None, **kwargs): r""" Copy object to the system clipboard. Write a text representation of object to the system clipboard. This can be pasted into Excel, for example. Parameters ---------- excel : bool, default True ...
[ "def", "to_clipboard", "(", "self", ",", "excel", "=", "True", ",", "sep", "=", "None", ",", "*", "*", "kwargs", ")", ":", "from", "pandas", ".", "io", "import", "clipboards", "clipboards", ".", "to_clipboard", "(", "self", ",", "excel", "=", "excel", ...
31.25
22.660714
def bulk_query_file(self, path, *multiparams): """Like Database.bulk_query, but takes a filename to load a query from.""" with self.get_connection() as conn: conn.bulk_query_file(path, *multiparams)
[ "def", "bulk_query_file", "(", "self", ",", "path", ",", "*", "multiparams", ")", ":", "with", "self", ".", "get_connection", "(", ")", "as", "conn", ":", "conn", ".", "bulk_query_file", "(", "path", ",", "*", "multiparams", ")" ]
44.6
12.2
def tdev(data, rate=1.0, data_type="phase", taus=None): """ Time deviation. Based on modified Allan variance. .. math:: \\sigma^2_{TDEV}( \\tau ) = { \\tau^2 \\over 3 } \\sigma^2_{MDEV}( \\tau ) Note that TDEV has a unit of seconds. Parameters ---------- data: np.arra...
[ "def", "tdev", "(", "data", ",", "rate", "=", "1.0", ",", "data_type", "=", "\"phase\"", ",", "taus", "=", "None", ")", ":", "phase", "=", "input_to_phase", "(", "data", ",", "rate", ",", "data_type", ")", "(", "taus", ",", "md", ",", "mde", ",", ...
28.787234
19.468085
def _json_pretty_print(self, content): """ Pretty print a JSON object ``content`` JSON object to pretty print """ temp = json.loads(content) return json.dumps( temp, sort_keys=True, indent=4, separators=( '...
[ "def", "_json_pretty_print", "(", "self", ",", "content", ")", ":", "temp", "=", "json", ".", "loads", "(", "content", ")", "return", "json", ".", "dumps", "(", "temp", ",", "sort_keys", "=", "True", ",", "indent", "=", "4", ",", "separators", "=", "...
23.785714
13.214286
def _sync_from_disk(self): """Read any changes made on disk to this Refpkg. This is necessary if other programs are making changes to the Refpkg on disk and your program must be synchronized to them. """ try: fobj = self.open_manifest('r') except IOError as ...
[ "def", "_sync_from_disk", "(", "self", ")", ":", "try", ":", "fobj", "=", "self", ".", "open_manifest", "(", "'r'", ")", "except", "IOError", "as", "e", ":", "if", "e", ".", "errno", "==", "errno", ".", "ENOENT", ":", "raise", "ValueError", "(", "\"c...
32.954545
18.090909
def run_on_opencv_image(self, image): """ Arguments: image (np.ndarray): an image as returned by OpenCV Returns: prediction (BoxList): the detected objects. Additional information of the detection properties can be found in the fields of t...
[ "def", "run_on_opencv_image", "(", "self", ",", "image", ")", ":", "predictions", "=", "self", ".", "compute_prediction", "(", "image", ")", "top_predictions", "=", "self", ".", "select_top_predictions", "(", "predictions", ")", "result", "=", "image", ".", "c...
39.958333
20.041667
def keep_retrain(nkeep, X_train, y_train, X_test, y_test, attr_test, model_generator, metric, trained_model, random_state): """ The model is retrained for each test sample with the non-important features set to a constant. If you want to know how important a set of features is you can ask how the model would b...
[ "def", "keep_retrain", "(", "nkeep", ",", "X_train", ",", "y_train", ",", "X_test", ",", "y_test", ",", "attr_test", ",", "model_generator", ",", "metric", ",", "trained_model", ",", "random_state", ")", ":", "warnings", ".", "warn", "(", "\"The retrain based ...
48.984127
27.190476
def update_alert(self, alert): '''**Description** Update a modified threshold-based alert. **Arguments** - **alert**: one modified alert object of the same format as those in the list returned by :func:`~SdcClient.get_alerts`. **Success Return Value** The up...
[ "def", "update_alert", "(", "self", ",", "alert", ")", ":", "if", "'id'", "not", "in", "alert", ":", "return", "[", "False", ",", "\"Invalid alert format\"", "]", "res", "=", "requests", ".", "put", "(", "self", ".", "url", "+", "'/api/alerts/'", "+", ...
41.388889
32.722222
def get_user_roles(self, user, url_prefix, auth, session, send_opts): """Get roles associated with the given user. Args: user (string): User name. url_prefix (string): Protocol + host such as https://api.theboss.io auth (string): Token to send in the request header. ...
[ "def", "get_user_roles", "(", "self", ",", "user", ",", "url_prefix", ",", "auth", ",", "session", ",", "send_opts", ")", ":", "req", "=", "self", ".", "get_user_role_request", "(", "'GET'", ",", "'application/json'", ",", "url_prefix", ",", "auth", ",", "...
37.068966
21.241379
def import_csv(self, file_name='*', folder_name='.', head_row=0, index_col=0, convert_col=True, concat_files=False): """ Imports csv file(s) and stores the result in data. Note ---- 1. If folder exists out of current directory, folder_name should contain correct regex ...
[ "def", "import_csv", "(", "self", ",", "file_name", "=", "'*'", ",", "folder_name", "=", "'.'", ",", "head_row", "=", "0", ",", "index_col", "=", "0", ",", "convert_col", "=", "True", ",", "concat_files", "=", "False", ")", ":", "# Import a specific or all...
41.25
23.966667
def rebinned(self, bins, axis=0): """ Return a new rebinned histogram Parameters ---------- bins : int, tuple, or iterable If ``bins`` is an int, then return a histogram that is rebinned by grouping N=``bins`` bins together along the axis ``axis``. ...
[ "def", "rebinned", "(", "self", ",", "bins", ",", "axis", "=", "0", ")", ":", "ndim", "=", "self", ".", "GetDimension", "(", ")", "if", "axis", ">=", "ndim", ":", "raise", "ValueError", "(", "\"axis must be less than the dimensionality of the histogram\"", ")"...
37.655172
15.632184
def warnpy3k(message, category=None, stacklevel=1): """Issue a deprecation warning for Python 3.x related changes. Warnings are omitted unless Python is started with the -3 option. """ if sys.py3kwarning: if category is None: category = DeprecationWarning warn(message, categ...
[ "def", "warnpy3k", "(", "message", ",", "category", "=", "None", ",", "stacklevel", "=", "1", ")", ":", "if", "sys", ".", "py3kwarning", ":", "if", "category", "is", "None", ":", "category", "=", "DeprecationWarning", "warn", "(", "message", ",", "catego...
36.666667
12.777778
def mp_check_impl(self, process_count): """ a multiprocessing-enabled check implementation. Will create up to process_count helper processes and use them to perform the DistJarReport and DistClassReport actions. """ from multiprocessing import Process, Queue opt...
[ "def", "mp_check_impl", "(", "self", ",", "process_count", ")", ":", "from", "multiprocessing", "import", "Process", ",", "Queue", "options", "=", "self", ".", "reporter", ".", "options", "# this is the function that will be run in a separate process,", "# which will hand...
36.952381
20.190476
def get_es_ids(self): """ reads all the elasticssearch ids for an index """ search = self.search.source(['uri']).sort(['uri']) es_ids = [item.meta.id for item in search.scan()] return es_ids
[ "def", "get_es_ids", "(", "self", ")", ":", "search", "=", "self", ".", "search", ".", "source", "(", "[", "'uri'", "]", ")", ".", "sort", "(", "[", "'uri'", "]", ")", "es_ids", "=", "[", "item", ".", "meta", ".", "id", "for", "item", "in", "se...
33.142857
12.285714
def cla_adder(a, b, cin=0, la_unit_len=4): """ Carry Lookahead Adder :param int la_unit_len: the length of input that every unit processes A Carry LookAhead Adder is an adder that is faster than a ripple carry adder, as it calculates the carry bits faster. It is not as fast as a Kogge-Stone add...
[ "def", "cla_adder", "(", "a", ",", "b", ",", "cin", "=", "0", ",", "la_unit_len", "=", "4", ")", ":", "a", ",", "b", "=", "pyrtl", ".", "match_bitwidth", "(", "a", ",", "b", ")", "if", "len", "(", "a", ")", "<=", "la_unit_len", ":", "sum", ",...
41
16.882353
def _load_region(self, acct_id, region_name, path): """load config from a single per-region subdirectory of an account""" lim_path = os.path.join(path, 'limit_overrides.json') thresh_path = os.path.join(path, 'threshold_overrides.json') res = {'limit_overrides': {}, 'threshold_overrides'...
[ "def", "_load_region", "(", "self", ",", "acct_id", ",", "region_name", ",", "path", ")", ":", "lim_path", "=", "os", ".", "path", ".", "join", "(", "path", ",", "'limit_overrides.json'", ")", "thresh_path", "=", "os", ".", "path", ".", "join", "(", "p...
56
13.75
def add(self, dn: str, mod_list: dict) -> None: """ Add a DN to the LDAP database; See ldap module. Doesn't return a result if transactions enabled. """ return self._do_with_retry(lambda obj: obj.add_s(dn, mod_list))
[ "def", "add", "(", "self", ",", "dn", ":", "str", ",", "mod_list", ":", "dict", ")", "->", "None", ":", "return", "self", ".", "_do_with_retry", "(", "lambda", "obj", ":", "obj", ".", "add_s", "(", "dn", ",", "mod_list", ")", ")" ]
35.857143
17.857143
def get_nameserver_detail_output_show_nameserver_nameserver_ag_base_device(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") get_nameserver_detail = ET.Element("get_nameserver_detail") config = get_nameserver_detail output = ET.SubElement(get_names...
[ "def", "get_nameserver_detail_output_show_nameserver_nameserver_ag_base_device", "(", "self", ",", "*", "*", "kwargs", ")", ":", "config", "=", "ET", ".", "Element", "(", "\"config\"", ")", "get_nameserver_detail", "=", "ET", ".", "Element", "(", "\"get_nameserver_det...
54.466667
24.266667
def refresh_db(**kwargs): ''' Updates the package list - ``True``: Database updated successfully - ``False``: Problem updating database CLI Example: .. code-block:: bash salt '*' pkg.refresh_db ''' ret = {} cmd = ['apk', 'update'] call = __salt__['cmd.run_all'](cmd, ...
[ "def", "refresh_db", "(", "*", "*", "kwargs", ")", ":", "ret", "=", "{", "}", "cmd", "=", "[", "'apk'", ",", "'update'", "]", "call", "=", "__salt__", "[", "'cmd.run_all'", "]", "(", "cmd", ",", "output_loglevel", "=", "'trace'", ",", "python_shell", ...
22.5625
21.625
def parse_breakend(alt_str): """Parse breakend and return tuple with results, parameters for BreakEnd constructor """ arr = BREAKEND_PATTERN.split(alt_str) mate_chrom, mate_pos = arr[1].split(":", 1) mate_pos = int(mate_pos) if mate_chrom[0] == "<": mate_chrom = mate_chrom[1:-1] ...
[ "def", "parse_breakend", "(", "alt_str", ")", ":", "arr", "=", "BREAKEND_PATTERN", ".", "split", "(", "alt_str", ")", "mate_chrom", ",", "mate_pos", "=", "arr", "[", "1", "]", ".", "split", "(", "\":\"", ",", "1", ")", "mate_pos", "=", "int", "(", "m...
37.45
14.1
def authorized_handler(self, f): """ Decorator for the route that is used as the callback for authorizing with GitHub. This callback URL can be set in the settings for the app or passed in during authorization. """ @wraps(f) def decorated(*args, **kwargs): ...
[ "def", "authorized_handler", "(", "self", ",", "f", ")", ":", "@", "wraps", "(", "f", ")", "def", "decorated", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "'code'", "in", "request", ".", "args", ":", "data", "=", "self", ".", "_han...
35.533333
14.466667
def synchronizer(self): """ access synchronizer """ if not self.synchronizer_path or self.synchronizer_path == 'None' or not self.layer: return False # ensure data is up to date if (self._synchronizer is not None and self._synchronizer_class.__name__ not in self.synchronizer_...
[ "def", "synchronizer", "(", "self", ")", ":", "if", "not", "self", ".", "synchronizer_path", "or", "self", ".", "synchronizer_path", "==", "'None'", "or", "not", "self", ".", "layer", ":", "return", "False", "# ensure data is up to date", "if", "(", "self", ...
48.583333
18
def main(): """The main entry point to alot. It parses the command line and prepares for the user interface main loop to run.""" options, command = parser() # logging root_logger = logging.getLogger() for log_handler in root_logger.handlers: root_logger.removeHandler(log_handler) r...
[ "def", "main", "(", ")", ":", "options", ",", "command", "=", "parser", "(", ")", "# logging", "root_logger", "=", "logging", ".", "getLogger", "(", ")", "for", "log_handler", "in", "root_logger", ".", "handlers", ":", "root_logger", ".", "removeHandler", ...
34.631579
17.438596
def facebook_request(self, path, callback, access_token=None, post_args=None, **args): """Fetches the given relative API path, e.g., "/btaylor/picture" If the request is a POST, post_args should be provided. Query string arguments should be given as keyword arguments....
[ "def", "facebook_request", "(", "self", ",", "path", ",", "callback", ",", "access_token", "=", "None", ",", "post_args", "=", "None", ",", "*", "*", "args", ")", ":", "url", "=", "\"https://graph.facebook.com\"", "+", "path", "all_args", "=", "{", "}", ...
44.530612
18.673469
def google(rest): "Look up a phrase on google" API_URL = 'https://www.googleapis.com/customsearch/v1?' try: key = pmxbot.config['Google API key'] except KeyError: return "Configure 'Google API key' in config" # Use a custom search that searches everything normally # http://stackoverflow.com/a/11206266/70170 ...
[ "def", "google", "(", "rest", ")", ":", "API_URL", "=", "'https://www.googleapis.com/customsearch/v1?'", "try", ":", "key", "=", "pmxbot", ".", "config", "[", "'Google API key'", "]", "except", "KeyError", ":", "return", "\"Configure 'Google API key' in config\"", "# ...
27.291667
17.875
def GET(self, courseid, taskid, path): # pylint: disable=arguments-differ """ GET request """ try: course = self.course_factory.get_course(courseid) if not self.user_manager.course_is_open_to_user(course): return self.template_helper.get_renderer().course_unavail...
[ "def", "GET", "(", "self", ",", "courseid", ",", "taskid", ",", "path", ")", ":", "# pylint: disable=arguments-differ", "try", ":", "course", "=", "self", ".", "course_factory", ".", "get_course", "(", "courseid", ")", "if", "not", "self", ".", "user_manager...
41.058824
24.205882
def OnFont(self, event): """Check event handler""" font_data = wx.FontData() # Disable color chooser on Windows font_data.EnableEffects(False) if self.chosen_font: font_data.SetInitialFont(self.chosen_font) dlg = wx.FontDialog(self, font_data) if ...
[ "def", "OnFont", "(", "self", ",", "event", ")", ":", "font_data", "=", "wx", ".", "FontData", "(", ")", "# Disable color chooser on Windows", "font_data", ".", "EnableEffects", "(", "False", ")", "if", "self", ".", "chosen_font", ":", "font_data", ".", "Set...
26.846154
19.192308
def history_view(self, request, object_id, extra_context=None): from django.template.response import TemplateResponse from django.contrib.admin.options import get_content_type_for_model from django.contrib.admin.utils import unquote from django.core.exceptions import PermissionDenied ...
[ "def", "history_view", "(", "self", ",", "request", ",", "object_id", ",", "extra_context", "=", "None", ")", ":", "from", "django", ".", "template", ".", "response", "import", "TemplateResponse", "from", "django", ".", "contrib", ".", "admin", ".", "options...
42.630435
20.282609
async def start(self): """ This method opens an IP connection on the IP device :return: None """ try: self.reader, self.writer = await asyncio.open_connection( self.ip_address, self.port, loop=self.loop) except OSError: print("Can'...
[ "async", "def", "start", "(", "self", ")", ":", "try", ":", "self", ".", "reader", ",", "self", ".", "writer", "=", "await", "asyncio", ".", "open_connection", "(", "self", ".", "ip_address", ",", "self", ".", "port", ",", "loop", "=", "self", ".", ...
31.166667
19.166667
def create_cluster(kwargs=None, call=None): ''' Create a new cluster under the specified datacenter in this VMware environment CLI Example: .. code-block:: bash salt-cloud -f create_cluster my-vmware-config name="myNewCluster" datacenter="datacenterName" ''' if call != 'function': ...
[ "def", "create_cluster", "(", "kwargs", "=", "None", ",", "call", "=", "None", ")", ":", "if", "call", "!=", "'function'", ":", "raise", "SaltCloudSystemExit", "(", "'The create_cluster function must be called with '", "'-f or --function.'", ")", "cluster_name", "=", ...
32.223881
24.492537
def _post(self, *args, **kwargs): """Wrapper around Requests for POST requests Returns: Response: A Requests Response object """ if 'timeout' not in kwargs: kwargs['timeout'] = self.timeout req = self.session.post(*args, **kwargs) ...
[ "def", "_post", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "'timeout'", "not", "in", "kwargs", ":", "kwargs", "[", "'timeout'", "]", "=", "self", ".", "timeout", "req", "=", "self", ".", "session", ".", "post", "(", "...
24.615385
16.230769
def _dimensionSelectedInComboBox(self, dimNr): """ Returns True if the dimension is selected in one of the combo boxes. """ for combobox in self._comboBoxes: if self._comboBoxDimensionIndex(combobox) == dimNr: return True return False
[ "def", "_dimensionSelectedInComboBox", "(", "self", ",", "dimNr", ")", ":", "for", "combobox", "in", "self", ".", "_comboBoxes", ":", "if", "self", ".", "_comboBoxDimensionIndex", "(", "combobox", ")", "==", "dimNr", ":", "return", "True", "return", "False" ]
41.142857
9
def generate_with_pattern(self, pattern=None): """ Algorithm that creates the list based on a given pattern The pattern must be like string format patter: e.g: a@b will match an 'a' follow by any character follow by a 'b' """ curlen = utils.get_pattern_length(pat...
[ "def", "generate_with_pattern", "(", "self", ",", "pattern", "=", "None", ")", ":", "curlen", "=", "utils", ".", "get_pattern_length", "(", "pattern", ")", "if", "curlen", ">", "0", ":", "str_generator", "=", "product", "(", "self", ".", "charset", ",", ...
39
12.066667
def get_trending_daily_not_starred(self): """Gets trending repositories NOT starred by user :return: List of daily-trending repositories which are not starred """ trending_daily = self.get_trending_daily() # repos trending daily starred_repos = self.get_starred_repos() # repos ...
[ "def", "get_trending_daily_not_starred", "(", "self", ")", ":", "trending_daily", "=", "self", ".", "get_trending_daily", "(", ")", "# repos trending daily", "starred_repos", "=", "self", ".", "get_starred_repos", "(", ")", "# repos starred by user", "repos_list", "=", ...
37.923077
17
def has_unitary(val: Any) -> bool: """Returns whether the value has a unitary matrix representation. Returns: If `val` has a _has_unitary_ method and its result is not NotImplemented, that result is returned. Otherwise, if `val` is a cirq.Gate or cirq.Operation, a decomposition is attem...
[ "def", "has_unitary", "(", "val", ":", "Any", ")", "->", "bool", ":", "from", "cirq", ".", "protocols", ".", "decompose", "import", "(", "decompose_once", ",", "decompose_once_with_qubits", ")", "# HACK: Avoids circular dependencies.", "from", "cirq", "import", "G...
43.619048
19.52381
def volatility(data, period): """ Volatility. Formula: SDt / SVt """ volatility = sd(data, period) / sv(data, period) return volatility
[ "def", "volatility", "(", "data", ",", "period", ")", ":", "volatility", "=", "sd", "(", "data", ",", "period", ")", "/", "sv", "(", "data", ",", "period", ")", "return", "volatility" ]
17.333333
18
def native(cls, value): """ Converts a CF* object into its python equivalent :param value: The CF* object to convert :return: The native python object """ type_id = CoreFoundation.CFGetTypeID(value) if type_id in cls._native_map: ...
[ "def", "native", "(", "cls", ",", "value", ")", ":", "type_id", "=", "CoreFoundation", ".", "CFGetTypeID", "(", "value", ")", "if", "type_id", "in", "cls", ".", "_native_map", ":", "return", "cls", ".", "_native_map", "[", "type_id", "]", "(", "value", ...
24.1875
16.8125
def write_molecule(filename, format=None): '''Write the system displayed in a file as a molecule.''' datafile(filename, format=format, mode='w').write('molecule',current_system())
[ "def", "write_molecule", "(", "filename", ",", "format", "=", "None", ")", ":", "datafile", "(", "filename", ",", "format", "=", "format", ",", "mode", "=", "'w'", ")", ".", "write", "(", "'molecule'", ",", "current_system", "(", ")", ")" ]
49.25
10.75
def f_get_groups(self, copy=True): """Returns a dictionary of groups hanging immediately below this group. :param copy: Whether the group's original dictionary or a shallow copy is returned. If you want the real dictionary please do not modify it at all! :returns: Dict...
[ "def", "f_get_groups", "(", "self", ",", "copy", "=", "True", ")", ":", "if", "copy", ":", "return", "self", ".", "_groups", ".", "copy", "(", ")", "else", ":", "return", "self", ".", "_groups" ]
29.066667
21.866667
def add_dummy_scores(iteratable, score=0): """Add zero scores to all sequences""" for seq in iteratable: seq.letter_annotations["phred_quality"] = (score,)*len(seq) yield seq
[ "def", "add_dummy_scores", "(", "iteratable", ",", "score", "=", "0", ")", ":", "for", "seq", "in", "iteratable", ":", "seq", ".", "letter_annotations", "[", "\"phred_quality\"", "]", "=", "(", "score", ",", ")", "*", "len", "(", "seq", ")", "yield", "...
38.8
13.2
def _get_ancestors_of(self, obs_nodes_list): """ Returns a list of all ancestors of all the observed nodes. Parameters ---------- obs_nodes_list: string, list-type name of all the observed nodes """ if not obs_nodes_list: return set() ...
[ "def", "_get_ancestors_of", "(", "self", ",", "obs_nodes_list", ")", ":", "if", "not", "obs_nodes_list", ":", "return", "set", "(", ")", "return", "set", "(", "obs_nodes_list", ")", "|", "set", "(", "self", ".", "parent_node", ")" ]
30.25
13.416667
def encode_params(self, data=None, **kwargs): """ Build the body for a text/plain request. Will successfully encode parameters when passed as a dict or a list of 2-tuples. Order is retained if data is a list of 2-tuples but arbitrary if parameters are supplied as a dict. ...
[ "def", "encode_params", "(", "self", ",", "data", "=", "None", ",", "*", "*", "kwargs", ")", ":", "charset", "=", "kwargs", ".", "get", "(", "\"charset\"", ",", "self", ".", "charset", ")", "collection_format", "=", "kwargs", ".", "get", "(", "\"collec...
49.2
23.511111
def add_comment(self, body, allow_create=False, allow_hashes=False, summary=None): "Implement as required by parent to store comment in CSV file." if allow_hashes: raise ValueError('allow_hashes not implemented for %s yet' % ( self.__class__.__name__)) ...
[ "def", "add_comment", "(", "self", ",", "body", ",", "allow_create", "=", "False", ",", "allow_hashes", "=", "False", ",", "summary", "=", "None", ")", ":", "if", "allow_hashes", ":", "raise", "ValueError", "(", "'allow_hashes not implemented for %s yet'", "%", ...
44.684211
17.210526
def exists(self, record_key): ''' a method to determine if a record exists in collection :param record_key: string with key of record :return: boolean reporting status ''' title = '%s.exists' % self.__class__.__name__ # validate...
[ "def", "exists", "(", "self", ",", "record_key", ")", ":", "title", "=", "'%s.exists'", "%", "self", ".", "__class__", ".", "__name__", "# validate inputs\r", "input_fields", "=", "{", "'record_key'", ":", "record_key", "}", "for", "key", ",", "value", "in",...
30.185185
20.407407
def _write(self, stream, text, byte_order): ''' Write the data to a PLY file. ''' if text: self._write_txt(stream) else: if self._have_list: # There are list properties, so serialization is # slightly complicated. ...
[ "def", "_write", "(", "self", ",", "stream", ",", "text", ",", "byte_order", ")", ":", "if", "text", ":", "self", ".", "_write_txt", "(", "stream", ")", "else", ":", "if", "self", ".", "_have_list", ":", "# There are list properties, so serialization is", "#...
34.764706
17.823529
def bls_parallel_pfind( times, mags, errs, magsarefluxes=False, startp=0.1, # by default, search from 0.1 d to... endp=100.0, # ... 100.0 d -- don't search full timebase stepsize=1.0e-4, mintransitduration=0.01, # minimum transit length in phase maxtransitdurat...
[ "def", "bls_parallel_pfind", "(", "times", ",", "mags", ",", "errs", ",", "magsarefluxes", "=", "False", ",", "startp", "=", "0.1", ",", "# by default, search from 0.1 d to...", "endp", "=", "100.0", ",", "# ... 100.0 d -- don't search full timebase", "stepsize", "=",...
39.589623
21.679245
def encodeIntoArray(self, inputData, output): """ See `nupic.encoders.base.Encoder` for more information. :param: inputData (tuple) Contains speed (float), longitude (float), latitude (float), altitude (float) :param: output (numpy.array) Stores encoded SDR in this numpy ar...
[ "def", "encodeIntoArray", "(", "self", ",", "inputData", ",", "output", ")", ":", "altitude", "=", "None", "if", "len", "(", "inputData", ")", "==", "4", ":", "(", "speed", ",", "longitude", ",", "latitude", ",", "altitude", ")", "=", "inputData", "els...
40.529412
17.588235
def run(self): """ Main thread function. """ if not hasattr(self, 'queue'): raise RuntimeError("Audio queue is not intialized.") chunk = None channel = None self.keep_listening = True while self.keep_listening: if chunk is None: try: frame = self.queue.get(timeout=queue_timeout) chunk =...
[ "def", "run", "(", "self", ")", ":", "if", "not", "hasattr", "(", "self", ",", "'queue'", ")", ":", "raise", "RuntimeError", "(", "\"Audio queue is not intialized.\"", ")", "chunk", "=", "None", "channel", "=", "None", "self", ".", "keep_listening", "=", "...
22.814815
20.111111
def run_migrations_online(): """Run migrations in 'online' mode. In this scenario we need to create an Engine and associate a connection with the context. """ app_conf = dci_config.generate_conf() connectable = dci_config.get_engine(app_conf) with connectable.connect() as connection: ...
[ "def", "run_migrations_online", "(", ")", ":", "app_conf", "=", "dci_config", ".", "generate_conf", "(", ")", "connectable", "=", "dci_config", ".", "get_engine", "(", "app_conf", ")", "with", "connectable", ".", "connect", "(", ")", "as", "connection", ":", ...
29.117647
13.117647
def jump_search(arr,target): """Jump Search Worst-case Complexity: O(√n) (root(n)) All items in list must be sorted like binary search Find block that contains target value and search it linearly in that block It returns a first target value in array reference: https://en.w...
[ "def", "jump_search", "(", "arr", ",", "target", ")", ":", "n", "=", "len", "(", "arr", ")", "block_size", "=", "int", "(", "math", ".", "sqrt", "(", "n", ")", ")", "block_prev", "=", "0", "block", "=", "block_size", "# return -1 means that array doesn't...
26
19.763158
def inverse_transform(self, maps): """This function transforms from component masses to chirp mass and mass ratio. Parameters ---------- maps : a mapping object Examples -------- Convert a dict of numpy.array: >>> import numpy >>> from p...
[ "def", "inverse_transform", "(", "self", ",", "maps", ")", ":", "out", "=", "{", "}", "m1", "=", "maps", "[", "parameters", ".", "mass1", "]", "m2", "=", "maps", "[", "parameters", ".", "mass2", "]", "out", "[", "parameters", ".", "mchirp", "]", "=...
32.16129
19.258065
def AddAC(self, device_name, model_name): '''Convenience method to add an AC object You have to specify a device name which must be a valid part of an object path, e. g. "mock_ac", and an arbitrary model name. Please note that this does not set any global properties such as "on-battery". Retu...
[ "def", "AddAC", "(", "self", ",", "device_name", ",", "model_name", ")", ":", "path", "=", "'/org/freedesktop/UPower/devices/'", "+", "device_name", "self", ".", "AddObject", "(", "path", ",", "DEVICE_IFACE", ",", "{", "'PowerSupply'", ":", "dbus", ".", "Boole...
37.590909
23.954545
def calc_particle_group_region_size(s, region_size=40, max_mem=1e9, **kwargs): """ Finds the biggest region size for LM particle optimization with a given memory constraint. Input Parameters ---------------- s : :class:`peri.states.ImageState` The state with the particles ...
[ "def", "calc_particle_group_region_size", "(", "s", ",", "region_size", "=", "40", ",", "max_mem", "=", "1e9", ",", "*", "*", "kwargs", ")", ":", "region_size", "=", "np", ".", "array", "(", "region_size", ")", ".", "astype", "(", "'int'", ")", "def", ...
43.789474
20.736842
def from_iso6709(coordinates): """Parse ISO 6709 coordinate strings. This function will parse ISO 6709-1983(E) "Standard representation of latitude, longitude and altitude for geographic point locations" elements. Unfortunately, the standard is rather convoluted and this implementation is incomplet...
[ "def", "from_iso6709", "(", "coordinates", ")", ":", "matches", "=", "iso6709_matcher", ".", "match", "(", "coordinates", ")", "if", "matches", ":", "latitude", ",", "longitude", ",", "altitude", "=", "matches", ".", "groups", "(", ")", "else", ":", "raise...
41.131148
20.868852
def verify_quote(self, quote_id, extra): """Verifies that a quote order is valid. :: extras = { 'hardware': {'hostname': 'test', 'domain': 'testing.com'}, 'quantity': 2 } manager = ordering.OrderingManager(env.client) resu...
[ "def", "verify_quote", "(", "self", ",", "quote_id", ",", "extra", ")", ":", "container", "=", "self", ".", "generate_order_template", "(", "quote_id", ",", "extra", ")", "clean_container", "=", "{", "}", "# There are a few fields that wil cause exceptions in the XML ...
40.892857
26.071429
def append(self, point): """ appends a copy of the given point to this sequence """ point = Point(point) self._elements.append(point)
[ "def", "append", "(", "self", ",", "point", ")", ":", "point", "=", "Point", "(", "point", ")", "self", ".", "_elements", ".", "append", "(", "point", ")" ]
28
8.333333
def surfacemassLOS(self,d,l,deg=True,target=True, romberg=False,nsigma=None,relative=None): """ NAME: surfacemassLOS PURPOSE: evaluate the surface mass along the LOS given l and d INPUT: d - distance along the line of sight (ca...
[ "def", "surfacemassLOS", "(", "self", ",", "d", ",", "l", ",", "deg", "=", "True", ",", "target", "=", "True", ",", "romberg", "=", "False", ",", "nsigma", "=", "None", ",", "relative", "=", "None", ")", ":", "#Calculate R and phi", "if", "_APY_LOADED"...
26.163636
24.890909
def get_channel_access(self, channel=None, read_mode='volatile'): """Get channel access :param channel: number [1:7] :param read_mode: non_volatile = get non-volatile Channel Access volatile = get present volatile (active) setting of Channel Access :return: A Pyth...
[ "def", "get_channel_access", "(", "self", ",", "channel", "=", "None", ",", "read_mode", "=", "'volatile'", ")", ":", "if", "channel", "is", "None", ":", "channel", "=", "self", ".", "get_network_channel", "(", ")", "data", "=", "[", "]", "data", ".", ...
29.514286
17.342857
def panels(self): """ Add 2 panels to the figure, top for signal and bottom for gene models """ ax1 = self.fig.add_subplot(211) ax2 = self.fig.add_subplot(212, sharex=ax1) return (ax2, self.gene_panel), (ax1, self.signal_panel)
[ "def", "panels", "(", "self", ")", ":", "ax1", "=", "self", ".", "fig", ".", "add_subplot", "(", "211", ")", "ax2", "=", "self", ".", "fig", ".", "add_subplot", "(", "212", ",", "sharex", "=", "ax1", ")", "return", "(", "ax2", ",", "self", ".", ...
38.428571
13.571429
def _csv_temp(self, cursor, fieldnames): """Writes the rows of `cursor` in CSV format to a temporary file and returns the path to that file. :param cursor: database cursor containing data to be output :type cursor: `sqlite3.Cursor` :param fieldnames: row headings :type f...
[ "def", "_csv_temp", "(", "self", ",", "cursor", ",", "fieldnames", ")", ":", "temp_fd", ",", "temp_path", "=", "tempfile", ".", "mkstemp", "(", "text", "=", "True", ")", "with", "open", "(", "temp_fd", ",", "'w'", ",", "encoding", "=", "'utf-8'", ",", ...
38.066667
14.666667
def _spin_product(variables): """Create a bqm with a gap of 2 that represents the product of two variables. Note that spin-product requires an auxiliary variable. Args: variables (list): multiplier, multiplicand, product, aux Returns: :obj:`.BinaryQuadraticModel` """ ...
[ "def", "_spin_product", "(", "variables", ")", ":", "multiplier", ",", "multiplicand", ",", "product", ",", "aux", "=", "variables", "return", "BinaryQuadraticModel", "(", "{", "multiplier", ":", "-", ".5", ",", "multiplicand", ":", "-", ".5", ",", "product"...
36.259259
17.740741
def evaluate_at(self, *args, **parameter_specification): # pragma: no cover """ Evaluate the function at the given x(,y,z) for the provided parameters, explicitly provided as part of the parameter_specification keywords. :param *args: :param **parameter_specification: :...
[ "def", "evaluate_at", "(", "self", ",", "*", "args", ",", "*", "*", "parameter_specification", ")", ":", "# pragma: no cover", "# Set the parameters to the provided values", "for", "parameter", "in", "parameter_specification", ":", "self", ".", "_get_child", "(", "par...
33.625
24.375
def remove_plugins_without_parameters(self): """ This used to be handled in BuildRequest, but with REACTOR_CONFIG, osbs-client doesn't have enough information. """ # Compatibility code for dockerfile_content plugin self.remove_plugin('prebuild_plugins', PLUGIN_DOCKERFILE...
[ "def", "remove_plugins_without_parameters", "(", "self", ")", ":", "# Compatibility code for dockerfile_content plugin", "self", ".", "remove_plugin", "(", "'prebuild_plugins'", ",", "PLUGIN_DOCKERFILE_CONTENT_KEY", ",", "'dockerfile_content is deprecated, please remove from config'", ...
48.9
21.7
def find_cell_content(self, lines): """Parse cell till its end and set content, lines_to_next_cell. Return the position of next cell start""" cell_end_marker, next_cell_start, self.explicit_eoc = self.find_cell_end(lines) # Metadata to dict if self.metadata is None: ...
[ "def", "find_cell_content", "(", "self", ",", "lines", ")", ":", "cell_end_marker", ",", "next_cell_start", ",", "self", ".", "explicit_eoc", "=", "self", ".", "find_cell_end", "(", "lines", ")", "# Metadata to dict", "if", "self", ".", "metadata", "is", "None...
42.305085
22.610169
def encode_label(label_data): """Run encoding to encode the label into the CDF target. """ systole = label_data[:, 1] diastole = label_data[:, 2] systole_encode = np.array([ (x < np.arange(600)) for x in systole ], dtype=np.uint8) diastole_encode = np.array([ (x <...
[ "def", "encode_label", "(", "label_data", ")", ":", "systole", "=", "label_data", "[", ":", ",", "1", "]", "diastole", "=", "label_data", "[", ":", ",", "2", "]", "systole_encode", "=", "np", ".", "array", "(", "[", "(", "x", "<", "np", ".", "arang...
34.416667
8
def _check_error_response(response, query): """ check for default error messages and throw correct exception """ if "error" in response: http_error = ["HTTP request timed out.", "Pool queue is full"] geo_error = [ "Page coordinates unknown.", "One ...
[ "def", "_check_error_response", "(", "response", ",", "query", ")", ":", "if", "\"error\"", "in", "response", ":", "http_error", "=", "[", "\"HTTP request timed out.\"", ",", "\"Pool queue is full\"", "]", "geo_error", "=", "[", "\"Page coordinates unknown.\"", ",", ...
43.375
12
def configure(cls, global_, key, val): """ Update and save configuration value to file. """ # first retrieve current configuration scope = 'global' if global_ else 'local' if scope not in cls._conffiles: cls._conffiles[scope] = {} config = cls._conffiles.get(scope, {}...
[ "def", "configure", "(", "cls", ",", "global_", ",", "key", ",", "val", ")", ":", "# first retrieve current configuration", "scope", "=", "'global'", "if", "global_", "else", "'local'", "if", "scope", "not", "in", "cls", ".", "_conffiles", ":", "cls", ".", ...
45.416667
6.75
def _create_bv_circuit(self, bit_map: Dict[str, str]) -> Program: """ Implementation of the Bernstein-Vazirani Algorithm. Given a list of input qubits and an ancilla bit, all initially in the :math:`\\vert 0\\rangle` state, create a program that can find :math:`\\vec{a}` with one ...
[ "def", "_create_bv_circuit", "(", "self", ",", "bit_map", ":", "Dict", "[", "str", ",", "str", "]", ")", "->", "Program", ":", "unitary", ",", "_", "=", "self", ".", "_compute_unitary_oracle_matrix", "(", "bit_map", ")", "full_bv_circuit", "=", "Program", ...
45.28
27.52
def dbStore(self, typ, py_value, context=None): """ Prepares to store this column for the a particular backend database. :param backend: <orb.Database> :param py_value: <variant> :param context: <orb.Context> :return: <variant> """ if py_value is None: ...
[ "def", "dbStore", "(", "self", ",", "typ", ",", "py_value", ",", "context", "=", "None", ")", ":", "if", "py_value", "is", "None", ":", "return", "None", "return", "self", ".", "valueToString", "(", "py_value", ",", "context", "=", "context", ")" ]
30.076923
15.153846
def get_as_nullable_float(self, key): """ Converts map element into a float or returns None if conversion is not possible. :param key: an index of element to get. :return: float value of the element or None if conversion is not supported. """ value = self.get(key) ...
[ "def", "get_as_nullable_float", "(", "self", ",", "key", ")", ":", "value", "=", "self", ".", "get", "(", "key", ")", "return", "FloatConverter", ".", "to_nullable_float", "(", "value", ")" ]
36
20.6
def cio_open(cinfo, src=None): """Wrapper for openjpeg library function opj_cio_open.""" argtypes = [ctypes.POINTER(CommonStructType), ctypes.c_char_p, ctypes.c_int] OPENJPEG.opj_cio_open.argtypes = argtypes OPENJPEG.opj_cio_open.restype = ctypes.POINTER(CioType) if src is None: ...
[ "def", "cio_open", "(", "cinfo", ",", "src", "=", "None", ")", ":", "argtypes", "=", "[", "ctypes", ".", "POINTER", "(", "CommonStructType", ")", ",", "ctypes", ".", "c_char_p", ",", "ctypes", ".", "c_int", "]", "OPENJPEG", ".", "opj_cio_open", ".", "a...
34
18.764706
def params(self): """ Returns a list where each element is a nicely formatted parameter of this function. This includes argument lists, keyword arguments and default values. """ def fmt_param(el): if isinstance(el, str) or isinstance(el, unicode): ...
[ "def", "params", "(", "self", ")", ":", "def", "fmt_param", "(", "el", ")", ":", "if", "isinstance", "(", "el", ",", "str", ")", "or", "isinstance", "(", "el", ",", "unicode", ")", ":", "return", "el", "else", ":", "return", "'(%s)'", "%", "(", "...
42.186047
18.093023
def release(self): """Release the lock.""" with self._lock: if not self._locked: raise RuntimeError('lock not currently held') elif self._reentrant and self._owner is not fibers.current(): raise RuntimeError('lock not owned by this fiber') ...
[ "def", "release", "(", "self", ")", ":", "with", "self", ".", "_lock", ":", "if", "not", "self", ".", "_locked", ":", "raise", "RuntimeError", "(", "'lock not currently held'", ")", "elif", "self", ".", "_reentrant", "and", "self", ".", "_owner", "is", "...
41.5
17.375
def dicts_from_table(table, keys=None): """Returns a list of dict() objects, one for each row in a list of lists (table)""" lod = [] for row in table: if not keys: keys = row if not all((k not in (None, '') or bool(k.strip())) for k in keys): keys = None ...
[ "def", "dicts_from_table", "(", "table", ",", "keys", "=", "None", ")", ":", "lod", "=", "[", "]", "for", "row", "in", "table", ":", "if", "not", "keys", ":", "keys", "=", "row", "if", "not", "all", "(", "(", "k", "not", "in", "(", "None", ",",...
36.727273
18.818182
def create(gandi, address, destination): """Create a domain mail forward.""" source, domain = address result = gandi.forward.create(domain, source, destination) return result
[ "def", "create", "(", "gandi", ",", "address", ",", "destination", ")", ":", "source", ",", "domain", "=", "address", "result", "=", "gandi", ".", "forward", ".", "create", "(", "domain", ",", "source", ",", "destination", ")", "return", "result" ]
26.571429
19.571429
def getCenters(self): """ Returns histogram's centers. """ return np.arange(self.histogram.size) * self.binWidth + self.minValue
[ "def", "getCenters", "(", "self", ")", ":", "return", "np", ".", "arange", "(", "self", ".", "histogram", ".", "size", ")", "*", "self", ".", "binWidth", "+", "self", ".", "minValue" ]
47.333333
18.666667
def blend_value(data, i, j, k, keys=None): """Computes the average value of the three vertices of a triangle in the simplex triangulation, where two of the vertices are on the lower horizontal.""" key_size = len(list(data.keys())[0]) if not keys: keys = triangle_coordinates(i, j, k) # R...
[ "def", "blend_value", "(", "data", ",", "i", ",", "j", ",", "k", ",", "keys", "=", "None", ")", ":", "key_size", "=", "len", "(", "list", "(", "data", ".", "keys", "(", ")", ")", "[", "0", "]", ")", "if", "not", "keys", ":", "keys", "=", "t...
32.5
15.944444
def make_get_thread_stack_message(self, py_db, seq, thread_id, topmost_frame, fmt, must_be_suspended=False, start_frame=0, levels=0): """ Returns thread stack as XML. :param must_be_suspended: If True and the thread is not suspended, returns None. """ try: # If frame...
[ "def", "make_get_thread_stack_message", "(", "self", ",", "py_db", ",", "seq", ",", "thread_id", ",", "topmost_frame", ",", "fmt", ",", "must_be_suspended", "=", "False", ",", "start_frame", "=", "0", ",", "levels", "=", "0", ")", ":", "try", ":", "# If fr...
49.59375
26.03125
def results(self): """ Get the table used for the results of the query. If the query is incomplete, this blocks. Raises: Exception if we timed out waiting for results or the query failed. """ self.wait() if self.failed: raise Exception('Query failed: %s' % str(self.errors)) return s...
[ "def", "results", "(", "self", ")", ":", "self", ".", "wait", "(", ")", "if", "self", ".", "failed", ":", "raise", "Exception", "(", "'Query failed: %s'", "%", "str", "(", "self", ".", "errors", ")", ")", "return", "self", ".", "_table" ]
32.1
20.7
def list_runner_book(self, market_id, selection_id, handicap=None, price_projection=None, order_projection=None, match_projection=None, include_overall_position=None, partition_matched_by_strategy_ref=None, customer_strategy_refs=None, currency_code=None, matched_since=...
[ "def", "list_runner_book", "(", "self", ",", "market_id", ",", "selection_id", ",", "handicap", "=", "None", ",", "price_projection", "=", "None", ",", "order_projection", "=", "None", ",", "match_projection", "=", "None", ",", "include_overall_position", "=", "...
72.294118
38.882353
def change_forms(self, *args, **keywords): """ Checks which form is currently displayed and toggles to the other one """ # Returns to previous Form in history if there is a previous Form try: self.parentApp.switchFormPrevious() except Exception as e: # pragma...
[ "def", "change_forms", "(", "self", ",", "*", "args", ",", "*", "*", "keywords", ")", ":", "# Returns to previous Form in history if there is a previous Form", "try", ":", "self", ".", "parentApp", ".", "switchFormPrevious", "(", ")", "except", "Exception", "as", ...
40.888889
13.555556
def ReplaceIxes(self, path, old_prefix, old_suffix, new_prefix, new_suffix): """ Replace old_prefix with new_prefix and old_suffix with new_suffix. env - Environment used to interpolate variables. path - the path that will be modified. old_prefix - construction variable for the ...
[ "def", "ReplaceIxes", "(", "self", ",", "path", ",", "old_prefix", ",", "old_suffix", ",", "new_prefix", ",", "new_suffix", ")", ":", "old_prefix", "=", "self", ".", "subst", "(", "'$'", "+", "old_prefix", ")", "old_suffix", "=", "self", ".", "subst", "(...
43.173913
16.130435
def ready(self): """ update Django Rest Framework serializer mappings """ from django.contrib.gis.db import models from rest_framework.serializers import ModelSerializer from .fields import GeometryField try: # drf 3.0 field_mapping = Mode...
[ "def", "ready", "(", "self", ")", ":", "from", "django", ".", "contrib", ".", "gis", ".", "db", "import", "models", "from", "rest_framework", ".", "serializers", "import", "ModelSerializer", "from", ".", "fields", "import", "GeometryField", "try", ":", "# dr...
37
16.153846
def columnize(rows): 'Generate (i,j) indexes for fixed-width columns found in rows' ## find all character columns that are not spaces allNonspaces = set() allNonspaces.add(max(len(r) for r in rows)+1) for r in rows: for i, ch in enumerate(r): if not ch.isspace(): ...
[ "def", "columnize", "(", "rows", ")", ":", "## find all character columns that are not spaces", "allNonspaces", "=", "set", "(", ")", "allNonspaces", ".", "add", "(", "max", "(", "len", "(", "r", ")", "for", "r", "in", "rows", ")", "+", "1", ")", "for", ...
25.1
19.7
def to_dict(self): """Create a dictionary with the information in this message. Returns: dict: The dictionary with information """ msg_dict = {} msg_dict['level'] = self.level msg_dict['message'] = self.message msg_dict['now_time'] = monotonic() ...
[ "def", "to_dict", "(", "self", ")", ":", "msg_dict", "=", "{", "}", "msg_dict", "[", "'level'", "]", "=", "self", ".", "level", "msg_dict", "[", "'message'", "]", "=", "self", ".", "message", "msg_dict", "[", "'now_time'", "]", "=", "monotonic", "(", ...
27.8125
14.625
def np_array_datetime64_compat(arr, *args, **kwargs): """ provide compat for construction of an array of strings to a np.array(..., dtype=np.datetime64(..)) tz-changes in 1.11 that make '2015-01-01 09:00:00Z' show a deprecation warning, when need to pass '2015-01-01 09:00:00' """ # is_list_l...
[ "def", "np_array_datetime64_compat", "(", "arr", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# is_list_like", "if", "(", "hasattr", "(", "arr", ",", "'__iter__'", ")", "and", "not", "isinstance", "(", "arr", ",", "(", "str", ",", "bytes", ")"...
36.5
15.928571
def rank_centrality(n_items, data, alpha=0.0): """Compute the Rank Centrality estimate of model parameters. This function implements Negahban et al.'s Rank Centrality algorithm [NOS12]_. The algorithm is similar to :func:`~choix.ilsr_pairwise`, but considers the *ratio* of wins for each pair (instead o...
[ "def", "rank_centrality", "(", "n_items", ",", "data", ",", "alpha", "=", "0.0", ")", ":", "_", ",", "chain", "=", "_init_lsr", "(", "n_items", ",", "alpha", ",", "None", ")", "for", "winner", ",", "loser", "in", "data", ":", "chain", "[", "loser", ...
36.294118
18.558824
def get_character(self, position, offset=0): """Return character at *position* with the given offset.""" position = self.get_position(position) + offset cursor = self.textCursor() cursor.movePosition(QTextCursor.End) if position < cursor.position(): cursor.setPo...
[ "def", "get_character", "(", "self", ",", "position", ",", "offset", "=", "0", ")", ":", "position", "=", "self", ".", "get_position", "(", "position", ")", "+", "offset", "cursor", "=", "self", ".", "textCursor", "(", ")", "cursor", ".", "movePosition",...
44.166667
10.166667
def ticker(self, currency="", **kwargs): """ This endpoint displays cryptocurrency ticker data in order of rank. The maximum number of results per call is 100. Pagination is possible by using the start and limit parameters. GET /ticker/ Optional parameters: (int) start - return results from rank [sta...
[ "def", "ticker", "(", "self", ",", "currency", "=", "\"\"", ",", "*", "*", "kwargs", ")", ":", "params", "=", "{", "}", "params", ".", "update", "(", "kwargs", ")", "# see https://github.com/barnumbirr/coinmarketcap/pull/28", "if", "currency", ":", "currency",...
39.526316
28.789474
def on_clear(self, event): """ initialize window to allow user to empty the working directory """ dia = pmag_menu_dialogs.ClearWD(self.parent, self.parent.WD) clear = dia.do_clear() if clear: # clear directory, but use previously acquired data_model ...
[ "def", "on_clear", "(", "self", ",", "event", ")", ":", "dia", "=", "pmag_menu_dialogs", ".", "ClearWD", "(", "self", ".", "parent", ",", "self", ".", "parent", ".", "WD", ")", "clear", "=", "dia", ".", "do_clear", "(", ")", "if", "clear", ":", "# ...
51.692308
23.384615
def get_submissions(self, limit=None): """Return a list of the images a user has submitted to the gallery.""" url = (self._imgur._base_url + "/3/account/{0}/submissions/" "{1}".format(self.name, '{}')) resp = self._imgur._send_request(url, limit=limit) return [_get_album_o...
[ "def", "get_submissions", "(", "self", ",", "limit", "=", "None", ")", ":", "url", "=", "(", "self", ".", "_imgur", ".", "_base_url", "+", "\"/3/account/{0}/submissions/\"", "\"{1}\"", ".", "format", "(", "self", ".", "name", ",", "'{}'", ")", ")", "resp...
60.166667
14.5
async def read(self, num_bytes=0) -> bytes: """ Reads a given number of bytes :param bytecount: How many bytes to read, leave it at default to read everything that is available :returns: incoming bytes """ if num_bytes < 1: num_bytes...
[ "async", "def", "read", "(", "self", ",", "num_bytes", "=", "0", ")", "->", "bytes", ":", "if", "num_bytes", "<", "1", ":", "num_bytes", "=", "self", ".", "in_waiting", "or", "1", "return", "await", "self", ".", "_read", "(", "num_bytes", ")" ]
31.333333
13.833333
def run(self, args): """Program counter.""" mainfile = self.core.filename(None) if self.core.is_running(): curframe = self.proc.curframe if curframe: line_no = inspect.getlineno(curframe) offset = curframe.f_lasti self.msg(...
[ "def", "run", "(", "self", ",", "args", ")", ":", "mainfile", "=", "self", ".", "core", ".", "filename", "(", "None", ")", "if", "self", ".", "core", ".", "is_running", "(", ")", ":", "curframe", "=", "self", ".", "proc", ".", "curframe", "if", "...
43.28125
17.40625
def output_buffer_size(self, output_buffer_size_b): """output_buffer_size (nsqd 0.2.21+) the size in bytes of the buffer nsqd will use when writing to this client. Valid range: 64 <= output_buffer_size <= configured_max (-1 disables output buffering) --max-output-buffer-size ...
[ "def", "output_buffer_size", "(", "self", ",", "output_buffer_size_b", ")", ":", "assert", "issubclass", "(", "output_buffer_size_b", ".", "__class__", ",", "int", ")", "return", "self", ".", "__push", "(", "'output_buffer_size'", ",", "output_buffer_size_b", ")" ]
33.866667
24.133333
def _set_params(self, x): """set the value of the parameters.""" assert x.size == self.num_params self.varianceU = x[0] self.varianceY = x[1] self.lengthscaleU = x[2] self.lengthscaleY = x[3]
[ "def", "_set_params", "(", "self", ",", "x", ")", ":", "assert", "x", ".", "size", "==", "self", ".", "num_params", "self", ".", "varianceU", "=", "x", "[", "0", "]", "self", ".", "varianceY", "=", "x", "[", "1", "]", "self", ".", "lengthscaleU", ...
33.285714
7.571429