text
stringlengths
81
112k
在指定元素上执行alt组合事件 @note: key event -> alt + key @param key: 如'X' def Alt(cls, key): """ 在指定元素上执行alt组合事件 @note: key event -> alt + key @param key: 如'X' """ element = cls._element() element.send_keys(Keys.ALT, key)
在指定输入框发送 Null, 用于设置焦点 @note: key event -> NULL def Focus(cls): """ 在指定输入框发送 Null, 用于设置焦点 @note: key event -> NULL """ element = cls._element() # element.send_keys(Keys.NULL) action = ActionChains(Web.driver) acti...
文件上传, 非原生input @todo: some upload.exe not prepared @param file: 文件名(文件必须存在在工程resource目录下), upload.exe工具放在工程tools目录下 def Upload(cls, filename): """ 文件上传, 非原生input @todo: some upload.exe not prepared @param file: 文件名(文件必须存在在工程resource目录下), upload.exe工具放在工程tools目录...
上传, 一般,上传页面如果是input,原生file文件框, 如: <input type="file" id="test-image-file" name="test" accept="image/gif">,像这样的,定位到该元素,然后使用 send_keys 上传的文件的绝对路径 @param file_name: 文件名(文件必须存在在工程resource目录下) def UploadType(cls, file_path): """ 上传, 一般,上传页面如果是input,原生file文件框, 如: <input type="file" id="test-im...
Updates the Dict with the given values. Turns internal dicts into Dicts. def update(xCqNck7t, **kwargs): """Updates the Dict with the given values. Turns internal dicts into Dicts.""" def dict_list_val(inlist): l = [] for i in inlist: if type(i)==dict: ...
sort the keys before returning them def keys(self, key=None, reverse=False): """sort the keys before returning them""" ks = sorted(list(dict.keys(self)), key=key, reverse=reverse) return ks
java -jar selenium-server.jar -role hub -port 4444 @param port: listen port of selenium hub def hub(self, port): ''' java -jar selenium-server.jar -role hub -port 4444 @param port: listen port of selenium hub ''' self._ip = "localhost" self._port = port ...
java -jar selenium-server.jar -role node -port 5555 -hub http://127.0.0.1:4444/grid/register/ @param port: listen port of selenium node @param hub_address: hub address which node will connect to def node(self,port, hub_address=("localhost", 4444)): ''' java -jar selenium-server.jar -role no...
start the selenium Remote Server. def start_server(self): """start the selenium Remote Server.""" self.__subp = subprocess.Popen(self.command) #print("\tselenium jar pid[%s] is running." %self.__subp.pid) time.sleep(2)
Determine whether hub server is running :return:True or False def is_runnnig(self): """Determine whether hub server is running :return:True or False """ resp = None try: resp = requests.get("http://%s:%s" %(self._ip, self._port)) if resp...
Implements two's complement negation. def negate_gate(wordlen, input='x', output='~x'): """Implements two's complement negation.""" neg = bitwise_negate(wordlen, input, "tmp") inc = inc_gate(wordlen, "tmp", output) return neg >> inc
Return a circuit taking a wordlen bitvector where only k valuations return True. Uses encoding from [1]. Note that this is equivalent to (~x < k). - TODO: Add automated simplification so that the circuits are equiv. [1]: Chakraborty, Supratik, et al. "From Weighted to Unweighted Model ...
Recursively flattens a list. :param lobj: List to flatten :type lobj: list :rtype: list For example: >>> import pmisc >>> pmisc.flatten_list([1, [2, 3, [4, 5, 6]], 7]) [1, 2, 3, 4, 5, 6, 7] def flatten_list(lobj): """ Recursively flattens a list. :param lobj: L...
tuple of (username, password). if use_keyring is set to true the password will be queried from the local keyring instead of taken from the configuration file. def auth(self): """ tuple of (username, password). if use_keyring is set to true the password will be queried from the local keyring ins...
load a configuration file. loads default config if file is not found def load(self, file=CONFIG_FILE): """ load a configuration file. loads default config if file is not found """ if not os.path.exists(file): print("Config file was not found under %s. Default file has been c...
Save configuration to provided path as a yaml file def save(self, file=CONFIG_FILE): """ Save configuration to provided path as a yaml file """ os.makedirs(os.path.dirname(file), exist_ok=True) with open(file, "w") as f: yaml.dump(self._settings, f, Dumper=yaml.Round...
opens a curses/picker based interface to select courses that should be downloaded. def selection_dialog(self, courses): """ opens a curses/picker based interface to select courses that should be downloaded. """ selected = list(filter(lambda x: x.course.id in self._settings["selected_cou...
Create the corresponding index. Will overwrite existing indexes of the same name. def create(self): """Create the corresponding index. Will overwrite existing indexes of the same name.""" body = dict() if self.mapping is not None: body['mappings'] = self.mapping if self.sett...
Search the index with a query. Can at most return 10'000 results from a search. If the search would yield more than 10'000 hits, only the first 10'000 are returned. The default number of hits returned is 100. def search(self, query=None, size=100, unpack=True): """Search the index with a query...
Scan the index with the query. Will return any number of results above 10'000. Important to note is, that all the data is loaded into memory at once and returned. This works only with small data sets. Use scroll otherwise which returns a generator to cycle through the resources in set c...
Scroll an index with the specified search query. Works as a generator. Will yield `size` results per iteration until all hits are returned. def scroll(self, query=None, scroll='5m', size=100, unpack=True): """Scroll an index with the specified search query. Works as a generator. Will yield `s...
Fetch document by _id. Returns None if it is not found. (Will log a warning if not found as well. Should not be used to search an id.) def get(self, identifier): """Fetch document by _id. Returns None if it is not found. (Will log a warning if not found as well. Should not be used ...
Index a single document into the index. def index_into(self, document, id) -> bool: """Index a single document into the index.""" try: self.instance.index(index=self.index, doc_type=self.doc_type, body=json.dumps(document, ensure_ascii=False), id=id) except RequestError as ex: ...
Delete a document with id. def delete(self, doc_id: str) -> bool: """Delete a document with id.""" try: self.instance.delete(self.index, self.doc_type, doc_id) except RequestError as ex: logging.error(ex) return False else: return True
Partial update to a single document. Uses the Update API with the specified partial document. def update(self, doc: dict, doc_id: str): """Partial update to a single document. Uses the Update API with the specified partial document. """ body = { 'doc': doc ...
Uses painless script to update a document. See documentation for more information. def script_update(self, script: str, params: Union[dict, None], doc_id: str): """Uses painless script to update a document. See documentation for more information. """ body = { 'scri...
Takes a list of dictionaries and an identifier key and indexes everything into this index. :param data: List of dictionaries containing the data to be indexed. :param identifier_key: The name of the dictionary element which should be used as _id. This will be removed from ...
Reindex the entire index. Scrolls the old index and bulk indexes all data into the new index. :param new_index_name: :param identifier_key: :param kwargs: Overwrite ElasticIndex __init__ params. :return: def reindex(self, new_index_name: str, identifier_key: str, **kw...
Dumps the entire index into a json file. :param path: The path to directory where the dump should be stored. :param file_name: Name of the file the dump should be stored in. If empty the index name is used. :param kwargs: Keyword arguments for the json converter. (ex. indent=4, ensure_ascii=Fa...
parse command line options and either launch some configuration dialog or start an instance of _MainLoop as a daemon def main(): """ parse command line options and either launch some configuration dialog or start an instance of _MainLoop as a daemon """ (options, _) = _parse_args() if options.chan...
Takes data and returns a signature :arg dict signature_data: data to use to generate a signature :returns: ``Result`` instance def generate(self, signature_data): """Takes data and returns a signature :arg dict signature_data: data to use to generate a signature :returns: ``...
Helper function to expand (blast) str -> int map into str -> bool map. This is used to send word level inputs to aiger. def _blast(bvname2vals, name_map): """Helper function to expand (blast) str -> int map into str -> bool map. This is used to send word level inputs to aiger.""" if len(name_map) == 0:...
Helper function to lift str -> bool maps used by aiger to the word level. Dual of the `_blast` function. def _unblast(name2vals, name_map): """Helper function to lift str -> bool maps used by aiger to the word level. Dual of the `_blast` function.""" def _collect(names): return tuple(name2vals[...
Generates a logger instance from the singleton def create_logger(self): """Generates a logger instance from the singleton""" name = "bors" if hasattr(self, "name"): name = self.name self.log = logging.getLogger(name) try: lvl = self.conf.get_log_level() ...
gets class from name and data, sets base level attrs defaults to facsimile.base.Facsimile def get_cls(project_name, project_data): """ gets class from name and data, sets base level attrs defaults to facsimile.base.Facsimile """ if project_name: cls = getattr(facsimile.base, project_dat...
Chech that the entered recaptcha data is correct def check_recaptcha(view_func): """Chech that the entered recaptcha data is correct""" @wraps(view_func) def _wrapped_view(request, *args, **kwargs): request.recaptcha_is_valid = None if request.method == 'POST': recaptcha_respons...
Internal request method def _request(self, url, method="GET", params=None, api_call=None): """Internal request method""" method = method.lower() params = params or {} func = getattr(requests, method) requests_args = {} if method == "get" or method == "delete": ...
Return dict of response received from Safecast's API :param endpoint: (required) Full url or Safecast API endpoint (e.g. measurements/users) :type endpoint: string :param method: (optional) Method of accessing data, either GET, POST, PUT or DELETE....
(Copied from implementation in https://github.com/greenelab/adage-server/blob/master/adage/analyze/api.py) Handle an incoming POST as a GET to work around URI length limitations def post_list(self, request, **kwargs): """ (Copied from implementation in https://github.com/greene...
Execute the strategies on the given context def execute(self, context): """Execute the strategies on the given context""" for ware in self.middleware: ware.premessage(context) context = ware.bind(context) ware.postmessage(context) return context
Perform cleanup! We're goin' down!!! def shutdown(self): """Perform cleanup! We're goin' down!!!""" for ware in self.middleware: ware.preshutdown() self._shutdown() ware.postshutdown()
Generates documentation for signature generation pipeline def main(argv=None): """Generates documentation for signature generation pipeline""" parser = argparse.ArgumentParser(description=DESCRIPTION) parser.add_argument( 'pipeline', help='Python dotted path to rules pipeline to document' ...
This function is called by the Django API to specify how this object will be saved to the database. def handle(self, *args, **options): """This function is called by the Django API to specify how this object will be saved to the database. """ taxonomy_id = options['taxonomy_id']...
Creates a window of given resolution. :param resolution: the resolution of the windows as (width, height) in pixels :type resolution: tuple :param pygame_flags: modify the creation of the window. For further information see :ref:`creating_a_window` :type pygame_flags: int :param dis...
Displays a pygame.Surface in the window. in pygame the window is represented through a surface, on which you can draw as on any other pygame.Surface. A refernce to to the screen can be optained via the :py:func:`pygame.display.get_surface` function. To display the contents of the screen surface in ...
Returns an empty surface filled with fill_color. :param fill_color: color to fill the surface with :type fill_color: pygame.Color :param size: the size of the new surface, if None its created to be the same size as the screen :type size: int-2-tuple def empty_surface(fill_color, size=None): ...
This is a convinience method for use with EventListener.wait_for_unicode_char(). In most cases it simply appends char to buffer. Some replacements are done because presing return will produce '\\r' but for most cases '\\n' would be desireable. Also backspace cant just be added to a string either, ther...
Called by internal API subsystem to initialize websockets connections in the API interface def run(self): """ Called by internal API subsystem to initialize websockets connections in the API interface """ self.api = self.context.get("cls")(self.context) self.cont...
Take a list of SockChannel objects and extend the websock listener def add_channels(self, channels): """ Take a list of SockChannel objects and extend the websock listener """ chans = [ SockChannel(chan, res, self._generate_result) for chan, res in channels.items...
Generate the result object def _generate_result(self, res_type, channel, result): """Generate the result object""" schema = self.api.ws_result_schema() schema.context['channel'] = channel schema.context['response_type'] = res_type self.callback(schema.load(result), self.context)
returns a random element from seq n times. If n is None, it continues indefinitly def rand_elem(seq, n=None): """returns a random element from seq n times. If n is None, it continues indefinitly""" return map(random.choice, repeat(seq, n) if n is not None else repeat(seq))
Return first paragraph of multiline_str as a oneliner. When without_trailing_dot is True, the last char of the first paragraph will be removed, if it is a dot ('.'). Examples: >>> multiline_str = 'first line\\nsecond line\\n\\nnext paragraph' >>> print(first_paragraph(multiline_str)) ...
Print the first paragraph of the docstring of the decorated function. The paragraph will be printed as a oneliner. May be invoked as a simple, argument-less decorator (i.e. ``@print_doc1``) or with named arguments ``color``, ``bold``, ``prefix`` of ``tail`` (eg. ``@print_doc1(color=utils.red, bold=Tru...
Decorator, print the full name of the decorated function. May be invoked as a simple, argument-less decorator (i.e. ``@print_doc1``) or with named arguments ``color``, ``bold``, or ``prefix`` (eg. ``@print_doc1(color=utils.red, bold=True, prefix=' ')``). def print_full_name(*args, **kwargs): '''Decora...
Return str template with applied substitutions. Example: >>> template = 'Asyl for {{name}} {{surname}}!' >>> filled_out_template_str(template, name='Edward', surname='Snowden') 'Asyl for Edward Snowden!' >>> template = '[[[foo]]] was substituted by {{foo}}' >>> filled_out_t...
Return content of file filename with applied substitutions. def filled_out_template(filename, **substitutions): '''Return content of file filename with applied substitutions.''' res = None with open(filename, 'r') as fp: template = fp.read() res = filled_out_template_str(template, **substit...
Search in file 'filename' for a line starting with 'prefix' and replace the line by 'new_line'. If a line starting with 'prefix' not exists 'new_line' will be appended. If the file not exists, it will be created. Return False if new_line was appended, else True (i.e. if the prefix was found within...
Comment line out by putting a comment sign in front of the line. If the file does not contain the line, the files content will not be changed (but the file will be touched in every case). def comment_out_line(filename, line, comment='#', update_or_append_line=update_or_append_line): '...
Remove the comment of an commented out line and make the line "active". If such an commented out line not exists it would be appended. def uncomment_or_update_or_append_line(filename, prefix, new_line, comment='#', keep_backup=True, upd...
Return a copy of `input` with every str component encoded from unicode to utf-8. def convert_unicode_2_utf8(input): '''Return a copy of `input` with every str component encoded from unicode to utf-8. ''' if isinstance(input, dict): try: # python-2.6 return dict((conv...
Return the json-file data, with all strings utf-8 encoded. def load_json(filename, gzip_mode=False): '''Return the json-file data, with all strings utf-8 encoded.''' open_file = open if gzip_mode: open_file = gzip.open try: with open_file(filename, 'rt') as fh: data = json...
Write the python data structure as a json-Object to filename. def write_json(data, filename, gzip_mode=False): '''Write the python data structure as a json-Object to filename.''' open_file = open if gzip_mode: open_file = gzip.open try: with open_file(filename, 'wt') as fh: ...
Return text with a `newline` inserted after each `line_length` char. Return `text` unchanged if line_length == 0. def text_with_newlines(text, line_length=78, newline='\n'): '''Return text with a `newline` inserted after each `line_length` char. Return `text` unchanged if line_length == 0. ''' if...
A memoize decorator for class properties. Return a cached property that is calculated by function `func` on first access. def lazy_val(func, with_del_hook=False): '''A memoize decorator for class properties. Return a cached property that is calculated by function `func` on first access. ''' ...
Read all lines from file. def _readlines(fname, fpointer1=open, fpointer2=open): # pragma: no cover """Read all lines from file.""" # fpointer1, fpointer2 arguments to ease testing try: with fpointer1(fname, "r") as fobj: return fobj.readlines() except UnicodeDecodeError: # pragma...
Generic interface to REST apiGeneric interface to REST api :param callname: query name :param data: dictionary of inputs :param args: keyword arguments added to the payload :return: def call(self, callname, data=None, **args): """ Generic interface to REST apiGener...
launch nagios_plugin command def launch_plugin(self): ''' launch nagios_plugin command ''' # nagios_plugins probes for plugin in self.plugins: # Construct the nagios_plugin command command = ('%s%s' % (self.plugins[plugin]['path'], self.plugins[plugin]['c...
for a given path and regexp pattern, return the files that match def match(Class, path, pattern, flags=re.I, sortkey=None, ext=None): """for a given path and regexp pattern, return the files that match""" return sorted( [ Class(fn=fn) for fn in rglob(path, f"...
copy the file to the new_fn, preserving atime and mtime def copy(self, new_fn): """copy the file to the new_fn, preserving atime and mtime""" new_file = self.__class__(fn=str(new_fn)) new_file.write(data=self.read()) new_file.utime(self.atime, self.mtime) return new_file
make a filesystem-compliant basename for this file def make_basename(self, fn=None, ext=None): """make a filesystem-compliant basename for this file""" fb, oldext = os.path.splitext(os.path.basename(fn or self.fn)) ext = ext or oldext.lower() fb = String(fb).hyphenify(ascii=True) ...
write the contents of the file to a tempfile and return the tempfile filename def tempfile(self, mode='wb', **args): "write the contents of the file to a tempfile and return the tempfile filename" tf = tempfile.NamedTemporaryFile(mode=mode) self.write(tf.name, mode=mode, **args) return ...
delete the file from the filesystem. def delete(self): """delete the file from the filesystem.""" if self.isfile: os.remove(self.fn) elif self.isdir: shutil.rmtree(self.fn)
given a number of bytes, return the file size in readable units def readable_size(C, bytes, suffix='B', decimals=1, sep='\u00a0'): """given a number of bytes, return the file size in readable units""" if bytes is None: return size = float(bytes) for unit in C.SIZE_UNITS: ...
given a readable_size (as produced by File.readable_size()), return the number of bytes. def bytes_from_readable_size(C, size, suffix='B'): """given a readable_size (as produced by File.readable_size()), return the number of bytes.""" s = re.split("^([0-9\.]+)\s*([%s]?)%s?" % (''.join(C.SIZE_UNITS), su...
Executed on startup of application def run(self): """Executed on startup of application""" for wsock in self.wsocks: wsock.run() for api in self.apis: api.run()
Executed on shutdown of application def shutdown(self): """Executed on shutdown of application""" for wsock in self.wsocks: wsock.shutdown() for api in self.apis: api.shutdown()
Makes a HTTP call, formats response and does error handling. def request(self, url, method, data=None, headers=None): """Makes a HTTP call, formats response and does error handling. """ http_headers = merge_dict(self.default_headers, headers or {}) request_data = merge_dict({'api_key': ...
Makes a GET request def get(self, action, params=None, headers=None): """Makes a GET request """ return self.request(make_url(self.endpoint, action), method='GET', data=params, headers=headers)
Makes a GET request def post(self, action, data=None, headers=None): """Makes a GET request """ return self.request(make_url(self.endpoint, action), method='POST', data=data, headers=headers)
Makes a GET request def delete(self, action, headers=None): """Makes a GET request """ return self.request(make_url(self.endpoint, action), method='DELETE', headers=headers)
Calculates a good piece size for a size def calc_piece_size(size, min_piece_size=20, max_piece_size=29, max_piece_count=1000): """ Calculates a good piece size for a size """ logger.debug('Calculating piece size for %i' % size) for i in range(min_piece_size, max_piece_size): # 20 = 1MB if ...
Prepare a list of all pieces grouped together def split_pieces(piece_list, segments, num): """ Prepare a list of all pieces grouped together """ piece_groups = [] pieces = list(piece_list) while pieces: for i in range(segments): p = pieces[i::segments][:num] if n...
recursive glob, gets all files that match the pattern within the directory tree def rglob(dirname, pattern, dirs=False, sort=True): """recursive glob, gets all files that match the pattern within the directory tree""" fns = [] path = str(dirname) if os.path.isdir(path): fns = glob(os.path....
Create a new Future whose completion depends on parent futures The new future will have a function that it calls once all its parents have completed, the return value of which will be its final value. There is a special case, however, in which the dependent future's callback returns a future or list of...
Wait for the completion of any (the first) one of multiple futures :param list futures: A list of :class:`Future`\s :param timeout: The maximum time to wait. With ``None``, will block indefinitely. :type timeout: float or None :returns: One of the futures from the provided list -- the ...
Wait for the completion of all futures in a list :param list future: a list of :class:`Future`\s :param timeout: The maximum time to wait. With ``None``, can block indefinitely. :type timeout: float or None :raises WaitTimeout: if a timeout is provided and hit def wait_all(futures, timeout=No...
The final value, if it has arrived :raises: AttributeError, if not yet complete :raises: an exception if the Future was :meth:`abort`\ed def value(self): '''The final value, if it has arrived :raises: AttributeError, if not yet complete :raises: an exception if the Future was ...
Give the future it's value and trigger any associated callbacks :param value: the new value for the future :raises: :class:`AlreadyComplete <junction.errors.AlreadyComplete>` if already complete def finish(self, value): '''Give the future it's value and trigger any asso...
Finish this future (maybe early) in an error state Takes a standard exception triple as arguments (like returned by ``sys.exc_info``) and will re-raise them as the value. Any :class:`Dependents` that are children of this one will also be aborted. :param class klass: the class ...
Assign a callback function to be run when successfully complete :param function func: A callback to run when complete. It will be given one argument (the value that has arrived), and it's return value is ignored. def on_finish(self, func): '''Assign a callback function to be ru...
Assign a callback function to be run when :meth:`abort`\ed :param function func: A callback to run when aborted. It will be given three arguments: - ``klass``: the exception class - ``exc``: the exception instance - ``tb``: the traceback object assoc...
Create a new Future whose completion depends on this one The new future will have a function that it calls once all its parents have completed, the return value of which will be its final value. There is a special case, however, in which the dependent future's callback returns a future ...
The results that the RPC has received *so far* This may also be the complete results if :attr:`complete` is ``True``. def partial_results(self): '''The results that the RPC has received *so far* This may also be the complete results if :attr:`complete` is ``True``. ''' results...
transforms any os path into unix style def os_path_transform(self, s, sep=os.path.sep): """ transforms any os path into unix style """ if sep == '/': return s else: return s.replace(sep, '/')
replaces $tokens$ with values will be replaced with config rendering def transform(self, tr_list, files): """ replaces $tokens$ with values will be replaced with config rendering """ singular = False if not isinstance(files, list) and not isinstance(files, tuple)...
finds the destination based on source if source is an absolute path, and there's no pattern, it copies the file to base dst_dir def resolve_dst(self, dst_dir, src): """ finds the destination based on source if source is an absolute path, and there's no pattern, it copies the file to bas...
copy the zip file from its filename to the given filename. def write(self, fn=None): """copy the zip file from its filename to the given filename.""" fn = fn or self.fn if not os.path.exists(os.path.dirname(fn)): os.makedirs(os.path.dirname(fn)) f = open(self.fn, 'rb') ...
Merge new attributes def assign(self, attrs): """Merge new attributes """ for k, v in attrs.items(): setattr(self, k, v)
Normalizes a single rust frame with a function def normalize_rust_function(self, function, line): """Normalizes a single rust frame with a function""" # Drop the prefix and return type if there is any function = drop_prefix_and_return_type(function) # Collapse types function = ...
Normalizes a single cpp frame with a function def normalize_cpp_function(self, function, line): """Normalizes a single cpp frame with a function""" # Drop member function cv/ref qualifiers like const, const&, &, and && for ref in ('const', 'const&', '&&', '&'): if function.endswith(...