text
stringlengths
81
112k
computes the hash of all of the trigrams in the chunk using a window of length 5 def process(self, chunk): """ computes the hash of all of the trigrams in the chunk using a window of length 5 """ self._digest = None if isinstance(chunk, text_type): c...
using a threshold (mean of the accumulator), computes the nilsimsa digest def compute_digest(self): """ using a threshold (mean of the accumulator), computes the nilsimsa digest """ num_trigrams = 0 if self.num_char == 3: # 3 chars -> 1 trigram num_trigrams ...
read in a file and compute digest def from_file(self, fname): """read in a file and compute digest""" f = open(fname, "rb") data = f.read() self.update(data) f.close()
returns difference between the nilsimsa digests between the current object and a given digest def compare(self, digest_2, is_hex = False): """ returns difference between the nilsimsa digests between the current object and a given digest """ # convert hex string to list o...
Login api **Parameters:**: - **data**: Dictionary containing data to POST as JSON - **api_version**: API version to use (default v2.0) **Returns:** requests.Response object extended with cgx_status and cgx_content properties. def login(self, data, api_version="v2.0"): "...
Forgot password API **Parameters:**: - **data**: Dictionary containing data to POST as JSON - **tenant_id**: Tenant ID - **api_version**: API version to use (default v2.0) **Returns:** requests.Response object extended with cgx_status and cgx_content properties. def t...
verify the validity of the given file. Never trust the End-User def is_valid_file(parser,arg): """verify the validity of the given file. Never trust the End-User""" if not os.path.exists(arg): parser.error("File %s not found"%arg) else: return arg
Get the language ID of the input file language def getID(code_file): """Get the language ID of the input file language""" json_path = ghostfolder+'/'+json_file if os.path.exists(json_path): pass else: download_file('https://ghostbin.com/languages.json') lang = detect_lang(code_file) json_data = json.load(f...
Detect the language used in the given file. def detect_lang(path): """Detect the language used in the given file.""" blob = FileBlob(path, os.getcwd()) if blob.is_text: print('Programming language of the file detected: {0}'.format(blob.language.name)) return blob.language.name else:#images, binary and what-hav...
Specify given *android_serial* device to perform test. You do not have to specify the device when there is only one device connects to the computer. When you need to use multiple devices, do not use this keyword to switch between devices in test execution. Using different library name when im...
Click at (x,y) coordinates. def click_at_coordinates(self, x, y): """ Click at (x,y) coordinates. """ self.device.click(int(x), int(y))
Swipe from (sx, sy) to (ex, ey) with *steps* . Example: | Swipe By Coordinates | 540 | 1340 | 940 | 1340 | | # Swipe from (540, 1340) to (940, 100) with default steps 10 | | Swipe By Coordinates | 540 | 1340 | 940 | 1340 | 100 | # Swipe from (540, 1340) to (940, 100) with steps 100 |...
Swipe the UI object with *selectors* from center to left. Example: | Swipe Left | description=Home screen 3 | | # swipe the UI object left | | Swipe Left | 5 | description=Home screen 3 | # swipe the UI object left with steps=5 | ...
Swipe the UI object with *selectors* from center to right See `Swipe Left` for more details. def swipe_right(self, steps=10, *args, **selectors): """ Swipe the UI object with *selectors* from center to right See `Swipe Left` for more details. """ self.device(**selector...
Swipe the UI object with *selectors* from center to top See `Swipe Left` for more details. def swipe_top(self, steps=10, *args, **selectors): """ Swipe the UI object with *selectors* from center to top See `Swipe Left` for more details. """ self.device(**selectors).swi...
Swipe the UI object with *selectors* from center to bottom See `Swipe Left` for more details. def swipe_bottom(self, steps=10, *args, **selectors): """ Swipe the UI object with *selectors* from center to bottom See `Swipe Left` for more details. """ self.device(**selec...
Drag from (sx, sy) to (ex, ey) with steps See `Swipe By Coordinates` also. def drag_by_coordinates(self,sx, sy, ex, ey, steps=10): """ Drag from (sx, sy) to (ex, ey) with steps See `Swipe By Coordinates` also. """ self.device.drag(sx, sy, ex, ey, steps)
Wait for the object which has *selectors* within the given timeout. Return true if the object *appear* in the given timeout. Else return false. def wait_for_exists(self, timeout=0, *args, **selectors): """ Wait for the object which has *selectors* within the given timeout. Return true...
Wait for the object which has *selectors* within the given timeout. Return true if the object *disappear* in the given timeout. Else return false. def wait_until_gone(self, timeout=0, *args, **selectors): """ Wait for the object which has *selectors* within the given timeout. Return t...
Perform fling forward (horizontally)action on the object which has *selectors* attributes. Return whether the object can be fling or not. def fling_forward_horizontally(self, *args, **selectors): """ Perform fling forward (horizontally)action on the object which has *selectors* attributes. ...
Perform fling backward (horizontally)action on the object which has *selectors* attributes. Return whether the object can be fling or not. def fling_backward_horizontally(self, *args, **selectors): """ Perform fling backward (horizontally)action on the object which has *selectors* attributes. ...
Perform fling forward (vertically)action on the object which has *selectors* attributes. Return whether the object can be fling or not. def fling_forward_vertically(self, *args, **selectors): """ Perform fling forward (vertically)action on the object which has *selectors* attributes. ...
Perform fling backward (vertically)action on the object which has *selectors* attributes. Return whether the object can be fling or not. def fling_backward_vertically(self, *args, **selectors): """ Perform fling backward (vertically)action on the object which has *selectors* attributes. ...
Scroll the object which has *selectors* attributes to *beginning* horizontally. See `Scroll Forward Vertically` for more details. def scroll_to_beginning_horizontally(self, steps=10, *args,**selectors): """ Scroll the object which has *selectors* attributes to *beginning* horizontally. ...
Scroll the object which has *selectors* attributes to *end* horizontally. See `Scroll Forward Vertically` for more details. def scroll_to_end_horizontally(self, steps=10, *args, **selectors): """ Scroll the object which has *selectors* attributes to *end* horizontally. See `Scroll For...
Perform scroll forward (horizontally)action on the object which has *selectors* attributes. Return whether the object can be Scroll or not. See `Scroll Forward Vertically` for more details. def scroll_forward_horizontally(self, steps=10, *args, **selectors): """ Perform scroll forward...
Perform scroll backward (horizontally)action on the object which has *selectors* attributes. Return whether the object can be Scroll or not. See `Scroll Forward Vertically` for more details. def scroll_backward_horizontally(self, steps=10, *args, **selectors): """ Perform scroll backw...
Scroll(horizontally) on the object: obj to specific UI object which has *selectors* attributes appears. Return true if the UI object, else return false. See `Scroll To Vertically` for more details. def scroll_to_horizontally(self, obj, *args,**selectors): """ Scroll(horizontally) on t...
Scroll the object which has *selectors* attributes to *beginning* vertically. See `Scroll Forward Vertically` for more details. def scroll_to_beginning_vertically(self, steps=10, *args,**selectors): """ Scroll the object which has *selectors* attributes to *beginning* vertically. See ...
Scroll the object which has *selectors* attributes to *end* vertically. See `Scroll Forward Vertically` for more details. def scroll_to_end_vertically(self, steps=10, *args, **selectors): """ Scroll the object which has *selectors* attributes to *end* vertically. See `Scroll Forward V...
Perform scroll forward (vertically)action on the object which has *selectors* attributes. Return whether the object can be Scroll or not. Example: | ${can_be_scroll} | Scroll Forward Vertically | className=android.widget.ListView | | # Scroll forward the...
Perform scroll backward (vertically)action on the object which has *selectors* attributes. Return whether the object can be Scroll or not. See `Scroll Forward Vertically` for more details. def scroll_backward_vertically(self, steps=10, *args, **selectors): """ Perform scroll backward ...
Scroll(vertically) on the object: obj to specific UI object which has *selectors* attributes appears. Return true if the UI object, else return false. Example: | ${list} | Get Object | className=android.widget.ListView | | # Get the list object | | ${...
Take a screenshot of device and log in the report with timestamp, scale for screenshot size and quality for screenshot quality default scale=1.0 quality=100 def screenshot(self, scale=None, quality=None): """ Take a screenshot of device and log in the report with timestamp, scale for screenshot...
The watcher click on the object which has the *selectors* when conditions match. def register_click_watcher(self, watcher_name, selectors, *condition_list): """ The watcher click on the object which has the *selectors* when conditions match. """ watcher = self.device.watcher(watcher_nam...
The watcher perform *press_keys* action sequentially when conditions match. def register_press_watcher(self, watcher_name, press_keys, *condition_list): """ The watcher perform *press_keys* action sequentially when conditions match. """ def unicode_to_list(a_unicode): a_list...
Remove watcher with *watcher_name* or remove all watchers. def remove_watchers(self, watcher_name = None): """ Remove watcher with *watcher_name* or remove all watchers. """ if watcher_name == None: self.device.watchers.remove() else: self.device.watchers...
Return the count of UI object with *selectors* Example: | ${count} | Get Count | text=Accessibility | # Get the count of UI object text=Accessibility | | ${accessibility_text} | Get Object | text=Accessibility | # These two keywords combination ...
return info dictionary of the *obj* The info example: { u'contentDescription': u'', u'checked': False, u'scrollable': True, u'text': u'', u'packageName': u'com.android.launcher', u'selected': False, u'enabled': True, u'bounds': ...
This keyword can use object method from original python uiautomator See more details from https://github.com/xiaocong/uiautomator Example: | ${accessibility_text} | Get Object | text=Accessibility | # Get the UI object | | Call | ${ac...
Set *input_text* to the UI object with *selectors* def set_text(self, input_text, *args, **selectors): """ Set *input_text* to the UI object with *selectors* """ self.device(**selectors).set_text(input_text)
Clear text of the UI object with *selectors* def clear_text(self, *args, **selectors): """ Clear text of the UI object with *selectors* """ while True: target = self.device(**selectors) text = target.info['text'] target.clear_text() rema...
Open notification Built in support for Android 4.3 (API level 18) Using swipe action as a workaround for API level lower than 18 def open_notification(self): """ Open notification Built in support for Android 4.3 (API level 18) Using swipe action as a workaround for ...
Sleep(no action) for *time* (in millisecond) def sleep(self, time): """ Sleep(no action) for *time* (in millisecond) """ target = 'wait for %s' % str(time) self.device(text=target).wait.exists(timeout=time)
[Test Agent] Connect to *ssid* with *password* def connect_to_wifi(self, ssid, password=None): """ [Test Agent] Connect to *ssid* with *password* """ cmd = 'am broadcast -a testagent -e action CONNECT_TO_WIFI -e ssid %s -e password %s' % (ssid, password) self.a...
Merge two precomputed similarity lists, truncating the result to `clip` most similar items. def merge_sims(oldsims, newsims, clip=None): """Merge two precomputed similarity lists, truncating the result to `clip` most similar items.""" if oldsims is None: result = newsims or [] elif newsims is None:...
Delete all files created by this index, invalidating `self`. Use with care. def terminate(self): """Delete all files created by this index, invalidating `self`. Use with care.""" try: self.id2sims.terminate() except: pass import glob for fname in glob.glo...
Update fresh index with new documents (potentially replacing old ones with the same id). `fresh_docs` is a dictionary-like object (=dict, sqlitedict, shelve etc) that maps document_id->document. def index_documents(self, fresh_docs, model): """ Update fresh index with new documents (pot...
Update id->pos mapping with new document ids. def update_ids(self, docids): """Update id->pos mapping with new document ids.""" logger.info("updating %i id mappings" % len(docids)) for docid in docids: if docid is not None: pos = self.id2pos.get(docid, None) ...
Synchronize id<->position mappings. def update_mappings(self): """Synchronize id<->position mappings.""" self.pos2id = dict((v, k) for k, v in self.id2pos.iteritems()) assert len(self.pos2id) == len(self.id2pos), "duplicate ids or positions detected"
Delete documents (specified by their ids) from the index. def delete(self, docids): """Delete documents (specified by their ids) from the index.""" logger.debug("deleting %i documents from %s" % (len(docids), self)) deleted = 0 for docid in docids: try: del s...
Convert raw similarity vector to a list of (docid, similarity) results. def sims2scores(self, sims, eps=1e-7): """Convert raw similarity vector to a list of (docid, similarity) results.""" result = [] if isinstance(sims, numpy.ndarray): sims = abs(sims) # TODO or maybe clip? are opp...
Return indexed vector corresponding to document `docid`. def vec_by_id(self, docid): """Return indexed vector corresponding to document `docid`.""" pos = self.id2pos[docid] return self.qindex.vector_by_id(pos)
Find the most similar documents to the (already indexed) document with `docid`. def sims_by_id(self, docid): """Find the most similar documents to the (already indexed) document with `docid`.""" result = self.id2sims.get(docid, None) if result is None: self.qindex.num_best = self.to...
Find the most similar documents to a given vector (=already processed document). def sims_by_vec(self, vec, normalize=None): """ Find the most similar documents to a given vector (=already processed document). """ if normalize is None: normalize = self.qindex.normalize ...
Merge documents from the other index. Update precomputed similarities in the process. def merge(self, other): """Merge documents from the other index. Update precomputed similarities in the process.""" other.qindex.normalize, other.qindex.num_best = False, self.topsims # update ...
Convert a single SimilarityDocument to vector. def doc2vec(self, doc): """Convert a single SimilarityDocument to vector.""" bow = self.dictionary.doc2bow(doc['tokens']) if self.method == 'lsi': return self.lsi[self.tfidf[bow]] elif self.method == 'lda': return se...
Convert multiple SimilarityDocuments to vectors (batch version of doc2vec). def docs2vecs(self, docs): """Convert multiple SimilarityDocuments to vectors (batch version of doc2vec).""" bows = (self.dictionary.doc2bow(doc['tokens']) for doc in docs) if self.method == 'lsi': return se...
Commit all changes, clear all caches. def flush(self, save_index=False, save_model=False, clear_buffer=False): """Commit all changes, clear all caches.""" if save_index: if self.fresh_index is not None: self.fresh_index.save(self.location('index_fresh')) if self....
Explicitly close open file handles, databases etc. def close(self): """Explicitly close open file handles, databases etc.""" try: self.payload.close() except: pass try: self.model.close() except: pass try: self....
Add a sequence of documents to be processed (indexed or trained on). Here, the documents are simply collected; real processing is done later, during the `self.index` or `self.train` calls. `buffer` can be called repeatedly; the result is the same as if it was called once, with a concat...
Create an indexing model. Will overwrite the model if it already exists. All indexes become invalid, because documents in them use a now-obsolete representation. The model is trained on documents previously entered via `buffer`, or directly on `corpus`, if specified. def train(self, co...
Permanently index all documents previously added via `buffer`, or directly index documents from `corpus`, if specified. The indexing model must already exist (see `train`) before this function is called. def index(self, corpus=None, clear_buffer=True): """ Permanently index all...
Precompute top similarities for all indexed documents. This speeds up `find_similar` queries by id (but not queries by fulltext). Internally, documents are moved from a fresh index (=no precomputed similarities) to an optimized index (precomputed similarities). Similarity queries always ...
Drop all indexed documents. If `keep_model` is False, also dropped the model. def drop_index(self, keep_model=True): """Drop all indexed documents. If `keep_model` is False, also dropped the model.""" modelstr = "" if keep_model else "and model " logger.info("deleting similarity index " + model...
Delete specified documents from the index. def delete(self, docids): """Delete specified documents from the index.""" logger.info("asked to drop %i documents" % len(docids)) for index in [self.opt_index, self.fresh_index]: if index is not None: index.delete(docids) ...
Find `max_results` most similar articles in the index, each having similarity score of at least `min_score`. The resulting list may be shorter than `max_results`, in case there are not enough matching documents. `doc` is either a string (=document id, previously indexed) or a dict conta...
Return ids of all indexed documents. def keys(self): """Return ids of all indexed documents.""" result = [] if self.fresh_index is not None: result += self.fresh_index.keys() if self.opt_index is not None: result += self.opt_index.keys() return result
Make sure a session is open. If it's not and autosession is turned on, create a new session automatically. If it's not and autosession is off, raise an exception. def check_session(self): """ Make sure a session is open. If it's not and autosession is turned on, create a new s...
Open a new session to modify this server. You can either call this fnc directly, or turn on autosession which will open/commit sessions for you transparently. def open_session(self): """ Open a new session to modify this server. You can either call this fnc directly, or turn o...
Buffer documents, in the current session def buffer(self, *args, **kwargs): """Buffer documents, in the current session""" self.check_session() result = self.session.buffer(*args, **kwargs) return result
Index documents, in the current session def index(self, *args, **kwargs): """Index documents, in the current session""" self.check_session() result = self.session.index(*args, **kwargs) if self.autosession: self.commit() return result
Drop all indexed documents from the session. Optionally, drop model too. def drop_index(self, keep_model=True): """Drop all indexed documents from the session. Optionally, drop model too.""" self.check_session() result = self.session.drop_index(keep_model) if self.autosession: ...
Delete documents from the current session. def delete(self, docids): """Delete documents from the current session.""" self.check_session() result = self.session.delete(docids) if self.autosession: self.commit() return result
Optimize index for faster by-document-id queries. def optimize(self): """Optimize index for faster by-document-id queries.""" self.check_session() result = self.session.optimize() if self.autosession: self.commit() return result
Commit changes made by the latest session. def commit(self): """Commit changes made by the latest session.""" if self.session is not None: logger.info("committing transaction in %s" % self) tmp = self.stable self.stable, self.session = self.session, None ...
Ignore all changes made in the latest session (terminate the session). def rollback(self): """Ignore all changes made in the latest session (terminate the session).""" if self.session is not None: logger.info("rolling back transaction in %s" % self) self.session.close() ...
Turn autosession (automatic committing after each modification call) on/off. If value is None, only query the current value (don't change anything). def set_autosession(self, value=None): """ Turn autosession (automatic committing after each modification call) on/off. If value is None, ...
Delete all files created by this server, invalidating `self`. Use with care. def terminate(self): """Delete all files created by this server, invalidating `self`. Use with care.""" logger.info("deleting entire server %s" % self) self.close() try: shutil.rmtree(self.basedir) ...
Find similar articles. With autosession off, use the index state *before* current session started, so that changes made in the session will not be visible here. With autosession on, close the current session first (so that session changes *are* committed and visible). def find_similar(...
Fetch a profile. async def profile(self, ctx, platform, name): '''Fetch a profile.''' player = await self.client.get_player(platform, name) solos = await player.get_solos() await ctx.send("# of kills in solos for {}: {}".format(name,solos.kills.value))
Begins watching source files for changes. .. versionchanged:: 4.1 The ``io_loop`` argument is deprecated. def start(io_loop=None, check_time=2): """Begins watching source files for changes. .. versionchanged:: 4.1 The ``io_loop`` argument is deprecated. """ io_loop = io_loop or asy...
Yield 'chunk_size' items from 'data' at a time. def generate_chunks(data, chunk_size=DEFAULT_CHUNK_SIZE): """Yield 'chunk_size' items from 'data' at a time.""" iterator = iter(repeated.getvalues(data)) while True: chunk = list(itertools.islice(iterator, chunk_size)) if not chunk: ...
Repeatedly call fold and merge on data and then finalize. Arguments: data: Input for the fold function. reducer: The IReducer to use. chunk_size: How many items should be passed to fold at a time? Returns: Return value of finalize. def reduce(reducer, data, chunk_size=DEFAULT_...
The if-else pairs. def conditions(self): """The if-else pairs.""" for idx in six.moves.range(1, len(self.children), 2): yield (self.children[idx - 1], self.children[idx])
**Purpose**: Substitute placeholders in staging attributes of a Task with actual paths to the corresponding tasks. :arguments: :path: string describing the staging paths, possibly containing a placeholder :placeholder_dict: dictionary holding the values for placeholders def resolve_placeholders(pa...
Purpose: Parse a Task object to extract the files to be staged as the output. Details: The extracted data is then converted into the appropriate RP directive depending on whether the data is to be copied/downloaded. :arguments: :task: EnTK Task object :placeholder_dict: dictionary holding ...
Purpose: Parse a Task object to extract the files to be staged as the output. Details: The extracted data is then converted into the appropriate RP directive depending on whether the data is to be copied/downloaded. :arguments: :task: EnTK Task object :placeholder_dict: dictionary holding ...
Purpose: Create a Compute Unit description based on the defined Task. :arguments: :task: EnTK Task object :placeholder_dict: dictionary holding the values for placeholders :return: ComputeUnitDescription def create_cud_from_task(task, placeholder_dict, prof=None): """ Purpose: Create ...
Purpose: Create a Task based on the Compute Unit. Details: Currently, only the uid, parent_stage and parent_pipeline are retrieved. The exact initial Task (that was converted to a CUD) cannot be recovered as the RP API does not provide the same attributes for a CU as for a CUD. Also, this is not required f...
Send Report E-mails. def handle_noargs(self, **options): """Send Report E-mails.""" r = get_r() since = datetime.utcnow() - timedelta(days=1) metrics = {} categories = r.metric_slugs_by_category() for category_name, slug_list in categories.items(): metrics[c...
Unique ID of the current stage (fully qualified). example: >>> stage.luid pipe.0001.stage.0004 :getter: Returns the fully qualified uid of the current stage :type: String def luid(self): """ Unique ID of the current stage (fully qualified). exa...
Adds tasks to the existing set of tasks of the Stage :argument: set of tasks def add_tasks(self, value): """ Adds tasks to the existing set of tasks of the Stage :argument: set of tasks """ tasks = self._validate_entities(value) self._tasks.update(tasks) ...
Convert current Stage into a dictionary :return: python dictionary def to_dict(self): """ Convert current Stage into a dictionary :return: python dictionary """ stage_desc_as_dict = { 'uid': self._uid, 'name': self._name, 'state': ...
Create a Stage from a dictionary. The change is in inplace. :argument: python dictionary :return: None def from_dict(self, d): """ Create a Stage from a dictionary. The change is in inplace. :argument: python dictionary :return: None """ if 'uid' in d:...
Purpose: Set state of all tasks of the current stage. :arguments: String def _set_tasks_state(self, value): """ Purpose: Set state of all tasks of the current stage. :arguments: String """ if value not in states.state_numbers.keys(): raise ValueError(obj=se...
Purpose: Check if all tasks of the current stage have completed, i.e., are in either DONE or FAILED state. def _check_stage_complete(self): """ Purpose: Check if all tasks of the current stage have completed, i.e., are in either DONE or FAILED state. """ try: for task in s...
Purpose: Validate whether the 'tasks' is of type set. Validate the description of each Task. def _validate_entities(self, tasks): """ Purpose: Validate whether the 'tasks' is of type set. Validate the description of each Task. """ if not tasks: raise TypeError(expected_type...
Purpose: Assign a uid to the current object based on the sid passed. Pass the current uid to children of current object def _assign_uid(self, sid): """ Purpose: Assign a uid to the current object based on the sid passed. Pass the current uid to children of current object """ ...
Purpose: Assign the parent Stage and the parent Pipeline to all the tasks of the current stage. :arguments: set of Tasks (optional) :return: list of updated Tasks def _pass_uid(self): """ Purpose: Assign the parent Stage and the parent Pipeline to all the tasks of the current stage. ...