text_prompt
stringlengths
157
13.1k
code_prompt
stringlengths
7
19.8k
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def div(self, key, value=2): """Divides the specified key value by the specified value. :param str|unicode key: :param int value: :rtype: bool """
return uwsgi.cache_mul(key, value, self.timeout, self.name)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def recv(request_context=None, non_blocking=False): """Receives data from websocket. :param request_context: :param bool non_blocking: :rtype: bytes|str :raises ...
if non_blocking: result = uwsgi.websocket_recv_nb(request_context) else: result = uwsgi.websocket_recv(request_context) return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def send(message, request_context=None, binary=False): """Sends a message to websocket. :param str message: data to send :param request_context: :raises IOError:...
if binary: return uwsgi.websocket_send_binary(message, request_context) return uwsgi.websocket_send(message, request_context)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def parser_feed(parser, text): """Direct wrapper over cmark_parser_feed."""
encoded_text = text.encode('utf-8') return _cmark.lib.cmark_parser_feed( parser, encoded_text, len(encoded_text))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def find_syntax_extension(name): """Direct wrapper over cmark_find_syntax_extension."""
encoded_name = name.encode('utf-8') extension = _cmark.lib.cmark_find_syntax_extension(encoded_name) if extension == _cmark.ffi.NULL: return None else: return extension
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_item(self, key, value, cache_name=None): """Add an item into the given cache. This is a commodity option (mainly useful for testing) allowing you to stor...
cache_name = cache_name or '' value = '%s %s=%s' % (cache_name, key, value) self._set('add-cache-item', value.strip(), multi=True) return self._section
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_file(self, filepath, gzip=False, cache_name=None): """Load a static file in the cache. .. note:: Items are stored with the filepath as is (relative or ab...
command = 'load-file-in-cache' if gzip: command += '-gzip' cache_name = cache_name or '' value = '%s %s' % (cache_name, filepath) self._set(command, value.strip(), multi=True) return self._section
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def register_timer(period, target=None): """Add timer. Can be used as a decorator: .. code-block:: python @register_timer(3) def repeat(): do() :param int perio...
return _automate_signal(target, func=lambda sig: uwsgi.add_timer(int(sig), period))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def register_cron(weekday=None, month=None, day=None, hour=None, minute=None, target=None): """Adds cron. The interface to the uWSGI signal cron facility. .. cod...
task_args_initial = {name: val for name, val in locals().items() if val is not None and name != 'target'} task_args_casted = {} def skip_task(check_funcs): now = datetime.now() allright = all((func(now) for func in check_funcs)) return not allright def check_date(now, attr, ta...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def truncate_ellipsis(line, length=30):
l = len(line) return line if l < length else line[:length - 3] + "..."
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def pyle_evaluate(expressions=None, modules=(), inplace=False, files=None, print_traceback=False): """The main method of pyle."""
eval_globals = {} eval_globals.update(STANDARD_MODULES) for module_arg in modules or (): for module in module_arg.strip().split(","): module = module.strip() if module: eval_globals[module] = __import__(module) if not expressions: # Default 'd...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def pyle(argv=None): """Execute pyle with the specified arguments, or sys.argv if no arguments specified."""
parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("-m", "--modules", dest="modules", action='append', help="import MODULE before evaluation. May be specified more than once.") parser.add_argument("-i", "--inplace", dest="inplace", action='store_true', default=False, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_login_form_component(self): """Initializes and returns the login form component @rtype: LoginForm @return: Initialized component """
self.dw.wait_until( lambda: self.dw.is_present(LoginForm.locators.form), failure_message='login form was never present so could not get the model ' 'upload form component' ) self.login_form = LoginForm( parent_page=self, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def __add_query_comment(sql): """ Adds a comment line to the query to be executed containing the line number of the calling function. This is useful for debuggin...
# Inspect the call stack for the originating call file_name = '' line_number = '' caller_frames = inspect.getouterframes(inspect.currentframe()) for frame in caller_frames: if "ShapewaysDb" not in frame[1]: file_name = frame[1] line_nu...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_single_instance(sql, class_type, *args, **kwargs): """Returns an instance of class_type populated with attributes from the DB record; throws an error if ...
record = CoyoteDb.get_single_record(sql, *args, **kwargs) try: instance = CoyoteDb.get_object_from_dictionary_representation(dictionary=record, class_type=class_type) except AttributeError: raise NoRecordsFoundException('No records found for {class_type} with sql run on ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_all_instances(sql, class_type, *args, **kwargs): """Returns a list of instances of class_type populated with attributes from the DB record @param sql: Sq...
records = CoyoteDb.get_all_records(sql, *args, **kwargs) instances = [CoyoteDb.get_object_from_dictionary_representation( dictionary=record, class_type=class_type) for record in records] for instance in instances: instance._query = sql return instances
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def escape_dictionary(dictionary, datetime_format='%Y-%m-%d %H:%M:%S'): """Escape dictionary values with keys as column names and values column values @type dict...
for k, v in dictionary.iteritems(): if isinstance(v, datetime.datetime): v = v.strftime(datetime_format) if isinstance(v, basestring): v = CoyoteDb.db_escape(str(v)) v = '"{}"'.format(v) if v is True: v = 1 ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_insert_fields_and_values_from_dict(dictionary, datetime_format='%Y-%m-%d %H:%M:%S', db_escape=True): """Formats a dictionary to strings of fields and val...
if db_escape: CoyoteDb.escape_dictionary(dictionary, datetime_format=datetime_format) fields = get_delimited_string_from_list(dictionary.keys(), delimiter=',') # keys have no quotes vals = get_delimited_string_from_list(dictionary.values(), delimiter=',') # strings get quotes ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_kwargs(**kwargs): """This method should be used in query functions where user can query on any number of fields """
d = dict() for k, v in kwargs.iteritems(): if v is not NOTSET: d[k] = v return d
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_update_clause_from_dict(dictionary, datetime_format='%Y-%m-%d %H:%M:%S'): """Builds the update values clause of an update statement based on the dictiona...
items = [] CoyoteDb.escape_dictionary(dictionary, datetime_format=datetime_format) for k,v in dictionary.iteritems(): item = '{k} = {v}'.format(k=k, v=v) items.append(item) clause = ', '.join(item for item in items) return clause
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_where_clause_from_dict(dictionary, join_operator='AND'): """Builds a where clause from a dictionary """
CoyoteDb.escape_dictionary(dictionary) clause = join_operator.join( (' {k} is {v} ' if str(v).lower() == 'null' else ' {k} = {v} ').format(k=k, v=v) # IS should be the operator for null values for k, v in dictionary.iteritems()) return clause
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_dictionary_representation_of_object_attributes(obj, omit_null_fields=False): """Returns a dictionary of object's attributes, ignoring methods @param obj:...
obj_dictionary = obj.__dict__ obj_dictionary_temp = obj_dictionary.copy() for k, v in obj_dictionary.iteritems(): if omit_null_fields: if v is None: obj_dictionary_temp.pop(k, None) if k.startswith('_'): obj_dictionary...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def build_where_clause(mappings, operator='AND'): """Constructs the where clause based on a dictionary of values """
where_clause_mappings = {} where_clause_mappings.update(mappings) where_clause = 'WHERE ' + ' {} '.format(operator).join( '{k} = {v}'.format(k=k, v='"{}"'.format(v) if isinstance(v, basestring) else v) for k, v in where_clause_mappings.iteritems() ) retu...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def execute_and_commit(*args, **kwargs): """Executes and commits the sql statement @return: None """
db, cursor = CoyoteDb.execute(*args, **kwargs) db.commit() return cursor
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def update(sql, *args, **kwargs): """Updates and commits with an insert sql statement, returns the record, but with a small chance of a race condition @param sql...
assert "update" in sql.lower(), 'This function requires an update statement, provided: {}'.format(sql) cursor = CoyoteDb.execute_and_commit(sql, *args, **kwargs) # now get that id last_row_id = cursor.lastrowid return last_row_id
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def delete(sql, *args, **kwargs): """Deletes and commits with an insert sql statement"""
assert "delete" in sql.lower(), 'This function requires a delete statement, provided: {}'.format(sql) CoyoteDb.execute_and_commit(sql, *args, **kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def update_object_from_dictionary_representation(dictionary, instance): """Given a dictionary and an object instance, will set all object attributes equal to the...
for key, value in dictionary.iteritems(): if hasattr(instance, key): setattr(instance, key, value) return instance
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def format_time(time): """Formats a time to be Shapeways database-compatible @param time: Datetime or string object to format @rtype: str @return: Time formatted...
# Handle time typing try: time = time.isoformat() except AttributeError: # Not a datetime object time = str(time) time = parser.parse(time).strftime('%Y-%m-%d %H:%M:%S') return time
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def format_date(date): """Formats a date to be Shapeways database-compatible @param date: Datetime or string object to format @rtype: str @return: Date formatted...
# Handle time typing try: date = date.isoformat() except AttributeError: # Not a datetime object date = str(date) date = parser.parse(date).strftime('%Y-%m-%d') return date
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def visit(self, url=''): """ Driver gets the provided url in the browser, returns True if successful url -- An absolute or relative url stored as a string """
def _visit(url): if len(url) > 0 and url[0] == '/': # url's first character is a forward slash; treat as relative path path = url full_url = self.driver.current_url parsed_url = urlparse(full_url) base_url = str(parsed_...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def is_alert_present(self): """Tests if an alert is present @return: True if alert is present, False otherwise """
current_frame = None try: current_frame = self.driver.current_window_handle a = self.driver.switch_to_alert() a.text except NoAlertPresentException: # No alert return False except UnexpectedAlertPresentException: # ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def find(self, locator, find_all=False, search_object=None, force_find=False, exclude_invisible=False): """ Attempts to locate an element, trying the number of t...
search_object = self.driver if search_object is None else search_object attempts = 0 while attempts < self.find_attempts + 1: if bool(force_find): js_locator = self.locator_handler.parse_locator(locator) if js_locator.By != 'css selector': ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _find_immediately(self, locator, search_object=None): ''' Attempts to immediately find elements on the page without waiting @type locator: webdriverwrapper.support.locator.Locator @param locator: Locator object describing @type search_object: webdriverwra...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def find_all(self, locator, search_object=None, force_find=False): ''' Find all elements matching locator @type locator: webdriverwrapper.support.locator.Locator @param locator: Locator object describing @rtype: list[WebElementWrapper] @...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def find_by_dynamic_locator(self, template_locator, variables, find_all=False, search_object=None): ''' Find with dynamic locator @type template_locator: webdriverwrapper.support.locator.Locator @param template_locator: Template locator w/ formatting bits to insert ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def is_present(self, locator, search_object=None): """ Determines whether an element is present on the page, retrying once if unable to locate @type locator: web...
all_elements = self._find_immediately(locator, search_object=search_object) if all_elements is not None and len(all_elements) > 0: return True else: return False
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def is_present_no_wait(self, locator): """ Determines whether an element is present on the page with no wait @type locator: webdriverwrapper.support.locator.Loca...
# first attempt to locate the element def execute(): ''' Generic function to execute wait ''' return True if len(self.locator_handler.find_by_locator(self.driver, locator, True)) < 0 else False return self.execute_and_handle_webdriver_exception...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def wait_until_present(self, locator, timeout=None, failure_message='Timeout waiting for element to be present'): """ Waits for an element to be present @type lo...
timeout = timeout if timeout is not None else self.timeout def wait(): ''' Wait function passed to executor ''' element = WebDriverWait(self.driver, timeout).until(EC.presence_of_element_located( (self.locator_handler.parse_locator(locato...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def wait_until_not_present(self, locator, timeout=None): """ Waits for an element to no longer be present @type locator: webdriverwrapper.support.locator.Locator...
# TODO: rethink about neg case with is_present and waiting too long timeout = timeout if timeout is not None else self.timeout this = self # for passing WebDriverWrapperReference to WebDriverWait def wait(): ''' Wait function pasted to executor ''' ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def wait_until_invisibility_of(self, locator, timeout=None): """ Waits for an element to be invisible @type locator: webdriverwrapper.support.locator.Locator @pa...
timeout = timeout if timeout is not None else self.timeout def wait(): ''' Wait function passed to executor ''' element = WebDriverWait(self.driver, timeout).until(EC.invisibility_of_element_located( (self.locator_handler.parse_locator(lo...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def wait_until_clickable(self, locator, timeout=None): """ Waits for an element to be clickable @type locator: webdriverwrapper.support.locator.Locator @param lo...
timeout = timeout if timeout is not None else self.timeout def wait(): ''' Wait function passed to executor ''' element = WebDriverWait(self.driver, timeout).until(EC.element_to_be_clickable( (self.locator_handler.parse_locator(locator).B...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def wait_until_stale(self, locator, timeout=None): """ Waits for an element to be stale in the DOM @type locator: webdriverwrapper.support.locator.Locator @param...
timeout = timeout if timeout is not None else self.timeout def wait(): ''' Wait function passed to executor ''' element = WebDriverWait(self.driver, timeout).until(EC.staleness_of( (self.locator_handler.parse_locator(locator).By, self.loc...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def wait_until_alert_is_present(self, timeout=None): """ Waits for an alert to be present @type timeout: int @param timeout: the maximum number of seconds the dr...
timeout = timeout if timeout is not None else self.timeout locator = None def wait(): ''' Wait function passed to executor ''' return WebDriverWait(self.driver, timeout).until(EC.alert_is_present()) return self.execute_and_handle_webdriv...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def wait_until_text_is_not_empty(self, locator, timeout=None): """ Waits for an element's text to not be empty @type locator: webdriverwrapper.support.locator.Lo...
timeout = timeout if timeout is not None else self.timeout self.wait_for(locator) # first check that element exists def wait(): ''' Wait function passed to executor ''' WebDriverWait(self.driver, timeout).until(lambda d: len(self.find(locator).t...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def wait_until_jquery_requests_are_closed(self, timeout=None): """Waits for AJAX requests made through @type timeout: int @param timeout: the maximum number of s...
timeout = timeout if timeout is not None else self.timeout def wait(): ''' Wait function passed to executor ''' WebDriverWait(self.driver, timeout).until( lambda d: self.js_executor.execute_template('isJqueryAjaxComplete', {})) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def execute_and_handle_webdriver_exceptions(self, function_to_execute, timeout=None, locator=None, failure_message=None): """ Executor for wait functions @type f...
logger = logging.getLogger(__name__) try: val = function_to_execute() for cb in self.action_callbacks: cb.__call__(self) return val except TimeoutException: raise WebDriverTimeoutException.WebDriverTimeoutException(self, timeout, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def pause_and_wait_for_user(self, timeout=None, prompt_text='Click to resume (WebDriver is paused)'): """Injects a radio button into the page and waits for the u...
timeout = timeout if timeout is not None else self.user_wait_timeout # Set the browser state paused self.paused = True def check_user_ready(driver): """Polls for the user to be "ready" (meaning they checked the checkbox) and the driver to be unpaused. If the che...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_browser_log(self, levels=None): """Gets the console log of the browser @type levels: @return: List of browser log entries """
logs = self.driver.get_log('browser') self.browser_logs += logs if levels is not None: logs = [entry for entry in logs if entry.get(u'level') in levels] return logs
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def quit(self): """Close driver and kill all associated displays """
# Kill the driver def _quit(): try: self.driver.quit() except Exception, err_driver: os.kill(self.driver_pid, signal.SIGKILL) raise finally: # Kill the display for this driver window try...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def visit(self, url=''): """Visit the url, checking for rr errors in the response @param url: URL @return: Visit result """
result = super(CoyoteDriver, self).visit(url) source = self.page_source() return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def load_config_vars(target_config, source_config): """Loads all attributes from source config into target config @type target_config: TestRunConfigManager @para...
# Overwrite all attributes in config with new config for attr in dir(source_config): # skip all private class attrs if attr.startswith('_'): continue val = getattr(source_config, attr) if val is not None: setattr(target_config, attr, val)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def run_parallel(*functions): """Runs a series of functions in parallel. Return values are ordered by the order in which their functions were passed. If an excep...
def target(fn): def wrapped(results_queue, error_queue, index): result = None try: result = fn() except Exception, e: # Swallow errors or else the process will hang error_queue.put(e) warnings.warn('Exception raised in par...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def copy_and_update(dictionary, update): """Returns an updated copy of the dictionary without modifying the original"""
newdict = dictionary.copy() newdict.update(update) return newdict
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_static_directory(): """Retrieves the full path of the static directory @return: Full path of the static directory """
directory = templates_dir = os.path.join(os.path.dirname(__file__), 'static') return directory
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def read_html_file(filename): """Reads the contents of an html file in the css directory @return: Contents of the specified file """
with open(os.path.join(get_static_directory(), 'html/{filename}'.format(filename=filename))) as f: contents = f.read() return contents
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def parse_locator(locator): """ Parses a valid selenium By and value from a locator; returns as a named tuple with properties 'By' and 'value' locator -- a valid...
# handle backwards compatibility to support new Locator class if isinstance(locator, loc.Locator): locator = '{by}={locator}'.format(by=locator.by, locator=locator.locator) locator_tuple = namedtuple('Locator', 'By value') if locator.count('=') > 0 and locator.count('css=...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def spin_assert(self, assertion, failure_message='Failed Assertion', timeout=None): """ Asserts that assertion function passed to it will return True, trying eve...
timeout = self.timeout if timeout is None else timeout time_spent = 0 while time_spent < timeout: try: assert assertion() is True return True except AssertionError: pass sleep(self.step) time_spent +...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def webdriver_assert(self, assertion, failure_message='Failed Assertion'): """ Assert the assertion, but throw a WebDriverAssertionException if assertion fails "...
try: assert assertion() is True except AssertionError: raise WebDriverAssertionException.WebDriverAssertionException(self.driver_wrapper, failure_message) return True
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def assert_true(self, value, failure_message='Expected value to be True, was: {}'): """ Asserts that a value is true @type value: bool @param value: value to tes...
assertion = lambda: bool(value) self.webdriver_assert(assertion, unicode(failure_message).format(value))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def assert_equals(self, actual_val, expected_val, failure_message='Expected values to be equal: "{}" and "{}"'): """ Calls smart_assert, but creates its own asse...
assertion = lambda: expected_val == actual_val self.webdriver_assert(assertion, unicode(failure_message).format(actual_val, expected_val))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def assert_numbers_almost_equal(self, actual_val, expected_val, allowed_delta=0.0001, failure_message='Expected numbers to be within {} of each other: "{}" and "{...
assertion = lambda: abs(expected_val - actual_val) <= allowed_delta self.webdriver_assert(assertion, unicode(failure_message).format(allowed_delta, actual_val, expected_val))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def assert_not_equal(self, actual_val, unexpected_val, failure_message='Expected values to differ: "{}" and "{}"'): """ Calls smart_assert, but creates its own a...
assertion = lambda: unexpected_val != actual_val self.webdriver_assert(assertion, unicode(failure_message).format(actual_val, unexpected_val))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def assert_is(self, actual_val, expected_type, failure_message='Expected type to be "{1}," but was "{0}"'): """ Calls smart_assert, but creates its own assertion...
assertion = lambda: expected_type is actual_val self.webdriver_assert(assertion, unicode(failure_message).format(actual_val, expected_type))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def assert_is_not(self, actual_val, unexpected_type, failure_message='Expected type not to be "{1}," but was "{0}"'): """ Calls smart_assert, but creates its own...
assertion = lambda: unexpected_type is not actual_val self.webdriver_assert(assertion, unicode(failure_message).format(actual_val, unexpected_type))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def assert_in(self, actual_collection_or_string, expected_value, failure_message='Expected "{1}" to be in "{0}"'): """ Calls smart_assert, but creates its own as...
assertion = lambda: expected_value in actual_collection_or_string self.webdriver_assert(assertion, unicode(failure_message).format(actual_collection_or_string, expected_value))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def assert_not_in(self, actual_collection_or_string, unexpected_value, failure_message='Expected "{1}" not to be in "{0}"'): """ Calls smart_assert, but creates ...
assertion = lambda: unexpected_value not in actual_collection_or_string self.webdriver_assert(assertion, unicode(failure_message).format(actual_collection_or_string, unexpected_value))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def assert_page_source_contains(self, expected_value, failure_message='Expected page source to contain: "{}"'): """ Asserts that the page source contains the str...
assertion = lambda: expected_value in self.driver_wrapper.page_source() self.webdriver_assert(assertion, unicode(failure_message).format(expected_value))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def assert_subset(self, subset, superset, failure_message='Expected collection "{}" to be a subset of "{}'): """ Asserts that a superset contains all elements of...
assertion = lambda: set(subset).issubset(set(superset)) failure_message = unicode(failure_message).format(superset, subset) self.webdriver_assert(assertion, failure_message)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def clear(self): """ Clears the field represented by this element @rtype: WebElementWrapper @return: Returns itself """
def clear_element(): """ Wrapper to clear element """ return self.element.clear() self.execute_and_handle_webelement_exceptions(clear_element, 'clear') return self
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def delete_content(self, max_chars=100): """ Deletes content in the input field by repeatedly typing HOME, then DELETE @rtype: WebElementWrapper @return: Returns...
def delete_content_element(): chars_deleted = 0 while len(self.get_attribute('value')) > 0 and chars_deleted < max_chars: self.click() self.send_keys(Keys.HOME) self.send_keys(Keys.DELETE) chars_deleted += 1 self.e...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def click(self, force_click=False): """ Clicks the element @type force_click: bool @param force_click: force a click on the element using javascript, skipping we...
js_executor = self.driver_wrapper.js_executor def click_element(): """ Wrapper to call click """ return self.element.click() def force_click_element(): """ Javascript wrapper to force_click the element """ ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_value(self): """Gets the value of a select or input element @rtype: str @return: The value of the element @raise: ValueError if element is not of type in...
def get_element_value(): if self.tag_name() == 'input': return self.get_attribute('value') elif self.tag_name() == 'select': selected_options = self.element.all_selected_options if len(selected_options) > 1: raise Value...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_attribute(self, name): """ Retrieves specified attribute from WebElement @type name: str @param name: Attribute to retrieve @rtype: str @return: String r...
def get_attribute_element(): """ Wrapper to retrieve element """ return self.element.get_attribute(name) return self.execute_and_handle_webelement_exceptions(get_attribute_element, 'get attribute "' + str(name) + '"')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def submit(self): """ Submit a webe element @rtype: WebElementWrapper @return: Self """
def submit_element(): """ Wrapper to submit element """ return self.element.submit() self.execute_and_handle_webelement_exceptions(submit_element, 'send keys') return self
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def value_of_css_property(self, property_name): """ Get value of CSS property for element @rtype: str @return: value of CSS property """
def value_of_css_property_element(): """ Wrapper to get css property """ return self.element.value_of_css_property(property_name) return self.execute_and_handle_webelement_exceptions(value_of_css_property_element, 'get css property "' + ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def has_class(self, classname): """Test if an element has a specific classname @type classname: str @param classname: Classname to test for; cannot contain space...
def element_has_class(): """Wrapper to test if element has a class""" pattern = re.compile('(\s|^){classname}(\s|$)'.format(classname=classname)) classes = self.element.get_attribute('class') matches = re.search(pattern, classes) if matches is not No...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def text(self, force_get=False): """ Get the text of the element @rtype: str @return: Text of the element """
def text_element(): """ Wrapper to get text of element """ return self.element.text def force_text_element(): """Get text by javascript""" return self.driver_wrapper.js_executor.execute_template_and_return_result( ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def highlight(self): """ Draws a dotted red box around the wrapped element using javascript @rtype: WebElementWrapper @return: Self """
js_executor = self.driver_wrapper.js_executor def highlight_element(): """ Wrapper to highlight elements """ location = self.element.location size = self.element.size js_executor.execute_template('elementHighlighterTemplate', { ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_attribute(self, name, value): """Sets the attribute of the element to a specified value @type name: str @param name: the name of the attribute @type valu...
js_executor = self.driver_wrapper.js_executor def set_attribute_element(): """ Wrapper to set attribute """ js_executor.execute_template('setAttributeTemplate', { 'attribute_name': str(name), 'attribute_value': str(value)},...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def select_option(self, value=None, text=None, index=None): """ Selects an option by value, text, or index. You must name the parameter @type value: str @param v...
def do_select(): """ Perform selection """ return self.set_select('select', value, text, index) return self.execute_and_handle_webelement_exceptions(do_select, 'select option')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def deselect_option(self, value=None, text=None, index=None): """ De-selects an option by value, text, or index. You must name the parameter @type value: str @pa...
def do_deselect(): """ Perform selection """ return self.set_select('deselect', value, text, index) return self.execute_and_handle_webelement_exceptions(do_deselect, 'deselect option')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_select(self, select_or_deselect = 'select', value=None, text=None, index=None): """ Private method used by select methods @type select_or_deselect: str @...
# TODO: raise exception if element is not select element if select_or_deselect is 'select': if value is not None: Select(self.element).select_by_value(value) elif text is not None: Select(self.element).select_by_visible_text(text) eli...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def checkbox_check(self, force_check=False): """ Wrapper to check a checkbox """
if not self.get_attribute('checked'): self.click(force_click=force_check)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def checkbox_uncheck(self, force_check=False): """ Wrapper to uncheck a checkbox """
if self.get_attribute('checked'): self.click(force_click=force_check)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def hover(self): """ Hovers the element """
def do_hover(): """ Perform hover """ ActionChains(self.driver_wrapper.driver).move_to_element(self.element).perform() return self.execute_and_handle_webelement_exceptions(do_hover, 'hover')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def find(self, locator, find_all=False, search_object=None, exclude_invisible=None, *args, **kwargs): """ Find wrapper, invokes webDriverWrapper find with the cu...
search_object = self.element if search_object is None else search_object return self.driver_wrapper.find( locator, find_all, search_object=search_object, exclude_invisible=exclude_invisible )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def find_once(self, locator): """ Find wrapper to run a single find @type locator: webdriverwrapper.support.locator.Locator @param locator: locator used in searc...
params = [] params.append(self.driver_wrapper.find_attempts) params.append(self.driver_wrapper.implicit_wait) self.driver_wrapper.find_attempts = 1 self.driver_wrapper.implicit_wait = 0 result = self.driver_wrapper._find_immediately(locator, self.element) # re...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def find_all(self, locator): """ Find wrapper, finds all elements @type locator: webdriverwrapper.support.locator.Locator @param locator: locator used in search ...
return self.driver_wrapper.find(locator, True, self.element)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def is_present(self, locator): """ Tests to see if an element is present @type locator: webdriverwrapper.support.locator.Locator @param locator: locator used in ...
return self.driver_wrapper.is_present(locator, search_object=self.element)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def wait_until_stale(self, timeout=None): """ Waits for the element to go stale in the DOM @type timeout: int @param timeout: override for default timeout @rtype...
timeout = timeout if timeout is not None else self.driver_wrapper.timeout def wait(): """ Wrapper to wait for element to be stale """ WebDriverWait(self.driver, timeout).until(EC.staleness_of(self.element)) return self return self.ex...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def execute_and_handle_webelement_exceptions(self, function_to_execute, name_of_action): """ Private method to be called by other methods to handle common WebDri...
if self.element is not None: attempts = 0 while attempts < self.driver_wrapper.find_attempts+1: try: attempts = attempts + 1 val = function_to_execute() for cb in self.driver_wrapper.action_callbacks: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def request(self, uri, method=GET, headers=None, cookies=None, params=None, data=None, post_files=None,**kwargs): """Makes a request using requests @param uri: T...
coyote_args = { 'headers': headers, 'cookies': cookies, 'params': params, 'files': post_files, 'data': data, 'verify': self.verify_certificates, } coyote_args.update(kwargs) if method == self.POST: r...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def validate_urls(urls, allowed_response_codes=None): """Validates that a list of urls can be opened and each responds with an allowed response code urls -- the ...
for url in urls: validate_url(url, allowed_response_codes=allowed_response_codes) return True
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def new_driver(browser_name, *args, **kwargs): """Instantiates a new WebDriver instance, determining class by environment variables """
if browser_name == FIREFOX: return webdriver.Firefox(*args, **kwargs) # elif options['local'] and options['browser_name'] == CHROME: # return webdriver.Chrome(*args, **kwargs) # # elif options['local'] and options['browser_name'] == IE: # return webd...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def encode_collection(collection, encoding='utf-8'): """Encodes all the string keys and values in a collection with specified encoding"""
if isinstance(collection, dict): return dict((encode_collection(key), encode_collection(value)) for key, value in collection.iteritems()) elif isinstance(collection, list): return [encode_collection(element) for element in input] elif isinstance(collection, unicode): return collect...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_delimited_string_from_list(_list, delimiter=', ', wrap_values_with_char=None, wrap_strings_with_char=None): """Given a list, returns a string representat...
if wrap_values_with_char is not None: return delimiter.join('{wrapper}{val}{wrapper}'.format( val=v, wrapper=wrap_values_with_char ) for v in _list) elif wrap_strings_with_char is not None: return delimiter.join(str(v) if not isinstance(v, str) else '{wrapper}{v...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def execute_script(self, string, args=None): """ Execute script passed in to function @type string: str @value string: Script to execute @type args: dict @value ...
result = None try: result = self.driver_wrapper.driver.execute_script(string, args) return result except WebDriverException: if result is not None: message = 'Returned: ' + str(result) else: message = "No message. ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def execute_template(self, template_name, variables, args=None): """ Execute script from a template @type template_name: str @value template_name: Script templat...
js_text = self.build_js_from_template(template_name, variables) try: self.execute_script(js_text, args) except WebDriverException: return False return True
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def execute_template_and_return_result(self, template_name, variables, args=None): """ Execute script from a template and return result @type template_name: str ...
js_text = self.build_js_from_template(template_name, variables) return self.execute_script(js_text, args)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def build_js_from_template(self, template_file, variables): """ Build a JS script from a template and args @type template_file: str @param template_file: Script ...
template_variable_character = '%' # raise an exception if user passed non-dictionary variables if not isinstance(variables, dict): raise TypeError('You must use a dictionary to populate variables in a javascript template') # This filename is not a full file, attempt to loc...