text
stringlengths
81
112k
convert dict value if value is bool type, False -> "false" True -> "true" def filter_params(params): """ convert dict value if value is bool type, False -> "false" True -> "true" """ if params is not None: new_params = copy.deepcopy(params) new_params = dict((k, v) for k...
error code response: { "request": "/statuses/home_timeline.json", "error_code": "20502", "error": "Need you follow uid." } :param response: :return: def _handler_response(self, response, data=None): """ error code response: { ...
request weibo api :param suffix: str, :param params: dict, url query parameters :return: def get(self, suffix, params=None): """ request weibo api :param suffix: str, :param params: dict, url query parameters :return: """ url = self.base...
:return: def post(self, suffix, params=None, data=None, files=None): """ :return: """ url = self.base + suffix params = filter_params(params) response = self.session.post(url=url, params=params, data=data, files=files) return self._handler_response(response, d...
Search for handles containing the specified key with the specified value. The search terms are passed on to the reverse lookup servlet as-is. The servlet is supposed to be case-insensitive, but if it isn't, the wrong case will cause a :exc:`~b2handle.handleexceptions.ReverseLookupException`. ...
Create the part of the solr request that comes after the question mark, e.g. ?URL=*dkrz*&CHECKSUM=*abc*. If allowed search keys are configured, only these are used. If no'allowed search keys are specified, all key-value pairs are passed on to the reverse lookup servlet. :param f...
Creates and sets the authentication string for accessing the reverse lookup servlet. No return, the string is set as an attribute to the client instance. :param username: Username. :param password: Password. def __set_revlookup_auth_string(self, username, password): '''...
Create a new instance of a PIDClientCredentials with information read from a local JSON file. :param json_filename: The path to the json credentials file. The json file should have the following format: .. code:: json { "handle_s...
Load fixtures using a data migration. The migration will by default provide a rollback, deleting items by primary key. This is not always what you want ; you may set reversible=False to prevent rolling back. Usage: import myapp import anotherapp operations = [ migrations.RunPytho...
Get all non-zero bits def nonzero(self): """ Get all non-zero bits """ return [i for i in xrange(self.size()) if self.test(i)]
Returns a hexadecimal string def tohexstring(self): """ Returns a hexadecimal string """ val = self.tostring() st = "{0:0x}".format(int(val, 2)) return st.zfill(len(self.bitmap)*2)
Construct BitMap from hex string def fromhexstring(cls, hexstring): """ Construct BitMap from hex string """ bitstring = format(int(hexstring, 16), "0" + str(len(hexstring)/4) + "b") return cls.fromstring(bitstring)
Construct BitMap from string def fromstring(cls, bitstring): """ Construct BitMap from string """ nbits = len(bitstring) bm = cls(nbits) for i in xrange(nbits): if bitstring[-i-1] == '1': bm.set(i) elif bitstring[-i-1] != '0': ...
Get version information or return default if unable to do so. def get_versions(): """Get version information or return default if unable to do so.""" # I am in _version.py, which lives at ROOT/VERSIONFILE_SOURCE. If we have # __file__, we can work backwards from there to the root. Some # py2exe/bbfreez...
Get a value that can be the boolean representation of a string or a boolean itself and returns It as a boolean. If this is not the case, It returns a string. :value: The HTTPS_verify input value. A string can be passed as a path to a CA_BUNDLE certificate :returns: True, False or a string. ...
Setup filter (only called when filter is actually used). def setup(self): """Setup filter (only called when filter is actually used).""" super(RequireJSFilter, self).setup() excluded_files = [] for bundle in self.excluded_bundles: excluded_files.extend( map(...
Initialize filter just before it will be used. def setup(self): """Initialize filter just before it will be used.""" super(CleanCSSFilter, self).setup() self.root = current_app.config.get('COLLECT_STATIC_ROOT')
Determine which option name to use. def rebase_opt(self): """Determine which option name to use.""" if not hasattr(self, '_rebase_opt'): # out = b"MAJOR.MINOR.REVISION" // b"3.4.19" or b"4.0.0" out, err = Popen( ['cleancss', '--version'], stdout=PIPE).communicate...
Input filtering. def input(self, _in, out, **kw): """Input filtering.""" args = [self.binary or 'cleancss'] + self.rebase_opt if self.extra_args: args.extend(self.extra_args) self.subprocess(args, out, _in)
Wrap translation in Angular module. def output(self, _in, out, **kwargs): """Wrap translation in Angular module.""" out.write( 'angular.module("{0}", ["gettext"]).run(' '["gettextCatalog", function (gettextCatalog) {{'.format( self.catalog_name ) ...
Process individual translation file. def input(self, _in, out, **kwargs): """Process individual translation file.""" language_code = _re_language_code.search(_in.read()).group( 'language_code' ) _in.seek(0) # move at the begining after matching the language catalog ...
Check the combination username/password that is valid on the database. def get_user_and_check_auth(self, username, password): """Check the combination username/password that is valid on the database. """ constraint = sql.or_( models.USERS.c.name == username, ...
Query the Github API to retrieve the needed infos. def retrieve_info(self): """Query the Github API to retrieve the needed infos.""" path = urlparse(self.url).path path = path.split('/')[1:] sanity_filter = re.compile('[\da-z-_]+', re.IGNORECASE) self.product = sanity_filter.m...
Cache the return value in the correct cache directory. Set 'method' to false for static methods. def disk_cache(cls, basename, function, *args, method=True, **kwargs): """ Cache the return value in the correct cache directory. Set 'method' to false for static methods. """ ...
Download a file into the correct cache directory. def download(cls, url, filename=None): """ Download a file into the correct cache directory. """ return utility.download(url, cls.directory(), filename)
Path that should be used for caching. Different for all subclasses. def directory(cls, prefix=None): """ Path that should be used for caching. Different for all subclasses. """ prefix = prefix or utility.read_config().directory name = cls.__name__.lower() directory = os....
Get the rconfiguration_id of the last job run by the remoteci. :param topic_id: the topic :param remoteci_id: the remoteci id :return: last rconfiguration_id of the remoteci def get_last_rconfiguration_id(topic_id, remoteci_id, db_conn=None): """Get the rconfiguration_id of the last job run by the rem...
Get a remoteci configuration. This will iterate over each configuration in a round robin manner depending on the last rconfiguration used by the remoteci. def get_remoteci_configuration(topic_id, remoteci_id, db_conn=None): """Get a remoteci configuration. This will iterate over each configuration in a...
Dispatches a request. Expects one and one only target handler :param request: The request to dispatch :return: None, will throw a ConfigurationException if more than one handler factor is registered for the command def send(self, request: Request) -> None: """ Dispatches a request. Expe...
Dispatches a request. Expects zero or more target handlers :param request: The request to dispatch :return: None. def publish(self, request: Request) -> None: """ Dispatches a request. Expects zero or more target handlers :param request: The request to dispatch :return: ...
Dispatches a request over middleware. Returns when message put onto outgoing channel by producer, does not wait for response from a consuming application i.e. is fire-and-forget :param request: The request to dispatch :return: None def post(self, request: Request) -> None: """ D...
Find and delete any text nodes containing nothing but whitespace in in the given node and its descendents. This is useful for cleaning up excess low-value text nodes in a document DOM after parsing a pretty-printed XML document. def ignore_whitespace_text_nodes(cls, wrapped_node): """ ...
Return a three-element tuple with the prefix, local name, and namespace URI for the given element/attribute name (in the context of the given node's hierarchy). If the name has no associated prefix or namespace information, None is return for those tuple members. def get_ns_info_from_node_name(...
:return: a builder representing an ancestor of the current element, by default the parent element. :param count: return the n'th ancestor element; defaults to 1 which means the immediate parent. If *count* is greater than the number of number of ancestors return the doc...
Add a child element to the :class:`xml4h.nodes.Element` node represented by this Builder. :return: a new Builder that represents the child element. Delegates to :meth:`xml4h.nodes.Element.add_element`. def element(self, *args, **kwargs): """ Add a child element to the :class:`...
Add one or more attributes to the :class:`xml4h.nodes.Element` node represented by this Builder. :return: the current Builder. Delegates to :meth:`xml4h.nodes.Element.set_attributes`. def attributes(self, *args, **kwargs): """ Add one or more attributes to the :class:`xml4h.no...
Add a processing instruction node to the :class:`xml4h.nodes.Element` node represented by this Builder. :return: the current Builder. Delegates to :meth:`xml4h.nodes.Element.add_instruction`. def processing_instruction(self, target, data): """ Add a processing instruction node...
Set the namespace prefix of the :class:`xml4h.nodes.Element` node represented by this Builder. :return: the current Builder. Delegates to :meth:`xml4h.nodes.Element.set_ns_prefix`. def ns_prefix(self, prefix, ns_uri): """ Set the namespace prefix of the :class:`xml4h.nodes.Ele...
Create a certificate request. Arguments: pkey - The key to associate with the request digest - Digestion method to use for signing, default is sha256 **name - The name of the subject of the request, possible arguments are: C - Cou...
Verify the existence of a resource in the database and then return it if it exists, according to the condition, or raise an exception. :param id: id of the resource :param table: the table object :param name: the name of the row to look for :param get_id: if True, return only the ID :return...
Retrieve the list of topics IDs a user has access to. def user_topic_ids(user): """Retrieve the list of topics IDs a user has access to.""" if user.is_super_admin() or user.is_read_only_user(): query = sql.select([models.TOPICS]) else: query = (sql.select([models.JOINS_TOPICS_TEAMS.c.topic...
Verify that the user's team does belongs to the given topic. If the user is an admin or read only user then it belongs to all topics. def verify_team_in_topic(user, topic_id): """Verify that the user's team does belongs to the given topic. If the user is an admin or read only user then it belongs to all to...
Transform sqlalchemy source: [{'a_id' : 'id1', 'a_name' : 'name1, 'b_id' : 'id2', 'b_name' : 'name2}, {'a_id' : 'id3', 'a_name' : 'name3, 'b_id' : 'id4', 'b_name' : 'name4} ] to [{'id' : 'id1', 'name': 'name2', 'b' : {'id': 'id2', 'name': 'name2'}, ...
From the _format_level_1 function we have a list of rows. Because of using joins, we have as many rows as join result. For example: [{'id' : 'id1', 'name' : 'name1, 'b' : {'id': 'id2, 'name': 'name2'} } {'id' : 'id1', 'name' : 'name1, 'b' : {'id' : 'id4', ...
Build a basic values object used in every create method. All our resources contain a same subset of value. Instead of redoing this code everytime, this method ensures it is done only at one place. def common_values_dict(): """Build a basic values object used in every create method. Al...
:param fetchall: get all rows :param fetchone: get only one row :param use_labels: prefix row columns names by the table name :return: def execute(self, fetchall=False, fetchone=False, use_labels=True): """ :param fetchall: get all rows :param fetchone: get only one ro...
Returns some information about the currently authenticated identity def get_identity(identity): """Returns some information about the currently authenticated identity""" return flask.Response( json.dumps( { 'identity': { 'id': identity.id, ...
Get all issues for a specific job. def get_issues_by_resource(resource_id, table): """Get all issues for a specific job.""" v1_utils.verify_existence_and_get(resource_id, table) # When retrieving the issues for a job, we actually retrieve # the issues attach to the job itself + the issues attached to...
Unattach an issue from a specific job. def unattach_issue(resource_id, issue_id, table): """Unattach an issue from a specific job.""" v1_utils.verify_existence_and_get(issue_id, _TABLE) if table.name == 'jobs': join_table = models.JOIN_JOBS_ISSUES where_clause = sql.and_(join_table.c.job_i...
Attach an issue to a specific job. def attach_issue(resource_id, table, user_id): """Attach an issue to a specific job.""" data = schemas.issue.post(flask.request.json) issue = _get_or_create_issue(data) # Second, insert a join record in the JOIN_JOBS_ISSUES or # JOIN_COMPONENTS_ISSUES database. ...
Remove collect's static root folder from list. def collect_staticroot_removal(app, blueprints): """Remove collect's static root folder from list.""" collect_root = app.extensions['collect'].static_root return [bp for bp in blueprints if ( bp.has_static_folder and bp.static_folder != collect_root)]
Get all jobstates. def get_all_jobstates(user, job_id): """Get all jobstates. """ args = schemas.args(flask.request.args.to_dict()) job = v1_utils.verify_existence_and_get(job_id, models.JOBS) if user.is_not_super_admin() and user.is_not_read_only_user(): if (job['team_id'] not in user.team...
Create the dci client in the master realm. def create_client(access_token): """Create the dci client in the master realm.""" url = 'http://keycloak:8080/auth/admin/realms/dci-test/clients' r = requests.post(url, data=json.dumps(client_data), headers=get_auth_head...
Create the a dci user. username=dci, password=dci, email=dci@distributed-ci.io def create_user_dci(access_token): """Create the a dci user. username=dci, password=dci, email=dci@distributed-ci.io""" user_data = {'username': 'dci', 'email': 'dci@distributed-ci.io', 'ena...
The name of the site. : str | `None` def initialize(self, name=None, dbname=None, base=None, generator=None, case=None, namespaces=None): self.name = none_or(name, str) """ The name of the site. : str | `None` """ self.dbname = none_or(dbname, str) "...
Convert all booleans to lowercase strings def _serializeBooleans(params): """"Convert all booleans to lowercase strings""" serialized = {} for name, value in params.items(): if value is True: value = 'true' elif value is False: value = 'fa...
Requests wrapper function def request(self, method, url, parameters=dict()): """Requests wrapper function""" # The requests library uses urllib, which serializes to "True"/"False" while Pingdom requires lowercase parameters = self._serializeBooleans(parameters) headers = {'App-Key': s...
Returns a list of actions (alerts) that have been generated for your account. Optional Parameters: * from -- Only include actions generated later than this timestamp. Format is UNIX time. Type: Integer Default: None *...
Pulls all checks from pingdom Optional Parameters: * limit -- Limits the number of returned probes to the specified quantity. Type: Integer (max 25000) Default: 25000 * offset -- Offset for listing (requires limit.) ...
Returns a detailed description of a specified check. def getCheck(self, checkid): """Returns a detailed description of a specified check.""" check = PingdomCheck(self, {'id': checkid}) check.getDetails() return check
Returns a list of all Pingdom probe servers Parameters: * limit -- Limits the number of returned probes to the specified quantity Type: Integer * offset -- Offset for listing (requires limit). Type: Integer De...
Perform a traceroute to a specified target from a specified Pingdom probe. Provide hostname to check and probeid to check from Returned structure: { 'result' : <String> Traceroute output 'probeid' : <Integer> Probe identifier ...
Returns a list of all contacts. Optional Parameters: * limit -- Limits the number of returned contacts to the specified quantity. Type: Integer Default: 100 * offset -- Offset for listing (requires limit.) Typ...
Create a new contact. Provide new contact name and any optional arguments. Returns new PingdomContact instance Optional Parameters: * email -- Contact email address Type: String * cellphone -- Cellphone number, without the country code part. In...
Modifies a list of contacts. Provide comma separated list of contact ids and desired paused state Returns status message def modifyContacts(self, contactids, paused): """Modifies a list of contacts. Provide comma separated list of contact ids and desired paused state Returns...
Returns a list of PingdomEmailReport instances. def getEmailReports(self): """Returns a list of PingdomEmailReport instances.""" reports = [PingdomEmailReport(self, x) for x in self.request('GET', 'reports.email').json()['subscriptions']] ret...
Creates a new email report Returns status message for operation Optional parameters: * checkid -- Check identifier. If omitted, this will be an overview report Type: Integer * frequency -- Report frequency Type: String [...
Returns a list of PingdomSharedReport instances def getSharedReports(self): """Returns a list of PingdomSharedReport instances""" response = self.request('GET', 'reports.shared').json()['shared']['banners'] reports = [PingdomSharedReport(self, x) for x in respo...
Create a shared report (banner). Returns status message for operation Optional parameters: * auto -- Automatic period (If false, requires: fromyear, frommonth, fromday, toyear, tomonth, today) Type: Boolean * type -- Banner type ...
When bool_encry is True, encrypt the data with master key. When it is False, the function extract the three nonce from the encrypted data (first 3*21 bytes), and decrypt the data. :param data: the data to encrypt or decrypt. :param masterkey: a 32 bytes key in bytes. :param bool_encry: if bool_encry is ...
Register the handler for the command :param request_class: The command or event to dispatch. It must implement getKey() :param handler_factory: A factory method to create the handler to dispatch to :return: def register(self, request_class: Request, handler_factory: Callable[[], Handler]) -> No...
Looks up the handler associated with a request - matches the key on the request to a registered handler :param request: The request we want to find a handler for :return: def lookup(self, request: Request) -> List[Callable[[], Handler]]: """ Looks up the handler associated with a reques...
Adds a message mapper to a factory, using the requests key :param mapper_func: A callback that creates a BrightsideMessage from a Request :param request_class: A request type def register(self, request_class: Request, mapper_func: Callable[[Request], BrightsideMessage]) -> None: """Adds a messa...
Looks up the message mapper function associated with this class. Function should take in a Request derived class and return a BrightsideMessage derived class, for sending on the wire :param request_class: :return: def lookup(self, request_class: Request) -> Callable[[Request], BrightsideMessag...
This type validation function can be used in two modes: * providing two arguments (x, ref_type), it returns `True` if isinstance(x, ref_type) and raises a HasWrongType error if not. If ref_type is a set of types, any match with one of the included types will do * providing a single argument (ref_type), t...
This type validation function can be used in two modes: * providing two arguments (c, ref_type), it returns `True` if issubclass(c, ref_type) and raises a IsWrongType error if not. If ref_type is a set of types, any match with one of the included types will do * providing a single argument (ref_type), th...
Function decorator for caching pickleable return values on disk. Uses a hash computed from the function arguments for invalidation. If 'method', skip the first argument, usually being self or cls. The cache filepath is 'directory/basename-hash.pickle'. def disk_cache(basename, directory, method=False): ...
Download a file and return its filename on the local file system. If the file is already there, it will not be downloaded again. The filename is derived from the url if not provided. Return the filepath. def download(url, directory, filename=None): """ Download a file and return its filename on the loc...
Create the directories along the provided directory path that do not exist. def ensure_directory(directory): """ Create the directories along the provided directory path that do not exist. """ directory = os.path.expanduser(directory) try: os.makedirs(directory) except OSError as e: ...
This function handles the various ways that users may enter 'validation functions', so as to output a single callable method. Setting "auto_and_wrapper" to False allows callers to get a list of callables instead. valid8 supports the following expressions for 'validation functions' * <ValidationFunc> ...
An 'and' validator: it returns `True` if all of the provided validators return `True`, or raises a `AtLeastOneFailed` failure on the first `False` received or `Exception` caught. Note that an implicit `and_` is performed if you provide a list of validators to any of the entry points (`validate`, `validatio...
Generates the inverse of the provided validation functions: when the validator returns `False` or raises a `Failure`, this function returns `True`. Otherwise it raises a `DidNotFail` failure. By default, exceptions of types other than `Failure` are not caught and therefore fail the validation (`catch_all=F...
An 'or' validator: returns `True` if at least one of the provided validators returns `True`. All exceptions will be silently caught. In case of failure, a global `AllValidatorsFailed` failure will be raised, together with details about all validation results. :param validation_func: the base validation fun...
A 'xor' validation function: returns `True` if exactly one of the provided validators returns `True`. All exceptions will be silently caught. In case of failure, a global `XorTooManySuccess` or `AllValidatorsFailed` will be raised, together with details about the various validation results. :param validati...
An alias for not_(and_(validators)). :param validation_func: the base validation function or list of base validation functions to use. A callable, a tuple(callable, help_msg_str), a tuple(callable, failure_type), or a list of several such elements. Nested lists are supported and indicate an implici...
This function is automatically used if you provide a tuple `(<function>, <msg>_or_<Failure_type>)`, to any of the methods in this page or to one of the `valid8` decorators. It transforms the provided `<function>` into a failure raiser, raising a subclass of `Failure` in case of failure (either not returning `Tr...
Internal utility method to extract optional arguments from kwargs. :param kwargs: :param names_with_defaults: :param allow_others: if False (default) then an error will be raised if kwargs still contains something at the end. :return: def pop_kwargs(kwargs, names_with_defaults, # type:...
Overrides the base method in order to give details on the various successes and failures def get_details(self): """ Overrides the base method in order to give details on the various successes and failures """ # transform the dictionary of failures into a printable form need_to_print_value = Tr...
Utility method to play all the provided validators on the provided value and output the :param validators: :param value: :return: def play_all_validators(self, validators, value): """ Utility method to play all the provided validators on the provided value and output the ...
Generates a secret of given length def gen_secret(length=64): """ Generates a secret of given length """ charset = string.ascii_letters + string.digits return ''.join(random.SystemRandom().choice(charset) for _ in range(length))
Encrypt a file and write it with .cryptoshop extension. :param filename: a string with the path to the file to encrypt. :param passphrase: a string with the user passphrase. :param algo: a string with the algorithm. Can be srp, aes, twf. Default is srp. :return: a string with "successfully encrypted" or...
Decrypt a file and write corresponding decrypted file. We remove the .cryptoshop extension. :param filename: a string with the path to the file to decrypt. :param passphrase: a string with the user passphrase. :return: a string with "successfully decrypted" or error. def decryptfile(filename, passphrase): ...
Split a sentence while preserving tags. def _tokenize(cls, sentence): """ Split a sentence while preserving tags. """ while True: match = cls._regex_tag.search(sentence) if not match: yield from cls._split(sentence) return ...
Implements a distributed stategy for processing XML files. This function constructs a set of py:mod:`multiprocessing` threads (spread over multiple cores) and uses an internal queue to aggregate outputs. To use this function, implement a `process()` function that takes two arguments -- a :class:`mwxml...
Return the object itself. def dump(self): """Return the object itself.""" return { 'title': self.title, 'issue_id': self.issue_id, 'reporter': self.reporter, 'assignee': self.assignee, 'status': self.status, 'product': self.produc...
Applies func_to_apply on each argument of func according to what's received in current call (cur_args, cur_kwargs). For each argument of func named 'att' in its signature, the following method is called: `func_to_apply(cur_att_value, func_to_apply_paramers_dict[att], func, att_name)` :param func: :par...
Ensure the user is a PRODUCT_OWNER. def is_product_owner(self, team_id): """Ensure the user is a PRODUCT_OWNER.""" if self.is_super_admin(): return True team_id = uuid.UUID(str(team_id)) return team_id in self.child_teams_ids
Test if user is in team def is_in_team(self, team_id): """Test if user is in team""" if self.is_super_admin(): return True team_id = uuid.UUID(str(team_id)) return team_id in self.teams or team_id in self.child_teams_ids
Ensure ther resource has the role REMOTECI. def is_remoteci(self, team_id=None): """Ensure ther resource has the role REMOTECI.""" if team_id is None: return self._is_remoteci team_id = uuid.UUID(str(team_id)) if team_id not in self.teams_ids: return False ...
Ensure ther resource has the role FEEDER. def is_feeder(self, team_id=None): """Ensure ther resource has the role FEEDER.""" if team_id is None: return self._is_feeder team_id = uuid.UUID(str(team_id)) if team_id not in self.teams_ids: return False return...