text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def in_ellipsoid(x, A, c): """ Determines which of the points ``x`` are in the closed ellipsoid with shape matrix ``A`` centered at ``c``. For a single point ``x``, this is computed as .. math:: (c-x)^T\cdot A^{-1}\cdot (c-x) \leq 1 :param np.ndarray x: Shape ``(n_points, dim)`...
[ "def", "in_ellipsoid", "(", "x", ",", "A", ",", "c", ")", ":", "if", "x", ".", "ndim", "==", "1", ":", "y", "=", "c", "-", "x", "return", "np", ".", "einsum", "(", "'j,jl,l'", ",", "y", ",", "np", ".", "linalg", ".", "inv", "(", "A", ")", ...
35.35
18.75
def HandleRequest(self, request): """Handles given HTTP request.""" impersonated_username = config.CONFIG["AdminUI.debug_impersonate_user"] if impersonated_username: logging.info("Overriding user as %s", impersonated_username) request.user = config.CONFIG["AdminUI.debug_impersonate_user"] i...
[ "def", "HandleRequest", "(", "self", ",", "request", ")", ":", "impersonated_username", "=", "config", ".", "CONFIG", "[", "\"AdminUI.debug_impersonate_user\"", "]", "if", "impersonated_username", ":", "logging", ".", "info", "(", "\"Overriding user as %s\"", ",", "...
41.846154
20.148352
def parse_args(): """ Parse arguments. """ parser = argparse.ArgumentParser() parser.add_argument('--gpu-id', type=int, default=0, help='GPU id (-1 means CPU)') parser.add_argument('--train-file', default='snli_1.0/snli_1.0_train.txt', help='traini...
[ "def", "parse_args", "(", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", ")", "parser", ".", "add_argument", "(", "'--gpu-id'", ",", "type", "=", "int", ",", "default", "=", "0", ",", "help", "=", "'GPU id (-1 means CPU)'", ")", "parser",...
52.511111
18.2
def get(key, default=''): ''' defaults.get is used much like pillar.get except that it will read a default value for a pillar from defaults.json or defaults.yaml files that are stored in the root of a salt formula. CLI Example: .. code-block:: bash salt '*' defaults.get core:users:roo...
[ "def", "get", "(", "key", ",", "default", "=", "''", ")", ":", "# Determine formula namespace from query", "if", "':'", "in", "key", ":", "namespace", ",", "key", "=", "key", ".", "split", "(", "':'", ",", "1", ")", "else", ":", "namespace", ",", "key"...
27.969697
25.727273
def send(self, data): """Send a formatted message to the ADB server""" self._send_data(int_to_hex(len(data))) self._send_data(data)
[ "def", "send", "(", "self", ",", "data", ")", ":", "self", ".", "_send_data", "(", "int_to_hex", "(", "len", "(", "data", ")", ")", ")", "self", ".", "_send_data", "(", "data", ")" ]
30.4
15.2
def link_label(link): '''return a link label as a string''' if hasattr(link, 'label'): label = link.label else: label = str(link.linknum+1) return label
[ "def", "link_label", "(", "link", ")", ":", "if", "hasattr", "(", "link", ",", "'label'", ")", ":", "label", "=", "link", ".", "label", "else", ":", "label", "=", "str", "(", "link", ".", "linknum", "+", "1", ")", "return", "label" ]
28.857143
12.571429
def combine_intersections( intersections, nodes1, degree1, nodes2, degree2, all_types ): r"""Combine curve-curve intersections into curved polygon(s). .. note:: This is a helper used only by :meth:`.Surface.intersect`. Does so assuming each intersection lies on an edge of one of two :class...
[ "def", "combine_intersections", "(", "intersections", ",", "nodes1", ",", "degree1", ",", "nodes2", ",", "degree2", ",", "all_types", ")", ":", "if", "intersections", ":", "return", "basic_interior_combine", "(", "intersections", ")", "elif", "all_types", ":", "...
39.104167
26.229167
def open_macros(self, filepath): """Loads macros from file and marks grid as changed Parameters ---------- filepath: String \tPath to macro file """ try: wx.BeginBusyCursor() self.main_window.grid.Disable() with open(filepat...
[ "def", "open_macros", "(", "self", ",", "filepath", ")", ":", "try", ":", "wx", ".", "BeginBusyCursor", "(", ")", "self", ".", "main_window", ".", "grid", ".", "Disable", "(", ")", "with", "open", "(", "filepath", ")", "as", "macro_infile", ":", "# Ent...
30.155556
23.444444
def replace_customer_by_id(cls, customer_id, customer, **kwargs): """Replace Customer Replace all attributes of Customer This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.replace_customer_by_id(...
[ "def", "replace_customer_by_id", "(", "cls", ",", "customer_id", ",", "customer", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'async'", ")", ":", "return", "cls", ".", ...
45.090909
22.454545
def _build_appid_info(self, master, dict): ''' Builds the appid info object @param master: the master dict @param dict: the dict object received @return: the appid info object ''' master['total_crawlids'] = 0 master['total_pending'] = 0 master['to...
[ "def", "_build_appid_info", "(", "self", ",", "master", ",", "dict", ")", ":", "master", "[", "'total_crawlids'", "]", "=", "0", "master", "[", "'total_pending'", "]", "=", "0", "master", "[", "'total_domains'", "]", "=", "0", "master", "[", "'crawlids'", ...
41.614286
24.585714
def get_medium(self, agent_type, index=0): '''Returns the medium class for the given agent_type. Optional index tells which one to give.''' mediums = list(x for x in self.agency._agents if x.get_descriptor().type_name == agent_type) try: return mediums[...
[ "def", "get_medium", "(", "self", ",", "agent_type", ",", "index", "=", "0", ")", ":", "mediums", "=", "list", "(", "x", "for", "x", "in", "self", ".", "agency", ".", "_agents", "if", "x", ".", "get_descriptor", "(", ")", ".", "type_name", "==", "a...
47.416667
17.416667
def netconf_state_schemas_schema_version(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") netconf_state = ET.SubElement(config, "netconf-state", xmlns="urn:ietf:params:xml:ns:yang:ietf-netconf-monitoring") schemas = ET.SubElement(netconf_state, "schemas")...
[ "def", "netconf_state_schemas_schema_version", "(", "self", ",", "*", "*", "kwargs", ")", ":", "config", "=", "ET", ".", "Element", "(", "\"config\"", ")", "netconf_state", "=", "ET", ".", "SubElement", "(", "config", ",", "\"netconf-state\"", ",", "xmlns", ...
47.375
16.3125
def remove_finished_work_units(self, work_spec_name, work_unit_names): '''Remove some finished work units. If `work_unit_names` is :const:`None` (which must be passed explicitly), all finished work units in `work_spec_name` are removed; otherwise only the specific named work units will ...
[ "def", "remove_finished_work_units", "(", "self", ",", "work_spec_name", ",", "work_unit_names", ")", ":", "return", "self", ".", "_remove_some_work_units", "(", "work_spec_name", ",", "work_unit_names", ",", "suffix", "=", "_FINISHED", ")" ]
43.4
23.266667
def rsync_upload(): """ Uploads the project with rsync excluding some files and folders. """ excludes = ["*.pyc", "*.pyo", "*.db", ".DS_Store", ".coverage", "local_settings.py", "/static", "/.git", "/.hg"] local_dir = os.getcwd() + os.sep return rsync_project(remote_dir=env.proj_...
[ "def", "rsync_upload", "(", ")", ":", "excludes", "=", "[", "\"*.pyc\"", ",", "\"*.pyo\"", ",", "\"*.db\"", ",", "\".DS_Store\"", ",", "\".coverage\"", ",", "\"local_settings.py\"", ",", "\"/static\"", ",", "\"/.git\"", ",", "\"/.hg\"", "]", "local_dir", "=", ...
42.333333
15.222222
def get_checks_status_counts(self, checks=None): """ Compute the counts of the different checks status and return it as a defaultdict(int) with the keys being the different status and the values being the count of the checks in that status. :checks: None or the checks you want to count ...
[ "def", "get_checks_status_counts", "(", "self", ",", "checks", "=", "None", ")", ":", "if", "checks", "is", "None", ":", "checks", "=", "self", ".", "checks", "res", "=", "defaultdict", "(", "int", ")", "res", "[", "\"total\"", "]", "=", "len", "(", ...
34.142857
16.619048
def neg_loglikelihood(y, mean, scale, shape, skewness): """ Negative loglikelihood function Parameters ---------- y : np.ndarray univariate time series mean : np.ndarray array of location parameters for the Poisson distribution scale : float ...
[ "def", "neg_loglikelihood", "(", "y", ",", "mean", ",", "scale", ",", "shape", ",", "skewness", ")", ":", "return", "-", "np", ".", "sum", "(", "-", "mean", "+", "np", ".", "log", "(", "mean", ")", "*", "y", "-", "sp", ".", "gammaln", "(", "y",...
27.76
22.72
def CreatedField(name='created', tz_aware=False, **kwargs): ''' A shortcut field for creation time. It sets the current date and time when it enters the database and then doesn't update on further saves. If you've used the Django ORM, this is the equivalent of auto_now_add :param tz_aware...
[ "def", "CreatedField", "(", "name", "=", "'created'", ",", "tz_aware", "=", "False", ",", "*", "*", "kwargs", ")", ":", "@", "computed_field", "(", "DateTimeField", "(", ")", ",", "one_time", "=", "True", ",", "*", "*", "kwargs", ")", "def", "created",...
41.647059
26.588235
def get_conn(): ''' Return a conn object for the passed VM data ''' vm_ = get_configured_provider() kwargs = vm_.copy() # pylint: disable=E1103 kwargs['username'] = vm_['user'] kwargs['project_id'] = vm_['tenant'] kwargs['auth_url'] = vm_['identity_url'] kwargs['region_name'] = vm...
[ "def", "get_conn", "(", ")", ":", "vm_", "=", "get_configured_provider", "(", ")", "kwargs", "=", "vm_", ".", "copy", "(", ")", "# pylint: disable=E1103", "kwargs", "[", "'username'", "]", "=", "vm_", "[", "'user'", "]", "kwargs", "[", "'project_id'", "]",...
32.916667
21.75
def read_colortable(fobj): r"""Read colortable information from a file. Reads a colortable, which consists of one color per line of the file, where a color can be one of: a tuple of 3 floats, a string with a HTML color name, or a string with a HTML hex color. Parameters ---------- fobj : a...
[ "def", "read_colortable", "(", "fobj", ")", ":", "ret", "=", "[", "]", "try", ":", "for", "line", "in", "fobj", ":", "literal", "=", "_parse", "(", "line", ")", "if", "literal", ":", "ret", ".", "append", "(", "mcolors", ".", "colorConverter", ".", ...
29.035714
22.642857
def check_encryption_password(self, password): """Checks whether the supplied password is correct for the medium. in password of type str The password to check. raises :class:`VBoxErrorNotSupported` Encryption is not configured for this medium. raises :...
[ "def", "check_encryption_password", "(", "self", ",", "password", ")", ":", "if", "not", "isinstance", "(", "password", ",", "basestring", ")", ":", "raise", "TypeError", "(", "\"password can only be an instance of type basestring\"", ")", "self", ".", "_call", "(",...
36.470588
15.235294
def set_password(self, service, username, password): """Set password for the username of the service """ segments = range(0, len(password), self._max_password_size) password_parts = [ password[i:i + self._max_password_size] for i in segments] for i, password_part in e...
[ "def", "set_password", "(", "self", ",", "service", ",", "username", ",", "password", ")", ":", "segments", "=", "range", "(", "0", ",", "len", "(", "password", ")", ",", "self", ".", "_max_password_size", ")", "password_parts", "=", "[", "password", "["...
47.545455
15.545455
def _set_value(self, slot_record): """Sets the value of this slot based on its corresponding _SlotRecord. Does nothing if the slot has not yet been filled. Args: slot_record: The _SlotRecord containing this Slot's value. """ if slot_record.status == _SlotRecord.FILLED: self.filled = Tr...
[ "def", "_set_value", "(", "self", ",", "slot_record", ")", ":", "if", "slot_record", ".", "status", "==", "_SlotRecord", ".", "FILLED", ":", "self", ".", "filled", "=", "True", "self", ".", "_filler_pipeline_key", "=", "_SlotRecord", ".", "filler", ".", "g...
35.571429
17.5
def on_new(self): """ Add a new empty code editor to the tab widget """ editor = self.tabWidget.create_new_document() editor.cursorPositionChanged.connect(self.on_cursor_pos_changed) self.refresh_color_scheme()
[ "def", "on_new", "(", "self", ")", ":", "editor", "=", "self", ".", "tabWidget", ".", "create_new_document", "(", ")", "editor", ".", "cursorPositionChanged", ".", "connect", "(", "self", ".", "on_cursor_pos_changed", ")", "self", ".", "refresh_color_scheme", ...
36
12.285714
def pause(): """ Pause the timer, preventing subsequent time from accumulating in the total. Renders the timer inactive, disabling other timing commands. Returns: float: The current time. Raises: PausedError: If timer already paused. StoppedError: If timer already stopped....
[ "def", "pause", "(", ")", ":", "t", "=", "timer", "(", ")", "if", "f", ".", "t", ".", "stopped", ":", "raise", "StoppedError", "(", "\"Cannot pause stopped timer.\"", ")", "if", "f", ".", "t", ".", "paused", ":", "raise", "PausedError", "(", "\"Timer a...
26.727273
19.636364
def profile_fields(user): """ Returns profile fields as a dict for the given user. Used in the profile view template when the ``ACCOUNTS_PROFILE_VIEWS_ENABLED`` setting is set to ``True``, and also in the account approval emails sent to administrators when the ``ACCOUNTS_APPROVAL_REQUIRED`` sett...
[ "def", "profile_fields", "(", "user", ")", ":", "fields", "=", "OrderedDict", "(", ")", "try", ":", "profile", "=", "get_profile_for_user", "(", "user", ")", "user_fieldname", "=", "get_profile_user_fieldname", "(", ")", "exclude", "=", "tuple", "(", "settings...
41.9
16.7
def getNumberOfJobsIssued(self, preemptable=None): """ Gets number of jobs that have been added by issueJob(s) and not removed by removeJob :param None or boolean preemptable: If none, return all types of jobs. If true, return just the number of preemptable jobs. If false, ret...
[ "def", "getNumberOfJobsIssued", "(", "self", ",", "preemptable", "=", "None", ")", ":", "if", "preemptable", "is", "None", ":", "return", "len", "(", "self", ".", "jobBatchSystemIDToIssuedJob", ")", "elif", "preemptable", ":", "return", "self", ".", "preemptab...
44.9375
21.4375
async def file(location, mime_type=None, headers=None, _range=None): '''Return a response object with file data. :param location: Location of file on system. :param mime_type: Specific mime_type. :param headers: Custom Headers. :param _range: ''' filename = path.split(location)[-1] asy...
[ "async", "def", "file", "(", "location", ",", "mime_type", "=", "None", ",", "headers", "=", "None", ",", "_range", "=", "None", ")", ":", "filename", "=", "path", ".", "split", "(", "location", ")", "[", "-", "1", "]", "async", "with", "open_async",...
35.16
17.16
def compiled_model(self): """Returns compile ORM class for the user supplied model""" return ALCHEMY_TEMPLATES.model.safe_substitute(class_name=self.class_name, table_name=self.table_name, colum...
[ "def", "compiled_model", "(", "self", ")", ":", "return", "ALCHEMY_TEMPLATES", ".", "model", ".", "safe_substitute", "(", "class_name", "=", "self", ".", "class_name", ",", "table_name", "=", "self", ".", "table_name", ",", "column_definitions", "=", "self", "...
93.28
53.4
def calculate_frechet_distance(mu1, sigma1, mu2, sigma2, eps=1e-6): """Numpy implementation of the Frechet Distance. The Frechet distance between two multivariate Gaussians X_1 ~ N(mu_1, C_1) and X_2 ~ N(mu_2, C_2) is d^2 = ||mu_1 - mu_2||^2 + Tr(C_1 + C_2 - 2*sqrt(C_1*C_2)). St...
[ "def", "calculate_frechet_distance", "(", "mu1", ",", "sigma1", ",", "mu2", ",", "sigma2", ",", "eps", "=", "1e-6", ")", ":", "mu1", "=", "np", ".", "atleast_1d", "(", "mu1", ")", "mu2", "=", "np", ".", "atleast_1d", "(", "mu2", ")", "sigma1", "=", ...
40.471698
23.886792
def solve(self, neigs=4, tol=0, guess=None, mode_profiles=True, initial_mode_guess=None): """ This function finds the eigenmodes. Parameters ---------- neigs : int number of eigenmodes to find tol : float Relative accuracy for eigenvalues. The def...
[ "def", "solve", "(", "self", ",", "neigs", "=", "4", ",", "tol", "=", "0", ",", "guess", "=", "None", ",", "mode_profiles", "=", "True", ",", "initial_mode_guess", "=", "None", ")", ":", "from", "scipy", ".", "sparse", ".", "linalg", "import", "eigen...
33.935897
21.448718
def rolling_returns_cumulative(returns, window, min_periods=1, geometric=True): """ return the rolling cumulative returns Parameters ---------- returns : DataFrame or Series window : number of observations min_periods : minimum number of observations in a window geometric : link the returns...
[ "def", "rolling_returns_cumulative", "(", "returns", ",", "window", ",", "min_periods", "=", "1", ",", "geometric", "=", "True", ")", ":", "if", "geometric", ":", "rc", "=", "lambda", "x", ":", "(", "1.", "+", "x", "[", "np", ".", "isfinite", "(", "x...
33.6875
20.1875
def generate_signature(method, version, endpoint, date, rel_url, content_type, content, access_key, secret_key, hash_type): ''' Generates the API request signature from the given parameters. ''' hash_type = hash_type hostname = endpoint._val.netloc # FI...
[ "def", "generate_signature", "(", "method", ",", "version", ",", "endpoint", ",", "date", ",", "rel_url", ",", "content_type", ",", "content", ",", "access_key", ",", "secret_key", ",", "hash_type", ")", ":", "hash_type", "=", "hash_type", "hostname", "=", "...
33.051282
23.769231
def get_itoken(self, env): """Returns the current internal token to use for the auth system's own actions with other services. Each process will create its own itoken and the token will be deleted and recreated based on the token_life configuration value. The itoken information is stored...
[ "def", "get_itoken", "(", "self", ",", "env", ")", ":", "if", "not", "self", ".", "itoken", "or", "self", ".", "itoken_expires", "<", "time", "(", ")", "or", "env", ".", "get", "(", "'HTTP_X_AUTH_NEW_TOKEN'", ",", "'false'", ")", ".", "lower", "(", "...
51.44
19.4
def broadcast(self, body, html_body=None, exclude=()): """Broadcast a message to users in the chatroom""" logger.info('broadcast on %s: %s' % (self.name, body,)) for member in filter(lambda m: m.get('STATUS') == 'ACTIVE' and m not in exclude, self.params['MEMBERS']): logger.debug(mem...
[ "def", "broadcast", "(", "self", ",", "body", ",", "html_body", "=", "None", ",", "exclude", "=", "(", ")", ")", ":", "logger", ".", "info", "(", "'broadcast on %s: %s'", "%", "(", "self", ".", "name", ",", "body", ",", ")", ")", "for", "member", "...
67.166667
24.5
def fs_decode(path): """ Decode a filesystem path using the proper filesystem encoding :param path: The filesystem path to decode from bytes or string :return: The filesystem path, decoded with the determined encoding :rtype: Text """ path = _get_path(path) if path is None: rai...
[ "def", "fs_decode", "(", "path", ")", ":", "path", "=", "_get_path", "(", "path", ")", "if", "path", "is", "None", ":", "raise", "TypeError", "(", "\"expected a valid path to decode\"", ")", "if", "isinstance", "(", "path", ",", "six", ".", "binary_type", ...
32.304348
20.304348
def to_description_dict(self): """ You might need keys below in some situation - caCertificateId - previousOwnedBy """ return { 'certificateArn': self.arn, 'certificateId': self.certificate_id, 'status': self.status, 'ce...
[ "def", "to_description_dict", "(", "self", ")", ":", "return", "{", "'certificateArn'", ":", "self", ".", "arn", ",", "'certificateId'", ":", "self", ".", "certificate_id", ",", "'status'", ":", "self", ".", "status", ",", "'certificatePem'", ":", "self", "....
33.625
10.25
def find(cls, device=None): """ Factory method that returns the requested :py:class:`USBDevice` device, or the first device. :param device: Tuple describing the USB device to open, as returned by find_all(). :type device: tuple :returns: :py:class...
[ "def", "find", "(", "cls", ",", "device", "=", "None", ")", ":", "if", "not", "have_pyftdi", ":", "raise", "ImportError", "(", "'The USBDevice class has been disabled due to missing requirement: pyftdi or pyusb.'", ")", "cls", ".", "find_all", "(", ")", "if", "len",...
34.038462
25.576923
def step_use_curdir_as_working_directory(context): """ Uses the current directory as working directory """ context.workdir = os.path.abspath(".") command_util.ensure_workdir_exists(context)
[ "def", "step_use_curdir_as_working_directory", "(", "context", ")", ":", "context", ".", "workdir", "=", "os", ".", "path", ".", "abspath", "(", "\".\"", ")", "command_util", ".", "ensure_workdir_exists", "(", "context", ")" ]
34
5
def relaxedEMDS(X0, N, d, C, b, KE, print_out=False, lamda=10): """ Find the set of points from an edge kernel with geometric constraints, using convex rank relaxation. """ E = C.shape[1] X = Variable((E, E), PSD=True) constraints = [C[i, :] * X == b[i] for i in range(C.shape[0])] obj = Minimi...
[ "def", "relaxedEMDS", "(", "X0", ",", "N", ",", "d", ",", "C", ",", "b", ",", "KE", ",", "print_out", "=", "False", ",", "lamda", "=", "10", ")", ":", "E", "=", "C", ".", "shape", "[", "1", "]", "X", "=", "Variable", "(", "(", "E", ",", "...
41.774194
23.483871
def execute(self, source=None, hidden=False, interactive=False): """ Reimplemented to the store history. """ if not hidden: history = self.input_buffer if source is None else source executed = super(HistoryConsoleWidget, self).execute( source, hidden, interactive...
[ "def", "execute", "(", "self", ",", "source", "=", "None", ",", "hidden", "=", "False", ",", "interactive", "=", "False", ")", ":", "if", "not", "hidden", ":", "history", "=", "self", ".", "input_buffer", "if", "source", "is", "None", "else", "source",...
37.130435
19.652174
def delete_bgedge(self, bgedge, key=None): """ Deletes a supplied :class:`bg.edge.BGEdge` from a perspective of multi-color substitution. If unique identifier ``key`` is not provided, most similar (from perspective of :meth:`bg.multicolor.Multicolor.similarity_score` result) edge between respective vertices is ...
[ "def", "delete_bgedge", "(", "self", ",", "bgedge", ",", "key", "=", "None", ")", ":", "self", ".", "__delete_bgedge", "(", "bgedge", "=", "bgedge", ",", "key", "=", "key", ")" ]
70.5
25
def install_yum(self, fn=None, package_name=None, update=0, list_only=0): """ Installs system packages listed in yum-requirements.txt. """ assert self.genv[ROLE] yum_req_fn = fn or self.find_template(self.genv.yum_requirments_fn) if not yum_req_fn: return [] ...
[ "def", "install_yum", "(", "self", ",", "fn", "=", "None", ",", "package_name", "=", "None", ",", "update", "=", "0", ",", "list_only", "=", "0", ")", ":", "assert", "self", ".", "genv", "[", "ROLE", "]", "yum_req_fn", "=", "fn", "or", "self", ".",...
41.92
19.6
def say(self, phrase, **_options): ''' Says the phrase, optionally allows to select/override any voice options. ''' language, voice, voiceinfo, options = self._configure(**_options) self._logger.debug("Saying '%s' with '%s'", phrase, self.SLUG) self._say(phrase, language,...
[ "def", "say", "(", "self", ",", "phrase", ",", "*", "*", "_options", ")", ":", "language", ",", "voice", ",", "voiceinfo", ",", "options", "=", "self", ".", "_configure", "(", "*", "*", "_options", ")", "self", ".", "_logger", ".", "debug", "(", "\...
48.714286
27
def color2idx(self, red, green, blue): """Get an Excel index from""" xlwt_colors = [ (0, 0, 0), (255, 255, 255), (255, 0, 0), (0, 255, 0), (0, 0, 255), (255, 255, 0), (255, 0, 255), (0, 255, 255), (0, 0, 0), (255, 255, 255), (255, 0, 0), (0, 255, 0), (0, 0, 255), ...
[ "def", "color2idx", "(", "self", ",", "red", ",", "green", ",", "blue", ")", ":", "xlwt_colors", "=", "[", "(", "0", ",", "0", ",", "0", ")", ",", "(", "255", ",", "255", ",", "255", ")", ",", "(", "255", ",", "0", ",", "0", ")", ",", "("...
51.357143
27.392857
def _handle_result_line(self, sline): """ Parses the data line and adds to the dictionary. :param sline: a split data line to parse :returns: the number of rows to jump and parse the next data line or return the code error -1 """ as_kw = sline[3] a_result ...
[ "def", "_handle_result_line", "(", "self", ",", "sline", ")", ":", "as_kw", "=", "sline", "[", "3", "]", "a_result", "=", "str", "(", "sline", "[", "5", "]", ".", "split", "(", "'^'", ")", "[", "0", "]", ")", "self", ".", "_cur_values", "[", "as_...
33.5
11.785714
def do_searchhex(self, arg): """ [~process] sh [address-address] <hexadecimal pattern> [~process] searchhex [address-address] <hexadecimal pattern> """ token_list = self.split_tokens(arg, 1, 3) pid, tid = self.get_process_and_thread_ids_from_prefix() process ...
[ "def", "do_searchhex", "(", "self", ",", "arg", ")", ":", "token_list", "=", "self", ".", "split_tokens", "(", "arg", ",", "1", ",", "3", ")", "pid", ",", "tid", "=", "self", ".", "get_process_and_thread_ids_from_prefix", "(", ")", "process", "=", "self"...
36.541667
13.208333
def get(self, key, default=None): """ Get item from object for given key (DataFrame column, Panel slice, etc.). Returns default value if not found. Parameters ---------- key : object Returns ------- value : same type as items contained in object ...
[ "def", "get", "(", "self", ",", "key", ",", "default", "=", "None", ")", ":", "try", ":", "return", "self", "[", "key", "]", "except", "(", "KeyError", ",", "ValueError", ",", "IndexError", ")", ":", "return", "default" ]
25.588235
19
def _read_opt_pad(self, code, *, desc): """Read HOPOPT padding options. Structure of HOPOPT padding options [RFC 8200]: * Pad1 Option: +-+-+-+-+-+-+-+-+ | 0 | +-+-+-+-+-+-+-+-+ Octets Bits Name ...
[ "def", "_read_opt_pad", "(", "self", ",", "code", ",", "*", ",", "desc", ")", ":", "_type", "=", "self", ".", "_read_opt_type", "(", "code", ")", "if", "code", "==", "0", ":", "opt", "=", "dict", "(", "desc", "=", "desc", ",", "type", "=", "_type...
37.490196
22.745098
def create_radius_stops(breaks, min_radius, max_radius): """Convert a data breaks into a radius ramp """ num_breaks = len(breaks) radius_breaks = scale_between(min_radius, max_radius, num_breaks) stops = [] for i, b in enumerate(breaks): stops.append([b, radius_breaks[i]]) return st...
[ "def", "create_radius_stops", "(", "breaks", ",", "min_radius", ",", "max_radius", ")", ":", "num_breaks", "=", "len", "(", "breaks", ")", "radius_breaks", "=", "scale_between", "(", "min_radius", ",", "max_radius", ",", "num_breaks", ")", "stops", "=", "[", ...
31.4
15.6
def alias_catalog(self, catalog_id, alias_id): """Adds an ``Id`` to a ``Catalog`` for the purpose of creating compatibility. The primary ``Id`` of the ``Catalog`` is determined by the provider. The new ``Id`` performs as an alias to the primary ``Id``. If the alias is a pointer to anoth...
[ "def", "alias_catalog", "(", "self", ",", "catalog_id", ",", "alias_id", ")", ":", "# Implemented from template for", "# osid.resource.BinLookupSession.alias_bin_template", "if", "self", ".", "_catalog_session", "is", "not", "None", ":", "return", "self", ".", "_catalog...
50.291667
21.041667
def height(self): """Returns the player's height (in inches). :returns: An int representing a player's height in inches. """ doc = self.get_main_doc() raw = doc('span[itemprop="height"]').text() try: feet, inches = map(int, raw.split('-')) return f...
[ "def", "height", "(", "self", ")", ":", "doc", "=", "self", ".", "get_main_doc", "(", ")", "raw", "=", "doc", "(", "'span[itemprop=\"height\"]'", ")", ".", "text", "(", ")", "try", ":", "feet", ",", "inches", "=", "map", "(", "int", ",", "raw", "."...
34.363636
12.727273
def to_string(cls, error_code): """Returns the string message for the given ``error_code``. Args: cls (JLinkEraseErrors): the ``JLinkEraseErrors`` class error_code (int): error code to convert Returns: An error string corresponding to the error code. Rais...
[ "def", "to_string", "(", "cls", ",", "error_code", ")", ":", "if", "error_code", "==", "cls", ".", "ILLEGAL_COMMAND", ":", "return", "'Failed to erase sector.'", "return", "super", "(", "JLinkEraseErrors", ",", "cls", ")", ".", "to_string", "(", "error_code", ...
33.0625
18.8125
def register_default_plugins(root_parser: ParserRegistryWithConverters): """ Utility method to register all default plugins on the given parser+converter registry :param root_parser: :return: """ # -------------------- CORE --------------------------- try: # -- primitive types ...
[ "def", "register_default_plugins", "(", "root_parser", ":", "ParserRegistryWithConverters", ")", ":", "# -------------------- CORE ---------------------------", "try", ":", "# -- primitive types", "from", "parsyfiles", ".", "plugins_base", ".", "support_for_primitive_types", "imp...
46.028169
25.295775
def default_cell_formatter(table, column, row, value, **_): """ :type column: tri.table.Column """ formatter = _cell_formatters.get(type(value)) if formatter: value = formatter(table=table, column=column, row=row, value=value) if value is None: return '' return conditional_...
[ "def", "default_cell_formatter", "(", "table", ",", "column", ",", "row", ",", "value", ",", "*", "*", "_", ")", ":", "formatter", "=", "_cell_formatters", ".", "get", "(", "type", "(", "value", ")", ")", "if", "formatter", ":", "value", "=", "formatte...
26.833333
18.166667
def submit_btn(self, value, success=None): """This presses an input button with type=submit. Success must be given as a tuple of a (coordinate, timeout). Use (coordinate,) if you want to use the default timeout.""" self.press("css=input[value='{}']".format(value)) if success is n...
[ "def", "submit_btn", "(", "self", ",", "value", ",", "success", "=", "None", ")", ":", "self", ".", "press", "(", "\"css=input[value='{}']\"", ".", "format", "(", "value", ")", ")", "if", "success", "is", "not", "None", ":", "assert", "self", ".", "is_...
52.714286
8.857143
def find_ip(family=AF_INET, flavour="opendns"): """Find the publicly visible IP address of the current system. This uses public DNS infrastructure that implement a special DNS "hack" to return the IP address of the requester rather than some other address. :param family: address family, optional, defa...
[ "def", "find_ip", "(", "family", "=", "AF_INET", ",", "flavour", "=", "\"opendns\"", ")", ":", "flavours", "=", "{", "\"opendns\"", ":", "{", "AF_INET", ":", "{", "\"@\"", ":", "(", "\"resolver1.opendns.com\"", ",", "\"resolver2.opendns.com\"", ")", ",", "\"...
37.666667
24.181818
def get_resource(self, resource_name, name): # pylint: disable=too-many-locals, too-many-nested-blocks """Get a specific resource by name""" try: logger.info("Trying to get %s: '%s'", resource_name, name) services_list = False if resource_name == 'host' and '...
[ "def", "get_resource", "(", "self", ",", "resource_name", ",", "name", ")", ":", "# pylint: disable=too-many-locals, too-many-nested-blocks", "try", ":", "logger", ".", "info", "(", "\"Trying to get %s: '%s'\"", ",", "resource_name", ",", "name", ")", "services_list", ...
49.591667
25.083333
def should_see_link_text(self, link_text, link_url): """Assert a link with the provided text points to the provided URL.""" elements = ElementSelector( world.browser, str('//a[@href="%s"][./text()="%s"]' % (link_url, link_text)), filter_displayed=True, ) if not elements: ...
[ "def", "should_see_link_text", "(", "self", ",", "link_text", ",", "link_url", ")", ":", "elements", "=", "ElementSelector", "(", "world", ".", "browser", ",", "str", "(", "'//a[@href=\"%s\"][./text()=\"%s\"]'", "%", "(", "link_url", ",", "link_text", ")", ")", ...
36
19
def fit(self, doc, # type: str predict_proba, # type: Callable[[Any], Any] ): # type: (...) -> TextExplainer """ Explain ``predict_proba`` probabilistic classification function for the ``doc`` example. This method fits a local classificat...
[ "def", "fit", "(", "self", ",", "doc", ",", "# type: str", "predict_proba", ",", "# type: Callable[[Any], Any]", ")", ":", "# type: (...) -> TextExplainer", "self", ".", "doc_", "=", "doc", "if", "self", ".", "position_dependent", ":", "samples", ",", "sims", ",...
32.983871
17.5
def mv_connect_stations(mv_grid_district, graph, debug=False): """ Connect LV stations to MV grid Args ---- mv_grid_district: MVGridDistrictDing0 MVGridDistrictDing0 object for which the connection process has to be done graph: :networkx:`NetworkX Graph Obj< >` NetworkX graph object...
[ "def", "mv_connect_stations", "(", "mv_grid_district", ",", "graph", ",", "debug", "=", "False", ")", ":", "# WGS84 (conformal) to ETRS (equidistant) projection", "proj1", "=", "partial", "(", "pyproj", ".", "transform", ",", "pyproj", ".", "Proj", "(", "init", "=...
50.758621
27.637931
def set_value(self, var_name, value): """Set the value of a given variable to a given value. Parameters ---------- var_name : str The name of the variable in the model whose value should be set. value : float The value the variable should be set to ...
[ "def", "set_value", "(", "self", ",", "var_name", ",", "value", ")", ":", "if", "var_name", "in", "self", ".", "outside_name_map", ":", "var_name", "=", "self", ".", "outside_name_map", "[", "var_name", "]", "print", "(", "'%s=%.5f'", "%", "(", "var_name",...
35.277778
14.777778
def _table_attrs(table): ''' Helper function to find valid table attributes ''' cmd = ['osqueryi'] + ['--json'] + ['pragma table_info({0})'.format(table)] res = __salt__['cmd.run_all'](cmd) if res['retcode'] == 0: attrs = [] text = salt.utils.json.loads(res['stdout']) for...
[ "def", "_table_attrs", "(", "table", ")", ":", "cmd", "=", "[", "'osqueryi'", "]", "+", "[", "'--json'", "]", "+", "[", "'pragma table_info({0})'", ".", "format", "(", "table", ")", "]", "res", "=", "__salt__", "[", "'cmd.run_all'", "]", "(", "cmd", ")...
30.692308
18.384615
def iglob(pathname, patterns): """ Allow multiple file formats. This is also recursive. For example: >>> iglob("apps", "*.py,*.pyc") """ matches = [] patterns = patterns.split(",") if "," in patterns else listify(patterns) for root, dirnames, filenames in os.walk(pathname): matching...
[ "def", "iglob", "(", "pathname", ",", "patterns", ")", ":", "matches", "=", "[", "]", "patterns", "=", "patterns", ".", "split", "(", "\",\"", ")", "if", "\",\"", "in", "patterns", "else", "listify", "(", "patterns", ")", "for", "root", ",", "dirnames"...
34.933333
15.866667
def _unpack_gvars(g): """ Unpack collection of GVars to BufferDict or numpy array. """ if g is not None: g = _gvar.gvar(g) if not hasattr(g, 'flat'): # must be a scalar (ie, not an array and not a dictionary) g = numpy.asarray(g) return g
[ "def", "_unpack_gvars", "(", "g", ")", ":", "if", "g", "is", "not", "None", ":", "g", "=", "_gvar", ".", "gvar", "(", "g", ")", "if", "not", "hasattr", "(", "g", ",", "'flat'", ")", ":", "# must be a scalar (ie, not an array and not a dictionary)", "g", ...
35.375
15.625
def draw_path(self, gc, path, transform, rgbFace=None): """ Draw the path """ nmax = rcParams['agg.path.chunksize'] # here at least for testing npts = path.vertices.shape[0] if (nmax > 100 and npts > nmax and path.should_simplify and rgbFace is None and gc.get...
[ "def", "draw_path", "(", "self", ",", "gc", ",", "path", ",", "transform", ",", "rgbFace", "=", "None", ")", ":", "nmax", "=", "rcParams", "[", "'agg.path.chunksize'", "]", "# here at least for testing", "npts", "=", "path", ".", "vertices", ".", "shape", ...
40.583333
12.25
def _update_version(connection, version): """ Updates version in the db to the given version. Args: connection (sqlalchemy connection): sqlalchemy session where to update version. version (int): version of the migration. """ if connection.engine.name == 'sqlite': connection.exe...
[ "def", "_update_version", "(", "connection", ",", "version", ")", ":", "if", "connection", ".", "engine", ".", "name", "==", "'sqlite'", ":", "connection", ".", "execute", "(", "'PRAGMA user_version = {}'", ".", "format", "(", "version", ")", ")", "elif", "c...
44.612903
30.483871
def allow_attribute_comments(chain, node): """ This augmentation is to allow comments on class attributes, for example: class SomeClass(object): some_attribute = 5 ''' This is a docstring for the above attribute ''' """ # TODO: find the relevant citation for why this is the correct...
[ "def", "allow_attribute_comments", "(", "chain", ",", "node", ")", ":", "# TODO: find the relevant citation for why this is the correct way to comment attributes", "if", "isinstance", "(", "node", ".", "previous_sibling", "(", ")", ",", "astroid", ".", "Assign", ")", "and...
35.764706
23.294118
def init_config(policy_config): """Get policy lambda execution configuration. cli parameters are serialized into the policy lambda config, we merge those with any policy specific execution options. --assume role and -s output directory get special handling, as to disambiguate any cli context. ...
[ "def", "init_config", "(", "policy_config", ")", ":", "global", "account_id", "exec_options", "=", "policy_config", ".", "get", "(", "'execution-options'", ",", "{", "}", ")", "# Remove some configuration options that don't make sense to translate from", "# cli to lambda auto...
41.77193
21.210526
def setrank(self,v): """set rank value for vertex v and add it to the corresponding layer. The Layer is created if it is the first vertex with this rank. """ assert self.dag r=max([self.grx[x].rank for x in v.N(-1)]+[-1])+1 self.grx[v].rank=r # add it to its la...
[ "def", "setrank", "(", "self", ",", "v", ")", ":", "assert", "self", ".", "dag", "r", "=", "max", "(", "[", "self", ".", "grx", "[", "x", "]", ".", "rank", "for", "x", "in", "v", ".", "N", "(", "-", "1", ")", "]", "+", "[", "-", "1", "]...
36.230769
12.384615
def get_headers(self): """ Return a HTTPStatus compliant headers attribute FIX: duplicate headers will collide terribly! """ headers = {'Content-Type': goldman.JSON_MIMETYPE} for error in self.errors: if 'headers' in error: headers.update(error['hea...
[ "def", "get_headers", "(", "self", ")", ":", "headers", "=", "{", "'Content-Type'", ":", "goldman", ".", "JSON_MIMETYPE", "}", "for", "error", "in", "self", ".", "errors", ":", "if", "'headers'", "in", "error", ":", "headers", ".", "update", "(", "error"...
28.25
17.25
def reply_contact( self, phone_number: str, first_name: str, quote: bool = None, last_name: str = "", vcard: str = "", disable_notification: bool = None, reply_to_message_id: int = None, reply_markup: Union[ "pyrogram.InlineKeyboardMark...
[ "def", "reply_contact", "(", "self", ",", "phone_number", ":", "str", ",", "first_name", ":", "str", ",", "quote", ":", "bool", "=", "None", ",", "last_name", ":", "str", "=", "\"\"", ",", "vcard", ":", "str", "=", "\"\"", ",", "disable_notification", ...
34.25
21.202381
def confirm(action, default=None, skip=False): """ A shortcut for typical confirmation prompt. :param action: a string describing the action, e.g. "Apply changes". A question mark will be appended. :param default: `bool` or `None`. Determines what happens when user hits :kbd:...
[ "def", "confirm", "(", "action", ",", "default", "=", "None", ",", "skip", "=", "False", ")", ":", "MAX_ITERATIONS", "=", "3", "if", "skip", ":", "return", "default", "else", ":", "defaults", "=", "{", "None", ":", "(", "'y'", ",", "'n'", ")", ",",...
29.968254
20.793651
def remove_existing_links(root_dir): """Delete any symlinks present at the root of a directory. Parameters ---------- root_dir : `str` Directory that might contain symlinks. Notes ----- This function is used to remove any symlinks created by `link_directories`. Running ``remove...
[ "def", "remove_existing_links", "(", "root_dir", ")", ":", "logger", "=", "logging", ".", "getLogger", "(", "__name__", ")", "for", "name", "in", "os", ".", "listdir", "(", "root_dir", ")", ":", "full_name", "=", "os", ".", "path", ".", "join", "(", "r...
35.545455
20.772727
def create_paste(self, content): """Create a raw paste of the given content. Returns a URL to the paste, or raises a ``pasteraw.Error`` if something tragic happens instead. """ r = requests.post( self.endpoint + '/pastes', data={'content': content}, ...
[ "def", "create_paste", "(", "self", ",", "content", ")", ":", "r", "=", "requests", ".", "post", "(", "self", ".", "endpoint", "+", "'/pastes'", ",", "data", "=", "{", "'content'", ":", "content", "}", ",", "allow_redirects", "=", "False", ")", "if", ...
27.75
17.333333
def create_admin(user_config_path: str = 'CONFIG.superuser') -> bool: """ Creates a superuser from a specified dict/object bundle located at ``user_config_path``. Skips if the specified object contains no email or no username. If a user with the specified username already exists and has no usable passwo...
[ "def", "create_admin", "(", "user_config_path", ":", "str", "=", "'CONFIG.superuser'", ")", "->", "bool", ":", "from", "django", ".", "conf", "import", "settings", "wf", "(", "'Creating superuser... '", ",", "False", ")", "username", ",", "email", ",", "passwo...
36.209677
23.403226
def setBendField(self, x): """ set bend magnetic field :param x: new bend field to be assigned, [T] :return: None """ if x != self.bend_field: self.bend_field = x self.refresh = True
[ "def", "setBendField", "(", "self", ",", "x", ")", ":", "if", "x", "!=", "self", ".", "bend_field", ":", "self", ".", "bend_field", "=", "x", "self", ".", "refresh", "=", "True" ]
26.555556
12.333333
def ReadCronJobRun(self, job_id, run_id, cursor=None): """Reads a single cron job run from the db.""" query = ("SELECT run, UNIX_TIMESTAMP(write_time) FROM cron_job_runs " "WHERE job_id = %s AND run_id = %s") num_runs = cursor.execute( query, [job_id, db_utils.CronJobRunIDToInt(run_id)]...
[ "def", "ReadCronJobRun", "(", "self", ",", "job_id", ",", "run_id", ",", "cursor", "=", "None", ")", ":", "query", "=", "(", "\"SELECT run, UNIX_TIMESTAMP(write_time) FROM cron_job_runs \"", "\"WHERE job_id = %s AND run_id = %s\"", ")", "num_runs", "=", "cursor", ".", ...
46
18
def trans(self, id, parameters=None, domain=None, locale=None): """ Throws RuntimeError whenever a message is missing """ if parameters is None: parameters = {} if locale is None: locale = self.locale else: self._assert_valid_locale(lo...
[ "def", "trans", "(", "self", ",", "id", ",", "parameters", "=", "None", ",", "domain", "=", "None", ",", "locale", "=", "None", ")", ":", "if", "parameters", "is", "None", ":", "parameters", "=", "{", "}", "if", "locale", "is", "None", ":", "locale...
28.423077
17.192308
def sort_by(self, *fields, **kwargs): """ Indicate how the results should be sorted. This can also be used for *top-N* style queries ### Parameters - **fields**: The fields by which to sort. This can be either a single field or a list of fields. If you wish to speci...
[ "def", "sort_by", "(", "self", ",", "*", "fields", ",", "*", "*", "kwargs", ")", ":", "self", ".", "_max", "=", "kwargs", ".", "get", "(", "'max'", ",", "0", ")", "if", "isinstance", "(", "fields", ",", "(", "string_types", ",", "SortDirection", ")...
31.540541
21.108108
def delete(self, bulk_id): """Update many objects with a single toa :param str bulk_id: The bulk id for the job you want to delete """ collection_name = self.request.headers.get("collection") if not collection_name: self.raise_error(400, "Missing a collection name ...
[ "def", "delete", "(", "self", ",", "bulk_id", ")", ":", "collection_name", "=", "self", ".", "request", ".", "headers", ".", "get", "(", "\"collection\"", ")", "if", "not", "collection_name", ":", "self", ".", "raise_error", "(", "400", ",", "\"Missing a c...
32.333333
28.722222
def tablestructure(tablename, dataman=True, column=True, subtable=False, sort=False): """Print the structure of a table. It is the same as :func:`table.showstructure`, but without the need to open the table first. """ t = table(tablename, ack=False) six.print_(t.showstructur...
[ "def", "tablestructure", "(", "tablename", ",", "dataman", "=", "True", ",", "column", "=", "True", ",", "subtable", "=", "False", ",", "sort", "=", "False", ")", ":", "t", "=", "table", "(", "tablename", ",", "ack", "=", "False", ")", "six", ".", ...
34.6
20.9
def _compute_magnitude_terms(self, rup, coeffs): """ First three terms of equation (8) on p. 203: ``c1 + c2*(M - 6) + c3*(M - 6)**2`` """ adj_mag = rup.mag - self.CONSTS['ref_mag'] return coeffs['c1'] + coeffs['c2']*adj_mag + coeffs['c3']*adj_mag**2
[ "def", "_compute_magnitude_terms", "(", "self", ",", "rup", ",", "coeffs", ")", ":", "adj_mag", "=", "rup", ".", "mag", "-", "self", ".", "CONSTS", "[", "'ref_mag'", "]", "return", "coeffs", "[", "'c1'", "]", "+", "coeffs", "[", "'c2'", "]", "*", "ad...
32.333333
16.555556
def counter(self, ch, part=None): """Return a counter on the channel ch. ch: string or integer. The channel index number or channel name. part: int or None The 0-based enumeration of a True part to return. This has an effect whether or not the mask or filter...
[ "def", "counter", "(", "self", ",", "ch", ",", "part", "=", "None", ")", ":", "return", "Counter", "(", "self", "(", "self", ".", "_key", "(", "ch", ")", ",", "part", "=", "part", ")", ")" ]
34.529412
20.823529
def parse_atom_bytes(data: bytes) -> AtomFeed: """Parse an Atom feed from a byte-string containing XML data.""" root = parse_xml(BytesIO(data)).getroot() return _parse_atom(root)
[ "def", "parse_atom_bytes", "(", "data", ":", "bytes", ")", "->", "AtomFeed", ":", "root", "=", "parse_xml", "(", "BytesIO", "(", "data", ")", ")", ".", "getroot", "(", ")", "return", "_parse_atom", "(", "root", ")" ]
46.75
5.75
def _set_position(self, value): """ Subclasses may override this method. """ pX, pY = self.position x, y = value dX = x - pX dY = y - pY self.moveBy((dX, dY))
[ "def", "_set_position", "(", "self", ",", "value", ")", ":", "pX", ",", "pY", "=", "self", ".", "position", "x", ",", "y", "=", "value", "dX", "=", "x", "-", "pX", "dY", "=", "y", "-", "pY", "self", ".", "moveBy", "(", "(", "dX", ",", "dY", ...
23.777778
10.666667
def save_file(self, path: str, file_id: int = None, file_part: int = 0, progress: callable = None, progress_args: tuple = ()): """Use this method to upload a file onto Telegram servers, without actually sending the message...
[ "def", "save_file", "(", "self", ",", "path", ":", "str", ",", "file_id", ":", "int", "=", "None", ",", "file_part", ":", "int", "=", "0", ",", "progress", ":", "callable", "=", "None", ",", "progress_args", ":", "tuple", "=", "(", ")", ")", ":", ...
39.454545
23.583333
async def get_delta_json( self, rr_delta_builder: Callable[['HolderProver', str, int, int, dict], Awaitable[Tuple[str, int]]], fro: int, to: int) -> (str, int): """ Get rev reg delta json, and its timestamp on the distributed ledger, from cached re...
[ "async", "def", "get_delta_json", "(", "self", ",", "rr_delta_builder", ":", "Callable", "[", "[", "'HolderProver'", ",", "str", ",", "int", ",", "int", ",", "dict", "]", ",", "Awaitable", "[", "Tuple", "[", "str", ",", "int", "]", "]", "]", ",", "fr...
44.266667
30.8
def set_info(self, info): """ set my state from the passed info """ idx = info.get(self.name) if idx is not None: self.__dict__.update(idx)
[ "def", "set_info", "(", "self", ",", "info", ")", ":", "idx", "=", "info", ".", "get", "(", "self", ".", "name", ")", "if", "idx", "is", "not", "None", ":", "self", ".", "__dict__", ".", "update", "(", "idx", ")" ]
34.2
7.6
def wrapFn(fn, *args, **kwargs): """ Makes a Job out of a function. \ Convenience function for constructor of :class:`toil.job.FunctionWrappingJob`. :param fn: Function to be run with ``*args`` and ``**kwargs`` as arguments. \ See toil.job.JobFunctionWrappingJob for reserved key...
[ "def", "wrapFn", "(", "fn", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "PromisedRequirement", ".", "convertPromises", "(", "kwargs", ")", ":", "return", "PromisedRequirementFunctionWrappingJob", ".", "create", "(", "fn", ",", "*", "args", "...
46.066667
19.933333
def mkBinPacking(w,q): """mkBinPacking: convert a cutting stock instance into bin packing format""" s = [] for j in range(len(w)): for i in range(q[j]): s.append(w[j]) return s
[ "def", "mkBinPacking", "(", "w", ",", "q", ")", ":", "s", "=", "[", "]", "for", "j", "in", "range", "(", "len", "(", "w", ")", ")", ":", "for", "i", "in", "range", "(", "q", "[", "j", "]", ")", ":", "s", ".", "append", "(", "w", "[", "j...
29.428571
16.285714
def validate( feed: "Feed", *, as_df: bool = True, include_warnings: bool = True ) -> Union[List, DataFrame]: """ Check whether the given feed satisfies the GTFS. Parameters ---------- feed : Feed as_df : boolean If ``True``, then return the resulting report as a DataFrame; ...
[ "def", "validate", "(", "feed", ":", "\"Feed\"", ",", "*", ",", "as_df", ":", "bool", "=", "True", ",", "include_warnings", ":", "bool", "=", "True", ")", "->", "Union", "[", "List", ",", "DataFrame", "]", ":", "problems", "=", "[", "]", "# Check for...
33.6
22.15
def returns_fake(self, *args, **kwargs): """Set the last call to return a new :class:`fudge.Fake`. Any given arguments are passed to the :class:`fudge.Fake` constructor Take note that this is different from the cascading nature of other methods. This will return an instance of the *ne...
[ "def", "returns_fake", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "exp", "=", "self", ".", "_get_current_call", "(", ")", "endpoint", "=", "kwargs", ".", "get", "(", "'name'", ",", "exp", ".", "call_name", ")", "name", "=", "...
35.392857
20.25
def get_fw_rule(self, rule_id): """Return the firewall rule, given its ID. """ rule = None try: rule = self.neutronclient.show_firewall_rule(rule_id) except Exception as exc: LOG.error("Failed to get firewall rule for id %(id)s " "Exc %(exc)s...
[ "def", "get_fw_rule", "(", "self", ",", "rule_id", ")", ":", "rule", "=", "None", "try", ":", "rule", "=", "self", ".", "neutronclient", ".", "show_firewall_rule", "(", "rule_id", ")", "except", "Exception", "as", "exc", ":", "LOG", ".", "error", "(", ...
40.888889
18.666667
def _installV2Powerups(anonymousSite): """ Install the given L{AnonymousSite} for the powerup interfaces it was given in version 2. """ anonymousSite.store.powerUp(anonymousSite, IWebViewer) anonymousSite.store.powerUp(anonymousSite, IMantissaSite)
[ "def", "_installV2Powerups", "(", "anonymousSite", ")", ":", "anonymousSite", ".", "store", ".", "powerUp", "(", "anonymousSite", ",", "IWebViewer", ")", "anonymousSite", ".", "store", ".", "powerUp", "(", "anonymousSite", ",", "IMantissaSite", ")" ]
38
14.571429
def get_source_by_name(self, name): """Return a single source in the ROI with the given name. The input name string can match any of the strings in the names property of the source object. Case and whitespace are ignored when matching name strings. If no sources are found or m...
[ "def", "get_source_by_name", "(", "self", ",", "name", ")", ":", "srcs", "=", "self", ".", "get_sources_by_name", "(", "name", ")", "if", "len", "(", "srcs", ")", "==", "1", ":", "return", "srcs", "[", "0", "]", "elif", "len", "(", "srcs", ")", "==...
31.961538
19.846154
def deep_type(obj, depth = None, max_sample = None, get_type = None): """Tries to construct a type for a given value. In contrast to type(...), deep_type does its best to fit structured types from typing as close as possible to the given value. E.g. deep_type((1, 2, 'a')) will return Tuple[int, int, str...
[ "def", "deep_type", "(", "obj", ",", "depth", "=", "None", ",", "max_sample", "=", "None", ",", "get_type", "=", "None", ")", ":", "return", "_deep_type", "(", "obj", ",", "[", "]", ",", "0", ",", "depth", ",", "max_sample", ",", "get_type", ")" ]
57.529412
23.647059
def ReadContainer(self, collection_link, options=None): """Reads a collection. :param str collection_link: The link to the document collection. :param dict options: The request options for the request. :return: The read Collection. :rtype: ...
[ "def", "ReadContainer", "(", "self", ",", "collection_link", ",", "options", "=", "None", ")", ":", "if", "options", "is", "None", ":", "options", "=", "{", "}", "path", "=", "base", ".", "GetPathFromLink", "(", "collection_link", ")", "collection_id", "="...
28.291667
16.75
def compose(self, *args, **kwargs): """ Compose layer and masks (mask, vector mask, and clipping layers). :return: :py:class:`PIL.Image`, or `None` if the layer has no pixel. """ from psd_tools.api.composer import compose_layer if self.bbox == (0, 0, 0, 0): r...
[ "def", "compose", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "from", "psd_tools", ".", "api", ".", "composer", "import", "compose_layer", "if", "self", ".", "bbox", "==", "(", "0", ",", "0", ",", "0", ",", "0", ")", ":", ...
37.3
16.1
def match_key(self) -> Tuple[bool, bool, int, List[WeightedPart]]: """A Key to sort the rules by weight for matching. The key leads to ordering: - By first order by defaults as they are simple rules without conversions. - Then on the complexity of the rule, i.e. does it ha...
[ "def", "match_key", "(", "self", ")", "->", "Tuple", "[", "bool", ",", "bool", ",", "int", ",", "List", "[", "WeightedPart", "]", "]", ":", "if", "self", ".", "map", "is", "None", ":", "raise", "RuntimeError", "(", "f\"{self!r} is not bound to a Map\"", ...
47.052632
24.157895
def download(self): ''' Downloads HTML from url. ''' self.page = requests.get(self.url) self.tree = html.fromstring(self.page.text)
[ "def", "download", "(", "self", ")", ":", "self", ".", "page", "=", "requests", ".", "get", "(", "self", ".", "url", ")", "self", ".", "tree", "=", "html", ".", "fromstring", "(", "self", ".", "page", ".", "text", ")" ]
26.8
15.2