text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def metrics_since(slugs, years, link_type="detail", granularity=None): """Renders a template with a menu to view a metric (or metrics) for a given number of years. * ``slugs`` -- A Slug or a set/list of slugs * ``years`` -- Number of years to show past metrics * ``link_type`` -- What type of chart ...
[ "def", "metrics_since", "(", "slugs", ",", "years", ",", "link_type", "=", "\"detail\"", ",", "granularity", "=", "None", ")", ":", "now", "=", "datetime", ".", "utcnow", "(", ")", "# Determine if we're looking at one slug or multiple slugs", "if", "type", "(", ...
43.578947
22.315789
def clean(self): """Remove all temporary files.""" rnftools.utils.shell('rm -fR "{}" "{}"'.format(self.report_dir, self._html_fn))
[ "def", "clean", "(", "self", ")", ":", "rnftools", ".", "utils", ".", "shell", "(", "'rm -fR \"{}\" \"{}\"'", ".", "format", "(", "self", ".", "report_dir", ",", "self", ".", "_html_fn", ")", ")" ]
36
27.75
def from_file(filename): """Read in filename and creates a trace object. :param filename: path to nu(x|s)mv output file :type filename: str :return: """ trace = Trace() reached = False with open(filename) as fp: for line in fp.readlines(): ...
[ "def", "from_file", "(", "filename", ")", ":", "trace", "=", "Trace", "(", ")", "reached", "=", "False", "with", "open", "(", "filename", ")", "as", "fp", ":", "for", "line", "in", "fp", ".", "readlines", "(", ")", ":", "if", "not", "reached", "and...
31.941176
13.823529
def _process_json(data): """ return a list of GradPetition objects. """ requests = [] for item in data: petition = GradPetition() petition.description = item.get('description') petition.submit_date = parse_datetime(item.get('submitDate')) petition.decision_date = pars...
[ "def", "_process_json", "(", "data", ")", ":", "requests", "=", "[", "]", "for", "item", "in", "data", ":", "petition", "=", "GradPetition", "(", ")", "petition", ".", "description", "=", "item", ".", "get", "(", "'description'", ")", "petition", ".", ...
36.6
17.2
def hessian_local_log_likelihood(self, x): """ d/dx (y - lmbda)^T C = d/dx -exp(Cx + d)^T C = -C^T exp(Cx + d)^T C """ # Observation likelihoods lmbda = np.exp(np.dot(x, self.C.T) + np.dot(self.inputs, self.D.T)) return np.einsum('tn, ni, nj ->tij', -lmbda, s...
[ "def", "hessian_local_log_likelihood", "(", "self", ",", "x", ")", ":", "# Observation likelihoods", "lmbda", "=", "np", ".", "exp", "(", "np", ".", "dot", "(", "x", ",", "self", ".", "C", ".", "T", ")", "+", "np", ".", "dot", "(", "self", ".", "in...
40.875
11.375
def W(self,value): """ set fixed effect design """ if value is None: value = sp.zeros((self._N, 0)) assert value.shape[0]==self._N, 'Dimension mismatch' self._K = value.shape[1] self._W = value self._notify() self.clear_cache('predict_in_sample','Yres')
[ "def", "W", "(", "self", ",", "value", ")", ":", "if", "value", "is", "None", ":", "value", "=", "sp", ".", "zeros", "(", "(", "self", ".", "_N", ",", "0", ")", ")", "assert", "value", ".", "shape", "[", "0", "]", "==", "self", ".", "_N", "...
38
14.375
def ip_address_add(session, ifname, ifaddr): """ Adds an IP address to interface record identified with the given "ifname". The arguments are similar to "ip address add" command of iproute2. :param session: Session instance connecting to database. :param ifname: Name of interface. :param ifadd...
[ "def", "ip_address_add", "(", "session", ",", "ifname", ",", "ifaddr", ")", ":", "def", "_append_inet_addr", "(", "intf_inet", ",", "addr", ")", ":", "addr_list", "=", "intf_inet", ".", "split", "(", "','", ")", "if", "addr", "in", "addr_list", ":", "LOG...
32.083333
17.638889
def project_data_dir(self, *args) -> str: """ Directory where to store data """ return os.path.normpath(os.path.join(self.project_dir, 'data', *args))
[ "def", "project_data_dir", "(", "self", ",", "*", "args", ")", "->", "str", ":", "return", "os", ".", "path", ".", "normpath", "(", "os", ".", "path", ".", "join", "(", "self", ".", "project_dir", ",", "'data'", ",", "*", "args", ")", ")" ]
54.666667
13
def login(access_code:str, client_id:str=CLIENT_ID, client_secret:str=CLIENT_SECRET, headers:dict=HEADERS, redirect_uri:str=REDIRECT_URI): """ Get access_token fron an user authorized code, the client id and the client secret key. (See https://developer.google.com/v3/oauth/#web-application-flow). ...
[ "def", "login", "(", "access_code", ":", "str", ",", "client_id", ":", "str", "=", "CLIENT_ID", ",", "client_secret", ":", "str", "=", "CLIENT_SECRET", ",", "headers", ":", "dict", "=", "HEADERS", ",", "redirect_uri", ":", "str", "=", "REDIRECT_URI", ")", ...
53.526316
22.578947
async def get_historic_data(self, n_data): """Get historic data.""" query = gql( """ { viewer { home(id: "%s") { consumption(resolution: HOURLY, last: %s) { nodes { f...
[ "async", "def", "get_historic_data", "(", "self", ",", "n_data", ")", ":", "query", "=", "gql", "(", "\"\"\"\n {\n viewer {\n home(id: \"%s\") {\n consumption(resolution: HOURLY, last: %s) {\n no...
29.62069
13.551724
def plot_gaussian_projection(mu, lmbda, vecs, **kwargs): ''' Plots a ndim gaussian projected onto 2D vecs, where vecs is a matrix whose two columns are the subset of some orthonomral basis (e.g. from PCA on samples). ''' return plot_gaussian_2D(project_data(mu,vecs),project_ellipsoid(lmbda,vecs),**k...
[ "def", "plot_gaussian_projection", "(", "mu", ",", "lmbda", ",", "vecs", ",", "*", "*", "kwargs", ")", ":", "return", "plot_gaussian_2D", "(", "project_data", "(", "mu", ",", "vecs", ")", ",", "project_ellipsoid", "(", "lmbda", ",", "vecs", ")", ",", "*"...
53.5
35.5
def grabEmails(emails=None, emailsFile=None, nicks=None, nicksFile=None, domains=EMAIL_DOMAINS, excludeDomains=[]): """ Method that generates a list of emails. Args: ----- emails: Any premade list of emails. emailsFile: Filepath to the emails file (one per line). nicks: A list o...
[ "def", "grabEmails", "(", "emails", "=", "None", ",", "emailsFile", "=", "None", ",", "nicks", "=", "None", ",", "nicksFile", "=", "None", ",", "domains", "=", "EMAIL_DOMAINS", ",", "excludeDomains", "=", "[", "]", ")", ":", "email_candidates", "=", "[",...
36.348837
16.627907
def uploads(self): """returns an object to work with the site uploads""" if self._resources is None: self.__init() if "uploads" in self._resources: url = self._url + "/uploads" return _uploads.Uploads(url=url, securityHandle...
[ "def", "uploads", "(", "self", ")", ":", "if", "self", ".", "_resources", "is", "None", ":", "self", ".", "__init", "(", ")", "if", "\"uploads\"", "in", "self", ".", "_resources", ":", "url", "=", "self", ".", "_url", "+", "\"/uploads\"", "return", "...
42.384615
14
def write(self): """ Writes a single frame of the progress spinner to the terminal. This function updates the current frame before returning. """ if self.text is None: # Text has not been sent through the pipe yet. # Do not write anything until it is set to no...
[ "def", "write", "(", "self", ")", ":", "if", "self", ".", "text", "is", "None", ":", "# Text has not been sent through the pipe yet.", "# Do not write anything until it is set to non-None value.", "return", "None", "if", "self", ".", "_last_text", "==", "self", ".", "...
38.47619
14.52381
def list_api_keys(awsclient): """Print the defined API keys. """ _sleep() client_api = awsclient.get_client('apigateway') print('listing api keys') response = client_api.get_api_keys()['items'] for item in response: print(json2table(item))
[ "def", "list_api_keys", "(", "awsclient", ")", ":", "_sleep", "(", ")", "client_api", "=", "awsclient", ".", "get_client", "(", "'apigateway'", ")", "print", "(", "'listing api keys'", ")", "response", "=", "client_api", ".", "get_api_keys", "(", ")", "[", "...
24.272727
15.818182
def map_function(func_str, fw_action_addtion=None,bw_action_addtion=None, alias_func=None): ''' Sample usage: print map_function('set',alias_func = "ini_items");# -> ini_items print map_function('set',fw_action_addtion="action_steps_",bw_action_addtion="_for_upd",alias_func = "ini_items"); # -> a...
[ "def", "map_function", "(", "func_str", ",", "fw_action_addtion", "=", "None", ",", "bw_action_addtion", "=", "None", ",", "alias_func", "=", "None", ")", ":", "split_action_value", "=", "re", ".", "compile", "(", "\"^(\\w+)(\\((.*)\\)$)?\"", ")", "matched", "="...
45.222222
29.888889
def render_page(path): """Internal interface to the page view. :param path: Page path. :returns: The rendered template. """ try: page = Page.get_by_url(request.path) except NoResultFound: abort(404) return render_template( [page.template_name, current_app.config['PA...
[ "def", "render_page", "(", "path", ")", ":", "try", ":", "page", "=", "Page", ".", "get_by_url", "(", "request", ".", "path", ")", "except", "NoResultFound", ":", "abort", "(", "404", ")", "return", "render_template", "(", "[", "page", ".", "template_nam...
25
18.428571
def get_root_gradebook_ids(self): """Gets the root gradebook ``Ids`` in this hierarchy. return: (osid.id.IdList) - the root gradebook ``Ids`` raise: OperationFailed - unable to complete request raise: PermissionDenied - authorization failure *compliance: mandatory -- This meth...
[ "def", "get_root_gradebook_ids", "(", "self", ")", ":", "# Implemented from template for", "# osid.resource.BinHierarchySession.get_root_bin_ids", "if", "self", ".", "_catalog_session", "is", "not", "None", ":", "return", "self", ".", "_catalog_session", ".", "get_root_cata...
43.285714
16.428571
def path_iter(path): """Returns an iterator over all the file & folder names in a path.""" parts = [] while path: path, item = os.path.split(path) if item: parts.append(item) return reversed(parts)
[ "def", "path_iter", "(", "path", ")", ":", "parts", "=", "[", "]", "while", "path", ":", "path", ",", "item", "=", "os", ".", "path", ".", "split", "(", "path", ")", "if", "item", ":", "parts", ".", "append", "(", "item", ")", "return", "reversed...
30.125
14.375
def run(function_name, in_files, wp=None, in_params=None, out_files=None, mpi_params=None, log_params=None): """ Run TauDEM function. - 1. The command will not execute if any input file does not exist. - 2. An error will be detected after running the TauDEM command if ...
[ "def", "run", "(", "function_name", ",", "in_files", ",", "wp", "=", "None", ",", "in_params", "=", "None", ",", "out_files", "=", "None", ",", "mpi_params", "=", "None", ",", "log_params", "=", "None", ")", ":", "# Check input files", "if", "in_files", ...
46.505208
19.765625
def withdraw(self, uuid, organization, from_date=None, to_date=None): """Withdraw a unique identity from an organization. This method removes all the enrollments between the unique identity, identified by <uuid>, and <organization>. Both entities must exist on the registry before being ...
[ "def", "withdraw", "(", "self", ",", "uuid", ",", "organization", ",", "from_date", "=", "None", ",", "to_date", "=", "None", ")", ":", "# Empty or None values for uuid and organizations are not allowed,", "# so do nothing", "if", "not", "uuid", "or", "not", "organi...
41.241379
22
def upsert_pending_licensors(cursor, document_id): """Update or insert records for pending license acceptors.""" cursor.execute("""\ SELECT "uuid", "metadata" FROM pending_documents WHERE id = %s""", (document_id,)) uuid_, metadata = cursor.fetchone() acceptors = set([uid for uid, type_ in _dissect_role...
[ "def", "upsert_pending_licensors", "(", "cursor", ",", "document_id", ")", ":", "cursor", ".", "execute", "(", "\"\"\"\\\nSELECT \"uuid\", \"metadata\"\nFROM pending_documents\nWHERE id = %s\"\"\"", ",", "(", "document_id", ",", ")", ")", "uuid_", ",", "metadata", "=", ...
31.142857
14
def _delete_dummy_intf_rtr(self, tenant_id, tenant_name, rtr_id): """Function to delete a dummy interface of a router. """ dummy_router_dict = self.get_dummy_router_net(tenant_id) ret = self.delete_os_dummy_rtr_nwk(dummy_router_dict.get('router_id'), du...
[ "def", "_delete_dummy_intf_rtr", "(", "self", ",", "tenant_id", ",", "tenant_name", ",", "rtr_id", ")", ":", "dummy_router_dict", "=", "self", ".", "get_dummy_router_net", "(", "tenant_id", ")", "ret", "=", "self", ".", "delete_os_dummy_rtr_nwk", "(", "dummy_route...
60.333333
23
def ntile(n): """ Window function: returns the ntile group id (from 1 to `n` inclusive) in an ordered window partition. For example, if `n` is 4, the first quarter of the rows will get value 1, the second quarter will get 2, the third quarter will get 3, and the last quarter will get 4. This is...
[ "def", "ntile", "(", "n", ")", ":", "sc", "=", "SparkContext", ".", "_active_spark_context", "return", "Column", "(", "sc", ".", "_jvm", ".", "functions", ".", "ntile", "(", "int", "(", "n", ")", ")", ")" ]
36.769231
20.769231
def run_loop(leds=all_leds): """ Start the loop. :param `leds`: Which LEDs to light up upon switch press. :type `leds`: sequence of LED objects """ print('Loop started.\nPress Ctrl+C to break out of the loop.') while 1: try: if switch(): [led.on() for led...
[ "def", "run_loop", "(", "leds", "=", "all_leds", ")", ":", "print", "(", "'Loop started.\\nPress Ctrl+C to break out of the loop.'", ")", "while", "1", ":", "try", ":", "if", "switch", "(", ")", ":", "[", "led", ".", "on", "(", ")", "for", "led", "in", "...
28.9375
16.9375
def record_rename(object_id, input_params={}, always_retry=True, **kwargs): """ Invokes the /record-xxxx/rename API method. For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Name#API-method%3A-%2Fclass-xxxx%2Frename """ return DXHTTPRequest('/%s/rename' % object_id, input_param...
[ "def", "record_rename", "(", "object_id", ",", "input_params", "=", "{", "}", ",", "always_retry", "=", "True", ",", "*", "*", "kwargs", ")", ":", "return", "DXHTTPRequest", "(", "'/%s/rename'", "%", "object_id", ",", "input_params", ",", "always_retry", "="...
50.428571
31.285714
def _send_output(self, message_body=None): """Send the currently buffered request and clear the buffer. Appends an extra \\r\\n to the buffer. A message_body may be specified, to be appended to the request. """ self._buffer.extend((bytes(b""), bytes(b""))) msg = bytes(b"...
[ "def", "_send_output", "(", "self", ",", "message_body", "=", "None", ")", ":", "self", ".", "_buffer", ".", "extend", "(", "(", "bytes", "(", "b\"\"", ")", ",", "bytes", "(", "b\"\"", ")", ")", ")", "msg", "=", "bytes", "(", "b\"\\r\\n\"", ")", "....
43.3
13.15
def rivermap_update(self, river, water_flow, rivermap, precipitations): """Update the rivermap with the rainfall that is to become the waterflow""" isSeed = True px, py = (0, 0) for x, y in river: if isSeed: rivermap[y, x] = water_flow[y, x] ...
[ "def", "rivermap_update", "(", "self", ",", "river", ",", "water_flow", ",", "rivermap", ",", "precipitations", ")", ":", "isSeed", "=", "True", "px", ",", "py", "=", "(", "0", ",", "0", ")", "for", "x", ",", "y", "in", "river", ":", "if", "isSeed"...
34.307692
17.538462
def delete_attribute_group_items(attributegroupitems, **kwargs): """ remove attribute groups items . ** attributegroupitems : a list of items, of the form: ```{ 'attr_id' : X, 'group_id' : Y, 'network_id' : Z, ...
[ "def", "delete_attribute_group_items", "(", "attributegroupitems", ",", "*", "*", "kwargs", ")", ":", "user_id", "=", "kwargs", ".", "get", "(", "'user_id'", ")", "log", ".", "info", "(", "\"Deleting %s attribute group items\"", ",", "len", "(", "attributegroupite...
32.276596
25.553191
def fit(epochs:int, learn:BasicLearner, callbacks:Optional[CallbackList]=None, metrics:OptMetrics=None)->None: "Fit the `model` on `data` and learn using `loss_func` and `opt`." assert len(learn.data.train_dl) != 0, f"""Your training dataloader is empty, can't train a model. Use a smaller batch size (ba...
[ "def", "fit", "(", "epochs", ":", "int", ",", "learn", ":", "BasicLearner", ",", "callbacks", ":", "Optional", "[", "CallbackList", "]", "=", "None", ",", "metrics", ":", "OptMetrics", "=", "None", ")", "->", "None", ":", "assert", "len", "(", "learn",...
51.785714
22.821429
def recode(self, table: pd.DataFrame, validate=False) -> pd.DataFrame: """Pass the appropriate columns through each recoder function sequentially and return the final result. Args: table (pd.DataFrame): A dataframe on which to apply recoding logic. validate (bool): If ``True``, ...
[ "def", "recode", "(", "self", ",", "table", ":", "pd", ".", "DataFrame", ",", "validate", "=", "False", ")", "->", "pd", ".", "DataFrame", ":", "return", "self", ".", "_recode_output", "(", "self", ".", "_recode_input", "(", "table", ",", "validate", "...
58.25
29.75
def paginate_update(update): """ attempts to get next and previous on updates """ from happenings.models import Update time = update.pub_time event = update.event try: next = Update.objects.filter( event=event, pub_time__gt=time ).order_by('pub_time')....
[ "def", "paginate_update", "(", "update", ")", ":", "from", "happenings", ".", "models", "import", "Update", "time", "=", "update", ".", "pub_time", "event", "=", "update", ".", "event", "try", ":", "next", "=", "Update", ".", "objects", ".", "filter", "(...
27.363636
13.909091
def should_not_sample_path(request): """Decided whether current request path should be sampled or not. This is checked previous to `should_not_sample_route` and takes precedence. :param: current active pyramid request :returns: boolean whether current request path is blacklisted. """ blackliste...
[ "def", "should_not_sample_path", "(", "request", ")", ":", "blacklisted_paths", "=", "request", ".", "registry", ".", "settings", ".", "get", "(", "'zipkin.blacklisted_paths'", ",", "[", "]", ")", "# Only compile strings, since even recompiling existing", "# compiled rege...
41
15.375
def keep(self, diff): """ Mark this diff (or volume) to be kept in path. """ (toUUID, fromUUID) = self.toArg.diff(diff) self._client.keep(toUUID, fromUUID) logger.debug("Kept %s", diff)
[ "def", "keep", "(", "self", ",", "diff", ")", ":", "(", "toUUID", ",", "fromUUID", ")", "=", "self", ".", "toArg", ".", "diff", "(", "diff", ")", "self", ".", "_client", ".", "keep", "(", "toUUID", ",", "fromUUID", ")", "logger", ".", "debug", "(...
42.6
7
def check_backends(title): """Invoke test() for all backends and fail (raise) if some dep is missing. """ path = os.path.dirname(fulltext.backends.__file__) errs = [] for name in os.listdir(path): if not name.endswith('.py'): continue if name == '__init__.py': ...
[ "def", "check_backends", "(", "title", ")", ":", "path", "=", "os", ".", "path", ".", "dirname", "(", "fulltext", ".", "backends", ".", "__file__", ")", "errs", "=", "[", "]", "for", "name", "in", "os", ".", "listdir", "(", "path", ")", ":", "if", ...
30.911765
15.235294
def is_vertex_cover(G, vertex_cover): """Determines whether the given set of vertices is a vertex cover of graph G. A vertex cover is a set of vertices such that each edge of the graph is incident with at least one vertex in the set. Parameters ---------- G : NetworkX graph The graph on...
[ "def", "is_vertex_cover", "(", "G", ",", "vertex_cover", ")", ":", "cover", "=", "set", "(", "vertex_cover", ")", "return", "all", "(", "u", "in", "cover", "or", "v", "in", "cover", "for", "u", ",", "v", "in", "G", ".", "edges", ")" ]
27.648649
22.027027
def OnBGColor(self, event): """Background color choice event handler""" color = event.GetValue().GetRGB() post_command_event(self, self.BackgroundColorMsg, color=color)
[ "def", "OnBGColor", "(", "self", ",", "event", ")", ":", "color", "=", "event", ".", "GetValue", "(", ")", ".", "GetRGB", "(", ")", "post_command_event", "(", "self", ",", "self", ".", "BackgroundColorMsg", ",", "color", "=", "color", ")" ]
31.5
20.666667
def predict_covariance(self, X, with_noise=True): """ Predicts the covariance matric for points in X. Parameters: X (np.ndarray) - points to run the prediction for. with_noise (bool) - whether to add noise to the prediction. Default is True. """ _, v = se...
[ "def", "predict_covariance", "(", "self", ",", "X", ",", "with_noise", "=", "True", ")", ":", "_", ",", "v", "=", "self", ".", "_predict", "(", "X", ",", "True", ",", "with_noise", ")", "return", "v" ]
36
18.8
def _check_if_both_have_same_parameters(self, other_trajectory, ignore_data, consecutive_merge): """ Checks if two trajectories live in the same space and can be merged. """ if not isinstance(other_trajectory, Trajectory): raise TypeError('Can onl...
[ "def", "_check_if_both_have_same_parameters", "(", "self", ",", "other_trajectory", ",", "ignore_data", ",", "consecutive_merge", ")", ":", "if", "not", "isinstance", "(", "other_trajectory", ",", "Trajectory", ")", ":", "raise", "TypeError", "(", "'Can only merge tra...
50.865169
22.955056
def bm3_g(p, v0, g0, g0p, k0, k0p): """ calculate shear modulus at given pressure. not fully tested with mdaap. :param p: pressure :param v0: volume at reference condition :param g0: shear modulus at reference condition :param g0p: pressure derivative of shear modulus at reference condition...
[ "def", "bm3_g", "(", "p", ",", "v0", ",", "g0", ",", "g0p", ",", "k0", ",", "k0p", ")", ":", "return", "cal_g_bm3", "(", "p", ",", "[", "g0", ",", "g0p", "]", ",", "[", "v0", ",", "k0", ",", "k0p", "]", ")" ]
38.214286
13.071429
def restart_with_reloader(): """Create a new process and a subprocess in it with the same arguments as this one. """ cwd = os.getcwd() args = _get_args_for_reloading() new_environ = os.environ.copy() new_environ["SANIC_SERVER_RUNNING"] = "true" cmd = " ".join(args) worker_process = P...
[ "def", "restart_with_reloader", "(", ")", ":", "cwd", "=", "os", ".", "getcwd", "(", ")", "args", "=", "_get_args_for_reloading", "(", ")", "new_environ", "=", "os", ".", "environ", ".", "copy", "(", ")", "new_environ", "[", "\"SANIC_SERVER_RUNNING\"", "]", ...
30.5
13.625
def new_code_cell(code=None, prompt_number=None): """Create a new code cell with input and output""" cell = NotebookNode() cell.cell_type = u'code' if code is not None: cell.code = unicode(code) if prompt_number is not None: cell.prompt_number = int(prompt_number) return cell
[ "def", "new_code_cell", "(", "code", "=", "None", ",", "prompt_number", "=", "None", ")", ":", "cell", "=", "NotebookNode", "(", ")", "cell", ".", "cell_type", "=", "u'code'", "if", "code", "is", "not", "None", ":", "cell", ".", "code", "=", "unicode",...
34.222222
10.888889
def get_units(**kwargs): """ Returns all the units """ units_list = db.DBSession.query(Unit).all() units = [] for unit in units_list: new_unit = JSONObject(unit) units.append(new_unit) return units
[ "def", "get_units", "(", "*", "*", "kwargs", ")", ":", "units_list", "=", "db", ".", "DBSession", ".", "query", "(", "Unit", ")", ".", "all", "(", ")", "units", "=", "[", "]", "for", "unit", "in", "units_list", ":", "new_unit", "=", "JSONObject", "...
21.454545
13.818182
def server_error(request, template_name='500.html'): """ Custom 500 error handler. The exception clause is so broad to capture any 500 errors that may have been generated from getting the response page e.g. if the database was down. If they were not handled they would cause a 500 themselves and...
[ "def", "server_error", "(", "request", ",", "template_name", "=", "'500.html'", ")", ":", "try", ":", "rendered_page", "=", "get_response_page", "(", "request", ",", "http", ".", "HttpResponseServerError", ",", "'icekit/response_pages/500.html'", ",", "abstract_models...
31.966667
19.033333
def admin_create_user(self, username, temporary_password='', attr_map=None, **kwargs): """ Create a user using admin super privileges. :param username: User Pool username :param temporary_password: The temporary password to give the user. Leave blank to make Cognito generate a te...
[ "def", "admin_create_user", "(", "self", ",", "username", ",", "temporary_password", "=", "''", ",", "attr_map", "=", "None", ",", "*", "*", "kwargs", ")", ":", "response", "=", "self", ".", "client", ".", "admin_create_user", "(", "UserPoolId", "=", "self...
43.190476
15.285714
def write(self, filename, blocksize=32768, progress_cb=None, progress_opaque=None): # type: (str, int, Optional[Callable[[int, int, Any], None]], Optional[Any]) -> None ''' Write a properly formatted ISO out to the filename passed in. This also goes by the name of 'mastering'. ...
[ "def", "write", "(", "self", ",", "filename", ",", "blocksize", "=", "32768", ",", "progress_cb", "=", "None", ",", "progress_opaque", "=", "None", ")", ":", "# type: (str, int, Optional[Callable[[int, int, Any], None]], Optional[Any]) -> None", "if", "not", "self", "...
51.238095
31.52381
def Handle(self, args, token=None): """Renders specified config option.""" if not args.name: raise ValueError("Name not specified.") return ApiConfigOption().InitFromConfigOption(args.name)
[ "def", "Handle", "(", "self", ",", "args", ",", "token", "=", "None", ")", ":", "if", "not", "args", ".", "name", ":", "raise", "ValueError", "(", "\"Name not specified.\"", ")", "return", "ApiConfigOption", "(", ")", ".", "InitFromConfigOption", "(", "arg...
29
18.428571
def get_field_descriptor(self, class_name, field_name, descriptor): """ Return the specific field :param class_name: the class name of the field :type class_name: string :param field_name: the name of the field :type field_name: string :param descriptor: the desc...
[ "def", "get_field_descriptor", "(", "self", ",", "class_name", ",", "field_name", ",", "descriptor", ")", ":", "key", "=", "class_name", "+", "field_name", "+", "descriptor", "if", "self", ".", "__cache_fields", "is", "None", ":", "self", ".", "__cache_fields"...
33.916667
16
def Z_device(self, filter_order=None, window_size=None, tol=0.05): ''' Compute the impedance *(including resistive and capacitive load)* of the DMF device *(i.e., dielectric and droplet)*. See :func:`calibrate.compute_from_transfer_function` for details. ''' ind ...
[ "def", "Z_device", "(", "self", ",", "filter_order", "=", "None", ",", "window_size", "=", "None", ",", "tol", "=", "0.05", ")", ":", "ind", "=", "mlab", ".", "find", "(", "self", ".", "fb_resistor", ">=", "0", ")", "Z1", "=", "np", ".", "empty", ...
47.484375
21.796875
def __walk_chain(rel_dict, src_id): """ given a dict of pointing relations and a start node, this function will return a list of paths (each path is represented as a list of node IDs -- from the first node of the path to the last). Parameters ---------- rel_dict : dict a dictionary ...
[ "def", "__walk_chain", "(", "rel_dict", ",", "src_id", ")", ":", "paths_starting_with_id", "=", "[", "]", "for", "target_id", "in", "rel_dict", "[", "src_id", "]", ":", "if", "target_id", "in", "rel_dict", ":", "for", "tail", "in", "__walk_chain", "(", "re...
35.407407
19.481481
def find_initial_offset(self, pyramids=6): """Estimate time offset This sets and returns the initial time offset estimation. Parameters --------------- pyramids : int Number of pyramids to use for ZNCC calculations. If initial estimation ...
[ "def", "find_initial_offset", "(", "self", ",", "pyramids", "=", "6", ")", ":", "flow", "=", "self", ".", "video", ".", "flow", "gyro_rate", "=", "self", ".", "parameter", "[", "'gyro_rate'", "]", "frame_times", "=", "np", ".", "arange", "(", "len", "(...
36.5
22.961538
def model(self, name=None, model=None, mask=None, **kwargs): """ Model registration decorator. """ if isinstance(model, (flask_marshmallow.Schema, flask_marshmallow.base_fields.FieldABC)): if not name: name = model.__class__.__name__ api_model = Mo...
[ "def", "model", "(", "self", ",", "name", "=", "None", ",", "model", "=", "None", ",", "mask", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "isinstance", "(", "model", ",", "(", "flask_marshmallow", ".", "Schema", ",", "flask_marshmallow", "...
46.181818
14.909091
def find_api_id(self): """Given API name, find API ID.""" allapis = self.client.get_rest_apis() api_name = self.trigger_settings['api_name'] api_id = None for api in allapis['items']: if api['name'] == api_name: api_id = api['id'] self....
[ "def", "find_api_id", "(", "self", ")", ":", "allapis", "=", "self", ".", "client", ".", "get_rest_apis", "(", ")", "api_name", "=", "self", ".", "trigger_settings", "[", "'api_name'", "]", "api_id", "=", "None", "for", "api", "in", "allapis", "[", "'ite...
31.714286
13.714286
def draw(self): """Draws the button in its current state. Should be called every time through the main loop """ if not self.visible: return # Blit the button's current appearance to the surface. if self.isEnabled: if self.mouseIsDown:...
[ "def", "draw", "(", "self", ")", ":", "if", "not", "self", ".", "visible", ":", "return", "# Blit the button's current appearance to the surface.\r", "if", "self", ".", "isEnabled", ":", "if", "self", ".", "mouseIsDown", ":", "if", "self", ".", "mouseOverButton"...
34.708333
20.541667
def make_rr_subparser(subparsers, rec_type, args_and_types): """ Make a subparser for a given type of DNS record """ sp = subparsers.add_parser(rec_type) sp.add_argument("name", type=str) sp.add_argument("ttl", type=int, nargs='?') sp.add_argument(rec_type, type=str) for my_spec in arg...
[ "def", "make_rr_subparser", "(", "subparsers", ",", "rec_type", ",", "args_and_types", ")", ":", "sp", "=", "subparsers", ".", "add_parser", "(", "rec_type", ")", "sp", ".", "add_argument", "(", "\"name\"", ",", "type", "=", "str", ")", "sp", ".", "add_arg...
31.055556
13.166667
def get_segment_count_data(self, start, end, use_shapes=True): """ Get segment data including PTN vehicle counts per segment that are fully _contained_ within the interval (start, end) Parameters ---------- start : int start time of the simulation in unix tim...
[ "def", "get_segment_count_data", "(", "self", ",", "start", ",", "end", ",", "use_shapes", "=", "True", ")", ":", "cur", "=", "self", ".", "conn", ".", "cursor", "(", ")", "# get all possible trip_ids that take place between start and end", "trips_df", "=", "self"...
43.556962
18.594937
def replace_namespaced_pod(self, name, namespace, body, **kwargs): # noqa: E501 """replace_namespaced_pod # noqa: E501 replace the specified Pod # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True ...
[ "def", "replace_namespaced_pod", "(", "self", ",", "name", ",", "namespace", ",", "body", ",", "*", "*", "kwargs", ")", ":", "# noqa: E501", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'async_req'", ")", "...
58.48
32.8
def tgread_vector(self): """Reads a vector (a list) of Telegram objects.""" if 0x1cb5c415 != self.read_int(signed=False): raise RuntimeError('Invalid constructor code, vector was expected') count = self.read_int() return [self.tgread_object() for _ in range(count)]
[ "def", "tgread_vector", "(", "self", ")", ":", "if", "0x1cb5c415", "!=", "self", ".", "read_int", "(", "signed", "=", "False", ")", ":", "raise", "RuntimeError", "(", "'Invalid constructor code, vector was expected'", ")", "count", "=", "self", ".", "read_int", ...
43.428571
19.428571
def dlogpdf_dlink(self, link_f, y, Y_metadata=None): """ derivative of logpdf wrt link_f param .. math:: :param link_f: latent variables link(f) :type link_f: Nx1 array :param y: data :type y: Nx1 array :param Y_metadata: includes censoring information in...
[ "def", "dlogpdf_dlink", "(", "self", ",", "link_f", ",", "y", ",", "Y_metadata", "=", "None", ")", ":", "assert", "np", ".", "atleast_1d", "(", "link_f", ")", ".", "shape", "==", "np", ".", "atleast_1d", "(", "y", ")", ".", "shape", "c", "=", "np",...
42.928571
19.5
def get_base(self): """ Get the single base at this position. :returns: base :rtype: char """ if self._type == 'query': return self._observable.get_query_base() return self._observable.get_target_base()
[ "def", "get_base", "(", "self", ")", ":", "if", "self", ".", "_type", "==", "'query'", ":", "return", "self", ".", "_observable", ".", "get_query_base", "(", ")", "return", "self", ".", "_observable", ".", "get_target_base", "(", ")" ]
22.5
16.9
def create_venv( ctx, python, venv_path, inputs=None, outputs=None, pip_setup_file=None, pip_setup_touch=None, virtualenv_setup_touch=None, task_name=None, cache_key=None, always=False, ): """ Create task that sets up virtual environment. :param ctx: BuildContext...
[ "def", "create_venv", "(", "ctx", ",", "python", ",", "venv_path", ",", "inputs", "=", "None", ",", "outputs", "=", "None", ",", "pip_setup_file", "=", "None", ",", "pip_setup_touch", "=", "None", ",", "virtualenv_setup_touch", "=", "None", ",", "task_name",...
23.51938
23.03876
def postag_descriptions(self): """Human-readable POS-tag descriptions.""" if not self.is_tagged(ANALYSIS): self.tag_analysis() return [POSTAG_DESCRIPTIONS.get(tag, '') for tag in self.get_analysis_element(POSTAG)]
[ "def", "postag_descriptions", "(", "self", ")", ":", "if", "not", "self", ".", "is_tagged", "(", "ANALYSIS", ")", ":", "self", ".", "tag_analysis", "(", ")", "return", "[", "POSTAG_DESCRIPTIONS", ".", "get", "(", "tag", ",", "''", ")", "for", "tag", "i...
49
14.6
def down(removekeys=False, tgt='*', tgt_type='glob', timeout=None, gather_job_timeout=None): ''' .. versionchanged:: 2017.7.0 The ``expr_form`` argument has been renamed to ``tgt_type``, earlier releases must use ``expr_form``. Print a list of all the down or unresponsive salt minions O...
[ "def", "down", "(", "removekeys", "=", "False", ",", "tgt", "=", "'*'", ",", "tgt_type", "=", "'glob'", ",", "timeout", "=", "None", ",", "gather_job_timeout", "=", "None", ")", ":", "ret", "=", "status", "(", "output", "=", "False", ",", "tgt", "=",...
30.758621
21.37931
def move(src, dst): """Recursively move a file or directory to another location. This is similar to the Unix "mv" command. If the destination is a directory or a symlink to a directory, the source is moved inside the directory. The destination path must not already exist. If the destination al...
[ "def", "move", "(", "src", ",", "dst", ")", ":", "real_dst", "=", "dst", "if", "os", ".", "path", ".", "isdir", "(", "dst", ")", ":", "if", "_samefile", "(", "src", ",", "dst", ")", ":", "# We might be on a case insensitive filesystem,", "# perform the ren...
36.333333
20.717949
def _get_sub_prop(self, key, default=None): """Get a value in the ``self._properties[self._job_type]`` dictionary. Most job properties are inside the dictionary related to the job type (e.g. 'copy', 'extract', 'load', 'query'). Use this method to access those properties:: s...
[ "def", "_get_sub_prop", "(", "self", ",", "key", ",", "default", "=", "None", ")", ":", "return", "_helpers", ".", "_get_sub_prop", "(", "self", ".", "_properties", ",", "[", "self", ".", "_job_type", ",", "key", "]", ",", "default", "=", "default", ")...
36.5
22.392857
def set_config(self, config): ''' Set launch data from a ToolConfig. ''' if self.launch_url == None: self.launch_url = config.launch_url self.custom_params.update(config.custom_params)
[ "def", "set_config", "(", "self", ",", "config", ")", ":", "if", "self", ".", "launch_url", "==", "None", ":", "self", ".", "launch_url", "=", "config", ".", "launch_url", "self", ".", "custom_params", ".", "update", "(", "config", ".", "custom_params", ...
33.428571
14.571429
def has_api_key(file_name): """ Detect whether the file contains an api key in the Token object that is not 40*'0'. See issue #86. :param file: path-to-file to check :return: boolean """ f = open(file_name, 'r') text = f.read() if re.search(real_api_regex, text) is not None and \ ...
[ "def", "has_api_key", "(", "file_name", ")", ":", "f", "=", "open", "(", "file_name", ",", "'r'", ")", "text", "=", "f", ".", "read", "(", ")", "if", "re", ".", "search", "(", "real_api_regex", ",", "text", ")", "is", "not", "None", "and", "re", ...
30.384615
16.230769
def sumdiffsquared(x, y): """ Takes pairwise differences of the values in lists x and y, squares these differences, and returns the sum of these squares. Usage: lsumdiffsquared(x,y) Returns: sum[(x[i]-y[i])**2] """ sds = 0 for i in range(len(x)): sds = sds + (x[i] - y[i]) ** 2 return sds
[ "def", "sumdiffsquared", "(", "x", ",", "y", ")", ":", "sds", "=", "0", "for", "i", "in", "range", "(", "len", "(", "x", ")", ")", ":", "sds", "=", "sds", "+", "(", "x", "[", "i", "]", "-", "y", "[", "i", "]", ")", "**", "2", "return", ...
25.333333
15.833333
def move_down(lines=1, file=sys.stdout): """ Move the cursor down a number of lines. Esc[<lines>B: Moves the cursor down by the specified number of lines without changing columns. If the cursor is already on the bottom line, ANSI.SYS ignores this sequence. """ move.down(line...
[ "def", "move_down", "(", "lines", "=", "1", ",", "file", "=", "sys", ".", "stdout", ")", ":", "move", ".", "down", "(", "lines", ")", ".", "write", "(", "file", "=", "file", ")" ]
36.777778
13.666667
def read_scenarios(filename): """Read keywords dictionary from file. :param filename: Name of file holding scenarios . :return Dictionary of with structure like this {{ 'foo' : { 'a': 'b', 'c': 'd'}, { 'bar' : { 'd': 'e', 'f': 'g'}} A scenarios file may look like this: [j...
[ "def", "read_scenarios", "(", "filename", ")", ":", "# Input checks", "filename", "=", "os", ".", "path", ".", "abspath", "(", "filename", ")", "blocks", "=", "{", "}", "parser", "=", "ConfigParser", "(", ")", "# Parse the file content.", "# if the content don't...
31.105263
14.982456
def parse_document(text, options=0): """Parse a document and return the root node. Args: text (str): The text to parse. options (int): The cmark options. Returns: Any: Opaque reference to the root node of the parsed syntax tree. """ encoded_text = text.encode('utf...
[ "def", "parse_document", "(", "text", ",", "options", "=", "0", ")", ":", "encoded_text", "=", "text", ".", "encode", "(", "'utf-8'", ")", "return", "_cmark", ".", "lib", ".", "cmark_parse_document", "(", "encoded_text", ",", "len", "(", "encoded_text", ")...
31.384615
14.461538
def synchronized(func): """ Decorator for synchronizing method access. """ @wraps(func) def wrapped(self, *args, **kwargs): try: rlock = self._sync_lock except AttributeError: from multiprocessing import RLock rlock = self.__dict__.setdefault('_syn...
[ "def", "synchronized", "(", "func", ")", ":", "@", "wraps", "(", "func", ")", "def", "wrapped", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "try", ":", "rlock", "=", "self", ".", "_sync_lock", "except", "AttributeError", ":", ...
29.285714
12.285714
def iter(self, order='', sort=True): """Return a :class:`tableiter` object on this column.""" from casacore.tables import tableiter return tableiter(self._table, [self._column], order, sort)
[ "def", "iter", "(", "self", ",", "order", "=", "''", ",", "sort", "=", "True", ")", ":", "from", "casacore", ".", "tables", "import", "tableiter", "return", "tableiter", "(", "self", ".", "_table", ",", "[", "self", ".", "_column", "]", ",", "order",...
52.75
8.75
def values(cls, dataset, dim, expanded=True, flat=True, compute=True): """ Returns an array of the values along the supplied dimension. """ dim = dataset.get_dimension(dim, strict=True) if dim in dataset.vdims: coord_names = [c.name() for c in dataset.data.dim_coords]...
[ "def", "values", "(", "cls", ",", "dataset", ",", "dim", ",", "expanded", "=", "True", ",", "flat", "=", "True", ",", "compute", "=", "True", ")", ":", "dim", "=", "dataset", ".", "get_dimension", "(", "dim", ",", "strict", "=", "True", ")", "if", ...
45.733333
16.666667
def get_all_domains(self, max_domains=None, next_token=None): """ Returns a :py:class:`boto.resultset.ResultSet` containing all :py:class:`boto.sdb.domain.Domain` objects associated with this connection's Access Key ID. :keyword int max_domains: Limit the returned ...
[ "def", "get_all_domains", "(", "self", ",", "max_domains", "=", "None", ",", "next_token", "=", "None", ")", ":", "params", "=", "{", "}", "if", "max_domains", ":", "params", "[", "'MaxNumberOfDomains'", "]", "=", "max_domains", "if", "next_token", ":", "p...
49.956522
21
def get_shared_secret(priv, pub): """ Derive the share secret between ``priv`` and ``pub`` :param `Base58` priv: Private Key :param `Base58` pub: Public Key :return: Shared secret :rtype: hex The shared secret is generated such that:: Pub(Alice) * Priv(Bob) = P...
[ "def", "get_shared_secret", "(", "priv", ",", "pub", ")", ":", "pub_point", "=", "pub", ".", "point", "(", ")", "priv_point", "=", "int", "(", "repr", "(", "priv", ")", ",", "16", ")", "res", "=", "pub_point", "*", "priv_point", "res_hex", "=", "\"%0...
27.45
15.8
def as_dict(self): """ Return the URI object as a dictionary""" d = {k:v for (k,v) in self.__dict__.items()} return d
[ "def", "as_dict", "(", "self", ")", ":", "d", "=", "{", "k", ":", "v", "for", "(", "k", ",", "v", ")", "in", "self", ".", "__dict__", ".", "items", "(", ")", "}", "return", "d" ]
34.5
14.5
def parse(self): ''' The first method that should be called after creating an ExhaleRoot object. The Breathe graph is parsed first, followed by the Doxygen xml documents. By the end of this method, all of the ``self.<breathe_kind>``, ``self.all_compounds``, and ``self.all_nodes...
[ "def", "parse", "(", "self", ")", ":", "self", ".", "discoverAllNodes", "(", ")", "# now reparent everything we can", "# NOTE: it's very important that this happens before `fileRefDiscovery`, since", "# in that method we only want to consider direct descendants", "self", ".", "...
45.378378
24.243243
def gen_checkbox_edit(sig_dic): ''' for checkbox ''' edit_wuneisheshi = '''<label for="{0}"><span> <a class="glyphicon glyphicon-star" style="color: red;font-size: xx-small;"> </a>{1}</span> '''.format(sig_dic['en'], sig_dic['zh']) dic_tmp = sig_dic['dic'] for key in dic_tmp.keys...
[ "def", "gen_checkbox_edit", "(", "sig_dic", ")", ":", "edit_wuneisheshi", "=", "'''<label for=\"{0}\"><span>\n <a class=\"glyphicon glyphicon-star\" style=\"color: red;font-size: xx-small;\">\n </a>{1}</span>\n '''", ".", "format", "(", "sig_dic", "[", "'en'", "]", ",", ...
32.095238
20.190476
def _cast(self, value): """ Try to cast value to int or float if possible :param value: value to cast :return: casted value """ if value.isdigit(): value = int(value) elif re.compile("^\d+\.\d+").match(value): value = float(value) r...
[ "def", "_cast", "(", "self", ",", "value", ")", ":", "if", "value", ".", "isdigit", "(", ")", ":", "value", "=", "int", "(", "value", ")", "elif", "re", ".", "compile", "(", "\"^\\d+\\.\\d+\"", ")", ".", "match", "(", "value", ")", ":", "value", ...
29.181818
9.727273
def remove_tier(self, id_tier, clean=True): """Remove a tier. :param str id_tier: Name of the tier. :param bool clean: Flag to also clean the timeslots. :raises KeyError: If tier is non existent. """ del(self.tiers[id_tier]) if clean: self.clean_time_...
[ "def", "remove_tier", "(", "self", ",", "id_tier", ",", "clean", "=", "True", ")", ":", "del", "(", "self", ".", "tiers", "[", "id_tier", "]", ")", "if", "clean", ":", "self", ".", "clean_time_slots", "(", ")" ]
31.8
11.4
def surface_nodes(self): """ :param points: a list of Point objects :returns: a Node of kind 'griddedSurface' """ line = [] for point in self.mesh: line.append(point.longitude) line.append(point.latitude) line.append(point.depth) ...
[ "def", "surface_nodes", "(", "self", ")", ":", "line", "=", "[", "]", "for", "point", "in", "self", ".", "mesh", ":", "line", ".", "append", "(", "point", ".", "longitude", ")", "line", ".", "append", "(", "point", ".", "latitude", ")", "line", "."...
34.727273
9.636364
def pretty_string(fc): '''construct a nice looking string for an FC ''' s = [] for fname, feature in sorted(fc.items()): if isinstance(feature, StringCounter): feature = [u'%s: %d' % (k, v) for (k,v) in feature.most_common()] feature = u'\n\t' + u'\...
[ "def", "pretty_string", "(", "fc", ")", ":", "s", "=", "[", "]", "for", "fname", ",", "feature", "in", "sorted", "(", "fc", ".", "items", "(", ")", ")", ":", "if", "isinstance", "(", "feature", ",", "StringCounter", ")", ":", "feature", "=", "[", ...
35.909091
13.545455
def split(self, widget, orientation): """ Split the the current widget in new SplittableTabWidget. :param widget: widget to split :param orientation: orientation of the splitter :return: the new splitter """ if widget.original: base = widget.original ...
[ "def", "split", "(", "self", ",", "widget", ",", "orientation", ")", ":", "if", "widget", ".", "original", ":", "base", "=", "widget", ".", "original", "else", ":", "base", "=", "widget", "clone", "=", "base", ".", "split", "(", ")", "if", "not", "...
37.651163
13.837209
def get_primary_group(obj_name, obj_type='file'): r''' Gets the primary group of the passed object Args: obj_name (str): The path for which to obtain primary group information obj_type (str): The type of object to query. This value changes the format of the ...
[ "def", "get_primary_group", "(", "obj_name", ",", "obj_type", "=", "'file'", ")", ":", "# Not all filesystems mountable within windows have SecurityDescriptors.", "# For instance, some mounted SAMBA shares, or VirtualBox shared folders. If", "# we can't load a file descriptor for the file, w...
37.27381
21.964286
def configure_rmq_ssl_off(self, sentry_units, deployment, max_wait=60): """Turn ssl charm config option off, confirm that it is disabled on every unit. :param sentry_units: list of sentry units :param deployment: amulet deployment object pointer :param max_wait: maximum time to ...
[ "def", "configure_rmq_ssl_off", "(", "self", ",", "sentry_units", ",", "deployment", ",", "max_wait", "=", "60", ")", ":", "self", ".", "log", ".", "debug", "(", "'Setting ssl charm config option: off'", ")", "# Disable RMQ SSL", "config", "=", "{", "'ssl'", ":...
35.896552
20.344828
def query(self, terms=None, negated_terms=None): """ Basic boolean query, using inference. Arguments: - terms: list list of class ids. Returns the set of subjects that have at least one inferred annotation to each of the specified classes. - negated_terms: list...
[ "def", "query", "(", "self", ",", "terms", "=", "None", ",", "negated_terms", "=", "None", ")", ":", "if", "terms", "is", "None", ":", "terms", "=", "[", "]", "matches_all", "=", "'owl:Thing'", "in", "terms", "if", "negated_terms", "is", "None", ":", ...
34.586207
24.586207
def ParseByteStream( self, parser_mediator, byte_stream, parent_path_segments=None, codepage='cp1252'): """Parses the shell items from the byte stream. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. ...
[ "def", "ParseByteStream", "(", "self", ",", "parser_mediator", ",", "byte_stream", ",", "parent_path_segments", "=", "None", ",", "codepage", "=", "'cp1252'", ")", ":", "if", "parent_path_segments", "and", "isinstance", "(", "parent_path_segments", ",", "list", ")...
34.965517
19.724138
def trending(params): """gets trending content values """ # get params try: series = params.get("site", [DEFAULT_SERIES])[0] offset = params.get("offset", [DEFAULT_GROUP_BY])[0] limit = params.get("limit", [20])[0] except Exception as e: LOGGER.exception(e) re...
[ "def", "trending", "(", "params", ")", ":", "# get params", "try", ":", "series", "=", "params", ".", "get", "(", "\"site\"", ",", "[", "DEFAULT_SERIES", "]", ")", "[", "0", "]", "offset", "=", "params", ".", "get", "(", "\"offset\"", ",", "[", "DEFA...
31.294118
20.941176
def getValues(self, suffixes=None): """ If a list of suffixes is provided, get the specified suffixes value for all instances. Otherwise, get all the principal values of this entity. The specific returned value depends on the type of entity (see list below). For: - Varia...
[ "def", "getValues", "(", "self", ",", "suffixes", "=", "None", ")", ":", "if", "suffixes", "is", "None", ":", "return", "DataFrame", ".", "_fromDataFrameRef", "(", "self", ".", "_impl", ".", "getValues", "(", ")", ")", "else", ":", "suffixes", "=", "li...
41.833333
22
def serializeEc(P, compress=True): """ Generates a compact binary version of this point. """ return _serialize(P, compress, librelic.ec_size_bin_abi, librelic.ec_write_bin_abi)
[ "def", "serializeEc", "(", "P", ",", "compress", "=", "True", ")", ":", "return", "_serialize", "(", "P", ",", "compress", ",", "librelic", ".", "ec_size_bin_abi", ",", "librelic", ".", "ec_write_bin_abi", ")" ]
32.5
7.5
def set_settings(self): """ :reference: https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/post-account-settings :allowed_param:'sleep_time_enabled', 'start_sleep_time', 'end_sleep_time', 'time_zone', 'trend_location_woeid', 'allow_...
[ "def", "set_settings", "(", "self", ")", ":", "return", "bind_api", "(", "api", "=", "self", ",", "path", "=", "'/account/settings.json'", ",", "method", "=", "'POST'", ",", "payload_type", "=", "'json'", ",", "allowed_param", "=", "[", "'sleep_time_enabled'",...
45.588235
15.882353
def import_string(import_name, silent=False): """Imports an object based on a string. This is useful if you want to use import paths as endpoints or something similar. An import path can be specified either in dotted notation (``xml.sax.saxutils.escape``) or with a colon as object delimiter (``xml.sax...
[ "def", "import_string", "(", "import_name", ",", "silent", "=", "False", ")", ":", "try", ":", "if", "':'", "in", "import_name", ":", "module", ",", "obj", "=", "import_name", ".", "split", "(", "':'", ",", "1", ")", "elif", "'.'", "in", "import_name",...
36.916667
17.958333
def interface_type(self): """The interface type of the resource as a number. """ return self.visalib.parse_resource(self._resource_manager.session, self.resource_name)[0].interface_type
[ "def", "interface_type", "(", "self", ")", ":", "return", "self", ".", "visalib", ".", "parse_resource", "(", "self", ".", "_resource_manager", ".", "session", ",", "self", ".", "resource_name", ")", "[", "0", "]", ".", "interface_type" ]
49.6
17.8
def iter_fields(self, exclude=None, only=None): """This method iterates over all fields that are defined and yields ``(key, value)`` tuples. Per default all fields are returned, but it's possible to limit that to some fields by providing the `only` parameter or to exclude some using the...
[ "def", "iter_fields", "(", "self", ",", "exclude", "=", "None", ",", "only", "=", "None", ")", ":", "for", "name", "in", "self", ".", "fields", ":", "if", "(", "exclude", "is", "only", "is", "None", ")", "or", "(", "exclude", "is", "not", "None", ...
48.533333
14.266667
def reflash_firmware(self, hardware_id, ipmi=True, raid_controller=True, bios=True): """Reflash hardware firmware. This will cause the server to be unavailable for ~60 minutes. The firmware will ...
[ "def", "reflash_firmware", "(", "self", ",", "hardware_id", ",", "ipmi", "=", "True", ",", "raid_controller", "=", "True", ",", "bios", "=", "True", ")", ":", "return", "self", ".", "hardware", ".", "createFirmwareReflashTransaction", "(", "bool", "(", "ipmi...
39.958333
22.041667
def _datetime_to_utc(self, dt): """Convert naive datetimes to UTC""" if not dt.tzinfo: dt = dt.replace(tzinfo=tz.gettz()) return dt.astimezone(tz.gettz('UTC'))
[ "def", "_datetime_to_utc", "(", "self", ",", "dt", ")", ":", "if", "not", "dt", ".", "tzinfo", ":", "dt", "=", "dt", ".", "replace", "(", "tzinfo", "=", "tz", ".", "gettz", "(", ")", ")", "return", "dt", ".", "astimezone", "(", "tz", ".", "gettz"...
31.833333
12.5
def whois_emails(self, emails): """Calls WHOIS Email end point Args: emails: An enumerable of string Emails Returns: A dict of {email: domain_result} """ api_name = 'opendns-whois-emails' fmt_url_path = u'whois/emails/{0}' return self._mul...
[ "def", "whois_emails", "(", "self", ",", "emails", ")", ":", "api_name", "=", "'opendns-whois-emails'", "fmt_url_path", "=", "u'whois/emails/{0}'", "return", "self", ".", "_multi_get", "(", "api_name", ",", "fmt_url_path", ",", "emails", ")" ]
31.636364
12.636364
def permission_update(self, token, id, **kwargs): """ To update an existing permission. https://www.keycloak.org/docs/latest/authorization_services/index.html#_service_authorization_uma_policy_api :param str token: client access token :param str id: permission id :rtyp...
[ "def", "permission_update", "(", "self", ",", "token", ",", "id", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "_realm", ".", "client", ".", "put", "(", "'{}/{}'", ".", "format", "(", "self", ".", "well_known", "[", "'policy_endpoint'", "]...
32.6875
18.8125
def check_available(self): """ Check for availability of a layer and provide run metrics. """ success = True start_time = datetime.datetime.utcnow() message = '' LOGGER.debug('Checking layer id %s' % self.id) signals.post_save.disconnect(layer_post_save, ...
[ "def", "check_available", "(", "self", ")", ":", "success", "=", "True", "start_time", "=", "datetime", ".", "datetime", ".", "utcnow", "(", ")", "message", "=", "''", "LOGGER", ".", "debug", "(", "'Checking layer id %s'", "%", "self", ".", "id", ")", "s...
32.447368
19.289474