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, AttributeError, ValueError): pass return 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_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're not using subscriptions. """
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 if you're not using subscriptions. Converts the Vera level property for dimmable lights from a percentage to the 0 - 255 scale used by HA. """
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 by HA. """
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 colors]
<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] return [int(v.split('=')[1]) for v in val] except IndexError: 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_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,' + str(rgbi[0]) + '=' + str(rgb[0]) + ',' + str(rgbi[1]) + '=' + str(rgb[1]) + ',' + str(rgbi[2]) + '=' + str(rgb[2])) self.set_cache_complex_value("CurrentColor", target)
<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're not using subscriptions. """
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 not using subscriptions. """
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: # Get the UserID="" and UserName="" fields separately raw_userid, raw_username = val.split(' ') # Get the right hand value without quotes of UserID="<here>" userid = raw_userid.split('=')[1].split('"')[1] # Get the right hand value without quotes of UserName="<here>" username = raw_username.split('=')[1].split('"')[1] except Exception as ex: logger.error('Got unsupported user string {}: {}'.format(val, ex)) return None return ( userid, username )
<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#DoorLock1 # Remove the trailing tab # ignore the version and next available at the start # and split out each set of code attributes raw_code_list = [] try: raw_code_list = val.rstrip().split('\t')[1:] except Exception as ex: logger.error('Got unsupported string {}: {}'.format(val, ex)) # Loop to create a list of codes codes = [] for code in raw_code_list: try: # Strip off trailing semicolon # Create a list from csv code_addrs = code.split(';')[0].split(',') # Get the code ID (slot) and see if it should have values slot, active = code_addrs[:2] if active != '0': # Since it has additional attributes, get the remaining ones _, _, pin, name = code_addrs[2:] # And add them as a tuple to the list codes.append((slot, name, pin)) except Exception as ex: logger.error('Problem parsing pin code string {}: {}'.format(code, ex)) return codes
<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 you're not using subscriptions. """
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 needed if you're not using subscriptions. """
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.text) self._active = 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 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 registration """
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 str :type target str :type value float :type metadata str :rtype: str """
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 enumerate(sorted(lines_nodes)): nodes[node] = 'n{}'.format(i+1) # print(lines_nodes, nodes) graph = list() # some basic style definition # https://graphviz.gitlab.io/_pages/doc/info/lang.html graph.append('digraph G {') # https://graphviz.gitlab.io/_pages/doc/info/shapes.html#record graph.append('\tgraph [ center=true, margin=0.75, nodesep=0.5, ranksep=0.75, rankdir=LR ];') graph.append('\tnode [ shape=box, style="rounded,filled" width=0, height=0, ' 'fontname=Helvetica, fontsize=11 ];') graph.append('\tedge [ fontname=Helvetica, fontsize=9 ];') # emit nodes definition graph.append('\n\t// nodes') # https://www.graphviz.org/doc/info/colors.html#brewer group_colors = dict() for label, name in nodes.items(): if ':' in label: (group, label) = str(label).split(':', 1) # register a new group for coloring if group not in group_colors: group_colors[group] = len(group_colors.keys()) + 1 else: group = None label = escape_graphviz_entry(label) graph.append('\t{name} [label="{label}"{group}];'.format( name=name, label="{}\\n{}".format(group, label) if group is not None else label, group=' group="{}" colorscheme=pastel28 color={}'.format( group, group_colors[group]) if group is not None else '' )) # now, connect the nodes graph.append('\n\t// edges') for line in lines: label = line.get('metadata', '') graph.append('\t{source} -> {target} [{label}];'.format( source=nodes[line['source']], target=nodes[line['target']], label='label="{}"'.format(escape_graphviz_entry(label)) if label != '' else '' )) graph.append('}') return '\n'.join(graph)
<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 creating and destroying ChromeController instances, you may need to *explicitly* call this before destruction. ''' if self.cr_proc: try: if 'win' in sys.platform: self.__close_internal_windows() else: self.__close_internal_linux() except Exception as e: for line in traceback.format_exc().split("\n"): self.log.error(line) ACTIVE_PORTS.discard(self.port)
<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 endpoint. """
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 tab (%s active)", len(self.tablist)) self.__create_new_tab(tab_key) self.__connect_to_tab(tab_key) break except cr_exceptions.ChromeConnectFailure as e: if fails > 6: self.log.error("Failed to fetch tab websocket URL after %s retries. Aborting!", fails) raise e self.log.info("Tab may not have started yet (%s tabs active). Recreating.", len(self.tablist)) # self.log.info("Tag: %s", self.tablist[tab_idx]) # For reasons I don't understand, sometimes a new tab doesn't get a websocket # debugger URL. Anyways, we close and re-open the tab if that happens. # TODO: Handle the case when this happens on the first tab. I think closing the first # tab will kill chromium. self.__close_tab(tab_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 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, returning the response from the 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 = self.recv(message_id=send_id, tab_key=tab_key) self.log.debug(" Response: '%s'", str(resp).encode("ascii", 'ignore').decode("ascii")) # self.log.debug(" resolved tab idx %s:", self.tab_id_map[tab_key]) return resp
<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. ''' self.__check_open_socket(tab_key) sent_id = self.msg_id command = { "id": self.msg_id, "method": command, } if params: command["params"] = params navcom = json.dumps(command) # self.log.debug(" Sending: '%s'", navcom) try: self.soclist[tab_key].send(navcom) except (socket.timeout, websocket.WebSocketTimeoutException): raise cr_exceptions.ChromeCommunicationsError("Failure sending command to chromium.") except websocket.WebSocketConnectionClosedException: raise cr_exceptions.ChromeCommunicationsError("Websocket appears to have been closed. Is the" " remote chromium instance dead?") self.msg_id += 1 return sent_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 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 times out. Timeout is the number of seconds to wait for a response, or `None` if the timeout has expired with no response. ''' self.__check_open_socket(tab_key) # First, check if the message has already been received. for idx in range(len(self.messages[tab_key])): if self.messages[tab_key][idx]: if "id" in self.messages[tab_key][idx] and message_id: if self.messages[tab_key][idx]['id'] == message_id: return self.messages[tab_key].pop(idx) # Then spin untill we either have the message, # or have timed out. def check_func(message): if message_id is None: return True if not message: self.log.debug("Message is not true (%s)!", message) return False if "id" in message: return message['id'] == message_id return False return self.recv_filtered(check_func, tab_key, 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 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'] = False resp['mimie'] = 'text/html' if not noprint: if resp['binary'] is False: print(resp['content']) else: print("Response is a binary file") print("Cannot print!") if outfile: with open(outfile, "wb") as fp: if resp['binary']: fp.write(resp['content']) else: fp.write(resp['content'].encode("UTF-8"))
<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 extra headers update. If no 'User-Agent' key is present in the new headers, the first item in the tuple will be None ''' assert isinstance(header_args, dict), "header_args must be a dict, passed type was %s" \ % (type(header_args), ) ua = header_args.pop('User-Agent', None) ret_1 = None if ua: ret_1 = self.Network_setUserAgentOverride(userAgent=ua) ret_2 = self.Network_setExtraHTTPHeaders(headers = header_args) return (ret_1, ret_2)
<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 return value in function response!" assert 'cookies' in ret['result'], "No 'cookies' key in function response" cookies = [] for raw_cookie in ret['result']['cookies']: # Chromium seems to support the following key values for the cookie dict: # "name" # "value" # "domain" # "path" # "expires" # "httpOnly" # "session" # "secure" # # This seems supported by the fact that the underlying chromium cookie implementation has # the following members: # std::string name_; # std::string value_; # std::string domain_; # std::string path_; # base::Time creation_date_; # base::Time expiry_date_; # base::Time last_access_date_; # bool secure_; # bool httponly_; # CookieSameSite same_site_; # CookiePriority priority_; # # See chromium/net/cookies/canonical_cookie.h for more. # # I suspect the python cookie implementation is derived exactly from the standard, while the # chromium implementation is more of a practically derived structure. # Network.setCookie baked_cookie = http.cookiejar.Cookie( # We assume V0 cookies, principally because I don't think I've /ever/ actually encountered a V1 cookie. # Chromium doesn't seem to specify it. version = 0, name = raw_cookie['name'], value = raw_cookie['value'], port = None, port_specified = False, domain = raw_cookie['domain'], domain_specified = True, domain_initial_dot = False, path = raw_cookie['path'], path_specified = False, secure = raw_cookie['secure'], expires = raw_cookie['expires'], discard = raw_cookie['session'], comment = None, comment_url = None, rest = {"httponly":"%s" % raw_cookie['httpOnly']}, rfc2109 = False ) cookies.append(baked_cookie) return cookies
<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: # Required arguments: # 'url' (type: string) -> The request-URI to associate with the setting of the cookie. This value can affect the default domain and path values of the created cookie. # 'name' (type: string) -> The name of the cookie. # 'value' (type: string) -> The value of the cookie. # Optional arguments: # 'domain' (type: string) -> If omitted, the cookie becomes a host-only cookie. # 'path' (type: string) -> Defaults to the path portion of the url parameter. # 'secure' (type: boolean) -> Defaults ot false. # 'httpOnly' (type: boolean) -> Defaults to false. # 'sameSite' (type: CookieSameSite) -> Defaults to browser default behavior. # 'expirationDate' (type: Timestamp) -> If omitted, the cookie becomes a session cookie. # Returns: # 'success' (type: boolean) -> True if successfully set cookie. # Description: Sets a cookie with the given cookie data; may overwrite equivalent cookies if they exist. assert isinstance(cookie, http.cookiejar.Cookie), 'The value passed to `set_cookie` must be an instance of http.cookiejar.Cookie().' + \ ' Passed: %s ("%s").' % (type(cookie), cookie) # Yeah, the cookielib stores this attribute as a string, despite it containing a # boolean value. No idea why. is_http_only = str(cookie.get_nonstandard_attr('httponly', 'False')).lower() == "true" # I'm unclear what the "url" field is actually for. A cookie only needs the domain and # path component to be fully defined. Considering the API apparently allows the domain and # path parameters to be unset, I think it forms a partially redundant, with some # strange interactions with mode-changing between host-only and more general # cookies depending on what's set where. # Anyways, given we need a URL for the API to work properly, we produce a fake # host url by building it out of the relevant cookie properties. fake_url = urllib.parse.urlunsplit(( "http" if is_http_only else "https", # Scheme cookie.domain, # netloc cookie.path, # path '', # query '', # fragment )) params = { 'url' : fake_url, 'name' : cookie.name, 'value' : cookie.value if cookie.value else "", 'domain' : cookie.domain, 'path' : cookie.path, 'secure' : cookie.secure, 'expires' : float(cookie.expires) if cookie.expires else float(2**32), 'httpOnly' : is_http_only, # The "sameSite" flag appears to be a chromium-only extension for controlling # cookie sending in non-first-party contexts. See: # https://bugs.chromium.org/p/chromium/issues/detail?id=459154 # Anyways, we just use the default here, whatever that is. # sameSite = cookie.xxx } ret = self.Network_setCookie(**params) 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 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' in res['result'] return res['result']['entries'][res['result']['currentIndex']]['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_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 targets['result'] for tgt in targets['result']['targetInfos']: if tgt['targetId'] == cr_tab_id: # { # 'title': 'Page Title 1', # 'targetId': '9d2c503c-e39e-42cc-b950-96db073918ee', # 'attached': True, # 'url': 'http://localhost:47181/with_title_1', # 'type': 'page' # } title = tgt['title'] cur_url = tgt['url'] return title, cur_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 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 contained markup during rendering (via javascript), this function will not reflect the changes made by the javascript. The rendered page content can be retreived by calling `get_rendered_page_source()`. Due to the remote api structure, accessing the raw content after the content has been loaded is not possible, so any task requiring the raw content must be careful to request it before it actually navigates to said content. Return value is a dictionary with two keys: { 'binary' : (boolean, true if content is binary, false if not) 'content' : (string of bytestring, depending on whether `binary` is true or not) } ''' resp = self.blocking_navigate(url, timeout) assert 'requestId' in resp assert 'response' in resp # self.log.debug('blocking_navigate Response %s', pprint.pformat(resp)) ctype = 'application/unknown' resp_response = resp['response'] if 'mimeType' in resp_response: ctype = resp_response['mimeType'] if 'headers' in resp_response and 'content-type' in resp_response['headers']: ctype = resp_response['headers']['content-type'].split(";")[0] self.log.debug("Trying to get response body") try: ret = self.get_unpacked_response_body(resp['requestId'], mimetype=ctype) except ChromeError: ret = self.handle_page_location_changed(timeout) 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 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 page. For unmodified content, use `blocking_navigate_and_get_source()` dom_idle_requirement_secs specifies the period of time for which there must have been no DOM modifications before treating the rendered output as "final". This call will therefore block for at least dom_idle_requirement_secs seconds. ''' # There are a bunch of events which generally indicate a page is still doing *things*. # I have some concern about how this will handle things like advertisements, which # basically load crap forever. That's why we have the max_wait_timeout. target_events = [ "Page.frameResized", "Page.frameStartedLoading", "Page.frameNavigated", "Page.frameAttached", "Page.frameStoppedLoading", "Page.frameScheduledNavigation", "Page.domContentEventFired", "Page.frameClearedScheduledNavigation", "Page.loadEventFired", "DOM.documentUpdated", "DOM.childNodeInserted", "DOM.childNodeRemoved", "DOM.childNodeCountUpdated", ] start_time = time.time() try: while 1: if time.time() - start_time > max_wait_timeout: self.log.debug("Page was not idle after waiting %s seconds. Giving up and extracting content now.", max_wait_timeout) self.transport.recv_filtered(filter_funcs.wait_for_methods(target_events), tab_key=self.tab_id, timeout=dom_idle_requirement_secs) except ChromeResponseNotReceived: # We timed out, the DOM is probably idle. pass # We have to find the DOM root node ID dom_attr = self.DOM_getDocument(depth=-1, pierce=False) assert 'result' in dom_attr assert 'root' in dom_attr['result'] assert 'nodeId' in dom_attr['result']['root'] # Now, we have the root node ID. root_node_id = dom_attr['result']['root']['nodeId'] # Use that to get the HTML for the specified node response = self.DOM_getOuterHTML(nodeId=root_node_id) assert 'result' in response assert 'outerHTML' in response['result'] return response['result']['outerHTML']
<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 page is ready. Internals: A navigation command results in a sequence of events: - Page.frameStartedLoading" (with frameid) - Page.frameStoppedLoading" (with frameid) - Page.loadEventFired" (not attached to an ID) Therefore, this call triggers a navigation option, and then waits for the expected set of response event messages. ''' self.transport.flush(tab_key=self.tab_id) ret = self.Page_navigate(url = url) assert("result" in ret), "Missing return content" assert("frameId" in ret['result']), "Missing 'frameId' in return content" assert("loaderId" in ret['result']), "Missing 'loaderId' in return content" expected_id = ret['result']['frameId'] loader_id = ret['result']['loaderId'] try: self.log.debug("Waiting for frame navigated command response.") self.transport.recv_filtered(filter_funcs.check_frame_navigated_command(expected_id), tab_key=self.tab_id, timeout=timeout) self.log.debug("Waiting for frameStartedLoading response.") self.transport.recv_filtered(filter_funcs.check_frame_load_command("Page.frameStartedLoading"), tab_key=self.tab_id, timeout=timeout) self.log.debug("Waiting for frameStoppedLoading response.") self.transport.recv_filtered(filter_funcs.check_frame_load_command("Page.frameStoppedLoading"), tab_key=self.tab_id, timeout=timeout) # self.transport.recv_filtered(check_load_event_fired, tab_key=self.tab_id, timeout=timeout) self.log.debug("Waiting for responseReceived response.") resp = self.transport.recv_filtered(filter_funcs.network_response_recieved_for_url(url=None, expected_id=expected_id), tab_key=self.tab_id, timeout=timeout) if resp is None: raise ChromeNavigateTimedOut("Blocking navigate timed out!") return resp['params'] # The `Page.frameNavigated ` event does not get fired for non-markup responses. # Therefore, if we timeout on waiting for that, check to see if we received a binary response. except ChromeResponseNotReceived: # So this is basically broken, fix is https://bugs.chromium.org/p/chromium/issues/detail?id=831887 # but that bug report isn't fixed yet. # Siiiigh. self.log.warning("Failed to receive expected response to navigate command. Checking if response is a binary object.") resp = self.transport.recv_filtered( keycheck = filter_funcs.check_frame_loader_command( method_name = "Network.responseReceived", loader_id = loader_id ), tab_key = self.tab_id, timeout = timeout) return resp['params']
<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() constructor. ''' log = logging.getLogger("Main.ChromeController.ChromeContext") chrome_created = False try: chrome_instance = ChromeRemoteDebugInterface(*args, **kwargs) chrome_created = True log.info("Entering chrome context") yield chrome_instance except Exception as e: log.error("Exception in chrome context!") for line in traceback.format_exc().split("\n"): log.error(line) raise e finally: log.info("Exiting chrome context") if chrome_created: chrome_instance.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 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 chrome instance describing the problem and it's cause. Otherwise, the decoded json data-structure returned from the remote instance is returned. ''' self.transport.check_process_ded() ret = self.transport.synchronous_command(tab_key=self.tab_id, *args, **kwargs) self.transport.check_process_ded() self.__check_ret(ret) self.transport.check_process_ded() 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 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 type needs. ''' self.transport.check_process_ded() ret = self.transport.drain(tab_key=self.tab_id) self.transport.check_process_ded() 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 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. Therefore, we manually enter the logging module, and forcefully release all the locks it holds. THIS IS NOT SAFE (or thread-safe). Basically, it MUST be called right after a process starts, and no where else. ''' try: logging._releaseLock() except RuntimeError: pass # The lock is already released # Iterate over the root logger hierarchy, and # force-free all locks. # if logging.Logger.root for handler in logging.Logger.manager.loggerDict.values(): if hasattr(handler, "lock") and handler.lock: try: handler.lock.release() except RuntimeError: pass
<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: Other party's public key :type other_public_key: int :param echo_return_key: Echo return shared key :type bool :return: void :rtype: void """
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.shared_secret.bit_length() // 8 + 1, byteorder='big') _h = sha256() _h.update(bytes(shared_secret_as_bytes)) self.shared_key = _h.hexdigest() if echo_return_key is True: return self.shared_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 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 enough to use this to effect definition of both public and private key. """
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 stamp. print_frame_info (bool) : Add frame info to the print message. """
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) try: response = urlopen(request) return True, response.code except urllib2.HTTPError as e: return False, e.code
<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.google.com/?q=hello+world") WebUtils.get_base_url(driver) #returns 'http://www.google.com' """
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 matching the provided PageObject class. Args: page_class (PageObject): Page class to search for/instantiate. webdriver (WebDriver): Selenium webdriver. Usage:: WebUtils.switch_to_window(DetailsPopUpPage, driver) # switches to the pop up window. """
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: pass webdriver.switch_to_window(original_window) raise WindowNotFoundError( u("Window {0} not found.").format(page_class.__class__.__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 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_path = temp_path("myfile") copyfile("myfile", temp_file_path) # copies 'myfile' to '/tmp/myfile' """
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 the contents of a URL to a tempfile, which you then can open and use to validate the downloaded contents. Args: url (str) : URL of the contents to download. Kwargs: file_name (str): Name of file. extension (str): Extension to use. Return: str - Returns path to the temp file. """
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_path(file_name + ext) webFile = urllib.urlopen(url) localFile = open(file_path, 'w') localFile.write(webFile.read()) webFile.close() localFile.close() return file_path
<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. Args: webdriver (Webdriver): Instance of Selenium Webdriver. Returns: PageObject Raises: InvalidPageError """
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_object_class_or_interface (Class): PageObject class, AbstractBaseClass, or Interface to attempt to consturct. Kwargs: webdriver (WebDriver): Selenium Webdriver to use to instantiate the page. If none is provided, then it was use the default from WTF_WEBDRIVER_MANAGER Returns: PageObject Raises: NoMatchingPageError Instantiating a Page from PageObject from class usage:: my_page_instance = PageFactory.create_page(MyPageClass) Instantiating a Page from an Interface or base class:: import pages.mysite.* # Make sure you import classes first, or else PageFactory will not know about it. my_page_instance = PageFactory.create_page(MyPageInterfaceClass) Instantiating a Page from a list of classes.:: my_page_instance = PageFactory.create_page([PossiblePage1, PossiblePage2]) Note: It'll only be able to detect pages that are imported. To it's best to do an import of all pages implementing a base class or the interface inside the __init__.py of the package directory. """
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 # Walk through all classes if a list was passed. if type(page_object_class_or_interface) == list: subclasses = [] for page_class in page_object_class_or_interface: # attempt to instantiate class. page = PageFactory.__instantiate_page_object(page_class, webdriver, **kwargs) if isinstance(page, PageObject): was_validate_called = True if (current_matched_page == None or page > current_matched_page): current_matched_page = page elif page is True: was_validate_called = True # check for subclasses subclasses += PageFactory.__itersubclasses(page_class) else: # A single class was passed in, try to instantiate the class. page_class = page_object_class_or_interface page = PageFactory.__instantiate_page_object(page_class, webdriver, **kwargs) # Check if we got a valid PageObject back. if isinstance(page, PageObject): was_validate_called = True current_matched_page = page elif page is True: was_validate_called = True # check for subclasses subclasses = PageFactory.__itersubclasses( page_object_class_or_interface) # Iterate over subclasses of the passed in classes to see if we have a # better match. for pageClass in subclasses: try: page = PageFactory.__instantiate_page_object(pageClass, webdriver, **kwargs) # If we get a valid PageObject match, check to see if the ranking is higher # than our current PageObject. if isinstance(page, PageObject): was_validate_called = True if current_matched_page == None or page > current_matched_page: current_matched_page = page elif page is True: was_validate_called = True except InvalidPageError as e: _wtflog.debug("InvalidPageError: %s", e) pass # This happens when the page fails check. except TypeError as e: _wtflog.debug("TypeError: %s", e) # this happens when it tries to instantiate the original # abstract class. pass except Exception as e: _wtflog.debug("Exception during page instantiation: %s", e) # Unexpected exception. raise e # If no matching classes. if not isinstance(current_matched_page, PageObject): # Check that there is at least 1 valid page object that was passed in. if was_validate_called is False: raise TypeError("Neither the PageObjects nor it's subclasses have implemented " + "'PageObject._validate(self, webdriver)'.") try: current_url = webdriver.current_url raise NoMatchingPageError(u("There's, no matching classes to this page. URL:{0}") .format(current_url)) except: raise NoMatchingPageError(u("There's, no matching classes to this page. ")) else: return current_matched_page
<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 instantiate. webdriver (WebDriver) - Selenium webdriver to associate with the PageObject Returns: PageObject - If page object instantiation succeeded. True - If page object instantiation failed, but validation was called. None - If validation did not occur. """
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: # this happens when it tries to instantiate the original abstract # class, or a PageObject where _validate() was not implemented. return False except Exception as e: # Unexpected exception. raise 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 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: webdriver (Webdriver) : Selenium Webdriver instance selectors (str) : N number of CSS selectors strings to match against the page. Returns: True, False - if the page matches all selectors. Usage Example:: # Checks for a Form with id='loginForm' and a button with class 'login' if not PageObjectUtils.check_css_selectors("form#loginForm", "button.login"): raise InvalidPageError("This is not the login page.") You can use this within a PageObject's `_validate_page(webdriver)` method for validating pages. """
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 until the page is loaded. Args: page_obj_class (Class) : PageObject class Kwargs: webdriver (Webdriver) : Selenium Webdriver. Default uses WTF_WEBDRIVER_MANAGER's instance. timeout (number) : Number of seconds to wait to allow the page to load. sleep (number) : Number of seconds to wait between polling. bad_page_classes (list) : List of PageObject classes to fail if matched. For example, ServerError page. message (string) : Use your own message with PageLoadTimeoutError raised. Returns: PageObject Raises: PageUtilOperationTimeoutError : Timeout occurred before the desired PageObject was matched. BadPageEncounteredError : One or more of the PageObject in the specified 'bad_page_classes' list was matched. Usage Example:: webdriver.get("http://www.mysite.com/login") # Wait up to 60 seconds for the page to load. login_page = wait_until_page_loaded(LoginPage, timeout=60, [ServerErrorPage]) This will wait for the login_page to load, then return a LoginPage() PageObject. """
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 = None while datetime.now() < end_time: # Check to see if we're at our target page. try: page = PageFactory.create_page( page_obj_class, webdriver=webdriver, **kwargs) return page except Exception as e: _wtflog.debug("Encountered exception: %s ", e) last_exception = e # Check to see if we're at one of those labled 'Bad' pages. for bad_page_class in bad_page_classes: try: PageFactory.create_page( bad_page_class, webdriver=webdriver, **kwargs) # if the if/else statement succeeds, than we have an error. raise BadPageEncounteredError( u("Encountered a bad page. ") + bad_page_class.__name__) except BadPageEncounteredError as e: raise e except: pass # We didn't hit a bad page class yet. # sleep till the next iteration. time.sleep(sleep) print "Unable to construct page, last exception", last_exception # Attempt to get current URL to assist in debugging try: current_url = webdriver.current_url except: # unable to get current URL, could be a webdriver for a non-webpage like mobile app. current_url = None if message: err_msg = u(message) + u("{page}:{url}")\ .format(page=PageUtils.__get_name_for_class__(page_obj_class), url=current_url) else: err_msg = u("Timed out while waiting for {page} to load. Url:{url}")\ .format(page=PageUtils.__get_name_for_class__(page_obj_class), url=current_url) raise PageLoadTimeoutError(err_msg)
<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 a file in /assets folder to fetch the path for. Returns: str - path to the target file. Raises: AssetNotFoundError - if asset does not exist in the asset folder. Usage:: path = WTF_ASSET_MANAGER.get_asset_path("my_asset.png") # path = /your/workspace/location/WTFProjectName/assets/my_asset.png """
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, this gets appended to the test name sent to selenium grid. Returns: WebDriver - Selenium Webdriver instance. ''' try: driver_type = self._config_reader.get( self.DRIVER_TYPE_CONFIG) except: driver_type = self.DRIVER_TYPE_LOCAL _wtflog.warn("%s setting is missing from config. Using default setting, %s", self.DRIVER_TYPE_CONFIG, driver_type) if driver_type == self.DRIVER_TYPE_REMOTE: # Create desired capabilities. self.webdriver = self.__create_remote_webdriver_from_config( testname=testname) else: # handle as local webdriver self.webdriver = self.__create_driver_from_browser_config() try: self.webdriver.maximize_window() except: # wait a short period and try again. time.sleep(self._timeout_mgr.BRIEF) try: self.webdriver.maximize_window() except Exception as e: if (isinstance(e, WebDriverException) and "implemented" in e.msg.lower()): pass # Maximizing window not supported by this webdriver. else: _wtflog.warn("Unable to maxmize browser window. " + "It may be possible the browser did not instantiate correctly. % s", e) return self.webdriver
<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: selenium_server_path = self._config_reader.get( self.SELENIUM_SERVER_LOCATION) self._env_vars[ self.__SELENIUM_SERVER_JAR_ENV] = selenium_server_path except KeyError: raise RuntimeError(u("Missing selenium server path config {0}.").format( self.SELENIUM_SERVER_LOCATION)) return webdriver.Safari()
<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']) except KeyError: return webdriver.PhantomJS(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(): for driver in self.__registered_drivers[key]: try: _wtflog.debug( "Shutdown hook closing Webdriver for thread: %s", key) driver.quit() except: pass except: pass
<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.herokuapp.com") WTF_WEBDRIVER_MANAGER.close_driver() """
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: driver.delete_all_cookies() # check to see if webdriver is still responding driver.get("about:blank") except: pass if driver is not None: try: driver.quit() except: pass self.__unregister_driver(channel) if driver in self.__registered_drivers[channel]: self.__registered_drivers[channel].remove(driver) self.webdriver = 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 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.herokuapp.com") same_driver = WTF_WEBDRIVER_MANAGER.get_driver() print(driver is same_driver) # True ''' driver = self.__get_driver_for_channel(self.__get_channel()) if driver is None: driver = self.new_driver() return driver
<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].append(webdriver) # Set singleton instance for the channel self.__webdriver[channel] = webdriver
<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 screenshot as. """
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_name (str) - File name to save screenshot as. """
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(webdriver, remote.webdriver.WebDriver): # If this is a remote webdriver. We need to transmit the image data # back across system boundries as a base 64 encoded string so it can # be decoded back on the local system and written to disk. base64_data = webdriver.get_screenshot_as_base64() screenshot_data = base64.decodestring(base64_data) screenshot_file = open(file_location, "wb") screenshot_file.write(screenshot_data) screenshot_file.close() else: webdriver.save_screenshot(file_location)
<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: timeout (number) : Maximum number of seconds to wait. sleep (number) : Sleep time to wait between iterations. Example:: wait_and_ignore(lambda: driver.find_element_by_id("success").is_displayed(), timeout=30, sleep=0.5) is equivalent to:: end_time = datetime.now() + timedelta(seconds=30) while datetime.now() < end_time: try: if driver.find_element_by_id("success").is_displayed(): break; except: pass time.sleep(0.5) ''' try: return wait_until(condition, timeout, sleep) except: pass
<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 to search for. Kwargs: match_recipient (str) : Recipient to match exactly. (don't care if not specified) Returns: True - email found, False - email not found """
# 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 Exception as e: raise 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 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 matching subjects is found. Args: subject (str) - Subject to search for. Kwargs: limit (int) - Limit search to X number of matches, default 50 match_recipient (str) - Recipient to exactly (don't care if not specified) Returns: list - List of Integers representing imap message UIDs. """
# 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: message_type: Can be 'text' or 'html' """
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_type: return part.get_payload(decode=True) except: # handle as plain text email return msg.get_payload(decode=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 __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}")' .format(subject=subject)) uid_list = data[0].split() return uid_list else: _, data = self._mail.uid('search', None, '(HEADER SUBJECT "{subject}" TO "{recipient}")' .format(subject=subject, recipient=match_recipient)) filtered_list = [] uid_list = data[0].split() for uid in uid_list: # Those hard coded indexes [1][0][1] is a hard reference to the message email message headers # that's burried in all those wrapper objects that's associated # with fetching a message. to_addr = re.search( "[^-]To: (.*)", self._mail.uid('fetch', uid, "(RFC822)")[1][0][1]).group(1).strip() if (to_addr == match_recipient or to_addr == "<{0}>".format(match_recipient)): # Add matching entry to the list. filtered_list.append(uid) return filtered_list
<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: default_value - Default value to return if config is not specified. Returns: Returns value stored in config file. ''' # First attempt to get the var from OS enviornment. os_env_string = ConfigReader.ENV_PREFIX + key os_env_string = os_env_string.replace(".", "_") if type(os.getenv(os_env_string)) != NoneType: return os.getenv(os_env_string) # Otherwise search through config files. for data_map in self._dataMaps: try: if "." in key: # this is a multi levl string namespaces = key.split(".") temp_var = data_map for name in namespaces: temp_var = temp_var[name] return temp_var else: value = data_map[key] return value except (AttributeError, TypeError, KeyError): pass if default_value == self.__NoDefaultSpecified__: raise KeyError(u("Key '{0}' does not exist").format(key)) else: return default_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 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 verification. ", partial_url) except: # use full url since we couldn't extract a partial. partial_url = url print("Could not find usable partial url, using full url.", url) # Attempt to map input objects. print("Processing page source...") response = urllib2.urlopen(url) html = response.read() input_tags_expr = u('<\s*input[^>]*>') input_tag_iter = re.finditer(input_tags_expr, html, re.IGNORECASE) objectmap = "" print("Creating object map for <input> tags...") for input_tag_match in input_tag_iter: if not "hidden" in input_tag_match.group(0): try: print("processing", input_tag_match.group(0)) obj_map_entry = _process_input_tag(input_tag_match.group(0)) objectmap += u(" ") + obj_map_entry + "\n" except Exception as e: print(e) # we failed to process it, nothing more we can do. pass return _page_object_template_.contents.format(date=datetime.now(), url=url, pagename=page_name, partialurl=partial_url, objectmap=objectmap)
<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_prefix (string) : Name of subfolder, ex: 'qa' will find files in /data/qa Returns: String - path to file. Usage:: open(WTF_DATA_MANAGER.get_data_path('testdata.csv') Note: WTF_DATA_MANAGER is a provided global instance of DataManager """
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 DataNotFoundError( u("Cannot find data file: {0}").format(target_file))
<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() raise 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 wait_until_element_not_visible(webdriver, locator_lambda_expression, timeout=WTF_TIMEOUT_MANAGER.NORMAL, sleep=0.5): """ Wait for a WebElement to disappear. Args: webdriver (Webdriver) - Selenium Webdriver locator (lambda) - Locator lambda expression. Kwargs: timeout (number) - timeout period sleep (number) - sleep period between intervals. """
# 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) if element.is_displayed(): time.sleep(sleep) else: break except TimeoutException: pass
<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 subject. number_of_random_chars (int) : Number of random characters to append. This method is helpful for creating unique names with timestamps in them so when you have to troubleshoot an issue, the name is easier to find.:: self.project_name = generate_timestamped_string("project") new_project_page.create_project(project_name) """
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=random_str)
<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_chars (int) : Number of characters long character_set (str): Specify a character set. Default is ASCII """
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 applicable for nominal and string types. """
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] == TYPE_NOMINAL cls_index, cls_value = index.split(':') #return self.attribute_data[name][index-1] if cls_value != MISSING: assert cls_value in self.attribute_data[name], \ 'Predicted value "%s" but only values %s are allowed.' \ % (cls_value, ', '.join(self.attribute_data[name])) return cls_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 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.deepcopy(self.data) return o
<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 prevents you from directly accessing the data via Python, but when generating a huge file, this prevents all your data from being stored in memory. """
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) self.write(fout=self.fout, data_only=True) self.fout.flush()
<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('% ' + re.sub("\n", "\n% ", '\n'.join(self.comment)), file=fout) print("@relation " + self.relation, file=fout) self.write_attributes(fout=fout) if not schema_only: print("@data", file=fout) for d in self.data: line_str = self.write_line(d, fmt=fmt) if line_str: print(line_str, file=fout) if isinstance(fout, StringIO) and close: return fout.getvalue()