Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
388,400
def histogram_voltage(self, timestep=None, title=True, **kwargs): data = self.network.results.v_res() if title is True: if timestep is not None: title = "Voltage histogram for time step {}".format(timestep) else: title = "Voltage histogram...
Plots histogram of voltages. For more information see :func:`edisgo.tools.plots.histogram`. Parameters ---------- timestep : :pandas:`pandas.Timestamp<timestamp>` or None, optional Specifies time step histogram is plotted for. If timestep is None all time steps ...
388,401
def yaml_dump(data, stream=None): return yaml.dump( data, stream=stream, Dumper=Dumper, default_flow_style=False )
Dump data to a YAML string/file. Args: data (YamlData): The data to serialize as YAML. stream (TextIO): The file-like object to save to. If given, this function will write the resulting YAML to that stream. Returns: str: The YAML string.
388,402
def _dict_increment(self, dictionary, key): if key in dictionary: dictionary[key] += 1 else: dictionary[key] = 1
Increments the value of the dictionary at the specified key.
388,403
def reply_message(self, reply_token, messages, timeout=None): if not isinstance(messages, (list, tuple)): messages = [messages] data = { : reply_token, : [message.as_json_dict() for message in messages] } self._post( , data=json....
Call reply message API. https://devdocs.line.me/en/#reply-message Respond to events from users, groups, and rooms. Webhooks are used to notify you when an event occurs. For events that you can respond to, a replyToken is issued for replying to messages. Because the replyToken...
388,404
def get_membership_document(membership_type: str, current_block: dict, identity: Identity, salt: str, password: str) -> Membership: timestamp = BlockUID(current_block[], current_block[]) key = SigningKey.from_credentials(salt, password) membership = Members...
Get a Membership document :param membership_type: "IN" to ask for membership or "OUT" to cancel membership :param current_block: Current block data :param identity: Identity document :param salt: Passphrase of the account :param password: Password of the account :rtype: Membership
388,405
def define(cls, name, parent=None, interleave=False): node = cls("define", parent, interleave=interleave) node.occur = 0 node.attr["name"] = name return node
Create define node.
388,406
def _member_def(self, member): member_docstring = textwrap.dedent(member.docstring).strip() member_docstring = textwrap.fill( member_docstring, width=78, initial_indent=*4, subsequent_indent=*4 ) return % (member.name, member_docstring)
Return an individual member definition formatted as an RST glossary entry, wrapped to fit within 78 columns.
388,407
def make_application_error(name, tag): cls = type(xso.XSO)(name, (xso.XSO,), { "TAG": tag, }) Error.as_application_condition(cls) return cls
Create and return a **class** inheriting from :class:`.xso.XSO`. The :attr:`.xso.XSO.TAG` is set to `tag` and the class’ name will be `name`. In addition, the class is automatically registered with :attr:`.Error.application_condition` using :meth:`~.Error.as_application_condition`. Keep in mind th...
388,408
def authorization_url(self, **kwargs): payload = {: , : self._client_id} for key in kwargs.keys(): payload[key] = kwargs[key] payload = sorted(payload.items(), key=lambda val: val[0]) params = urlencode(payload) url = self.get_url() ret...
Get authorization URL to redirect the resource owner to. https://tools.ietf.org/html/rfc6749#section-4.1.1 :param str redirect_uri: (optional) Absolute URL of the client where the user-agent will be redirected to. :param str scope: (optional) Space delimited list of strings. ...
388,409
def cartesian_to_index(ranges, maxima=None): if maxima is None: return reduce(lambda y,x: (x*y[1] + y[0],(np.max(x)+1)*y[1]), ranges[:,::-1].transpose(), (np.array([0]*ranges.shape[0]),1))[0] else: maxima_prod = np.concatenate([np.cumprod(np.array(maxima)[::-1])[1::-1],[1]]) return ...
Inverts tuples from a cartesian product to a numeric index ie. the index this tuple would have in a cartesian product. Each column gets multiplied with a place value according to the preceding columns maxmimum and all columns are summed up. This function in the same direction as utils...
388,410
def readFromProto(cls, proto): instance = cls() instance.implementation = proto.implementation instance.steps = proto.steps instance.stepsList = [int(i) for i in proto.steps.split(",")] instance.alpha = proto.alpha instance.verbosity = proto.verbosity instance.maxCategoryCount = proto....
Read state from proto object. :param proto: SDRClassifierRegionProto capnproto object
388,411
def _get_operator_param_name_and_values(operator_class_name, task_details): operator_task_details = task_details.copy() if in operator_task_details.keys(): del operator_task_details[] if in operator_task_details.keys(): del operator_task_details[] if (operat...
Internal helper gets the name of the python parameter for the Airflow operator class. In some cases, we do not expose the airflow parameter name in its native form, but choose to expose a name that's more standard for Datalab, or one that's more friendly. For example, Airflow's BigQueryOperator uses '...
388,412
def atFontFace(self, declarations): result = self.ruleset([self.selector()], declarations) data = list(result[0].values())[0] if "src" not in data: return {}, {} names = data["font-family"] fweight = str(data.get("font-weight", "normal"...
Embed fonts
388,413
def set_bank_1(self, bits): res = yield from self._pigpio_aio_command(_PI_CMD_BS1, bits, 0) return _u2i(res)
Sets gpios 0-31 if the corresponding bit in bits is set. bits:= a 32 bit mask with 1 set if the corresponding gpio is to be set. A returned status of PI_SOME_PERMITTED indicates that the user is not allowed to write to one or more of the gpios. ... pi.set_bank_1(i...
388,414
def make_form(fields=None, layout=None, layout_class=None, base_class=None, get_form_field=None, name=None, rules=None, **kwargs): from uliweb.utils.sorteddict import SortedDict get_form_field = get_form_field or (lambda name, f:None) props = SortedDict({}) for f in fields or [...
Make a from according dict data: {'fields':[ {'name':'name', 'type':'str', 'label':'label, 'rules':{ 'required': 'email' 'required:back|front' #back means server side, front means front side } ...
388,415
def acquire_lock(self): try: self.collection.insert_one(dict(_id=self.id)) except pymongo.errors.DuplicateKeyError: pass unlocked_spec = dict(_id=self.id, locked=None) lock_timer = ( timers.Timer.after(self.lock_timeout) if self.lock_timeout else timers.NeverExpires() ) while not lock_t...
Acquire the lock. Blocks indefinitely until lock is available unless `lock_timeout` was supplied. If the lock_timeout elapses, raises LockTimeout.
388,416
def windowed(seq, n, fillvalue=None, step=1): if n < 0: raise ValueError() if n == 0: yield tuple() return if step < 1: raise ValueError() it = iter(seq) window = deque([], n) append = window.append for _ in range(n): append(next(it, fillva...
Return a sliding window of width *n* over the given iterable. >>> all_windows = windowed([1, 2, 3, 4, 5], 3) >>> list(all_windows) [(1, 2, 3), (2, 3, 4), (3, 4, 5)] When the window is larger than the iterable, *fillvalue* is used in place of missing values:: >>> list(windowed(...
388,417
def add_JSsource(self, new_src): if isinstance(new_src, list): for h in new_src: self.JSsource.append(h) elif isinstance(new_src, basestring): self.JSsource.append(new_src) else: raise OptionTypeError("Option: %s Not Allowed For Series...
add additional js script source(s)
388,418
def oauth_client_create(self, data, **kwargs): "https://developer.zendesk.com/rest_api/docs/core/oauth_clients api_path = "/api/v2/oauth/clients.json" return self.call(api_path, method="POST", data=data, **kwargs)
https://developer.zendesk.com/rest_api/docs/core/oauth_clients#create-client
388,419
def autodiff(func, wrt=(0,), optimized=True, motion=, mode=, preserve_result=False, check_dims=True, input_derivative=INPUT_DERIVATIVE.Required, verbose=0): func = getattr(func, , func) node, namespace ...
Build the vector-Jacobian or Jacobian-vector product of a function `func`. For a vector-Jacobian product (reverse-mode autodiff): This function proceeds by finding the primals and adjoints of all the functions in the call tree. For a Jacobian-vector product (forward-mode autodiff): We first find the primals ...
388,420
def stop(logfile, time_format): "stop tracking for the active project" def save_and_output(records): records = server.stop(records) write(records, logfile, time_format) def output(r): print "worked on %s" % colored(r[0], attrs=[]) print " from %s" % colored( server.date_to_txt(...
stop tracking for the active project
388,421
def knx_to_time(knxdata): if len(knxdata) != 3: raise KNXException("Can only convert a 3 Byte object to time") dow = knxdata[0] >> 5 res = time(knxdata[0] & 0x1f, knxdata[1], knxdata[2]) return [res, dow]
Converts a KNX time to a tuple of a time object and the day of week
388,422
def ram_dp_rf(clka, clkb, wea, web, addra, addrb, dia, dib, doa, dob): memL = [Signal(intbv(0)[len(dia):]) for _ in range(2**len(addra))] @always(clka.posedge) def writea(): if wea: memL[int(addra)].next = dia doa.next = memL[int(addra)] @always(clkb.posedge) def...
RAM: Dual-Port, Read-First
388,423
def get_dependency_graph_for_set(self, id, **kwargs): kwargs[] = True if kwargs.get(): return self.get_dependency_graph_for_set_with_http_info(id, **kwargs) else: (data) = self.get_dependency_graph_for_set_with_http_info(id, **kwargs) return data
Gets dependency graph for a Build Group Record (running and completed). This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(respons...
388,424
def match_pattern(expr_or_pattern: object, expr: object) -> MatchDict: try: return expr_or_pattern.match(expr) except AttributeError: if expr_or_pattern == expr: return MatchDict() else: res = MatchDict() res.success = False res....
Recursively match `expr` with the given `expr_or_pattern` Args: expr_or_pattern: either a direct expression (equal to `expr` for a successful match), or an instance of :class:`Pattern`. expr: the expression to be matched
388,425
def dict2dzn( objs, declare=False, assign=True, declare_enums=True, wrap=True, fout=None ): log = logging.getLogger(__name__) vals = [] enums = set() for key, val in objs.items(): if _is_enum(val) and declare_enums: enum_type = type(val) enum_name = enum_type.__...
Serializes the objects in input and produces a list of strings encoding them into dzn format. Optionally, the produced dzn is written on a file. Supported types of objects include: ``str``, ``int``, ``float``, ``set``, ``list`` or ``dict``. List and dict are serialized into dzn (multi-dimensional) arra...
388,426
def add_node(self, payload): self.nodes.append(Node(len(self.nodes), payload)) return len(self.nodes) - 1
Returns ------- int Identifier for the inserted node.
388,427
def logging_syslog_facility_local(self, **kwargs): config = ET.Element("config") logging = ET.SubElement(config, "logging", xmlns="urn:brocade.com:mgmt:brocade-ras") syslog_facility = ET.SubElement(logging, "syslog-facility") local = ET.SubElement(syslog_facility, "local") ...
Auto Generated Code
388,428
def load_default_moderator(): if appsettings.FLUENT_COMMENTS_DEFAULT_MODERATOR == : return moderation.FluentCommentsModerator(None) elif appsettings.FLUENT_COMMENTS_DEFAULT_MODERATOR == : return moderation.AlwaysDeny(None) elif str(appsettings.FLUENT_COMMENTS_DEFAULT_M...
Find a moderator object
388,429
def find_or_create_by_name(self, item_name, items_list, item_type): item = self.find_by_name(item_name, items_list) if not item: item = self.data_lists[item_type][2](item_name, None) return item
See if item with item_name exists in item_list. If not, create that item. Either way, return an item of type item_type.
388,430
def _ensure_set_contains(test_object, required_object, test_set_name=None): assert isinstance(test_object, (set, dict)), % (test_object, test_set_name) assert isinstance(required_object, (set, dict)), % (required_object, test_set_name) test_set = set(test_object) required_set = set(required_...
Ensure that the required entries (set or keys of a dict) are present in the test set or keys of the test dict. :param set|dict test_object: The test set or dict :param set|dict required_object: The entries that need to be present in the test set (keys of input dict if input is dict) :param ...
388,431
def tvdb_login(api_key): url = "https://api.thetvdb.com/login" body = {"apikey": api_key} status, content = _request_json(url, body=body, cache=False) if status == 401: raise MapiProviderException("invalid api key") elif status != 200 or not content.get("token"): raise MapiNetwo...
Logs into TVDb using the provided api key Note: You can register for a free TVDb key at thetvdb.com/?tab=apiregister Online docs: api.thetvdb.com/swagger#!/Authentication/post_login=
388,432
def complex_validates(validate_rule): ref_dict = { } for column_names, predicate_refs in validate_rule.items(): for column_name in _to_tuple(column_names): ref_dict[column_name] = \ ref_dict.get(column_name, tuple()) + _normalize...
Quickly setup attributes validation by one-time, based on `sqlalchemy.orm.validates`. Don't like `sqlalchemy.orm.validates`, you don't need create many model method, as long as pass formatted validate rule. (Cause of SQLAlchemy's validate mechanism, you need assignment this funciton's return value to a...
388,433
def get_members(self, api=None): api = api or self._API response = api.get(url=self._URL[].format(id=self.id)) data = response.json() total = response.headers[] members = [Member(api=api, **member) for member in data[]] links = [Link(**link) for link in data[]]...
Retrieve dataset members :param api: Api instance :return: Collection object
388,434
def K(self, parm): return RQ_K_matrix(self.X, parm) + np.identity(self.X.shape[0])*(10**-10)
Returns the Gram Matrix Parameters ---------- parm : np.ndarray Parameters for the Gram Matrix Returns ---------- - Gram Matrix (np.ndarray)
388,435
def delete(self, key, **kwargs): payload = { "key": _encode(key), } payload.update(kwargs) result = self.post(self.get_url("/kv/deleterange"), json=payload) if in result: return True return False
DeleteRange deletes the given range from the key-value store. A delete request increments the revision of the key-value store and generates a delete event in the event history for every deleted key. :param key: :param kwargs: :return:
388,436
def load_app_resource(**kwargs): s workspace container, and the handler for it will be returned. If the app resources container ID is not found in DX_RESOURCES_ID, falls back to looking in the current project. Example:: @dxpy.entry_point() def main(*args, **kwargs): x = load_ap...
:param kwargs: keyword args for :func:`~dxpy.bindings.search.find_one_data_object`, with the exception of "project" :raises: :exc:`~dxpy.exceptions.DXError` if "project" is given, if this is called with dxpy.JOB_ID not set, or if "DX_RESOURCES_ID" or "DX_PROJECT_CONTEXT_ID" is not found in the environment variables...
388,437
def heatmap(dm, partition=None, cmap=CM.Blues, fontsize=10): assert isinstance(dm, DistanceMatrix) datamax = float(np.abs(dm.values).max()) length = dm.shape[0] if partition: sorting = np.array(flatten_list(partition.get_membership())) new_dm = dm.reorder(dm.df.columns[sorting]) ...
heatmap(dm, partition=None, cmap=CM.Blues, fontsize=10) Produce a 2D plot of the distance matrix, with values encoded by coloured cells. Args: partition: treeCl.Partition object - if supplied, will reorder rows and columns of the distance matrix to reflect ...
388,438
def apply(self, func, applyto=, noneval=nan, setdata=False): applyto = applyto.lower() if applyto == : if self.data is not None: data = self.data elif self.datafile is None: return noneval else: data = self.read...
Apply func either to self or to associated data. If data is not already parsed, try and read it. Parameters ---------- func : callable The function either accepts a measurement object or an FCS object. Does some calculation and returns the result. applyto...
388,439
def submit_job(job_ini, username, hazard_job_id=None): job_id = logs.init() oq = engine.job_from_file( job_ini, job_id, username, hazard_calculation_id=hazard_job_id) pik = pickle.dumps(oq, protocol=0) code = RUNCALC % dict(job_id=job_id, hazard_job_id=hazard_job_id, pik=pik, ...
Create a job object from the given job.ini file in the job directory and run it in a new process. Returns the job ID and PID.
388,440
def dir_df_boot(dir_df, nb=5000, par=False): N = dir_df.dir_dec.values.shape[0] BDIs = [] for k in range(nb): pdir_df = dir_df.sample(n=N, replace=True) pdir_df.reset_index(inplace=True) if par: for i in pdir_df.index: n = pdir_df.loc[i, ] ...
Performs a bootstrap for direction DataFrame with optional parametric bootstrap Parameters _________ dir_df : Pandas DataFrame with columns: dir_dec : mean declination dir_inc : mean inclination Required for parametric bootstrap dir_n : number of data points in mean di...
388,441
def remove_container(self, container, **kwargs): self.push_log("Removing container .".format(container)) set_raise_on_error(kwargs) super(DockerFabricClient, self).remove_container(container, **kwargs)
Identical to :meth:`dockermap.client.base.DockerClientWrapper.remove_container` with additional logging.
388,442
def _run_atstart(): global _atstart for callback, args, kwargs in _atstart: callback(*args, **kwargs) del _atstart[:]
Hook frameworks must invoke this before running the main hook body.
388,443
def _parse_uri(uri): tokens = urlparse(uri) if tokens.netloc != : logger.error("Invalid URI: %s", uri) raise ValueError("MediaFire URI format error: " "host should be empty - mf:///path") if tokens.scheme != and tokens.scheme != U...
Parse and validate MediaFire URI.
388,444
def execute(self): self.prepare_models() self.prepare_worker() if self.options.print_options: self.print_options() self.run()
Main method to call to run the worker
388,445
def get(self, source, media, collection=None, start_date=None, days=None, query=None, years=None, genres=None, languages=None, countries=None, runtimes=None, ratings=None, certifications=None, networks=None, status=None, **kwargs): if source not in [, ]: raise ValueE...
Retrieve calendar items. The `all` calendar displays info for all shows airing during the specified period. The `my` calendar displays episodes for all shows that have been watched, collected, or watchlisted. :param source: Calendar source (`all` or `my`) :type source: str :pa...
388,446
def get_sub_commands(parser: argparse.ArgumentParser) -> List[str]: sub_cmds = [] if parser is not None and parser._subparsers is not None: for action in parser._subparsers._actions: if isinstance(action, argparse._SubParsersAction): for sub_cmd, sub_cmd_...
Get a list of sub-commands for an ArgumentParser
388,447
def pos_by_percent(self, x_percent, y_percent): x = round(x_percent * self.width) y = round(y_percent * self.height) return int(x), int(y)
Finds a point inside the box that is exactly at the given percentage place. :param x_percent: how much percentage from left edge :param y_percent: how much percentage from top edge :return: A point inside the box
388,448
def _retf(ins): output = _float_oper(ins.quad[1]) output.append() output.append( % str(ins.quad[2])) return output
Returns from a procedure / function a Floating Point (40bits) value
388,449
def map_single_end(credentials, instance_config, instance_name, script_dir, index_dir, fastq_file, output_dir, num_threads=None, seed_start_lmax=None, mismatch_nmax=None, multimap_nmax=None, splice_min_overhang=None, out_mult...
Maps single-end reads using STAR. Reads are expected in FASTQ format. By default, they are also expected to be compressed with gzip. - recommended machine type: "n1-standard-16" (60 GB of RAM, 16 vCPUs). - recommended disk size: depends on size of FASTQ files, at least 128 GB. TODO: docstring
388,450
def create_hit(MaxAssignments=None, AutoApprovalDelayInSeconds=None, LifetimeInSeconds=None, AssignmentDurationInSeconds=None, Reward=None, Title=None, Keywords=None, Description=None, Question=None, RequesterAnnotation=None, QualificationRequirements=None, UniqueRequestToken=None, AssignmentReviewPolicy=None, HITRevie...
The CreateHIT operation creates a new Human Intelligence Task (HIT). The new HIT is made available for Workers to find and accept on the Amazon Mechanical Turk website. This operation allows you to specify a new HIT by passing in values for the properties of the HIT, such as its title, reward amount and number of a...
388,451
def handle_hooks(stage, hooks, provider, context, dump, outline): if not outline and not dump and hooks: utils.handle_hooks( stage=stage, hooks=hooks, provider=provider, context=context )
Handle pre/post hooks. Args: stage (str): The name of the hook stage - pre_build/post_build. hooks (list): A list of dictionaries containing the hooks to execute. provider (:class:`stacker.provider.base.BaseProvider`): The provider the current stack is using. context (:c...
388,452
def isdir(self, path=None, client_kwargs=None, virtual_dir=True, assume_exists=None): relative = self.relpath(path) if not relative: return True if path[-1] == or self.is_locator(relative, relative=True): exists = self.exists(path=pat...
Return True if path is an existing directory. Args: path (str): Path or URL. client_kwargs (dict): Client arguments. virtual_dir (bool): If True, checks if directory exists virtually if an object path if not exists as a specific object. assume_exi...
388,453
def main(arguments=None): if not arguments: arguments = sys.argv[1:] wordlist, sowpods, by_length, start, end = argument_parser(arguments) for word in wordlist: pretty_print( word, anagrams_in_word(word, sowpods, start, end), by_length, )
Main command line entry point.
388,454
def handle_call(self, body, message): try: r = self._DISPATCH(body, ticket=message.properties[]) except self.Next: pass else: self.reply(message, r)
Handle call message.
388,455
def subnet_group_exists(name, tags=None, region=None, key=None, keyid=None, profile=None): try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return {: bool(conn)} rds = conn.describe_db_subnet_groups(DBSubnetGro...
Check to see if an RDS subnet group exists. CLI example:: salt myminion boto_rds.subnet_group_exists my-param-group \ region=us-east-1
388,456
def progress_view(shell): while not ShellProgressView.done: _, col = get_window_dim() col = int(col) progress = get_progress_message() if in progress: prog_list = progress.split() prog_val = len(prog_list[-1]) else: prog_val = len(pro...
updates the view
388,457
def set_climate_hold(self, index, climate, hold_type="nextTransition"): body = {"selection": { "selectionType": "thermostats", "selectionMatch": self.thermostats[index][]}, "functions": [{"type": "setHold", "params": { "holdTyp...
Set a climate hold - ie away, home, sleep
388,458
def chop(array, epsilon=1e-10): ret = np.array(array) if np.isrealobj(ret): ret[abs(ret) < epsilon] = 0.0 else: ret.real[abs(ret.real) < epsilon] = 0.0 ret.imag[abs(ret.imag) < epsilon] = 0.0 return ret
Truncate small values of a complex array. Args: array (array_like): array to truncte small values. epsilon (float): threshold. Returns: np.array: A new operator with small values set to zero.
388,459
def update_room_name(self): try: response = self.client.api.get_room_name(self.room_id) if "name" in response and response["name"] != self.name: self.name = response["name"] return True else: return False except...
Updates self.name and returns True if room name has changed.
388,460
def list_handler(HandlerResult="nparray"): def decorate(func): def wrapper(*args, **kwargs): sequences = [] enumsUnitCheck = enumerate(args) argsList = list(args) for num, arg in enumsUnitCheck: if ty...
Wraps a function to handle list inputs.
388,461
def from_api_repr(cls, resource, client): name = resource.get("name") dns_name = resource.get("dnsName") if name is None or dns_name is None: raise KeyError( "Resource lacks required identity information:" ) zone = cls(name, dns_name, cli...
Factory: construct a zone given its API representation :type resource: dict :param resource: zone resource representation returned from the API :type client: :class:`google.cloud.dns.client.Client` :param client: Client which holds credentials and project config...
388,462
def add_paragraph(self, text=, style=None): return super(_Cell, self).add_paragraph(text, style)
Return a paragraph newly added to the end of the content in this cell. If present, *text* is added to the paragraph in a single run. If specified, the paragraph style *style* is applied. If *style* is not specified or is |None|, the result is as though the 'Normal' style was applied. Not...
388,463
def first(o): if o is None: return None if isinstance(o, ISeq): return o.first s = to_seq(o) if s is None: return None return s.first
If o is a ISeq, return the first element from o. If o is None, return None. Otherwise, coerces o to a Seq and returns the first.
388,464
def mod_bufsize(iface, *args, **kwargs): * if __grains__[] == : if os.path.exists(): return _mod_bufsize_linux(iface, *args, **kwargs) return False
Modify network interface buffers (currently linux only) CLI Example: .. code-block:: bash salt '*' network.mod_bufsize tx=<val> rx=<val> rx-mini=<val> rx-jumbo=<val>
388,465
def get_preferred(self, addr_1, addr_2): if addr_1 > addr_2: addr_1, addr_2 = addr_2, addr_1 return self._cache.get((addr_1, addr_2))
Return the preferred address.
388,466
def checkUserManage(worksheet, request, redirect=True): allowed = worksheet.checkUserManage() if allowed == False and redirect == True: destination_url = worksheet.absolute_url() + "/manage_results" request.response.redirect(destination_url)
Checks if the current user has granted access to the worksheet and if has also privileges for managing it. If the user has no granted access and redirect's value is True, redirects to /manage_results view. Otherwise, does nothing
388,467
def get_version_url(self, version): for each_version in self.other_versions(): if version == each_version[] and in each_version: return each_version.get() raise VersionNotInHive(version)
Retrieve the URL for the designated version of the hive.
388,468
def delete(self, url, headers=None, **kwargs): if headers is None: headers = [] if kwargs: url = url + UrlEncoded( + _encode(**kwargs), skip_encode=True) message = { : "DELETE", : headers, } retur...
Sends a DELETE request to a URL. :param url: The URL. :type url: ``string`` :param headers: A list of pairs specifying the headers for the HTTP response (for example, ``[('Content-Type': 'text/cthulhu'), ('Token': 'boris')]``). :type headers: ``list`` :param kwargs: ...
388,469
def add_self_defined_objects(raw_objects): logger.info("- creating internally defined commands...") if not in raw_objects: raw_objects[] = [] raw_objects[].append({ : , : , : }) raw_objects[].append({ ...
Add self defined command objects for internal processing ; bp_rule, _internal_host_up, _echo, _internal_host_check, _interna_service_check :param raw_objects: Raw config objects dict :type raw_objects: dict :return: raw_objects with some more commands :rtype: dict
388,470
def _snakify_name(self, name): name = self._strip_diacritics(name) name = name.lower() name = name.replace(, ) return name
Snakify a name string. In this context, "to snakify" means to strip a name of all diacritics, convert it to lower case, and replace any spaces inside the name with hyphens. This way the name is made "machine-friendly", and ready to be combined with a second name component into ...
388,471
def key_from_keybase(username, fingerprint=None): url = keybase_lookup_url(username) resp = requests.get(url) if resp.status_code == 200: j_resp = json.loads(polite_string(resp.content)) if in j_resp and len(j_resp[]) == 1: kb_obj = j_resp[][0] if fingerprint: ...
Look up a public key from a username
388,472
def revert(self, unchanged_only=False): if self._reverted: raise errors.ChangelistError() change = self._change if self._change == 0: change = cmd = [, , str(change)] if unchanged_only: cmd.append() files = [f.depotFile fo...
Revert all files in this changelist :param unchanged_only: Only revert unchanged files :type unchanged_only: bool :raises: :class:`.ChangelistError`
388,473
def text_extract(path, password=None): pdf = Info(path, password).pdf return [pdf.getPage(i).extractText() for i in range(pdf.getNumPages())]
Extract text from a PDF file
388,474
def create_process_behavior(self, behavior, process_id): route_values = {} if process_id is not None: route_values[] = self._serialize.url(, process_id, ) content = self._serialize.body(behavior, ) response = self._send(http_method=, loc...
CreateProcessBehavior. [Preview API] Creates a single behavior in the given process. :param :class:`<ProcessBehaviorCreateRequest> <azure.devops.v5_0.work_item_tracking_process.models.ProcessBehaviorCreateRequest>` behavior: :param str process_id: The ID of the process :rtype: :class:`<P...
388,475
def get_relationships_for_source_on_date(self, source_id, from_, to): if self._can(): return self._provider_session.get_relationships_for_source_on_date(source_id, from_, to) self._check_lookup_conditions() query = self._query_session.get_relationship_que...
Pass through to provider RelationshipLookupSession.get_relationships_for_source_on_date
388,476
def _initializer_wrapper(actual_initializer, *rest): signal.signal(signal.SIGINT, signal.SIG_IGN) if actual_initializer is not None: actual_initializer(*rest)
We ignore SIGINT. It's up to our parent to kill us in the typical condition of this arising from ``^C`` on a terminal. If someone is manually killing us with that signal, well... nothing will happen.
388,477
def add_seconds(self, datetimestr, n): a_datetime = self.parse_datetime(datetimestr) return a_datetime + timedelta(seconds=n)
Returns a time that n seconds after a time. :param datetimestr: a datetime object or a datetime str :param n: number of seconds, value can be negative **中文文档** 返回给定日期N秒之后的时间。
388,478
def send_messages(self, email_messages): if not email_messages: return with self._lock: try: stream_created = self.open() for message in email_messages: if six.PY3: self.write_message(message) ...
Write all messages to the stream in a thread-safe way.
388,479
def dump_info(): vultr = Vultr(API_KEY) try: logging.info(, dumps( vultr.account.info(), indent=2 )) logging.info(, dumps( vultr.app.list(), indent=2 )) logging.info(, dumps( vultr.backup.list(), indent=2 )) log...
Shows various details about the account & servers
388,480
def params_values(self): return [p.value for p in atleast_list(self.params) if p.has_value]
Get a list of the ``Parameter`` values if they have a value. This does not include the basis regularizer.
388,481
def TAPQuery(RAdeg=180.0, DECdeg=0.0, width=1, height=1): QUERY =( ) QUERY = QUERY.format( RAdeg, DECdeg, width, height) data={"QUERY": QUERY, "REQUEST": "doQuery", ...
Do a query of the CADC Megacam table. Get all observations insize the box. Returns a file-like object
388,482
def loader_for_type(self, ctype): for loadee, mimes in Mimer.TYPES.iteritems(): for mime in mimes: if ctype.startswith(mime): return loadee
Gets a function ref to deserialize content for a certain mimetype.
388,483
def obtainInfo(self): try: info = self.ytdl.extract_info(self.yid, download=False) except youtube_dl.utils.DownloadError: raise ConnectionError if not self.preferences[]: self.url = (info[][0][], info[][1][]) return True ...
Method for obtaining information about the movie.
388,484
def make_levels_set(levels): for level_key,level_filters in levels.items(): levels[level_key] = make_level_set(level_filters) return levels
make set efficient will convert all lists of items in levels to a set to speed up operations
388,485
def interactive_update_stack(self, fqn, template, old_parameters, parameters, stack_policy, tags, **kwargs): logger.debug("Using interactive provider mode for %s.", fqn) changes, change_set_id = create_change_set( sel...
Update a Cloudformation stack in interactive mode. Args: fqn (str): The fully qualified name of the Cloudformation stack. template (:class:`stacker.providers.base.Template`): A Template object to use when updating the stack. old_parameters (list): A list of d...
388,486
def _get_absolute_reference(self, ref_key): key_str = u", ".join(map(str, ref_key)) return u"S[" + key_str + u"]"
Returns absolute reference code for key.
388,487
def filter(self, func): self._data = xfilter(func, self._data) return self
A lazy way to skip elements in the stream that gives False for the given function.
388,488
def set_errors(self, errors): if errors is None: self.__errors__ = None return self.__errors__ = [asscalar(e) for e in errors]
Set parameter error estimate
388,489
def vdistg(v1, v2, ndim): v1 = stypes.toDoubleVector(v1) v2 = stypes.toDoubleVector(v2) ndim = ctypes.c_int(ndim) return libspice.vdistg_c(v1, v2, ndim)
Return the distance between two vectors of arbitrary dimension. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/vdistg_c.html :param v1: ndim-dimensional double precision vector. :type v1: list[ndim] :param v2: ndim-dimensional double precision vector. :type v2: list[ndim] :param ndi...
388,490
def dotproduct(X, Y): return sum([x * y for x, y in zip(X, Y)])
Return the sum of the element-wise product of vectors x and y. >>> dotproduct([1, 2, 3], [1000, 100, 10]) 1230
388,491
def build_variant(variant, institute_id, gene_to_panels = None, hgncid_to_gene=None, sample_info=None): gene_to_panels = gene_to_panels or {} hgncid_to_gene = hgncid_to_gene or {} sample_info = sample_info or {} variant_obj = dict( _id = variant[][], document...
Build a variant object based on parsed information Args: variant(dict) institute_id(str) gene_to_panels(dict): A dictionary with {<hgnc_id>: { 'panel_names': [<panel_name>, ..], 'disease_associated_transcripts': [<trans...
388,492
def _unsigned_bounds(self): ssplit = self._ssplit() if len(ssplit) == 1: lb = ssplit[0].lower_bound ub = ssplit[0].upper_bound return [ (lb, ub) ] elif len(ssplit) == 2: lb_1 = ssplit[0].lower_bound ub_1 = sspli...
Get lower bound and upper bound for `self` in unsigned arithmetic. :return: a list of (lower_bound, upper_bound) tuples.
388,493
def process_embed(embed_items=None, embed_tracks=None, embed_metadata=None, embed_insights=None): result = None embed = if embed_items: embed = if embed_tracks: if embed != : embed += embed += if emb...
Returns an embed field value based on the parameters.
388,494
def remove_block(self, block, index="-1"): self[index]["__blocks__"].remove(block) self[index]["__names__"].remove(block.raw())
Remove block element from scope Args: block (Block): Block object
388,495
def disassociate(self, eip_or_aid): if "." in eip_or_aid: return "true" == self.call("DisassociateAddress", response_data_key="return", PublicIp=eip_or_aid) else: ...
Disassociates an EIP. If the EIP was allocated for a VPC instance, an AllocationId(aid) must be provided instead of a PublicIp.
388,496
def from_raw(self, rval: RawValue, jptr: JSONPointer = "") -> Value: def convert(val): if isinstance(val, list): res = ArrayValue([convert(x) for x in val]) elif isinstance(val, dict): res = ObjectValue({x: convert(val[x]) for x in val}) ...
Override the superclass method.
388,497
def get_user_logins(self, user_id, params={}): url = USERS_API.format(user_id) + "/logins" data = self._get_paged_resource(url, params=params) logins = [] for login_data in data: logins.append(Login(data=login_data)) return logins
Return a user's logins for the given user_id. https://canvas.instructure.com/doc/api/logins.html#method.pseudonyms.index
388,498
def invalid(cls, data, context=None): return cls(cls.TagType.INVALID, data, context)
Shortcut to create an INVALID Token.
388,499
def calc_max_flexural_wavelength(self): if np.isscalar(self.D): Dmax = self.D else: Dmax = self.D.max() alpha = (4*Dmax/(self.drho*self.g))**.25 self.maxFlexuralWavelength = 2*np.pi*alpha self.maxFlexuralWavelength_ncells_x = int(np.ceil(self.maxFlexuralWavelength / self....
Returns the approximate maximum flexural wavelength This is important when padding of the grid is required: in Flexure (this code), grids are padded out to one maximum flexural wavelength, but in any case, the flexural wavelength is a good characteristic distance for any truncation limit