text
stringlengths
75
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
0.18
def execute_notebook( input_path, output_path, parameters=None, engine_name=None, prepare_only=False, kernel_name=None, progress_bar=True, log_output=False, start_timeout=60, report_mode=False, cwd=None, ): """Executes a single notebook locally. Parameters ------...
[ "def", "execute_notebook", "(", "input_path", ",", "output_path", ",", "parameters", "=", "None", ",", "engine_name", "=", "None", ",", "prepare_only", "=", "False", ",", "kernel_name", "=", "None", ",", "progress_bar", "=", "True", ",", "log_output", "=", "...
33.264368
0.001007
def get_interface_switchport_output_switchport_default_vlan(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") get_interface_switchport = ET.Element("get_interface_switchport") config = get_interface_switchport output = ET.SubElement(get_interface_s...
[ "def", "get_interface_switchport_output_switchport_default_vlan", "(", "self", ",", "*", "*", "kwargs", ")", ":", "config", "=", "ET", ".", "Element", "(", "\"config\"", ")", "get_interface_switchport", "=", "ET", ".", "Element", "(", "\"get_interface_switchport\"", ...
50.823529
0.002273
def push(self, item): '''Push the value item onto the heap, maintaining the heap invariant. If the item is not hashable, a TypeError is raised. ''' hash(item) heapq.heappush(self._items, item)
[ "def", "push", "(", "self", ",", "item", ")", ":", "hash", "(", "item", ")", "heapq", ".", "heappush", "(", "self", ".", "_items", ",", "item", ")" ]
37.833333
0.008621
def stored_messages_list(context, num_elements=10): """ Renders a list of unread stored messages for the current user """ if "user" in context: user = context["user"] if user.is_authenticated(): qs = Inbox.objects.select_related("message").filter(user=user) return...
[ "def", "stored_messages_list", "(", "context", ",", "num_elements", "=", "10", ")", ":", "if", "\"user\"", "in", "context", ":", "user", "=", "context", "[", "\"user\"", "]", "if", "user", ".", "is_authenticated", "(", ")", ":", "qs", "=", "Inbox", ".", ...
34.083333
0.002381
def send_notification(self, method, args, kwargs): """Send a notification.""" msg = dumps([1, method, args, kwargs]) self.send(msg)
[ "def", "send_notification", "(", "self", ",", "method", ",", "args", ",", "kwargs", ")", ":", "msg", "=", "dumps", "(", "[", "1", ",", "method", ",", "args", ",", "kwargs", "]", ")", "self", ".", "send", "(", "msg", ")" ]
38
0.012903
def get_multiplicon_properties(self, value): """ Return a dictionary describing multiplicon data: id, parent, level, number_of_anchorpoints, profile_length, is_redundant and the contributing genome segments """ sql = '''SELECT id, parent, level, number_of_anchorpoints, ...
[ "def", "get_multiplicon_properties", "(", "self", ",", "value", ")", ":", "sql", "=", "'''SELECT id, parent, level, number_of_anchorpoints,\n profile_length, is_redundant\n FROM multiplicons WHERE id=:id'''", "cur", "=", "self", ".", "_dbconn",...
49.052632
0.002105
def _get_cpu_info_from_sysinfo_v2(): ''' Returns the CPU info gathered from sysinfo. Returns {} if sysinfo is not found. ''' try: # Just return {} if there is no sysinfo if not DataSource.has_sysinfo(): return {} # If sysinfo fails return {} returncode, output = DataSource.sysinfo_cpu() if output == ...
[ "def", "_get_cpu_info_from_sysinfo_v2", "(", ")", ":", "try", ":", "# Just return {} if there is no sysinfo", "if", "not", "DataSource", ".", "has_sysinfo", "(", ")", ":", "return", "{", "}", "# If sysinfo fails return {}", "returncode", ",", "output", "=", "DataSourc...
31.5
0.040765
def data_period_end_day(self, value=None): """Corresponds to IDD Field `data_period_end_day` Args: value (str): value for IDD Field `data_period_end_day` if `value` is None it will not be checked against the specification and is assumed to be a missing value ...
[ "def", "data_period_end_day", "(", "self", ",", "value", "=", "None", ")", ":", "if", "value", "is", "not", "None", ":", "try", ":", "value", "=", "str", "(", "value", ")", "except", "ValueError", ":", "raise", "ValueError", "(", "'value {} need to be of t...
35.916667
0.00226
def nth_child_production(self, lexeme, tokens): """Parse args and pass them to pclass_func_validator.""" args = self.match(tokens, 'expr') pat = self.nth_child_pat.match(args) if pat.group(5): a = 2 b = 1 if pat.group(5) == 'odd' else 0 elif pat.group(6...
[ "def", "nth_child_production", "(", "self", ",", "lexeme", ",", "tokens", ")", ":", "args", "=", "self", ".", "match", "(", "tokens", ",", "'expr'", ")", "pat", "=", "self", ".", "nth_child_pat", ".", "match", "(", "args", ")", "if", "pat", ".", "gro...
26.333333
0.001627
def measure_sidechain_torsion_angles(residue, verbose=True): """Calculates sidechain dihedral angles for a residue Parameters ---------- residue : [ampal.Residue] `Residue` object. verbose : bool, optional If `true`, tells you when a residue does not have any known dihedral ...
[ "def", "measure_sidechain_torsion_angles", "(", "residue", ",", "verbose", "=", "True", ")", ":", "chi_angles", "=", "[", "]", "aa", "=", "residue", ".", "mol_code", "if", "aa", "not", "in", "side_chain_dihedrals", ":", "if", "verbose", ":", "print", "(", ...
34.97619
0.000662
def _GetValue(self, name): """Returns the TextFSMValue object natching the requested name.""" for value in self.values: if value.name == name: return value
[ "def", "_GetValue", "(", "self", ",", "name", ")", ":", "for", "value", "in", "self", ".", "values", ":", "if", "value", ".", "name", "==", "name", ":", "return", "value" ]
34.6
0.011299
def timespan(self, from_date, to_date=None, span=None, current=False): """ Takes a beginning date a filters entries. An optional to_date can be specified, or a span, which is one of ('month', 'week', 'day'). N.B. - If given a to_date, it does not include that date, only before. "...
[ "def", "timespan", "(", "self", ",", "from_date", ",", "to_date", "=", "None", ",", "span", "=", "None", ",", "current", "=", "False", ")", ":", "if", "span", "and", "not", "to_date", ":", "diff", "=", "None", "if", "span", "==", "'month'", ":", "d...
43.7
0.00224
def calc_ifft_with_PyCUDA(Signalfft): """ Calculates the inverse-FFT of the passed FFT-signal by using the scikit-cuda libary which relies on PyCUDA Parameters ---------- Signalfft : ndarray FFT-Signal to be transformed into Real space Returns ------- Signal : ndarray ...
[ "def", "calc_ifft_with_PyCUDA", "(", "Signalfft", ")", ":", "print", "(", "\"starting ifft\"", ")", "Signalfft", "=", "Signalfft", ".", "astype", "(", "_np", ".", "complex64", ")", "Signalfft_gpu", "=", "_gpuarray", ".", "to_gpu", "(", "Signalfft", "[", "0", ...
32.625
0.009926
def tree(): """Example showing tree progress view""" ############# # Test data # ############# # For this example, we're obviously going to be feeding fictitious data # to ProgressTree, so here it is leaf_values = [Value(0) for i in range(6)] bd_defaults = dict(type=Bar, kwargs=dict(...
[ "def", "tree", "(", ")", ":", "#############", "# Test data #", "#############", "# For this example, we're obviously going to be feeding fictitious data", "# to ProgressTree, so here it is", "leaf_values", "=", "[", "Value", "(", "0", ")", "for", "i", "in", "range", "(",...
33.541667
0.001207
def all_apps(self): """Capture a backup of the app.""" cmd = ["heroku", "apps", "--json"] if self.team: cmd.extend(["--team", self.team]) return json.loads(self._result(cmd))
[ "def", "all_apps", "(", "self", ")", ":", "cmd", "=", "[", "\"heroku\"", ",", "\"apps\"", ",", "\"--json\"", "]", "if", "self", ".", "team", ":", "cmd", ".", "extend", "(", "[", "\"--team\"", ",", "self", ".", "team", "]", ")", "return", "json", "....
35.5
0.009174
def generate_tolerances(morph1, morph2): """Generates all reasonable tolerant particle morphs:: >>> set(generate_tolerances(u'이', u'가')) set([u'이(가)', u'(이)가', u'가(이)', u'(가)이']) >>> set(generate_tolerances(u'이면', u'면')) set([u'(이)면']) """ if morph1 == morph2: # Tolerance not requi...
[ "def", "generate_tolerances", "(", "morph1", ",", "morph2", ")", ":", "if", "morph1", "==", "morph2", ":", "# Tolerance not required.", "return", "if", "not", "(", "morph1", "and", "morph2", ")", ":", "# Null allomorph exists.", "yield", "u'(%s)'", "%", "(", "...
35.657895
0.000718
def _on_connection_open(self, connection): """ Callback invoked when the connection is successfully established. Args: connection (pika.connection.SelectConnection): The newly-estabilished connection. """ _log.info("Successfully opened connection to %...
[ "def", "_on_connection_open", "(", "self", ",", "connection", ")", ":", "_log", ".", "info", "(", "\"Successfully opened connection to %s\"", ",", "connection", ".", "params", ".", "host", ")", "self", ".", "_channel", "=", "connection", ".", "channel", "(", "...
42.1
0.011628
def ec_init(spec): """ Initiate a key bundle with an elliptic curve key. :param spec: Key specifics of the form:: {"type": "EC", "crv": "P-256", "use": ["sig"]} :return: A KeyBundle instance """ kb = KeyBundle(keytype="EC") if 'use' in spec: for use in spec["use"]: ...
[ "def", "ec_init", "(", "spec", ")", ":", "kb", "=", "KeyBundle", "(", "keytype", "=", "\"EC\"", ")", "if", "'use'", "in", "spec", ":", "for", "use", "in", "spec", "[", "\"use\"", "]", ":", "eck", "=", "new_ec_key", "(", "crv", "=", "spec", "[", "...
23.25
0.002066
def renumber_atoms(lines): ''' Takes in a list of PDB lines and renumbers the atoms appropriately ''' new_lines = [] current_number = 1 for line in lines: if line.startswith('ATOM') or line.startswith('HETATM'): new_lines.append( line[:6] + string.rjust('%d' %...
[ "def", "renumber_atoms", "(", "lines", ")", ":", "new_lines", "=", "[", "]", "current_number", "=", "1", "for", "line", "in", "lines", ":", "if", "line", ".", "startswith", "(", "'ATOM'", ")", "or", "line", ".", "startswith", "(", "'HETATM'", ")", ":",...
30.941176
0.001845
def branches(config, searchstring=""): """List all branches. And if exactly 1 found, offer to check it out.""" repo = config.repo branches_ = list(find(repo, searchstring)) if branches_: merged = get_merged_branches(repo) info_out("Found existing branches...") print_list(branche...
[ "def", "branches", "(", "config", ",", "searchstring", "=", "\"\"", ")", ":", "repo", "=", "config", ".", "repo", "branches_", "=", "list", "(", "find", "(", "repo", ",", "searchstring", ")", ")", "if", "branches_", ":", "merged", "=", "get_merged_branch...
40.259259
0.001797
def read(self, n): '''read some bytes''' if len(self.buf) == 0: self._recv() if len(self.buf) > 0: if n > len(self.buf): n = len(self.buf) ret = self.buf[:n] ...
[ "def", "read", "(", "self", ",", "n", ")", ":", "if", "len", "(", "self", ".", "buf", ")", "==", "0", ":", "self", ".", "_recv", "(", ")", "if", "len", "(", "self", ".", "buf", ")", ">", "0", ":", "if", "n", ">", "len", "(", "self", ".", ...
40
0.008726
def build(cls, value: object, binary: bool = False, fallback: object = None) -> Union[Nil, 'String']: """Produce either a :class:`QuotedString` or :class:`LiteralString` based on the contents of ``data``. This is useful to improve readability of response data. Args: ...
[ "def", "build", "(", "cls", ",", "value", ":", "object", ",", "binary", ":", "bool", "=", "False", ",", "fallback", ":", "object", "=", "None", ")", "->", "Union", "[", "Nil", ",", "'String'", "]", ":", "if", "value", "is", "None", ":", "if", "fa...
38.1
0.001919
def get_all_server_credentials(self, authorization, **kwargs): # noqa: E501 """Fetch all (Bootstrap and LwM2M) server credentials. # noqa: E501 This REST API is intended to be used by customers to fetch all (Bootstrap and LwM2M) server credentials that they will need to use with their clients to conn...
[ "def", "get_all_server_credentials", "(", "self", ",", "authorization", ",", "*", "*", "kwargs", ")", ":", "# noqa: E501", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'asynchronous'", ")", ":", "return", "self...
65.904762
0.001425
def watch_from_file(connection, file_name): """ Start watching a new volume :type connection: boto.ec2.connection.EC2Connection :param connection: EC2 connection object :type file_name: str :param file_name: path to config file :returns: None """ with open(file_name, 'r') as filehandle:...
[ "def", "watch_from_file", "(", "connection", ",", "file_name", ")", ":", "with", "open", "(", "file_name", ",", "'r'", ")", "as", "filehandle", ":", "for", "line", "in", "filehandle", ".", "xreadlines", "(", ")", ":", "volume", ",", "interval", ",", "ret...
34.5
0.001764
def deploy(target): """Deploys the package and documentation. Proceeds in the following steps: 1. Ensures proper environment variables are set and checks that we are on Circle CI 2. Tags the repository with the new version 3. Creates a standard distribution and a wheel 4. Updates version.py to...
[ "def", "deploy", "(", "target", ")", ":", "# Ensure proper environment", "if", "not", "os", ".", "getenv", "(", "CIRCLECI_ENV_VAR", ")", ":", "# pragma: no cover", "raise", "EnvironmentError", "(", "'Must be on CircleCI to run this script'", ")", "current_branch", "=", ...
40.883721
0.002499
def spkw08(handle, body, center, inframe, first, last, segid, degree, n, states, epoch1, step): # see libspice args for solution to array[][N] problem """ Write a type 8 segment to an SPK file. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/spkw08_c.html :param handle: Handle o...
[ "def", "spkw08", "(", "handle", ",", "body", ",", "center", ",", "inframe", ",", "first", ",", "last", ",", "segid", ",", "degree", ",", "n", ",", "states", ",", "epoch1", ",", "step", ")", ":", "# see libspice args for solution to array[][N] problem", "hand...
36.404255
0.001707
def dispatch(self, request, *args, **kwargs): """ Most views in a CMS require a login, so this is the default setup. If a login is not required then the requires_login property can be set to False to disable this. """ if self.requires_login: if settings.LOGIN...
[ "def", "dispatch", "(", "self", ",", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "self", ".", "requires_login", ":", "if", "settings", ".", "LOGIN_URL", "is", "None", "or", "settings", ".", "LOGOUT_URL", "is", "None", ":", "...
36.666667
0.002215
def show_hc(kwargs=None, call=None): ''' Show the details of an existing health check. CLI Example: .. code-block:: bash salt-cloud -f show_hc gce name=hc ''' if call != 'function': raise SaltCloudSystemExit( 'The show_hc function must be called with -f or --functi...
[ "def", "show_hc", "(", "kwargs", "=", "None", ",", "call", "=", "None", ")", ":", "if", "call", "!=", "'function'", ":", "raise", "SaltCloudSystemExit", "(", "'The show_hc function must be called with -f or --function.'", ")", "if", "not", "kwargs", "or", "'name'"...
24.681818
0.001773
def cp(src_path, dst_path, follow_links=False, recursive=True): """Copy source to destination. >>> if cp('/tmp/one', '/tmp/two'): ... print('OK') OK """ successful = False try: if follow_links and os.path.islink(src_path): src_path = os.path.realpath(src_path) ...
[ "def", "cp", "(", "src_path", ",", "dst_path", ",", "follow_links", "=", "False", ",", "recursive", "=", "True", ")", ":", "successful", "=", "False", "try", ":", "if", "follow_links", "and", "os", ".", "path", ".", "islink", "(", "src_path", ")", ":",...
37.607143
0.001852
def zip_columns(columns): """ Zip together multiple columns. Args: columns (WeldObject / Numpy.ndarray): lust of columns Returns: A WeldObject representing this computation """ weld_obj = WeldObject(encoder_, decoder_) column_vars = [] for column in columns: col...
[ "def", "zip_columns", "(", "columns", ")", ":", "weld_obj", "=", "WeldObject", "(", "encoder_", ",", "decoder_", ")", "column_vars", "=", "[", "]", "for", "column", "in", "columns", ":", "col_var", "=", "weld_obj", ".", "update", "(", "column", ")", "if"...
22.228571
0.001232
def log_config(log_level: Union[str, int]) -> dict: """ Setup default config. for dictConfig. :param log_level: str name or django debugging int :return: dict suitable for ``logging.config.dictConfig`` """ if isinstance(log_level, int): # to match django log_level = {3: 'DEBUG', ...
[ "def", "log_config", "(", "log_level", ":", "Union", "[", "str", ",", "int", "]", ")", "->", "dict", ":", "if", "isinstance", "(", "log_level", ",", "int", ")", ":", "# to match django", "log_level", "=", "{", "3", ":", "'DEBUG'", ",", "2", ":", "'IN...
32.547619
0.00142
def removeComponent(self, index): """Removes the component at *index* from the model. If the two last rows are now empty, trims the last row.""" if index.row() == self.rowCount() -1 and self.columnCountForRow(index.row()) == 1: self.beginRemoveRows(QtCore.QModelIndex(), self._stim....
[ "def", "removeComponent", "(", "self", ",", "index", ")", ":", "if", "index", ".", "row", "(", ")", "==", "self", ".", "rowCount", "(", ")", "-", "1", "and", "self", ".", "columnCountForRow", "(", "index", ".", "row", "(", ")", ")", "==", "1", ":...
52.923077
0.01
def get_hosts_unfinished(self, scan_id): """ Get a list of finished hosts.""" unfinished_hosts = list() for target in self.scans_table[scan_id]['finished_hosts']: unfinished_hosts.extend(target_str_to_list(target)) for target in self.scans_table[scan_id]['finished_hosts']: ...
[ "def", "get_hosts_unfinished", "(", "self", ",", "scan_id", ")", ":", "unfinished_hosts", "=", "list", "(", ")", "for", "target", "in", "self", ".", "scans_table", "[", "scan_id", "]", "[", "'finished_hosts'", "]", ":", "unfinished_hosts", ".", "extend", "("...
42
0.008475
def setColumns( self, columns ): """ Sets the columns for this gantt widget's tree to the inputed list of columns. :param columns | {<str>, ..] """ self.treeWidget().setColumns(columns) item = self.treeWidget().headerItem() for i in ...
[ "def", "setColumns", "(", "self", ",", "columns", ")", ":", "self", ".", "treeWidget", "(", ")", ".", "setColumns", "(", "columns", ")", "item", "=", "self", ".", "treeWidget", "(", ")", ".", "headerItem", "(", ")", "for", "i", "in", "range", "(", ...
37.090909
0.011962
def eventFilter( self, object, event ): """ Filters the object for particular events. :param object | <QObject> event | <QEvent> :return <bool> | consumed """ if ( event.type() == event.KeyPress ): if (...
[ "def", "eventFilter", "(", "self", ",", "object", ",", "event", ")", ":", "if", "(", "event", ".", "type", "(", ")", "==", "event", ".", "KeyPress", ")", ":", "if", "(", "event", ".", "key", "(", ")", "in", "(", "Qt", ".", "Key_Return", ",", "Q...
29.866667
0.02381
def getIcon( data ): """Return the data from the resource as a wxIcon""" import cStringIO stream = cStringIO.StringIO(data) image = wx.ImageFromStream(stream) icon = wx.EmptyIcon() icon.CopyFromBitmap(wx.BitmapFromImage(image)) return icon
[ "def", "getIcon", "(", "data", ")", ":", "import", "cStringIO", "stream", "=", "cStringIO", ".", "StringIO", "(", "data", ")", "image", "=", "wx", ".", "ImageFromStream", "(", "stream", ")", "icon", "=", "wx", ".", "EmptyIcon", "(", ")", "icon", ".", ...
32.5
0.011236
def set_color_in_session(intent, session): """ Sets the color in the session and prepares the speech to reply to the user. """ card_title = intent['name'] session_attributes = {} should_end_session = False if 'Color' in intent['slots']: favorite_color = intent['slots']['Color']['va...
[ "def", "set_color_in_session", "(", "intent", ",", "session", ")", ":", "card_title", "=", "intent", "[", "'name'", "]", "session_attributes", "=", "{", "}", "should_end_session", "=", "False", "if", "'Color'", "in", "intent", "[", "'slots'", "]", ":", "favo...
46.5
0.00081
def default_qai(qareport): """QAI = 2 * (TP * (PT/PNC) * COV) / (1 + exp(MSE/tau)) Where: TP: If all tests passes is 1, 0 otherwise. PT: Processors and commands tested. PCN: The number number of processors (Loader, Steps and Alerts) and commands. COV: The code cover...
[ "def", "default_qai", "(", "qareport", ")", ":", "TP", "=", "1.", "if", "qareport", ".", "is_test_sucess", "else", "0.", "PCN", "=", "qareport", ".", "processors_number", "+", "qareport", ".", "commands_number", "PT_div_PCN", "=", "float", "(", "qareport", "...
35
0.001159
def find_period(data, min_period=0.2, max_period=32.0, coarse_precision=1e-5, fine_precision=1e-9, periodogram=Lomb_Scargle, period_jobs=1): """find_period(data, min_period=0.2, max_period=32.0, coarse_precision=1e-5, fine_precision=1e-9, periodogram=L...
[ "def", "find_period", "(", "data", ",", "min_period", "=", "0.2", ",", "max_period", "=", "32.0", ",", "coarse_precision", "=", "1e-5", ",", "fine_precision", "=", "1e-9", ",", "periodogram", "=", "Lomb_Scargle", ",", "period_jobs", "=", "1", ")", ":", "if...
38.826087
0.001092
def adaptStandardLogging(loggerName, logCategory, targetModule): """ Make a logger from the standard library log through the Flumotion logging system. @param loggerName: The standard logger to adapt, e.g. 'library.module' @type loggerName: str @param logCategory: The Flumotion log category to u...
[ "def", "adaptStandardLogging", "(", "loggerName", ",", "logCategory", ",", "targetModule", ")", ":", "logger", "=", "logging", ".", "getLogger", "(", "loggerName", ")", "# if there is already a FluHandler, exit", "if", "map", "(", "lambda", "h", ":", "isinstance", ...
47.863636
0.000931
def commit(self): """ Insert the text at the current cursor position. """ # Backup and remove the currently selected text (may be none). tc = self.qteWidget.textCursor() self.selText = tc.selection().toHtml() self.selStart = tc.selectionStart() self.selEn...
[ "def", "commit", "(", "self", ")", ":", "# Backup and remove the currently selected text (may be none).", "tc", "=", "self", ".", "qteWidget", ".", "textCursor", "(", ")", "self", ".", "selText", "=", "tc", ".", "selection", "(", ")", ".", "toHtml", "(", ")", ...
39.21875
0.001555
def get(self, sid): """ Constructs a FeedbackSummaryContext :param sid: A string that uniquely identifies this feedback summary resource :returns: twilio.rest.api.v2010.account.call.feedback_summary.FeedbackSummaryContext :rtype: twilio.rest.api.v2010.account.call.feedback_summ...
[ "def", "get", "(", "self", ",", "sid", ")", ":", "return", "FeedbackSummaryContext", "(", "self", ".", "_version", ",", "account_sid", "=", "self", ".", "_solution", "[", "'account_sid'", "]", ",", "sid", "=", "sid", ",", ")" ]
45.6
0.012903
def render_inline_styles(self): "Hard-code the styles into the SVG XML if style sheets are not used." if not self.css_inline: # do nothing return styles = self.parse_css() for node in self.root.xpath('//*[@class]'): cl = '.' + node.attrib['class'] if cl not in styles: continue style = styles...
[ "def", "render_inline_styles", "(", "self", ")", ":", "if", "not", "self", ".", "css_inline", ":", "# do nothing", "return", "styles", "=", "self", ".", "parse_css", "(", ")", "for", "node", "in", "self", ".", "root", ".", "xpath", "(", "'//*[@class]'", ...
27.066667
0.035714
def asDictionary(self): """returns object as a dictionary""" if self._json_dict is None: self.__init(url=self._url) return self._json_dict
[ "def", "asDictionary", "(", "self", ")", ":", "if", "self", ".", "_json_dict", "is", "None", ":", "self", ".", "__init", "(", "url", "=", "self", ".", "_url", ")", "return", "self", ".", "_json_dict" ]
34
0.011494
def extract_paths_dead(self, paths, *args, **kwargs): """ Thin method that just uses the provider """ return self.provider.extract_paths_dead(paths, *args, **kwargs)
[ "def", "extract_paths_dead", "(", "self", ",", "paths", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "provider", ".", "extract_paths_dead", "(", "paths", ",", "*", "args", ",", "*", "*", "kwargs", ")" ]
38.6
0.010152
def get_compiler(compiler, **compiler_attrs): """get and customize a compiler""" if compiler is None or isinstance(compiler, str): cc = ccompiler.new_compiler(compiler=compiler, verbose=0) customize_compiler(cc) if cc.compiler_type == 'mingw32': customize_mingw(cc) else: ...
[ "def", "get_compiler", "(", "compiler", ",", "*", "*", "compiler_attrs", ")", ":", "if", "compiler", "is", "None", "or", "isinstance", "(", "compiler", ",", "str", ")", ":", "cc", "=", "ccompiler", ".", "new_compiler", "(", "compiler", "=", "compiler", "...
29.666667
0.002179
def dlog(msg, log_path=DEFAULT_LOG_PATH): """A handy log utility for debugging multi-process, multi-threaded activities.""" with open(log_path, 'a') as f: f.write('\n{}@{}: {}'.format(os.getpid(), threading.current_thread().name, msg))
[ "def", "dlog", "(", "msg", ",", "log_path", "=", "DEFAULT_LOG_PATH", ")", ":", "with", "open", "(", "log_path", ",", "'a'", ")", "as", "f", ":", "f", ".", "write", "(", "'\\n{}@{}: {}'", ".", "format", "(", "os", ".", "getpid", "(", ")", ",", "thre...
60
0.020576
def quantile(x, q, weights=None): """ Compute (weighted) quantiles from an input set of samples. Parameters ---------- x : `~numpy.ndarray` with shape (nsamps,) Input samples. q : `~numpy.ndarray` with shape (nquantiles,) The list of quantiles to compute from `[0., 1.]`. we...
[ "def", "quantile", "(", "x", ",", "q", ",", "weights", "=", "None", ")", ":", "# Initial check.", "x", "=", "np", ".", "atleast_1d", "(", "x", ")", "q", "=", "np", ".", "atleast_1d", "(", "q", ")", "# Quantile check.", "if", "np", ".", "any", "(", ...
31.288889
0.000689
def maskInMicrolensRegion(ch, col, row, padding=0): """Is a target in the K2C9 superstamp, including padding? This function is identical to pixelInMicrolensRegion, except it takes the extra `padding` argument. The coordinate must be within the K2C9 superstamp by at least `padding` number of pixels on e...
[ "def", "maskInMicrolensRegion", "(", "ch", ",", "col", ",", "row", ",", "padding", "=", "0", ")", ":", "if", "padding", "==", "0", ":", "return", "pixelInMicrolensRegion", "(", "ch", ",", "col", ",", "row", ")", "combinations", "=", "[", "[", "col", ...
36.933333
0.00088
def _convert_variant_file_to_dict(varfile): """ Converts tsv to dicts with this structure { 'patient_1': { 'variant-id': { 'build': 'hg19' 'chromosome': 'chr7', 'reference_allele': 'A', 'v...
[ "def", "_convert_variant_file_to_dict", "(", "varfile", ")", ":", "patient_variant_map", "=", "{", "}", "# line_num = 0 note this is builtin to the reader as reader.line_num", "reader", "=", "csv", ".", "reader", "(", "varfile", ",", "delimiter", "=", "\"\\t\"", ")", ...
37.222973
0.001238
def pipelines(self): """ Property for accessing :class:`PipelineManager` instance, which is used to manage pipelines. :rtype: yagocd.resources.pipeline.PipelineManager """ if self._pipeline_manager is None: self._pipeline_manager = PipelineManager(session=self._sessi...
[ "def", "pipelines", "(", "self", ")", ":", "if", "self", ".", "_pipeline_manager", "is", "None", ":", "self", ".", "_pipeline_manager", "=", "PipelineManager", "(", "session", "=", "self", ".", "_session", ")", "return", "self", ".", "_pipeline_manager" ]
39.222222
0.00831
def guard_assign(analysis): """Return whether the transition "assign" can be performed or not """ # Only if the request was done from worksheet context. if not is_worksheet_context(): return False # Cannot assign if the Sample has not been received if not analysis.isSampleReceived(): ...
[ "def", "guard_assign", "(", "analysis", ")", ":", "# Only if the request was done from worksheet context.", "if", "not", "is_worksheet_context", "(", ")", ":", "return", "False", "# Cannot assign if the Sample has not been received", "if", "not", "analysis", ".", "isSampleRec...
33
0.001733
def ancovan(dv=None, covar=None, between=None, data=None, export_filename=None): """ANCOVA with n covariates. This is an internal function. The main call to this function should be done by the :py:func:`pingouin.ancova` function. Parameters ---------- dv : string Name of co...
[ "def", "ancovan", "(", "dv", "=", "None", ",", "covar", "=", "None", ",", "between", "=", "None", ",", "data", "=", "None", ",", "export_filename", "=", "None", ")", ":", "# Check that stasmodels is installed", "from", "pingouin", ".", "utils", "import", "...
31.301587
0.000492
def stop_process(self): """Request the module process to stop and release it :return: None """ if not self.process: return logger.info("I'm stopping module %r (pid=%d)", self.name, self.process.pid) self.kill() # Clean inner process reference ...
[ "def", "stop_process", "(", "self", ")", ":", "if", "not", "self", ".", "process", ":", "return", "logger", ".", "info", "(", "\"I'm stopping module %r (pid=%d)\"", ",", "self", ".", "name", ",", "self", ".", "process", ".", "pid", ")", "self", ".", "kil...
27.416667
0.008824
def remove_tcp_port(self, port): """ Removes an associated TCP port number from this project. :param port: TCP port number """ if port in self._used_tcp_ports: self._used_tcp_ports.remove(port)
[ "def", "remove_tcp_port", "(", "self", ",", "port", ")", ":", "if", "port", "in", "self", ".", "_used_tcp_ports", ":", "self", ".", "_used_tcp_ports", ".", "remove", "(", "port", ")" ]
26.555556
0.008097
def requires(self): """ Returns the default workflow requirements in an ordered dictionary, which is updated with the return value of the task's *workflow_requires* method. """ reqs = OrderedDict() reqs.update(self.task.workflow_requires()) return reqs
[ "def", "requires", "(", "self", ")", ":", "reqs", "=", "OrderedDict", "(", ")", "reqs", ".", "update", "(", "self", ".", "task", ".", "workflow_requires", "(", ")", ")", "return", "reqs" ]
37.625
0.00974
def find_scraperclasses(comic, multiple_allowed=False): """Get a list comic scraper classes. Can return more than one entries if multiple_allowed is True, else it raises a ValueError if multiple modules match. The match is a case insensitive substring search.""" if not comic: raise ValueError("e...
[ "def", "find_scraperclasses", "(", "comic", ",", "multiple_allowed", "=", "False", ")", ":", "if", "not", "comic", ":", "raise", "ValueError", "(", "\"empty comic name\"", ")", "candidates", "=", "[", "]", "cname", "=", "comic", ".", "lower", "(", ")", "fo...
41.666667
0.000978
def import_key(kwargs=None, call=None): ''' List the keys available CLI Example: .. code-block:: bash salt-cloud -f import_key joyent keyname=mykey keyfile=/tmp/mykey.pub ''' if call != 'function': log.error( 'The import_key function must be called with -f or --fun...
[ "def", "import_key", "(", "kwargs", "=", "None", ",", "call", "=", "None", ")", ":", "if", "call", "!=", "'function'", ":", "log", ".", "error", "(", "'The import_key function must be called with -f or --function.'", ")", "return", "False", "if", "not", "kwargs"...
26.727273
0.001641
def register_type(self, typename): """ Registers a type name so that it may be used to send and receive packages. :param typename: Name of the packet type. A method with the same name and a "on_" prefix should be added to handle incomming packets. :raise...
[ "def", "register_type", "(", "self", ",", "typename", ")", ":", "typekey", "=", "typehash", "(", "typename", ")", "if", "typekey", "in", "self", ".", "_type_register", ":", "raise", "ValueError", "(", "\"Type name collision. Type %s has the same hash.\"", "%", "re...
47.230769
0.01278
def jwks_to_keyjar(jwks, iss=''): """ Convert a JWKS to a KeyJar instance. :param jwks: String representation of a JWKS :return: A :py:class:`oidcmsg.key_jar.KeyJar` instance """ if not isinstance(jwks, dict): try: jwks = json.loads(jwks) except json.JSONDecodeError:...
[ "def", "jwks_to_keyjar", "(", "jwks", ",", "iss", "=", "''", ")", ":", "if", "not", "isinstance", "(", "jwks", ",", "dict", ")", ":", "try", ":", "jwks", "=", "json", ".", "loads", "(", "jwks", ")", "except", "json", ".", "JSONDecodeError", ":", "r...
26.375
0.002288
def logic_subset(self, op=None): """Return set of logicnets, filtered by the type(s) of logic op provided as op. If no op is specified, the full set of logicnets associated with the Block are returned. This is helpful for getting all memories of a block for example.""" if op is None: ...
[ "def", "logic_subset", "(", "self", ",", "op", "=", "None", ")", ":", "if", "op", "is", "None", ":", "return", "self", ".", "logic", "else", ":", "return", "set", "(", "x", "for", "x", "in", "self", ".", "logic", "if", "x", ".", "op", "in", "op...
46
0.011848
def matrix(self, x=(0, 0), y=(0, 0) , z=(0, 0)): """ Copy the ``pyny.Polygon`` along a 3D matrix given by the three tuples x, y, z: :param x: Number of copies and distance between them in this direction. :type x: tuple (len=2) :returns: list ...
[ "def", "matrix", "(", "self", ",", "x", "=", "(", "0", ",", "0", ")", ",", "y", "=", "(", "0", ",", "0", ")", ",", "z", "=", "(", "0", ",", "0", ")", ")", ":", "space", "=", "Space", "(", "Place", "(", "Surface", "(", "self", ")", ")", ...
38
0.009881
def create_surface_grid(nr_electrodes=None, spacing=None, electrodes_x=None, depth=None, left=None, right=None, char_lengths=None, lines=None, ...
[ "def", "create_surface_grid", "(", "nr_electrodes", "=", "None", ",", "spacing", "=", "None", ",", "electrodes_x", "=", "None", ",", "depth", "=", "None", ",", "left", "=", "None", ",", "right", "=", "None", ",", "char_lengths", "=", "None", ",", "lines"...
35.057143
0.001321
def config_status(): """ Check config status in an account. """ s = boto3.Session() client = s.client('config') channels = client.describe_delivery_channel_status()[ 'DeliveryChannelsStatus'] for c in channels: print(yaml.safe_dump({ c['name']: dict( s...
[ "def", "config_status", "(", ")", ":", "s", "=", "boto3", ".", "Session", "(", ")", "client", "=", "s", ".", "client", "(", "'config'", ")", "channels", "=", "client", ".", "describe_delivery_channel_status", "(", ")", "[", "'DeliveryChannelsStatus'", "]", ...
36.833333
0.001471
def load_project(self, filename, overwrite=False): r""" Loads a Project from the specified 'pnm' file The loaded project is added to the Workspace . This will *not* delete any existing Projects in the Workspace and will rename any Projects being loaded if necessary. Par...
[ "def", "load_project", "(", "self", ",", "filename", ",", "overwrite", "=", "False", ")", ":", "filename", "=", "self", ".", "_parse_filename", "(", "filename", "=", "filename", ",", "ext", "=", "'pnm'", ")", "temp", "=", "{", "}", "# Read file into tempor...
41.789474
0.00082
def setHoverForeground( self, column, brush ): """ Returns the brush to use when coloring when the user hovers over the item for the given column. :param column | <int> brush | <QtGui.QBrush> """ self._hoverForeground[column] = Q...
[ "def", "setHoverForeground", "(", "self", ",", "column", ",", "brush", ")", ":", "self", ".", "_hoverForeground", "[", "column", "]", "=", "QtGui", ".", "QBrush", "(", "brush", ")" ]
36.666667
0.014793
def blocks(self, blocksize=None, overlap=0, frames=-1, dtype='float64', always_2d=False, fill_value=None, out=None): """Return a generator for block-wise reading. By default, the generator yields blocks of the given `blocksize` (using a given `overlap`) until the end of the file ...
[ "def", "blocks", "(", "self", ",", "blocksize", "=", "None", ",", "overlap", "=", "0", ",", "frames", "=", "-", "1", ",", "dtype", "=", "'float64'", ",", "always_2d", "=", "False", ",", "fill_value", "=", "None", ",", "out", "=", "None", ")", ":", ...
36.483516
0.001173
def _Enum(docstring, *names): """Utility to generate enum classes used by annotations. Args: docstring: Docstring for the generated enum class. *names: Enum names. Returns: A class that contains enum names as attributes. """ enums = dict(zip(names, range(len(names)))) reverse = dict((value, ke...
[ "def", "_Enum", "(", "docstring", ",", "*", "names", ")", ":", "enums", "=", "dict", "(", "zip", "(", "names", ",", "range", "(", "len", "(", "names", ")", ")", ")", ")", "reverse", "=", "dict", "(", "(", "value", ",", "key", ")", "for", "key",...
30.2
0.014989
def add_entity(self, domain, **kwargs): ''' Add a new Entity to tracking. ''' # Set the entity's mapping func if one was specified map_func = kwargs.get('map_func', None) if map_func is not None and not callable(kwargs['map_func']): if self.entity_mapper is None: ...
[ "def", "add_entity", "(", "self", ",", "domain", ",", "*", "*", "kwargs", ")", ":", "# Set the entity's mapping func if one was specified", "map_func", "=", "kwargs", ".", "get", "(", "'map_func'", ",", "None", ")", "if", "map_func", "is", "not", "None", "and"...
43.46875
0.001406
def check_tuple(data: typing.Tuple, hint: typing.Union[type, typing.TypingMeta]) -> bool: """Check argument type & return type of :class:`typing.Tuple`. since it raises check :class:`typing.Tuple` using `isinstance`, so compare in diffrent way :param data: tuple given as a argument ...
[ "def", "check_tuple", "(", "data", ":", "typing", ".", "Tuple", ",", "hint", ":", "typing", ".", "Union", "[", "type", ",", "typing", ".", "TypingMeta", "]", ")", "->", "bool", ":", "if", "not", "isinstance", "(", "data", ",", "tuple", ")", ":", "r...
36.058824
0.000794
def _mass_from_knownmass_eta(known_mass, eta, known_is_secondary=False, force_real=True): r"""Returns the other component mass given one of the component masses and the symmetric mass ratio. This requires finding the roots of the quadratic equation: .. math:: \eta m...
[ "def", "_mass_from_knownmass_eta", "(", "known_mass", ",", "eta", ",", "known_is_secondary", "=", "False", ",", "force_real", "=", "True", ")", ":", "roots", "=", "numpy", ".", "roots", "(", "[", "eta", ",", "(", "2", "*", "eta", "-", "1", ")", "*", ...
34.853659
0.001361
def get_media_backend(fail_silently=True, handles_media_types=None, handles_file_extensions=None, supports_thumbnails=None): """ Returns the MediaBackend subclass that is configured for use with media_tree. """ backends = app_settings.MEDIA_TREE_MEDIA_BACKENDS if no...
[ "def", "get_media_backend", "(", "fail_silently", "=", "True", ",", "handles_media_types", "=", "None", ",", "handles_file_extensions", "=", "None", ",", "supports_thumbnails", "=", "None", ")", ":", "backends", "=", "app_settings", ".", "MEDIA_TREE_MEDIA_BACKENDS", ...
47.846154
0.014972
def parse(self, document, text): """Depth-first search over the provided tree. Implemented as an iterative procedure. The structure of the state needed to parse each node is also defined in this function. :param document: the Document context :param text: the structured text of...
[ "def", "parse", "(", "self", ",", "document", ",", "text", ")", ":", "stack", "=", "[", "]", "root", "=", "lxml", ".", "html", ".", "fromstring", "(", "text", ")", "# flattens children of node that are in the 'flatten' list", "if", "self", ".", "flatten", ":...
40.675
0.0018
def absent(name, user=None, config=None): ''' Verifies that the specified host is not known by the given user name The host name Note that only single host names are supported. If foo.example.com and bar.example.com are the same machine and you need to exclude both, you wil...
[ "def", "absent", "(", "name", ",", "user", "=", "None", ",", "config", "=", "None", ")", ":", "ret", "=", "{", "'name'", ":", "name", ",", "'changes'", ":", "{", "}", ",", "'result'", ":", "True", ",", "'comment'", ":", "''", "}", "if", "not", ...
36.615385
0.001535
def _get_indexers_coords_and_indexes(self, indexers): """ Extract coordinates from indexers. Returns an OrderedDict mapping from coordinate name to the coordinate variable. Only coordinate with a name different from any of self.variables will be attached. """ fr...
[ "def", "_get_indexers_coords_and_indexes", "(", "self", ",", "indexers", ")", ":", "from", ".", "dataarray", "import", "DataArray", "coord_list", "=", "[", "]", "indexes", "=", "OrderedDict", "(", ")", "for", "k", ",", "v", "in", "indexers", ".", "items", ...
42.785714
0.001088
def proto_0111(theABF): """protocol: IC ramp for AP shape analysis.""" abf=ABF(theABF) abf.log.info("analyzing as an IC ramp") # AP detection ap=AP(abf) ap.detect() # also calculate derivative for each sweep abf.derivative=True # create the multi-plot figure plt.figure(figsize...
[ "def", "proto_0111", "(", "theABF", ")", ":", "abf", "=", "ABF", "(", "theABF", ")", "abf", ".", "log", ".", "info", "(", "\"analyzing as an IC ramp\"", ")", "# AP detection", "ap", "=", "AP", "(", "abf", ")", "ap", ".", "detect", "(", ")", "# also cal...
31.735849
0.028835
def train_df(self, df): """ Train scale from a dataframe """ aesthetics = sorted(set(self.aesthetics) & set(df.columns)) for ae in aesthetics: self.train(df[ae])
[ "def", "train_df", "(", "self", ",", "df", ")", ":", "aesthetics", "=", "sorted", "(", "set", "(", "self", ".", "aesthetics", ")", "&", "set", "(", "df", ".", "columns", ")", ")", "for", "ae", "in", "aesthetics", ":", "self", ".", "train", "(", "...
29.571429
0.00939
def dolby(word, max_length=-1, keep_vowels=False, vowel_char='*'): r"""Return the Dolby Code of a name. This is a wrapper for :py:meth:`Dolby.encode`. Parameters ---------- word : str The word to transform max_length : int Maximum length of the returned Dolby code -- this also ...
[ "def", "dolby", "(", "word", ",", "max_length", "=", "-", "1", ",", "keep_vowels", "=", "False", ",", "vowel_char", "=", "'*'", ")", ":", "return", "Dolby", "(", ")", ".", "encode", "(", "word", ",", "max_length", ",", "keep_vowels", ",", "vowel_char",...
21.985294
0.00064
def _rsync_cmd(self): """Helper method to generate base rsync command.""" cmd = ['rsync'] if self._identity_file: cmd += ['-e', 'ssh -i ' + os.path.expanduser(self._identity_file)] return cmd
[ "def", "_rsync_cmd", "(", "self", ")", ":", "cmd", "=", "[", "'rsync'", "]", "if", "self", ".", "_identity_file", ":", "cmd", "+=", "[", "'-e'", ",", "'ssh -i '", "+", "os", ".", "path", ".", "expanduser", "(", "self", ".", "_identity_file", ")", "]"...
38.333333
0.008511
def getXlogStatus(self): """Returns Transaction Logging or Recovery Status. @return: Dictionary of status items. """ inRecovery = None if self.checkVersion('9.0'): inRecovery = self._simpleQuery("SELECT pg_is_in_recovery();") cur = self._conn...
[ "def", "getXlogStatus", "(", "self", ")", ":", "inRecovery", "=", "None", "if", "self", ".", "checkVersion", "(", "'9.0'", ")", ":", "inRecovery", "=", "self", ".", "_simpleQuery", "(", "\"SELECT pg_is_in_recovery();\"", ")", "cur", "=", "self", ".", "_conn"...
41.8125
0.008035
def default(self, line): """Overriding default to get access to any argparse commands we have specified.""" if any((line.startswith(x) for x in self.argparse_names())): try: args = self.argparser.parse_args(shlex.split(line)) except Exception: # intentionally ca...
[ "def", "default", "(", "self", ",", "line", ")", ":", "if", "any", "(", "(", "line", ".", "startswith", "(", "x", ")", "for", "x", "in", "self", ".", "argparse_names", "(", ")", ")", ")", ":", "try", ":", "args", "=", "self", ".", "argparser", ...
39.166667
0.008316
def make_join_request(self, password = None, history_maxchars = None, history_maxstanzas = None, history_seconds = None, history_since = None): """ Make the presence stanza a MUC room join request. :Parameters: - `password`: password to the room. ...
[ "def", "make_join_request", "(", "self", ",", "password", "=", "None", ",", "history_maxchars", "=", "None", ",", "history_maxstanzas", "=", "None", ",", "history_seconds", "=", "None", ",", "history_since", "=", "None", ")", ":", "self", ".", "clear_muc_child...
44.53125
0.010989
def _prepare_file(self, finder, req_to_install): """Prepare a single requirements files. :return: A list of addition InstallRequirements to also install. """ # Tell user what we are doing for this requirement: # obtain (editable), skipping, processing (local url), collecting ...
[ "def", "_prepare_file", "(", "self", ",", "finder", ",", "req_to_install", ")", ":", "# Tell user what we are doing for this requirement:", "# obtain (editable), skipping, processing (local url), collecting", "# (remote url or package name)", "if", "req_to_install", ".", "editable", ...
47.713542
0.000214
def getStrings(lang_dict): """ Return a FunctionFS descriptor suitable for serialisation. lang_dict (dict) Key: language ID (ex: 0x0409 for en-us) Value: list of unicode objects All values must have the same number of items. """ field_list = [] kw = {} try: s...
[ "def", "getStrings", "(", "lang_dict", ")", ":", "field_list", "=", "[", "]", "kw", "=", "{", "}", "try", ":", "str_count", "=", "len", "(", "next", "(", "iter", "(", "lang_dict", ".", "values", "(", ")", ")", ")", ")", "except", "StopIteration", "...
28.714286
0.001375
def copy_part_from_key(self, src_bucket_name, src_key_name, part_num, start=None, end=None): """ Copy another part of this MultiPart Upload. :type src_bucket_name: string :param src_bucket_name: Name of the bucket containing the source key :type src_k...
[ "def", "copy_part_from_key", "(", "self", ",", "src_bucket_name", ",", "src_key_name", ",", "part_num", ",", "start", "=", "None", ",", "end", "=", "None", ")", ":", "if", "part_num", "<", "1", ":", "raise", "ValueError", "(", "'Part numbers must be greater th...
39.090909
0.002269
def set_config(self, key, value): '''set {key:value} paris to self.config''' self.config = self.read_file() self.config[key] = value self.write_file()
[ "def", "set_config", "(", "self", ",", "key", ",", "value", ")", ":", "self", ".", "config", "=", "self", ".", "read_file", "(", ")", "self", ".", "config", "[", "key", "]", "=", "value", "self", ".", "write_file", "(", ")" ]
35.6
0.010989
def avail_images(call=None): ''' Return available OpenNebula images. CLI Example: .. code-block:: bash salt-cloud --list-images opennebula salt-cloud --function avail_images opennebula salt-cloud -f avail_images opennebula ''' if call == 'action': raise SaltCl...
[ "def", "avail_images", "(", "call", "=", "None", ")", ":", "if", "call", "==", "'action'", ":", "raise", "SaltCloudSystemExit", "(", "'The avail_images function must be called with '", "'-f or --function, or with the --list-images option'", ")", "server", ",", "user", ","...
25.068966
0.001325
def _gradient_descent(objective, p0, it, n_iter, n_iter_check=1, n_iter_without_progress=300, momentum=0.8, learning_rate=200.0, min_gain=0.01, min_grad_norm=1e-7, verbose=0, args=None, kwargs=None): """Batch gradient descent with momentum and indivi...
[ "def", "_gradient_descent", "(", "objective", ",", "p0", ",", "it", ",", "n_iter", ",", "n_iter_check", "=", "1", ",", "n_iter_without_progress", "=", "300", ",", "momentum", "=", "0.8", ",", "learning_rate", "=", "200.0", ",", "min_gain", "=", "0.01", ","...
32.756098
0.000241
def add_graph(self, graph): """Adds a `Graph` protocol buffer to the event file.""" event = event_pb2.Event(graph_def=graph.SerializeToString()) self._add_event(event, None)
[ "def", "add_graph", "(", "self", ",", "graph", ")", ":", "event", "=", "event_pb2", ".", "Event", "(", "graph_def", "=", "graph", ".", "SerializeToString", "(", ")", ")", "self", ".", "_add_event", "(", "event", ",", "None", ")" ]
48.5
0.010152
def find_closest_trackpointLB(self,l,b,D,vlos,pmll,pmbb,interp=True, usev=False): """ NAME: find_closest_trackpointLB PURPOSE: find the closest point on the stream track to a given point in (l,b,...) coordinates INPUT: ...
[ "def", "find_closest_trackpointLB", "(", "self", ",", "l", ",", "b", ",", "D", ",", "vlos", ",", "pmll", ",", "pmbb", ",", "interp", "=", "True", ",", "usev", "=", "False", ")", ":", "if", "interp", ":", "nTrackPoints", "=", "len", "(", "self", "."...
36.072917
0.024733
def get_full_page_box_list_assigning_media_and_crop(input_doc, quiet=False): """Get a list of all the full-page box values for each page. The argument input_doc should be a PdfFileReader object. The boxes on the list are in the simple 4-float list format used by this program, not RectangleObject format.""...
[ "def", "get_full_page_box_list_assigning_media_and_crop", "(", "input_doc", ",", "quiet", "=", "False", ")", ":", "full_page_box_list", "=", "[", "]", "rotation_list", "=", "[", "]", "if", "args", ".", "verbose", "and", "not", "quiet", ":", "print", "(", "\"\\...
41.8
0.002338
def bind_protocol(self, proto): """Tries to bind given protocol to this peer. Should only be called by `proto` trying to bind. Once bound this protocol instance will be used to communicate with peer. If another protocol is already bound, connection collision resolution takes pla...
[ "def", "bind_protocol", "(", "self", ",", "proto", ")", ":", "LOG", ".", "debug", "(", "'Trying to bind protocol %s to peer %s'", ",", "proto", ",", "self", ")", "# Validate input.", "if", "not", "isinstance", "(", "proto", ",", "BgpProtocol", ")", ":", "raise...
43.756757
0.000604
def visitBuiltinValueType(self, ctx: jsgParser.BuiltinValueTypeContext): """ valueTypeExpr: JSON_STRING | JSON_NUMBER | JSON_INT | JSON_BOOL | JSON_NULL | JSON_ARRAY | JSON_OBJECT """ self._value_type_text = ctx.getText() self._typeinfo = self.parserTypeToImplClass[self._value_type_text]
[ "def", "visitBuiltinValueType", "(", "self", ",", "ctx", ":", "jsgParser", ".", "BuiltinValueTypeContext", ")", ":", "self", ".", "_value_type_text", "=", "ctx", ".", "getText", "(", ")", "self", ".", "_typeinfo", "=", "self", ".", "parserTypeToImplClass", "["...
77.25
0.009615
def help_center_article_subscriptions(self, article_id, locale=None, **kwargs): "https://developer.zendesk.com/rest_api/docs/help_center/subscriptions#list-article-subscriptions" api_path = "/api/v2/help_center/articles/{article_id}/subscriptions.json" api_path = api_path.format(article_id=artic...
[ "def", "help_center_article_subscriptions", "(", "self", ",", "article_id", ",", "locale", "=", "None", ",", "*", "*", "kwargs", ")", ":", "api_path", "=", "\"/api/v2/help_center/articles/{article_id}/subscriptions.json\"", "api_path", "=", "api_path", ".", "format", ...
70.375
0.010526
def background_model(self, ignore_black=True, use_hsv=False, scale=8): """Creates a background model for the given image. The background color is given by the modes of each channel's histogram. Parameters ---------- ignore_black : bool If True, the zero pixels will b...
[ "def", "background_model", "(", "self", ",", "ignore_black", "=", "True", ",", "use_hsv", "=", "False", ",", "scale", "=", "8", ")", ":", "# hsv color", "data", "=", "self", ".", "data", "if", "use_hsv", ":", "pil_im", "=", "PImage", ".", "fromarray", ...
36.481481
0.001483
def write_iso19115_metadata(layer_uri, keywords, version_35=False): """Create metadata object from a layer path and keywords dictionary. This function will save these keywords to the file system or the database. :param version_35: If we write keywords version 3.5. Default to False. :type version_35: ...
[ "def", "write_iso19115_metadata", "(", "layer_uri", ",", "keywords", ",", "version_35", "=", "False", ")", ":", "active_metadata_classes", "=", "METADATA_CLASSES", "if", "version_35", ":", "active_metadata_classes", "=", "METADATA_CLASSES35", "if", "'layer_purpose'", "i...
34.673469
0.000572
def listener_dict_to_tuple(listener): ''' Convert an ELB listener dict into a listener tuple used by certain parts of the AWS ELB API. CLI example: .. code-block:: bash salt myminion boto_elb.listener_dict_to_tuple '{"elb_port":80,"instance_port":80,"elb_protocol":"HTTP"}' ''' # W...
[ "def", "listener_dict_to_tuple", "(", "listener", ")", ":", "# We define all listeners as complex listeners.", "if", "'instance_protocol'", "not", "in", "listener", ":", "instance_protocol", "=", "listener", "[", "'elb_protocol'", "]", ".", "upper", "(", ")", "else", ...
37.380952
0.002484
def p_values(self, p): """values : | values value VALUE_SEPARATOR | values value""" if len(p) == 1: p[0] = list() else: p[1].append(p[2]) p[0] = p[1]
[ "def", "p_values", "(", "self", ",", "p", ")", ":", "if", "len", "(", "p", ")", "==", "1", ":", "p", "[", "0", "]", "=", "list", "(", ")", "else", ":", "p", "[", "1", "]", ".", "append", "(", "p", "[", "2", "]", ")", "p", "[", "0", "]...
26.333333
0.008163
def arguments_to_lists(function): """ Decorator for a function that converts all arguments to lists. :param function: target function :return: target function with only lists as parameters """ def l_function(*args, **kwargs): l_args = [_to_list(arg) for arg in args] l_kw...
[ "def", "arguments_to_lists", "(", "function", ")", ":", "def", "l_function", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "l_args", "=", "[", "_to_list", "(", "arg", ")", "for", "arg", "in", "args", "]", "l_kwargs", "=", "{", "}", "for", "k...
29.3125
0.002066
def logistic(x, a=0., b=1.): r"""Computes the logistic function with range :math:`\in (a, b)`. This is given by: .. math:: \mathrm{logistic}(x; a, b) = \frac{a + b e^x}{1 + e^x}. Note that this is also the inverse of the logit function with domain :math:`(a, b)`. ...
[ "def", "logistic", "(", "x", ",", "a", "=", "0.", ",", "b", "=", "1.", ")", ":", "expx", "=", "numpy", ".", "exp", "(", "x", ")", "return", "(", "a", "+", "b", "*", "expx", ")", "/", "(", "1.", "+", "expx", ")" ]
26.2
0.002454