Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
365,100
def check_basic_auth(user, passwd): auth = request.authorization return auth and auth.username == user and auth.password == passwd
Checks user authentication using HTTP Basic Auth.
365,101
def register(cls): if not issubclass(cls, Entity): raise ValueError("Class must be a subclass of abilian.core.entities.Entity") Commentable.register(cls) return cls
Register an :class:`Entity` as a commentable class. Can be used as a class decorator: .. code-block:: python @comment.register class MyContent(Entity): ...
365,102
def p_stop_raise(p): q = make_number(9, lineno=p.lineno(1)) if len(p) == 2 else p[2] z = make_number(1, lineno=p.lineno(1)) r = make_binary(p.lineno(1), , make_typecast(TYPE.ubyte, q, p.lineno(1)), z, lambda x, y: x - y) p[0] = make_sentence(, r)
statement : STOP expr | STOP
365,103
def _prepare_headers(self, additional_headers=None, **kwargs): user_agent = "pyseaweed/{version}".format(version=__version__) headers = {"User-Agent": user_agent} if additional_headers is not None: headers.update(additional_headers) return headers
Prepare headers for http communication. Return dict of header to be used in requests. Args: .. versionadded:: 0.3.2 **additional_headers**: (optional) Additional headers to be used with request Returns: Headers dict. Key and values are s...
365,104
def run(*args, **kwargs): signal.signal(signal.SIGTERM, _signal_handler) try: sys.exit(main(*args, **kwargs)) finally: _terminate_processes()
Run cwltool.
365,105
def new(cls, signatures: [Signature]) -> : logger = logging.getLogger(__name__) logger.debug("MultiSignature::new: >>>") signature_c_instances = (c_void_p * len(signatures))() for i in range(len(signatures)): signature_c_instances[i] = signatures[i].c_insta...
Creates and returns BLS multi signature that corresponds to the given signatures list. :param: signature - List of signatures :return: BLS multi signature
365,106
def predict_steadystate(self, u=0, B=None): if B is None: B = self.B if B is not None: self.x = dot(self.F, self.x) + dot(B, u) else: self.x = dot(self.F, self.x) self.x_prior = self.x.copy() self.P_prior = self.P....
Predict state (prior) using the Kalman filter state propagation equations. Only x is updated, P is left unchanged. See update_steadstate() for a longer explanation of when to use this method. Parameters ---------- u : np.array Optional control vector. If non...
365,107
def _controller(self): while self.running: try: cmd = self._controller_q.get(timeout=1) except (TimeoutError, Empty): continue log.debug("WSSAPI._controller(): Received command: %s", cmd) Thread(target=self.eval_command, ar...
This method runs in a dedicated thread, calling self.eval_command(). :return:
365,108
def _setup_rpc(self): self._plugin_rpc = agent_rpc.PluginApi(topics.PLUGIN) self._state_rpc = agent_rpc.PluginReportStateAPI(topics.PLUGIN) self._client = n_rpc.get_client(self.target) self._consumers.extend([ [topics.PORT, topics.UPDATE], [topics.NETWORK, topics.DE...
Setup the RPC client for the current agent.
365,109
def toggle_create_button(self): if len(self._drawn_tags) > 0: self.w.create_mask.set_enabled(True) else: self.w.create_mask.set_enabled(False)
Enable or disable Create Mask button based on drawn objects.
365,110
def project(ctx, project): if ctx.invoked_subcommand not in [, ]: ctx.obj = ctx.obj or {} ctx.obj[] = project
Commands for projects.
365,111
def select_one(self, tag): tags = self.select(tag, limit=1) return tags[0] if tags else None
Select a single tag.
365,112
def get_sns_topic_arn(topic_name, account, region): if topic_name.count() == 5 and topic_name.startswith(): return topic_name session = boto3.Session(profile_name=account, region_name=region) sns_client = session.client() topics = sns_client.list_topics()[] matched_topic = None fo...
Get SNS topic ARN. Args: topic_name (str): Name of the topic to lookup. account (str): Environment, e.g. dev region (str): Region name, e.g. us-east-1 Returns: str: ARN for requested topic name
365,113
def _dnsname_to_stdlib(name): def idna_encode(name): import idna for prefix in [u, u]: if name.startswith(prefix): name = name[len(prefix):] return prefix.encode() + idna.encode(name) return idna.encode(name) name = idna_encode(...
Converts a dNSName SubjectAlternativeName field to the form used by the standard library on the given Python version. Cryptography produces a dNSName as a unicode string that was idna-decoded from ASCII bytes. We need to idna-encode that string to get it back, and then on Python 3 we also need to conve...
365,114
def reset_image_attribute(self, image_id, attribute=): params = { : image_id, : attribute} return self.get_status(, params, verb=)
Resets an attribute of an AMI to its default value. :type image_id: string :param image_id: ID of the AMI for which an attribute will be described :type attribute: string :param attribute: The attribute to reset :rtype: bool :return: Whether the operation succeeded or ...
365,115
def setpassword(self, password): self._password = password if self._file_parser: if self._file_parser.has_header_encryption(): self._file_parser = None if not self._file_parser: self._parse() else: self._file_parser.setpassword...
Sets the password to use when extracting.
365,116
def check_ip(addr): try: addr = addr.rsplit(, 1) except AttributeError: return False if salt.utils.network.is_ipv4(addr[0]): try: if 1 <= int(addr[1]) <= 32: return True except ValueError: return False ...
Check if address is a valid IP. returns True if valid, otherwise False. CLI Example: .. code-block:: bash salt ns1 dig.check_ip 127.0.0.1 salt ns1 dig.check_ip 1111:2222:3333:4444:5555:6666:7777:8888
365,117
def mount_status_encode(self, target_system, target_component, pointing_a, pointing_b, pointing_c): return MAVLink_mount_status_message(target_system, target_component, pointing_a, pointing_b, pointing_c)
Message with some status from APM to GCS about camera or antenna mount target_system : System ID (uint8_t) target_component : Component ID (uint8_t) pointing_a : pitch(deg*100) (int32_t) pointing_b : roll...
365,118
def _scan(self, type): tok = self._scanner.token(self._pos, frozenset([type])) self._char_pos = tok[0] if tok[2] != type: raise SyntaxError("SyntaxError[@ char %s: %s]" % (repr(tok[0]), "Trying to find " + type)) self._pos += 1 return tok[3]
Returns the matched text, and moves to the next token
365,119
def start_polling(dispatcher, *, loop=None, skip_updates=False, reset_webhook=True, on_startup=None, on_shutdown=None, timeout=20, fast=True): executor = Executor(dispatcher, skip_updates=skip_updates, loop=loop) _setup_callbacks(executor, on_startup, on_shutdown) executor.start_poll...
Start bot in long-polling mode :param dispatcher: :param loop: :param skip_updates: :param reset_webhook: :param on_startup: :param on_shutdown: :param timeout:
365,120
def semester_feature(catalog, soup): raw = soup.coursedb[] catalog.year = int(raw[:4]) month_mapping = {1: , 5: , 9: } catalog.month = int(raw[4:]) catalog.semester = month_mapping[catalog.month] catalog.name = soup.coursedb[] logger.info( % catalog.name)
The year and semester information that this xml file hold courses for.
365,121
def _convert_xml_to_service_properties(response): if response is None or response.body is None: return None service_properties_element = ETree.fromstring(response.body) service_properties = ServiceProperties() logging = service_properties_element.find() if logging is not None: ...
<?xml version="1.0" encoding="utf-8"?> <StorageServiceProperties> <Logging> <Version>version-number</Version> <Delete>true|false</Delete> <Read>true|false</Read> <Write>true|false</Write> <RetentionPolicy> <Enabled>true|false</Enabl...
365,122
def rotate(self, clat, clon, coord_degrees=True, dj_matrix=None, nwinrot=None): self.coeffs = _np.zeros(((self.lwin + 1)**2, self.nwin)) self.clat = clat self.clon = clon self.coord_degrees = coord_degrees if nwinrot is not None: self.nwinrot ...
Rotate the spherical-cap windows centered on the North pole to clat and clon, and save the spherical harmonic coefficients in the attribute coeffs. Usage ----- x.rotate(clat, clon [coord_degrees, dj_matrix, nwinrot]) Parameters ---------- clat, clon : fl...
365,123
def add_device(self, device, container): if self.findtext("is_smart") == "false": self.add_object_to_path(device, container) else: raise ValueError("Devices may not be added to smart groups.")
Add a device to a group. Wraps JSSObject.add_object_to_path. Args: device: A JSSObject to add (as list data), to this object. location: Element or a string path argument to find()
365,124
def is_modifier(key): if _is_str(key): return key in all_modifiers else: if not _modifier_scan_codes: scan_codes = (key_to_scan_codes(name, False) for name in all_modifiers) _modifier_scan_codes.update(*scan_codes) return key in _modifier_scan_codes
Returns True if `key` is a scan code or name of a modifier key.
365,125
def _filter(self, query, **kwargs): query = self._auto_filter(query, **kwargs) return query
Filter a query with user-supplied arguments.
365,126
def decrypt(self, data, pad=None, padmode=None): ENCRYPT = des.ENCRYPT DECRYPT = des.DECRYPT data = self._guardAgainstUnicode(data) if pad is not None: pad = self._guardAgainstUnicode(pad) if self.getMode() == CBC: self.__key1.setIV(self.getIV()) self.__key2.setIV(self.getIV()) self.__key3.setI...
decrypt(data, [pad], [padmode]) -> bytes data : bytes to be encrypted pad : Optional argument for decryption padding. Must only be one byte padmode : Optional argument for overriding the padding mode. The data must be a multiple of 8 bytes and will be decrypted with the already specified key. In PAD_NORMAL...
365,127
def ensure_dir_does_not_exist(*args): path = os.path.join(*args) if os.path.isdir(path): shutil.rmtree(path)
Ensures that the given directory does not exist.
365,128
def deregister(self, subscriber): try: logger.debug() self.subscribers.remove(subscriber) except KeyError: logger.debug( + str(subscriber))
Stop publishing to a subscriber.
365,129
def import_jwks_as_json(self, jwks, issuer): return self.import_jwks(json.loads(jwks), issuer)
Imports all the keys that are represented in a JWKS expressed as a JSON object :param jwks: JSON representation of a JWKS :param issuer: Who 'owns' the JWKS
365,130
def mult_masses(mA, f_binary=0.4, f_triple=0.12, minmass=0.11, qmin=0.1, n=1e5): if np.size(mA) > 1: n = len(mA) else: mA = np.ones(n) * mA r = rand.random(n) is_single = r > (f_binary + f_triple) is_double = (r > f_triple) & (r < (f_binary + f_triple)) is...
Returns m1, m2, and m3 appropriate for TripleStarPopulation, given "primary" mass (most massive of system) and binary/triple fractions. star with m1 orbits (m2 + m3). This means that the primary mass mA will correspond either to m1 or m2. Any mass set to 0 means that component does not exist.
365,131
def add_cache_tier(self, cache_pool, mode): validator(value=cache_pool, valid_type=six.string_types) validator(value=mode, valid_type=six.string_types, valid_range=["readonly", "writeback"]) check_call([, , self.service, , , , self.name, cache_pool]) check_call([, , se...
Adds a new cache tier to an existing pool. :param cache_pool: six.string_types. The cache tier pool name to add. :param mode: six.string_types. The caching mode to use for this pool. valid range = ["readonly", "writeback"] :return: None
365,132
def build_job_configs(self, args): job_configs = {} components = Component.build_from_yamlfile(args[]) NAME_FACTORY.update_base_dict(args[]) mktime = args[] for comp in components: zcut = "zmax%i" % comp.zmax key = comp.make_key() n...
Hook to build job configurations
365,133
def ProcessEntry(self, responses): if not responses.success: return stat_responses = [ r.hit if isinstance(r, rdf_client_fs.FindSpec) else r for r in responses ] component_path = responses.request_data.get("component_path") if compone...
Process the responses from the client.
365,134
def get(self, test_id): self.select(, , [test_id]) row = self._cursor.fetchone() if not row: raise KeyError( % test_id) values = self.row_to_dict(row) content = self._deserialize_dict(values[]) return Report.from_dict(content)
get report by the test id :param test_id: test id :return: Report object
365,135
def is_defined(self, obj, force_import=False): from spyder_kernels.utils.dochelpers import isdefined ns = self._get_current_namespace(with_magics=True) return isdefined(obj, force_import=force_import, namespace=ns)
Return True if object is defined in current namespace
365,136
def create_dialog(obj, obj_name): from spyder_kernels.utils.nsview import (ndarray, FakeObject, Image, is_known_type, DataFrame, Series) from spyder.plugins.variableexplorer.widgets.texteditor import TextEdi...
Creates the editor dialog and returns a tuple (dialog, func) where func is the function to be called with the dialog instance as argument, after quitting the dialog box The role of this intermediate function is to allow easy monkey-patching. (uschmitt suggested this indirection here so that h...
365,137
def list_logstores(self, request): headers = {} params = {} resource = project = request.get_project() (resp, header) = self._send("GET", project, None, resource, params, headers) return ListLogstoresResponse(resp, header)
List all logstores of requested project. Unsuccessful opertaion will cause an LogException. :type request: ListLogstoresRequest :param request: the ListLogstores request parameters class. :return: ListLogStoresResponse :raise: LogException
365,138
def update(self, force=False): if self.is_404 and not force: return 0 if self._last_modified: headers = {: self._last_modified} else: headers = None try: res = self._board._requests_session.get(self._api_url, h...
Fetch new posts from the server. Arguments: force (bool): Force a thread update, even if thread has 404'd. Returns: int: How many new posts have been fetched.
365,139
def reftrick(iseq, consdict): altrefs = np.zeros((iseq.shape[1], 4), dtype=np.uint8) altrefs[:, 1] = 46 for col in xrange(iseq.shape[1]): fcounts = np.zeros(111, dtype=np.int64) counts = np.bincount(iseq[:, col]) fcounts[:counts.shape[0]] = counts fco...
Returns the most common base at each site in order.
365,140
def _validate_type_scalar(self, value): if isinstance( value, _int_types + (_str_type, float, date, datetime, bool) ): return True
Is not a list or a dict
365,141
def make_control_flow_handlers(self, cont_n, status_n, expected_return, has_cont, has_break): if expected_return: assign = cont_ass = [ast.Assign( [ast.Tuple(expected_return, ast.Store())], ast.Name(cont_n, ast.Load(), None)...
Create the statements in charge of gathering control flow information for the static_if result, and executes the expected control flow instruction
365,142
def _parse_values(s): if not _RE_NONTRIVIAL_DATA.search(s): return [None if s in (, ) else s for s in next(csv.reader([s]))] values, errors = zip(*_RE_DENSE_VALUES.findall( + s)) if not any(errors): return [_unquote(v) for v in values] if _RE_...
(INTERNAL) Split a line into a list of values
365,143
def random_adjspecies(sep=, maxlen=8, prevent_stutter=True): pair = random_adjspecies_pair(maxlen, prevent_stutter) return pair[0] + sep + pair[1]
Return a random adjective/species, separated by `sep`. The keyword arguments `maxlen` and `prevent_stutter` are the same as for `random_adjspecies_pair`, but note that the maximum length argument is not affected by the separator.
365,144
def applymap(self, func, **kwargs): return self.from_rdd( self._rdd.map(lambda data: data.applymap(func), **kwargs))
Return a new PRDD by applying a function to each element of each pandas DataFrame.
365,145
def show_multi_buffer(self): from safe.gui.tools.multi_buffer_dialog import ( MultiBufferDialog) dialog = MultiBufferDialog( self.iface.mainWindow(), self.iface, self.dock_widget) dialog.exec_()
Show the multi buffer tool.
365,146
def genes_with_a_representative_structure(self): tmp = DictList(x for x in self.genes if x.protein.representative_structure) return DictList(y for y in tmp if y.protein.representative_structure.structure_file)
DictList: All genes with a representative protein structure.
365,147
def get_free_udp_port(): import socket sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.bind((, 0)) addr = sock.getsockname() sock.close() return addr[1]
Get a free UDP port. Note this is vlunerable to race conditions.
365,148
def BitField(value, length, signed=False, min_value=None, max_value=None, encoder=ENC_INT_DEFAULT, fuzzable=True, name=None, full_range=False): if not full_range: return _LibraryBitField(value, length, signed, min_value, max_value, encoder, fuzzable, name) return _FullRangeBitField(value, length, s...
Returns an instance of some BitField class .. note:: Since BitField is frequently used in binary format, multiple aliases were created for it. See aliases.py for more details.
365,149
def translate_array(array, lval, obj_count=1, arr_count=1): array = array[1:-1] array, obj_rep, obj_count = remove_objects(array, obj_count) array, arr_rep, arr_count = remove_arrays(array, arr_count) array, hoisted, inline = functions.remove_functions(array, all_inline=True) ...
array has to be any js array for example [1,2,3] lval has to be name of this array. Returns python code that adds lval to the PY scope it should be put before lval
365,150
def cf_string_to_unicode(value): string_ptr = CoreFoundation.CFStringGetCStringPtr( value, kCFStringEncodingUTF8 ) string = None if is_null(string_ptr) else ffi.string(string_ptr) if string is None: buffer = buffer_from_bytes(1024) ...
Creates a python unicode string from a CFString object :param value: The CFString to convert :return: A python unicode string
365,151
def model_attr(attr_name): def model_attr(_value, context, **_params): value = getattr(context["model"], attr_name) return _attr(value) return model_attr
Creates a getter that will drop the current value and retrieve the model's attribute with specified name. @param attr_name: the name of an attribute belonging to the model. @type attr_name: str
365,152
def error_bars(self, n_bins, d_min, d_max): chain = self._chain len_chain = len(chain) try: n_dims = np.shape(chain)[1] except: n_dims = 1 try: assert n_bins == int(n_bins) except: raise TypeErr...
Error Bars create bars and error bars to plot Inputs : n_bins : number of bins plot_range : (shape) = (number of dimensions, 2) matrix which contain the min and max for each dimension as rows Outputs : x : domain p_x : ...
365,153
def primary_xi(mass1, mass2, spin1x, spin1y, spin2x, spin2y): spinx = primary_spin(mass1, mass2, spin1x, spin2x) spiny = primary_spin(mass1, mass2, spin1y, spin2y) return chi_perp_from_spinx_spiny(spinx, spiny)
Returns the effective precession spin argument for the larger mass.
365,154
def navigate(self, inst, kind, rel_id, phrase=): key = (kind.upper(), rel_id, phrase) if key in self.links: link = self.links[key] return link.navigate(inst) link1, link2 = self._find_assoc_links(kind, rel_id, phrase) inst_set = xtuml.OrderedSet(...
Navigate across a link with some *rel_id* and *phrase* that yields instances of some *kind*.
365,155
def _axis_properties(self, axis, title_size, title_offset, label_angle, label_align, color): if self.axes: axis = [a for a in self.axes if a.scale == axis][0] self._set_axis_properties(axis) self._set_all_axis_color(axis, color) ...
Assign axis properties
365,156
def get_relationship_family_assignment_session(self, proxy=None): if not self.supports_relationship_family_assignment(): raise Unimplemented() try: from . import sessions except ImportError: raise OperationFailed() proxy = self._convert_proxy(...
Gets the ``OsidSession`` associated with assigning relationships to families. arg: proxy (osid.proxy.Proxy): a proxy return: (osid.relationship.RelationshipFamilyAssignmentSession) - a ``RelationshipFamilyAssignmentSession`` raise: NullArgument - ``proxy`` is ``null`` ...
365,157
def open_url(absolute_or_relative_url): base_url = selene.config.app_host if selene.config.app_host else selene.config.base_url driver().get(base_url + absolute_or_relative_url)
Loads a web page in the current browser session. :param absolgenerateute_or_relative_url: an absolute url to web page in case of config.base_url is not specified, otherwise - relative url correspondingly :Usage: open_url('http://mydomain.com/subpage1') open_url('http://mydomain....
365,158
def collect(self, step, content): if step.startswith(): print(content) elif step.startswith(): self.collect_argument(step, content) elif step == : self.record_asciinema() elif step == "record_env...
given a name of a configuration key and the provided content, collect the required metadata from the user. Parameters ========== step: the key in the configuration. Can be one of: user_message_<name> runtime_arg_<name> ...
365,159
def _increment(sign, integer_part, non_repeating_part, base): (carry, non_repeating_part) = \ Nats.carry_in(non_repeating_part, 1, base) (carry, integer_part) = \ Nats.carry_in(integer_part, carry, base) return Radix( sign, integer_part if car...
Return an increment radix. :param int sign: -1, 0, or 1 as appropriate :param integer_part: the integer part :type integer_part: list of int :param non_repeating_part: the fractional part :type non_repeating_part: list of int :param int base: the base :returns: ...
365,160
def emit(self, *args, **kwargs): if self._block: return for slot in self._slots: if not slot: continue elif isinstance(slot, partial): slot() elif isinstance(slot, weakref.WeakKeyDictionary): ...
Calls all the connected slots with the provided args and kwargs unless block is activated
365,161
def simple_mean_function(max_iters=100, optimize=True, plot=True): mf = GPy.core.Mapping(1,1) mf.f = np.sin mf.update_gradients = lambda a,b: None X = np.linspace(0,10,50).reshape(-1,1) Y = np.sin(X) + 0.5*np.cos(3*X) + 0.1*np.random.randn(*X.shape) k =GPy.kern.RBF(1) lik = GPy.l...
The simplest possible mean function. No parameters, just a simple Sinusoid.
365,162
def _loop_wrapper_func(func, args, shared_mem_run, shared_mem_pause, interval, sigint, sigterm, name, logging_level, conn_send, func_running, log_queue): prefix = get_identifier(name) + global log log = logging.getLogger(__name__+".log_{}".format(get_identifier(name, bold=False...
to be executed as a separate process (that's why this functions is declared static)
365,163
def reindex(self, new_index=None, index_conf=None): t want to loose all the entries belonging to that index. This function is built in such a way that you can continue to use the old index name, this is achieved using index aliases. The old index will be cloned into a new one ...
Rebuilt the current index This function could be useful in the case you want to change some index settings/mappings and you don't want to loose all the entries belonging to that index. This function is built in such a way that you can continue to use the old index name, thi...
365,164
def update(self, key=values.unset, value=values.unset): data = values.of({: key, : value, }) payload = self._version.update( , self._uri, data=data, ) return VariableInstance( self._version, payload, servi...
Update the VariableInstance :param unicode key: The key :param unicode value: The value :returns: Updated VariableInstance :rtype: twilio.rest.serverless.v1.service.environment.variable.VariableInstance
365,165
def read_config_environment(self, config_data=None, quiet=False): if config_data is None: config_data = {} for key, val in os.environ.items(): if key.startswith(): config_key = key.replace(, , 1).lower() config_data[config_key] ...
read_config_environment is the second effort to get a username and key to authenticate to the Kaggle API. The environment keys are equivalent to the kaggle.json file, but with "KAGGLE_" prefix to define a unique namespace. Parameters ========== config_d...
365,166
def check_blank_before_after_class(self, class_, docstring): if docstring: before, _, after = class_.source.partition(docstring) blanks_before = list(map(is_blank, before.split()[:-1])) blanks_af...
D20{3,4}: Class docstring should have 1 blank line around them. Insert a blank line before and after all docstrings (one-line or multi-line) that document a class -- generally speaking, the class's methods are separated from each other by a single blank line, and the docstring needs to ...
365,167
def home(request): "Simple homepage view." context = {} if request.user.is_authenticated(): try: access = request.user.accountaccess_set.all()[0] except IndexError: access = None else: client = access.api_client context[] = client.get_p...
Simple homepage view.
365,168
def draw(graph, fname): ag = networkx.nx_agraph.to_agraph(graph) ag.draw(fname, prog=)
Draw a graph and save it into a file
365,169
def _make_attachment(self, attachment, str_encoding=None): is_inline_image = False if isinstance(attachment, MIMEBase): name = attachment.get_filename() content = attachment.get_payload(decode=True) mimetype = attachment.get_content_type() if att...
Returns EmailMessage.attachments item formatted for sending with Mailjet Returns mailjet_dict, is_inline_image
365,170
def _update_vdr_vxrheadtail(self, f, vdr_offset, VXRoffset): self._update_offset_value(f, vdr_offset+36, 8, VXRoffset)
This sets a VXR to be the first and last VXR in the VDR
365,171
def derive_data(data): for s_name, values in data.items(): total_called_variants = 0 for value_name in [, , , ]: total_called_variants = total_called_variants + int(values[value_name]) values[] = total_called_variants total_called_varian...
Based on the data derive additional data
365,172
def _generate_routes(self, namespace): self.cur_namespace = namespace if self.args.auth_type is not None: self.supported_auth_types = [auth_type.strip().lower() for auth_type in self.args.auth_type.split()] check_route_name_conflict(namespace) ...
Generates Python methods that correspond to routes in the namespace.
365,173
def run_decider_state(self, decider_state, child_errors, final_outcomes_dict): decider_state.state_execution_status = StateExecutionStatus.ACTIVE decider_state.child_errors = child_errors decider_state.final_outcomes_dict = final_outcomes_dict decider_state.inp...
Runs the decider state of the barrier concurrency state. The decider state decides on which outcome the barrier concurrency is left. :param decider_state: the decider state of the barrier concurrency state :param child_errors: error of the concurrent branches :param final_outcomes_dict:...
365,174
def find_or_new(self, id, columns=None): if columns is None: columns = ["*"] instance = self._query.find(id, columns) if instance is None: instance = self._related.new_instance() instance.set_attribute(self.get_plain_foreign_key(), self.get_parent_k...
Find a model by its primary key or return new instance of the related model. :param id: The primary key :type id: mixed :param columns: The columns to retrieve :type columns: list :rtype: Collection or Model
365,175
def circle(radius=None, center=None, **kwargs): from .path import Path2D if center is None: center = [0.0, 0.0] else: center = np.asanyarray(center, dtype=np.float64) if radius is None: radius = 1.0 else: radius = float(radius) three = arc.to_threepoin...
Create a Path2D containing a single or multiple rectangles with the specified bounds. Parameters -------------- bounds : (2, 2) float, or (m, 2, 2) float Minimum XY, Maximum XY Returns ------------- rect : Path2D Path containing specified rectangles
365,176
def apply_order(self): self._ensure_modification_is_safe() if len(self.query.orders) > 0: self._iterable = Order.sorted(self._iterable, self.query.orders)
Naively apply query orders.
365,177
def set_position(self, resource_id, to_position, db_session=None, *args, **kwargs): return self.service.set_position( resource_id=resource_id, to_position=to_position, db_session=db_session, *args, **kwargs )
Sets node position for new node in the tree :param resource_id: resource to move :param to_position: new position :param db_session: :return:def count_children(cls, resource_id, db_session=None):
365,178
def _dispense_plunger_position(self, ul): millimeters = ul / self._ul_per_mm(ul, ) destination_mm = self._get_plunger_position() + millimeters return round(destination_mm, 6)
Calculate axis position for a given liquid volume. Translates the passed liquid volume to absolute coordinates on the axis associated with this pipette. Calibration of the pipette motor's ul-to-mm conversion is required
365,179
def piprot(): cli_parser = argparse.ArgumentParser( epilog="Here-v--verbosestore_trueverbosity, can be supplied more than once (enabled by default, use --quiet to disable)-l--lateststore_trueprint the lastest available version for out of date requirements-x--verbatimstore_trueoutput the full requiremen...
Parse the command line arguments and jump into the piprot() function (unless the user just wants the post request hook).
365,180
def setsockopt(self, *sockopts): if type(sockopts[0]) in (list, tuple): for sock_opt in sockopts[0]: level, option, value = sock_opt self.connection.sockopts.add((level, option, value)) else: level, option, value = sockopts sel...
Add socket options to set
365,181
def check_int_param(self, param, low, high, name): try: param = int(param) except: raise ValueError( .format(name) ) if low != None or high != None: if not low <= param <= high: raise ValueEr...
Check if the value of the given parameter is in the given range and an int. Designed for testing parameters like `mu` and `eps`. To pass this function the variable `param` must be able to be converted into a float with a value between `low` and `high`. **Args:** * `para...
365,182
def set_references(references, components): if components == None: return for component in components: Referencer.set_references_for_one(references, component)
Sets references to multiple components. To set references components must implement [[IReferenceable]] interface. If they don't the call to this method has no effect. :param references: the references to be set. :param components: a list of components to set the references to.
365,183
def clear_task_instances(tis, session, activate_dag_runs=True, dag=None, ): job_ids = [] for ti in tis: if ti.state == State.RUNNING: if ti.job_id: ti.state = State.SHUTDO...
Clears a set of task instances, but makes sure the running ones get killed. :param tis: a list of task instances :param session: current session :param activate_dag_runs: flag to check for active dag run :param dag: DAG object
365,184
def printActiveIndices(self, state, andValues=False): if len(state.shape) == 2: (cols, cellIdxs) = state.nonzero() else: cols = state.nonzero()[0] cellIdxs = numpy.zeros(len(cols)) if len(cols) == 0: print "NONE" return prevCol = -1 for (col, cellIdx) in zip(cols...
Print the list of ``[column, cellIdx]`` indices for each of the active cells in state. :param state: TODO: document :param andValues: TODO: document
365,185
def _rmv_deps_answer(self): if self.meta.remove_deps_answer in ["y", "Y"]: remove_dep = self.meta.remove_deps_answer else: try: remove_dep = raw_input( "\nRemove dependencies (maybe used by " "other packages) [y/N]?...
Remove dependencies answer
365,186
def available_discounts(cls, user, categories, products): filtered_clauses = cls._filtered_clauses(user) categories = set(categories) products = set(products) product_categories = set(product.category for product in products) all_cat...
Returns all discounts available to this user for the given categories and products. The discounts also list the available quantity for this user, not including products that are pending purchase.
365,187
def __access(self, ts): with self.connection: self.connection.execute("INSERT OR REPLACE INTO access_timestamp (timestamp, domain) VALUES (?, ?)", (ts, self.domain))
Record an API access.
365,188
def list_tags(self, pattern: str = None) -> typing.List[str]: tags: typing.List[str] = [str(tag) for tag in self.repo.tags] if not pattern: LOGGER.debug(, tags) return tags LOGGER.debug(, pattern) filtered_tags: typing.List[str] = [tag for tag in tags if...
Returns list of tags, optionally matching "pattern" :param pattern: optional pattern to filter results :type pattern: str :return: existing tags :rtype: list of str
365,189
def register(self, *model_list, **options): databrowse_class = options.pop(, DefaultModelDatabrowse) for model in model_list: if model in self.registry: raise AlreadyRegistered( % model.__...
Registers the given model(s) with the given databrowse site. The model(s) should be Model classes, not instances. If a databrowse class isn't given, it will use DefaultModelDatabrowse (the default databrowse options). If a model is already registered, this will raise AlreadyRegistered...
365,190
def get_pdf_from_html(html: str, header_html: str = None, footer_html: str = None, wkhtmltopdf_filename: str = _WKHTMLTOPDF_FILENAME, wkhtmltopdf_options: Dict[str, Any] = None, file_encoding: str = "utf-8", ...
Takes HTML and returns a PDF. See the arguments to :func:`make_pdf_from_html` (except ``on_disk``). Returns: the PDF binary as a ``bytes`` object
365,191
def get(self): self.log.info() names, searchParams = self.get_crossmatch_names( listOfCoordinates=self.listOfCoordinates, radiusArcsec=self.arcsec ) search = namesearch.namesearch( log=self.log, names=names, ...
*get the conesearch object* **Return:** - ``conesearch`` .. todo:: - @review: when complete, clean get method - @review: when complete add logging
365,192
def syllable_split(string): string p = r[%s]+|`[%s]+|[%s]+|[^%s\ % (A, A, A, A) return re.findall(p, string, flags=FLAGS)
Split 'string' into (stressed) syllables and punctuation/whitespace.
365,193
def validate(self, value): try: if not self.blank or value: v = int(value) if v < 0: return None return value except ValueError: return None
Applies the validation criteria. Returns value, new value, or None if invalid. Overload this in derived classes.
365,194
def _has_data(self): return any([ len([ v for a in (s[0] if is_list_like(s) else [s]) for v in (a if is_list_like(a) else [a]) if v is not None ]) for s in self.raw_series ])
Check if there is any data
365,195
def set_maintext(self, index): dr = QtCore.Qt.DisplayRole text = "" model = index.model() for i in (1, 2, 3, 5, 6): new = model.index(index.row(), i, index.parent()).data(dr) if new is not None: text = " | ".join((text, new)) if text else ...
Set the maintext_lb to display text information about the given reftrack :param index: the index :type index: :class:`QtGui.QModelIndex` :returns: None :rtype: None :raises: None
365,196
def t_PLUS(self, t): r"\+" t.endlexpos = t.lexpos + len(t.value) return t
r"\+
365,197
def get_blocks_overview(block_representation_list, coin_symbol=, txn_limit=None, api_key=None): for block_representation in block_representation_list: assert is_valid_block_representation( block_representation=block_representation, coin_symbol=coin_symbol) assert is_...
Batch request version of get_blocks_overview
365,198
def match_http_version(entry, http_version, regex=True): response_version = entry[][] if regex: return re.search(http_version, response_version, flags=re.IGNORECASE) is not None else: return response_version == http_version
Helper function that returns entries with a request type matching the given `request_type` argument. :param entry: entry object to analyze :param request_type: ``str`` of request type to match :param regex: ``bool`` indicating whether to use a regex or string match
365,199
def url_builder(self, endpoint, *, root=None, params=None, url_params=None): if root is None: root = self.ROOT scheme, netloc, path, _, _ = urlsplit(root) return urlunsplit(( scheme, netloc, urljoin(path, endpoint), urlencode(u...
Create a URL for the specified endpoint. Arguments: endpoint (:py:class:`str`): The API endpoint to access. root: (:py:class:`str`, optional): The root URL for the service API. params: (:py:class:`dict`, optional): The values for format into the created URL...