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 update(self, params): """Update the dev_info data from a dictionary. Only updates if it already exists in the device. """
dev_info = self.json_state.get('deviceInfo') dev_info.update({k: params[k] for k in params if dev_info.get(k)})
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def level(self): """Get level from vera."""
# Used for dimmers, curtains # Have seen formats of 10, 0.0 and "0%"! level = self.get_value('level') try: return int(float(level)) except (TypeError, ValueError): pass try: return int(level.strip('%')) except (TypeError, Attri...
<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_switch_state(self, state): """Set the switch state, also update local state."""
self.set_service_value( self.switch_service, 'Target', 'newTargetValue', state) self.set_cache_value('Status', state)
<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_switched_on(self, refresh=False): """Get dimmer state. Refresh data from Vera if refresh is True, otherwise use local cache. Refresh is only needed if you...
if refresh: self.refresh() return self.get_brightness(refresh) > 0
<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_brightness(self, refresh=False): """Get dimmer brightness. Refresh data from Vera if refresh is True, otherwise use local cache. Refresh is only needed i...
if refresh: self.refresh() brightness = 0 percent = self.level if percent > 0: brightness = round(percent * 2.55) return int(brightness)
<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_brightness(self, brightness): """Set dimmer brightness. Converts the Vera level property for dimmable lights from a percentage to the 0 - 255 scale used ...
percent = 0 if brightness > 0: percent = round(brightness / 2.55) self.set_service_value( self.dimmer_service, 'LoadLevelTarget', 'newLoadlevelTarget', percent) self.set_cache_value('level', percent)
<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_color_index(self, colors, refresh=False): """Get color index. Refresh data from Vera if refresh is True, otherwise use local cache. """
if refresh: self.refresh_complex_value('SupportedColors') sup = self.get_complex_value('SupportedColors') if sup is None: return None sup = sup.split(',') if not set(colors).issubset(sup): return None return [sup.index(c) for c in c...
<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_color(self, refresh=False): """Get color. Refresh data from Vera if refresh is True, otherwise use local cache. """
if refresh: self.refresh_complex_value('CurrentColor') ci = self.get_color_index(['R', 'G', 'B'], refresh) cur = self.get_complex_value('CurrentColor') if ci is None or cur is None: return None try: val = [cur.split(',')[c] for c in ci] ...
<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_color(self, rgb): """Set dimmer color. """
target = ','.join([str(c) for c in rgb]) self.set_service_value( self.color_service, 'ColorRGB', 'newColorRGBTarget', target) rgbi = self.get_color_index(['R', 'G', 'B']) if rgbi is None: return target = ('0=0,1=0,' ...
<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_armed_state(self, state): """Set the armed state, also update local state."""
self.set_service_value( self.security_sensor_service, 'Armed', 'newArmedValue', state) self.set_cache_value('Armed', state)
<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_switched_on(self, refresh=False): """Get armed state. Refresh data from Vera if refresh is True, otherwise use local cache. Refresh is only needed if you'...
if refresh: self.refresh() val = self.get_value('Armed') return val == '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 is_open(self, refresh=False): """Get curtains state. Refresh data from Vera if refresh is True, otherwise use local cache. Refresh is only needed if you're n...
if refresh: self.refresh() return self.get_level(refresh) > 0
<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_level(self, level): """Set open level of the curtains. Scale is 0-100 """
self.set_service_value( self.dimmer_service, 'LoadLevelTarget', 'newLoadlevelTarget', level) self.set_cache_value('level', level)
<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_last_user(self, refresh=False): """Get the last used PIN user id"""
if refresh: self.refresh_complex_value('sl_UserCode') val = self.get_complex_value("sl_UserCode") # Syntax string: UserID="<pin_slot>" UserName="<pin_code_name>" # See http://wiki.micasaverde.com/index.php/Luup_UPnP_Variables_and_Actions#DoorLock1 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 get_pin_codes(self, refresh=False): """Get the list of PIN codes Codes can also be found with self.get_complex_value('PinCodes') """
if refresh: self.refresh() val = self.get_value("pincodes") # val syntax string: <VERSION=3>next_available_user_code_id\tuser_code_id,active,date_added,date_used,PIN_code,name;\t... # See (outdated) http://wiki.micasaverde.com/index.php/Luup_UPnP_Variables_and_Actions#DoorL...
<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_current_temperature(self, refresh=False): """Get current temperature"""
if refresh: self.refresh() try: return float(self.get_value('temperature')) except (TypeError, ValueError): return None
<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_hvac_mode(self, mode): """Set the hvac mode"""
self.set_service_value( self.thermostat_operating_service, 'ModeTarget', 'NewModeTarget', mode) self.set_cache_value('mode', mode)
<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_fan_mode(self, mode): """Set the fan mode"""
self.set_service_value( self.thermostat_fan_service, 'Mode', 'NewMode', mode) self.set_cache_value('fanmode', mode)
<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_last_scene_id(self, refresh=False): """Get last scene id. Refresh data from Vera if refresh is True, otherwise use local cache. Refresh is only needed if...
if refresh: self.refresh_complex_value('LastSceneID') self.refresh_complex_value('sl_CentralScene') val = self.get_complex_value('LastSceneID') or self.get_complex_value('sl_CentralScene') return 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 get_last_scene_time(self, refresh=False): """Get last scene time. Refresh data from Vera if refresh is True, otherwise use local cache. Refresh is only neede...
if refresh: self.refresh_complex_value('LastSceneTime') val = self.get_complex_value('LastSceneTime') return 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 vera_request(self, **kwargs): """Perfom a vera_request for this scene."""
request_payload = { 'output_format': 'json', 'SceneNum': self.scene_id, } request_payload.update(kwargs) return self.vera_controller.data_request(request_payload)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def activate(self): """Activate a Vera scene. This will call the Vera api to activate a scene. """
payload = { 'id': 'lu_action', 'action': 'RunScene', 'serviceId': self.scene_service } result = self.vera_request(**payload) logger.debug("activate: " "result of vera_request with payload %s: %s", payload, result.te...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def refresh(self): """Refresh the data used by get_value. Only needed if you're not using subscriptions. """
j = self.vera_request(id='sdata', output_format='json').json() scenes = j.get('scenes') for scene_data in scenes: if scene_data.get('id') == self.scene_id: self.update(scene_data)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def unregister(self, device, callback): """Remove a registered a callback. device: device that has the subscription callback: callback used in original registrat...
if not device: logger.error("Received an invalid device: %r", device) return logger.debug("Removing subscription for {}".format(device.name)) self._callbacks[device].remove(callback) self._devices[device.vera_device_id].remove(device)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def start(self): """Start a thread to handle Vera blocked polling."""
self._poll_thread = threading.Thread(target=self._run_poll_server, name='Vera Poll Thread') self._poll_thread.deamon = True self._poll_thread.start()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _pick_level(cls, btc_amount): """ amount specified. """
for size, level in cls.TICKER_LEVEL: if btc_amount < size: return level return cls.TICKER_LEVEL[-1][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 format_tsv_line(source, edge, target, value=None, metadata=None): """ Render a single line for TSV file with data flow described :type source str :type edge ...
return '{source}\t{edge}\t{target}\t{value}\t{metadata}'.format( source=source, edge=edge, target=target, value='{:.4f}'.format(value) if value is not None else '', metadata=metadata or '' ).rstrip(' \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 format_graphviz_lines(lines): """ Render a .dot file with graph definition from a given set of data :type lines list[dict] :rtype: str """
# first, prepare the unique list of all nodes (sources and targets) lines_nodes = set() for line in lines: lines_nodes.add(line['source']) lines_nodes.add(line['target']) # generate a list of all nodes and their names for graphviz graph nodes = OrderedDict() for i, node in en...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def close_chromium(self): ''' Close the remote chromium instance. This command is normally executed as part of the class destructor. It can be called early without issue, but calling ANY class functions after the remote chromium instance is shut down will have unknown effects. Note that if you are rapidly...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def connect(self, tab_key): """ Open a websocket connection to remote browser, determined by self.host and self.port. Each tab has it's own websocket end...
assert self.tablist is not None tab_idx = self._get_tab_idx_for_key(tab_key) if not self.tablist: self.tablist = self.fetch_tablist() for fails in range(9999): try: # If we're one past the end of the tablist, we need to create a new tab if tab_idx is None: self.log.debug("Creating new 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 close_websockets(self): """ Close websocket connection to remote browser."""
self.log.info("Websocket Teardown called") for key in list(self.soclist.keys()): if self.soclist[key]: self.soclist[key].close() self.soclist.pop(key)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def synchronous_command(self, command, tab_key, **params): """ Synchronously execute command `command` with params `params` in the remote chrome instance, ...
self.log.debug("Synchronous_command to tab %s (%s):", tab_key, self._get_cr_tab_meta_for_key(tab_key)) self.log.debug(" command: '%s'", command) self.log.debug(" params: '%s'", params) self.log.debug(" tab_key: '%s'", tab_key) send_id = self.send(command=command, tab_key=tab_key, params=params) resp = s...
<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(self, command, tab_key, params=None): ''' Send command `command` with optional parameters `params` to the remote chrome instance. The command `id` is automatically added to the outgoing message. return value is the command id, which can be used to match a command to it's associated response. ''...
<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(self, tab_key, message_id=None, timeout=30): ''' Recieve a message, optionally filtering for a specified message id. If `message_id` is none, the first command in the receive queue is returned. If `message_id` is not none, the command waits untill a message is received with the specified id, or it 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 fetch(url, binary, outfile, noprint, rendered): ''' Fetch a specified URL's content, and output it to the console. ''' with chrome_context.ChromeContext(binary=binary) as cr: resp = cr.blocking_navigate_and_get_source(url) if rendered: resp['content'] = cr.get_rendered_page_source() resp['binary'] = F...
<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_headers(self, header_args): ''' Given a set of headers, update both the user-agent and additional headers for the remote browser. header_args must be a dict. Keys are the names of the corresponding HTTP header. return value is a 2-tuple of the results of the user-agent update, as well as the ...
<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_cookies(self): ''' Retreive the cookies from the remote browser. Return value is a list of http.cookiejar.Cookie() instances. These can be directly used with the various http.cookiejar.XXXCookieJar cookie management classes. ''' ret = self.Network_getAllCookies() assert 'result' in ret, "No 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 set_cookie(self, cookie): ''' Add a cookie to the remote chromium instance. Passed value `cookie` must be an instance of `http.cookiejar.Cookie()`. ''' # Function path: Network.setCookie # Domain: Network # Method name: setCookie # WARNING: This function is marked 'Experimental'! # Parameters: ...
<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_current_url(self): ''' Probe the remote session for the current window URL. This is primarily used to do things like unwrap redirects, or circumvent outbound url wrappers. ''' res = self.Page_getNavigationHistory() assert 'result' in res assert 'currentIndex' in res['result'] assert 'entries...
<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_page_url_title(self): ''' Get the title and current url from the remote session. Return is a 2-tuple: (page_title, page_url). ''' cr_tab_id = self.transport._get_cr_tab_meta_for_key(self.tab_id)['id'] targets = self.Target_getTargets() assert 'result' in targets assert 'targetInfos' in targe...
<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_javascript(self, *args, **kwargs): ''' Execute a javascript string in the context of the browser tab. ''' ret = self.__exec_js(*args, **kwargs) return ret
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def blocking_navigate_and_get_source(self, url, timeout=DEFAULT_TIMEOUT_SECS): ''' Do a blocking navigate to url `url`, and then extract the response body and return that. This effectively returns the *unrendered* page content that's sent over the wire. As such, if the page does any modification of the conta...
<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_rendered_page_source(self, dom_idle_requirement_secs=3, max_wait_timeout=30): ''' Get the HTML markup for the current page. This is done by looking up the root DOM node, and then requesting the outer HTML for that node ID. This calls return will reflect any modifications made by javascript to the ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def take_screeshot(self): ''' Take a screenshot of the virtual viewport content. Return value is a png image as a bytestring. ''' resp = self.Page_captureScreenshot() assert 'result' in resp assert 'data' in resp['result'] imgdat = base64.b64decode(resp['result']['data']) return imgdat
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def blocking_navigate(self, url, timeout=DEFAULT_TIMEOUT_SECS): ''' Do a blocking navigate to url `url`. This function triggers a navigation, and then waits for the browser to claim the page has finished loading. Roughly, this corresponds to the javascript `DOMContentLoaded` event, meaning the dom for the...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def on_parent_exit(signame): """ Return a function to be run in a child process which will trigger SIGNAME to be sent when the parent process dies """
signum = getattr(signal, signame) def set_parent_exit_signal(): # http://linux.die.net/man/2/prctl result = cdll['libc.so.6'].prctl(PR_SET_PDEATHSIG, signum) if result != 0: raise PrCtlError('prctl failed with error code %s' % result) return set_parent_exit_signal
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def ChromeContext(*args, **kwargs): ''' Context manager for conveniently handling the lifetime of the underlying chromium instance. In general, this should be the preferred way to use an instance of `ChromeRemoteDebugInterface`. All parameters are forwarded through to the underlying ChromeRemoteDebugInterface() c...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def synchronous_command(self, *args, **kwargs): ''' Forward a command to the remote chrome instance via the transport connection, and check the return for an error. If the command resulted in an error, a `ChromeController.ChromeError` is raised, with the error string containing the response from the remote ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def drain_transport(self): ''' "Drain" the transport connection. This command simply returns all waiting messages sent from the remote chrome instance. This can be useful when waiting for a specific asynchronous message from chrome, but higher level calls are better suited for managing wait-for-message typ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def resetLoggingLocks(): ''' This function is a HACK! Basically, if we fork() while a logging lock is held, the lock is /copied/ while in the acquired state. However, since we've forked, the thread that acquired the lock no longer exists, so it can never unlock the lock, and we end up blocking forever. Theref...
<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_suite(self, suite, **kwargs): """This is the version from Django 1.7."""
return self.test_runner( verbosity=self.verbosity, failfast=self.failfast, no_colour=self.no_colour, ).run(suite)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def generate_public_key(self): """ Generates public key. :return: void :rtype: void """
self.public_key = pow(self.generator, self.__private_key, self.prime)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def generate_shared_secret(self, other_public_key, echo_return_key=False): """ Generates shared secret from the other party's public key. :param other_public_key...
if self.verify_public_key(other_public_key) is False: raise MalformedPublicKey self.shared_secret = pow(other_public_key, self.__private_key, self.prime) shared_secret_as_bytes = self.shared_secret.to_bytes(self.sha...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def requires_private_key(func): """ Decorator for functions that require the private key to be defined. """
def func_wrapper(self, *args, **kwargs): if hasattr(self, "_DiffieHellman__private_key"): func(self, *args, **kwargs) else: self.generate_private_key() func(self, *args, **kwargs) return func_wrapper
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def requires_public_key(func): """ Decorator for functions that require the public key to be defined. By definition, this includes the private key, as such, it's...
def func_wrapper(self, *args, **kwargs): if hasattr(self, "public_key"): func(self, *args, **kwargs) else: self.generate_public_key() func(self, *args, **kwargs) return func_wrapper
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def print_debug(*args, **kwargs): """ Print if and only if the debug flag is set true in the config.yaml file. Args: args : var args of print arguments. """
if WTF_CONFIG_READER.get("debug", False) == True: print(*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 print_time(self, message="Time is now: ", print_frame_info=True): """ Print the current elapsed time. Kwargs: message (str) : Message to prefix the time stam...
if print_frame_info: frame_info = inspect.getouterframes(inspect.currentframe())[1] print(message, (datetime.now() - self.start_time), frame_info) else: print(message, (datetime.now() - self.start_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 check_url(url): ''' Check if resource at URL is fetchable. (by trying to fetch it and checking for 200 status. Args: url (str): Url to check. Returns: Returns a tuple of {True/False, response code} ''' request = urllib2.Request(url) ...
<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_base_url(webdriver): """ Get the current base URL. Args: webdriver: Selenium WebDriver instance. Returns: str - base URL. Usage:: driver.get("http://www....
current_url = webdriver.current_url try: return re.findall("^[^/]+//[^/$]+", current_url)[0] except: raise RuntimeError( u("Unable to process base url: {0}").format(current_url))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def switch_to_window(page_class, webdriver): """ Utility method for switching between windows. It will search through currently open windows, then switch to the ...
window_list = list(webdriver.window_handles) original_window = webdriver.current_window_handle for window_handle in window_list: webdriver.switch_to_window(window_handle) try: return PageFactory.create_page(page_class, webdriver) except: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def start(self): """ Start standing by. A periodic command like 'current_url' will be sent to the webdriver instance to prevent it from timing out. """
self._end_time = datetime.now() + timedelta(seconds=self._max_time) self._thread = Thread(target=lambda: self.__stand_by_loop()) self._keep_running = True self._thread.start() 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 temp_path(file_name=None): """ Gets a temp path. Kwargs: file_name (str) : if file name is specified, it gets appended to the temp dir. Usage:: temp_file_pat...
if file_name is None: file_name = generate_timestamped_string("wtf_temp_file") return os.path.join(tempfile.gettempdir(), file_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 download_to_tempfile(url, file_name=None, extension=None): """ Downloads a URL contents to a tempfile. This is useful for testing downloads. It will download...
if not file_name: file_name = generate_timestamped_string("wtf_temp_file") if extension: file_path = temp_path(file_name + extension) else: ext = "" try: ext = re.search(u"\\.\\w+$", file_name).group(0) except: pass file_path = temp_...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_page(cls, webdriver=None, **kwargs): """Class method short cut to call PageFactory on itself. Use it to instantiate this PageObject using a webdriver....
if not webdriver: webdriver = WTF_WEBDRIVER_MANAGER.get_driver() return PageFactory.create_page(cls, webdriver=webdriver, **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 create_page(page_object_class_or_interface, webdriver=None, **kwargs): """ Instantiate a page object from a given Interface or Abstract class. Args: page_obj...
if not webdriver: webdriver = WTF_WEBDRIVER_MANAGER.get_driver() # will be used later when tracking best matched page. current_matched_page = None # used to track if there is a valid page object within the set of PageObjects searched. was_validate_called = 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 __instantiate_page_object(page_obj_class, webdriver, **kwargs): """ Attempts to instantiate a page object. Args: page_obj_class (PageObject) - PageObject to ...
try: page = page_obj_class(webdriver, **kwargs) return page except InvalidPageError: # This happens when the page fails check. # Means validate was implemented, but the check didn't pass. return True except TypeError: # thi...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def check_css_selectors(webdriver, *selectors): """Returns true if all CSS selectors passed in is found. This can be used to quickly validate a page. Args: webdr...
for selector in selectors: try: webdriver.find_element_by_css_selector(selector) except: return False # A selector failed. 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 wait_until_page_loaded(page_obj_class, webdriver=None, timeout=WTF_TIMEOUT_MANAGER.NORMAL, sleep=0.5, bad_page_classes=[], message=None, **kwargs): """ Waits...
if not webdriver: webdriver = WTF_WEBDRIVER_MANAGER.get_driver() # convert this param to list if not already. if type(bad_page_classes) != list: bad_page_classes = [bad_page_classes] end_time = datetime.now() + timedelta(seconds=timeout) last_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 get_asset_path(self, filename): """ Get the full system path of a given asset if it exists. Otherwise it throws an error. Args: filename (str) - File name of...
if os.path.exists(os.path.join(self._asset_path, filename)): return os.path.join(self._asset_path, filename) else: raise AssetNotFoundError( u("Cannot find asset: {0}").format(filename))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def create_webdriver(self, testname=None): ''' Creates an instance of Selenium webdriver based on config settings. This should only be called by a shutdown hook. Do not call directly within a test. Kwargs: testname: Optional test name to pass, 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 __create_safari_driver(self): ''' Creates an instance of Safari webdriver. ''' # Check for selenium jar env file needed for safari driver. if not os.getenv(self.__SELENIUM_SERVER_JAR_ENV): # If not set, check if we have a config setting for it. 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 __create_phantom_js_driver(self): ''' Creates an instance of PhantomJS driver. ''' try: return webdriver.PhantomJS(executable_path=self._config_reader.get(self.PHANTOMEJS_EXEC_PATH), service_args=['--ignore-ssl-errors=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 clean_up_webdrivers(self): ''' Clean up webdrivers created during execution. ''' # Quit webdrivers. _wtflog.info("WebdriverManager: Cleaning up webdrivers") try: if self.__use_shutdown_hook: for key in self.__registered_drivers.keys(): ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def close_driver(self): """ Close current running instance of Webdriver. Usage:: driver = WTF_WEBDRIVER_MANAGER.new_driver() driver.get("http://the-internet.hero...
channel = self.__get_channel() driver = self.__get_driver_for_channel(channel) if self.__config.get(self.REUSE_BROWSER, True): # If reuse browser is set, we'll avoid closing it and just clear out the cookies, # and reset the location. try: dri...
<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_driver(self): ''' Get an already running instance of Webdriver. If there is none, it will create one. Returns: Webdriver - Selenium Webdriver instance. Usage:: driver = WTF_WEBDRIVER_MANAGER.new_driver() driver.get("http://the-internet.herok...
<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_driver(self, channel, webdriver): "Register webdriver to a channel." # Add to list of webdrivers to cleanup. if not self.__registered_drivers.has_key(channel): self.__registered_drivers[channel] = [] # set to new empty array self.__registered_drivers[channel...
<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_channel(self): "Get the channel to register webdriver to." if self.__config.get(WebDriverManager.ENABLE_THREADING_SUPPORT, False): channel = current_thread().ident else: channel = 0 return channel
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def take_screenshot(webdriver, file_name): """ Captures a screenshot. Args: webdriver (WebDriver) - Selenium webdriver. file_name (str) - File name to save scree...
folder_location = os.path.join(ProjectUtils.get_project_root(), WebScreenShotUtil.SCREEN_SHOT_LOCATION) WebScreenShotUtil.__capture_screenshot( webdriver, folder_location, file_name + ".png")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def take_reference_screenshot(webdriver, file_name): """ Captures a screenshot as a reference screenshot. Args: webdriver (WebDriver) - Selenium webdriver. file_...
folder_location = os.path.join(ProjectUtils.get_project_root(), WebScreenShotUtil.REFERENCE_SCREEN_SHOT_LOCATION) WebScreenShotUtil.__capture_screenshot( webdriver, folder_location, file_name + ".png")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def __capture_screenshot(webdriver, folder_location, file_name): "Capture a screenshot" # Check folder location exists. if not os.path.exists(folder_location): os.makedirs(folder_location) file_location = os.path.join(folder_location, file_name) if isinstance(webdri...
<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_and_ignore(condition, timeout=WTF_TIMEOUT_MANAGER.NORMAL, sleep=0.5): ''' Waits wrapper that'll wait for the condition to become true, but will not error if the condition isn't met. Args: condition (lambda) - Lambda expression to wait for to evaluate to True. Kwargs: 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 check_email_exists_by_subject(self, subject, match_recipient=None): """ Searches for Email by Subject. Returns True or False. Args: subject (str): Subject t...
# Select inbox to fetch the latest mail on server. self._mail.select("inbox") try: matches = self.__search_email_by_subject(subject, match_recipient) if len(matches) <= 0: return False else: return True except Exceptio...
<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_emails_by_subject(self, subject, limit=50, match_recipient=None): """ Searches for Email by Subject. Returns email's imap message IDs as a list if match...
# Select inbox to fetch the latest mail on server. self._mail.select("inbox") matching_uids = self.__search_email_by_subject( subject, match_recipient) return matching_uids
<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_email_message(self, message_uid, message_type="text/plain"): """ Fetch contents of email. Args: message_uid (int): IMAP Message UID number. Kwargs: mess...
self._mail.select("inbox") result = self._mail.uid('fetch', message_uid, "(RFC822)") msg = email.message_from_string(result[1][0][1]) try: # Try to handle as multipart message first. for part in msg.walk(): if part.get_content_type() == message_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 __search_email_by_subject(self, subject, match_recipient): "Get a list of message numbers" if match_recipient is None: _, data = self._mail.uid('search', None, '(HEADER SUBJECT "{subject}")' ...
<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(self, key, default_value=__NoDefaultSpecified__): ''' Gets the value from the yaml config based on the key. No type casting is performed, any type casting should be performed by the caller. Args: key (str) - Config setting key. 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 generate_page_object(page_name, url): "Generate page object from URL" # Attempt to extract partial URL for verification. url_with_path = u('^.*//[^/]+([^?]+)?|$') try: match = re.match(url_with_path, url) partial_url = match.group(1) print("Using partial URL for location ver...
<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_data_path(self, filename, env_prefix=None): """ Get data path. Args: filename (string) : Name of file inside of /data folder to retrieve. Kwargs: env_pre...
if env_prefix == None: target_file = filename else: target_file = os.path.join(env_prefix, filename) if os.path.exists(os.path.join(self._data_path, target_file)): return os.path.join(self._data_path, target_file) else: raise DataNotFound...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def next(self): """ Gets next entry as a dictionary. Returns: object - Object key/value pair representing a row. """
try: entry = {} row = self._csv_reader.next() for i in range(0, len(row)): entry[self._headers[i]] = row[i] return entry except Exception as e: # close our file when we're done reading. self._file.close() ...
<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_element_not_visible(webdriver, locator_lambda_expression, timeout=WTF_TIMEOUT_MANAGER.NORMAL, sleep=0.5): """ Wait for a WebElement to disappear. ...
# Wait for loading progress indicator to go away. try: stoptime = datetime.now() + timedelta(seconds=timeout) while datetime.now() < stoptime: element = WebDriverWait(webdriver, WTF_TIMEOUT_MANAGER.BRIEF).until( locator_lambda_expression) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def generate_timestamped_string(subject="test", number_of_random_chars=4): """ `2013-01-31_14:12:23_SubjectString_a3Zg` Kwargs: subject (str): String to use as ...
random_str = generate_random_string(number_of_random_chars) timestamp = generate_timestamp() return u"{timestamp}_{subject}_{random_str}".format(timestamp=timestamp, subject=subject, random_str=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 generate_random_string(number_of_random_chars=8, character_set=string.ascii_letters): """ Generate a series of random characters. Kwargs: number_of_random_ch...
return u('').join(random.choice(character_set) for _ in range(number_of_random_chars))
<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_value(self, name, index): """ Returns the value associated with the given value index of the attribute with the given name. This is only applic...
if index == MISSING: return elif self.attribute_types[name] in NUMERIC_TYPES: at = self.attribute_types[name] if at == TYPE_INTEGER: return int(index) return Decimal(str(index)) else: assert self.attribute_types[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 load(cls, filename, schema_only=False): """ Load an ARFF File from a file. """
o = open(filename) s = o.read() a = cls.parse(s, schema_only=schema_only) if not schema_only: a._filename = filename o.close() return a
<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(cls, s, schema_only=False): """ Parse an ARFF File already loaded into a string. """
a = cls() a.state = 'comment' a.lineno = 1 for l in s.splitlines(): a.parseline(l) a.lineno += 1 if schema_only and a.state == 'data': # Don't parse data if we're only loading the schema. break return a
<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(self, schema_only=False): """ Creates a deepcopy of the instance. If schema_only is True, the data will be excluded from the copy. """
o = type(self)() o.relation = self.relation o.attributes = list(self.attributes) o.attribute_types = self.attribute_types.copy() o.attribute_data = self.attribute_data.copy() if not schema_only: o.comment = list(self.comment) o.data = copy.deepcop...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def open_stream(self, class_attr_name=None, fn=None): """ Save an arff structure to a file, leaving the file object open for writing of new data samples. This pr...
if fn: self.fout_fn = fn else: fd, self.fout_fn = tempfile.mkstemp() os.close(fd) self.fout = open(self.fout_fn, 'w') if class_attr_name: self.class_attr_name = class_attr_name self.write(fout=self.fout, schema_only=True) s...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def close_stream(self): """ Terminates an open stream and returns the filename of the file containing the streamed data. """
if self.fout: fout = self.fout fout_fn = self.fout_fn self.fout.flush() self.fout.close() self.fout = None self.fout_fn = None return fout_fn
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def save(self, filename=None): """ Save an arff structure to a file. """
filename = filename or self._filename o = open(filename, 'w') o.write(self.write()) o.close()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def write(self, fout=None, fmt=SPARSE, schema_only=False, data_only=False): """ Write an arff structure to a string. """
assert not (schema_only and data_only), 'Make up your mind.' assert fmt in FORMATS, 'Invalid format "%s". Should be one of: %s' % (fmt, ', '.join(FORMATS)) close = False if fout is None: close = True fout = StringIO() if not data_only: print('...