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 show_graph(cn_topo, showintfs=False, showaddrs=False): ''' Display the topology ''' __do_draw(cn_topo, showintfs=showintfs, showaddrs=showaddrs) pyp.show()
<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_graph(cn_topo, filename, showintfs=False, showaddrs=False): ''' Save the topology to an image file ''' __do_draw(cn_topo, showintfs=showintfs, showaddrs=showaddrs) pyp.savefig(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 load_from_file(filename): ''' Load a topology from filename and return it. ''' t = None with open(filename, 'rU') as infile: tdata = infile.read() t = Topology.unserialize(tdata) return 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 save_to_file(cn_topo, filename): ''' Save a topology to a file. ''' jstr = cn_topo.serialize() with open(filename, 'w') as outfile: outfile.write(jstr)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def __addNode(self, name, cls): ''' Add a node to the topology ''' if name in self.nodes: raise Exception("A node by the name {} already exists. Can't add a duplicate.".format(name)) self.__nxgraph.add_node(name) self.__nxgraph.node[name]['label'] = 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 addHost(self, name=None): ''' Add a new host node to the topology. ''' if name is None: while True: name = 'h' + str(self.__hnum) self.__hnum += 1 if name not in self.__nxgraph: break self.__addNo...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def addLink(self, node1, node2, capacity, delay): ''' Add a bidirectional link between node1 and node2 with the given capacity and delay to the topology. ''' for n in (node1, node2): if not self.__nxgraph.has_node(n): raise Exception("No node {} exists...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def serialize(self): ''' Return a JSON string of the serialized topology ''' return json.dumps(json_graph.node_link_data(self.__nxgraph), cls=Encoder)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def unserialize(jsonstr): ''' Unserialize a JSON string representation of a topology ''' topod = json.loads(jsonstr) G = json_graph.node_link_graph(topod) for n,ndict in G.nodes(data=True): if 'nodeobj' not in ndict or 'type' not in ndict: rais...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def getInterfaceAddresses(self, node, interface): ''' Return the Ethernet and IP+mask addresses assigned to a given interface on a node. ''' intf = self.getNode(node)['nodeobj'].getInterface(interface) return intf.ethaddr,intf.ipaddr,intf.netmask
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def addNodeLabelPrefix(self, prefix=None, copy=False): ''' Rename all nodes in the network from x to prefix_x. If no prefix is given, use the name of the graph as the prefix. The purpose of this method is to make node names unique so that composing two graphs is well-de...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def from_bytes(self, raw): '''Return a Null header object reconstructed from raw bytes, or an Exception if we can't resurrect the packet.''' if len(raw) < 4: raise NotEnoughDataError("Not enough bytes ({}) to reconstruct a Null object".format(len(raw))) fields = struct.unpack...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def add_header(self, ph): ''' Add a PacketHeaderBase derived class object, or a raw bytes object as the next "header" item in this packet. Note that 'header' may be a slight misnomer since the last portion of a packet is considered application payload and not a header per se. ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def has_header(self, hdrclass): ''' Return True if the packet has a header of the given hdrclass, False otherwise. ''' if isinstance(hdrclass, str): return self.get_header_by_name(hdrclass) is not None return self.get_header(hdrclass) is not 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_header(self, hdrclass, returnval=None): ''' Return the first header object that is of class hdrclass, or None if the header class isn't found. ''' if isinstance(hdrclass, str): return self.get_header_by_name(hdrclass) for hdr in self._headers:...
<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_header_class(self): '''Return class of next header, if known.''' if self._next_header_class_key == '': return None key = getattr(self, self._next_header_class_key) rv = self._next_header_map.get(key, None) if rv is None: log_warn("No class exists ...
<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, request, hook_id): """ Verify token when configuring webhook from facebook dev. MessengerBot.id is used for verification """
try: bot = caching.get_or_set(MessengerBot, hook_id) except MessengerBot.DoesNotExist: logger.warning("Hook id %s not associated to a bot" % hook_id) return Response(status=status.HTTP_404_NOT_FOUND) if request.query_params.get('hub.verify_token') == str(bot....
<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_value(self, value): """This function name was changed in Django 1.10 and removed in 2.0."""
# Use renamed format_name() for Django versions >= 1.10. if hasattr(self, 'format_value'): return super(DateTimePicker, self).format_value(value) # Use old _format_name() for Django versions < 1.10. else: return super(DateTimePicker, self)._format_value(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 authorize_url(self, client_id, redirect_uri, scope, state=None): """Get the authorization URL for your application, given the application's client_id, redire...
params = [ ('client_id', client_id), ('redirect_uri', redirect_uri), ('scope', scope) ] if state: params.append(('state', state)) return "%s?%s" % (CreateSend.oauth_uri, urlencode(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 exchange_token(self, client_id, client_secret, redirect_uri, code): """Exchange a provided OAuth code for an OAuth access token, 'expires in' value and refre...
params = [ ('grant_type', 'authorization_code'), ('client_id', client_id), ('client_secret', client_secret), ('redirect_uri', redirect_uri), ('code', code), ] response = self._post('', urlencode(params), 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 refresh_token(self): """Refresh an OAuth token given a refresh token."""
if (not self.auth_details or not 'refresh_token' in self.auth_details or not self.auth_details['refresh_token']): raise Exception( "auth_details['refresh_token'] does not contain a refresh token.") refresh_token = self.auth_details['refresh_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 stub_request(self, expected_url, filename, status=None, body=None): """Stub a web request for testing."""
self.fake_web = True self.faker = get_faker(expected_url, filename, status, body)
<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, client_id=None, email_address=None): """Gets a person by client ID and email address."""
params = {"email": email_address or self.email_address} response = self._get("/clients/%s/people.json" % (client_id or self.client_id), params=params) return json_to_py(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 add(self, client_id, email_address, name, access_level, password): """Adds a person to a client. Password is optional and if not supplied, an invitation will...
body = { "EmailAddress": email_address, "Name": name, "AccessLevel": access_level, "Password": password} response = self._post("/clients/%s/people.json" % client_id, json.dumps(body)) return json_to_py(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 update(self, new_email_address, name, access_level, password=None): """Updates the details for a person. Password is optional and is only updated if supplied...
params = {"email": self.email_address} body = { "EmailAddress": new_email_address, "Name": name, "AccessLevel": access_level, "Password": password} response = self._put("/clients/%s/people.json" % self.client_id, body=...
<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(self, client_id, subject, name, from_name, from_email, reply_to, html_url, text_url, list_ids, segment_ids): """Creates a new campaign for a client. :...
body = { "Subject": subject, "Name": name, "FromName": from_name, "FromEmail": from_email, "ReplyTo": reply_to, "HtmlUrl": html_url, "TextUrl": text_url, "ListIDs": list_ids, "SegmentIDs": segment_ids} ...
<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_from_template(self, client_id, subject, name, from_name, from_email, reply_to, list_ids, segment_ids, template_id, template_content): """Creates a new...
body = { "Subject": subject, "Name": name, "FromName": from_name, "FromEmail": from_email, "ReplyTo": reply_to, "ListIDs": list_ids, "SegmentIDs": segment_ids, "TemplateID": template_id, "TemplateContent...
<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_preview(self, recipients, personalize="fallback"): """Sends a preview of this campaign."""
body = { "PreviewRecipients": [recipients] if isinstance(recipients, str) else recipients, "Personalize": personalize} response = self._post(self.uri_for("sendpreview"), json.dumps(body))
<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, confirmation_email, send_date="immediately"): """Sends this campaign."""
body = { "ConfirmationEmail": confirmation_email, "SendDate": send_date} response = self._post(self.uri_for("send"), json.dumps(body))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def opens(self, date="", page=1, page_size=1000, order_field="date", order_direction="asc"): """Retrieves the opens for this campaign."""
params = { "date": date, "page": page, "pagesize": page_size, "orderfield": order_field, "orderdirection": order_direction} response = self._get(self.uri_for("opens"), params=params) return json_to_py(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 create(self, company, timezone, country): """Creates a client."""
body = { "CompanyName": company, "TimeZone": timezone, "Country": country} response = self._post("/clients.json", json.dumps(body)) self.client_id = json_to_py(response) return self.client_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 lists_for_email(self, email_address): """Gets the lists across a client to which a subscriber with a particular email address belongs."""
params = {"email": email_address} response = self._get(self.uri_for("listsforemail"), params=params) return json_to_py(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 suppressionlist(self, page=1, page_size=1000, order_field="email", order_direction="asc"): """Gets this client's suppression list."""
params = { "page": page, "pagesize": page_size, "orderfield": order_field, "orderdirection": order_direction} response = self._get(self.uri_for("suppressionlist"), params=params) return json_to_py(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 suppress(self, email): """Adds email addresses to a client's suppression list"""
body = { "EmailAddresses": [email] if isinstance(email, str) else email} response = self._post(self.uri_for("suppress"), json.dumps(body))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def unsuppress(self, email): """Unsuppresses an email address by removing it from the the client's suppression list"""
params = {"email": email} response = self._put(self.uri_for("unsuppress"), body=" ", params=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 set_payg_billing(self, currency, can_purchase_credits, client_pays, markup_percentage, markup_on_delivery=0, markup_per_recipient=0, markup_on_design_spam_tes...
body = { "Currency": currency, "CanPurchaseCredits": can_purchase_credits, "ClientPays": client_pays, "MarkupPercentage": markup_percentage, "MarkupOnDelivery": markup_on_delivery, "MarkupPerRecipient": markup_per_recipient, "M...
<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_monthly_billing(self, currency, client_pays, markup_percentage, monthly_scheme=None): """Sets the monthly billing settings for this client."""
body = { "Currency": currency, "ClientPays": client_pays, "MarkupPercentage": markup_percentage} if monthly_scheme is not None: body["MonthlyScheme"] = monthly_scheme response = self._put(self.uri_for( 'setmonthlybilling'), json.dump...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def transfer_credits(self, credits, can_use_my_credits_when_they_run_out): """Transfer credits to or from this client. :param credits: An Integer representing th...
body = { "Credits": credits, "CanUseMyCreditsWhenTheyRunOut": can_use_my_credits_when_they_run_out} response = self._post(self.uri_for('credits'), json.dumps(body)) return json_to_py(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 set_primary_contact(self, email): """assigns the primary contact for this client"""
params = {"email": email} response = self._put(self.uri_for('primarycontact'), params=params) return json_to_py(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 smart_email_list(self, status="all", client_id=None): """Gets the smart email list."""
if client_id is None: response = self._get( "/transactional/smartEmail?status=%s" % status) else: response = self._get( "/transactional/smartEmail?status=%s&clientID=%s" % (status, client_id)) return json_to_py(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 smart_email_send(self, smart_email_id, to, consent_to_track, cc=None, bcc=None, attachments=None, data=None, add_recipients_to_list=None): """Sends the smart...
validate_consent_to_track(consent_to_track) body = { "To": to, "CC": cc, "BCC": bcc, "Attachments": attachments, "Data": data, "AddRecipientsToList": add_recipients_to_list, "ConsentToTrack": consent_to_track, }...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def classic_email_send(self, subject, from_address, to, consent_to_track, client_id=None, cc=None, bcc=None, html=None, text=None, attachments=None, track_opens=T...
validate_consent_to_track(consent_to_track) body = { "Subject": subject, "From": from_address, "To": to, "CC": cc, "BCC": bcc, "HTML": html, "Text": text, "Attachments": attachments, "TrackOpens"...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def classic_email_groups(self, client_id=None): """Gets the list of classic email groups."""
if client_id is None: response = self._get("/transactional/classicEmail/groups") else: response = self._get( "/transactional/classicEmail/groups?clientID=%s" % client_id) return json_to_py(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 message_details(self, message_id, statistics=False): """Gets the details of this message."""
response = self._get( "/transactional/messages/%s?statistics=%s" % (message_id, statistics)) return json_to_py(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 create(self, list_id, title, rulegroups): """Creates a new segment."""
body = { "Title": title, "RuleGroups": rulegroups} response = self._post("/segments/%s.json" % list_id, json.dumps(body)) self.segment_id = json_to_py(response) return self.segment_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 update(self, title, rulegroups): """Updates this segment."""
body = { "Title": title, "RuleGroups": rulegroups} response = self._put("/segments/%s.json" % self.segment_id, json.dumps(body))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_rulegroup(self, rulegroup): """Adds a rulegroup to this segment."""
body = rulegroup response = self._post("/segments/%s/rules.json" % self.segment_id, json.dumps(body))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def subscribers(self, date="", page=1, page_size=1000, order_field="email", order_direction="asc", include_tracking_information=False): """Gets the active subscr...
params = { "date": date, "page": page, "pagesize": page_size, "orderfield": order_field, "orderdirection": order_direction, "includetrackinginformation": include_tracking_information } response = self._get(self.uri_for("act...
<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(self, client_id, name, html_url, zip_url): """Creates a new email template."""
body = { "Name": name, "HtmlPageURL": html_url, "ZipFileURL": zip_url} response = self._post("/templates/%s.json" % client_id, json.dumps(body)) self.template_id = json_to_py(response) return self.template_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 update(self, name, html_url, zip_url): """Updates this email template."""
body = { "Name": name, "HtmlPageURL": html_url, "ZipFileURL": zip_url} response = self._put("/templates/%s.json" % self.template_id, json.dumps(body))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add(self, email_address, name): """Adds an administrator to an account."""
body = { "EmailAddress": email_address, "Name": name} response = self._post("/admins.json", json.dumps(body)) return json_to_py(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 update(self, new_email_address, name): """Updates the details for an administrator."""
params = {"email": self.email_address} body = { "EmailAddress": new_email_address, "Name": name} response = self._put("/admins.json", body=json.dumps(body), params=params) # Update self.email_address, so this object can continue to be...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def delete(self): """Deletes the administrator from the account."""
params = {"email": self.email_address} response = self._delete("/admins.json", params=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 create(self, client_id, title, unsubscribe_page, confirmed_opt_in, confirmation_success_page, unsubscribe_setting="AllClientLists"): """Creates a new list fo...
body = { "Title": title, "UnsubscribePage": unsubscribe_page, "ConfirmedOptIn": confirmed_opt_in, "ConfirmationSuccessPage": confirmation_success_page, "UnsubscribeSetting": unsubscribe_setting} response = self._post("/lists/%s.json" % client_...
<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_custom_field(self, field_name, data_type, options=[], visible_in_preference_center=True): """Creates a new custom field for this list."""
body = { "FieldName": field_name, "DataType": data_type, "Options": options, "VisibleInPreferenceCenter": visible_in_preference_center} response = self._post(self.uri_for("customfields"), json.dumps(body)) return json_to_py(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 update_custom_field(self, custom_field_key, field_name, visible_in_preference_center): """Updates a custom field belonging to this list."""
custom_field_key = quote(custom_field_key, '') body = { "FieldName": field_name, "VisibleInPreferenceCenter": visible_in_preference_center} response = self._put(self.uri_for("customfields/%s" % custom_field_key), json.dumps(body)...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def delete_custom_field(self, custom_field_key): """Deletes a custom field associated with this list."""
custom_field_key = quote(custom_field_key, '') response = self._delete("/lists/%s/customfields/%s.json" % (self.list_id, custom_field_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 update_custom_field_options(self, custom_field_key, new_options, keep_existing_options): """Updates the options of a multi-optioned custom field on this list...
custom_field_key = quote(custom_field_key, '') body = { "Options": new_options, "KeepExistingOptions": keep_existing_options} response = self._put(self.uri_for( "customfields/%s/options" % custom_field_key), json.dumps(body))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def active(self, date="", page=1, page_size=1000, order_field="email", order_direction="asc", include_tracking_preference=False): """Gets the active subscribers ...
params = { "date": date, "page": page, "pagesize": page_size, "orderfield": order_field, "orderdirection": order_direction, "includetrackingpreference": include_tracking_preference, } response = self._get(self.uri_for("acti...
<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, title, unsubscribe_page, confirmed_opt_in, confirmation_success_page, unsubscribe_setting="AllClientLists", add_unsubscribes_to_supp_list=False, ...
body = { "Title": title, "UnsubscribePage": unsubscribe_page, "ConfirmedOptIn": confirmed_opt_in, "ConfirmationSuccessPage": confirmation_success_page, "UnsubscribeSetting": unsubscribe_setting, "AddUnsubscribesToSuppList": add_unsubscribe...
<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, list_id=None, email_address=None, include_tracking_preference=False): """Gets a subscriber by list ID and email address."""
params = { "email": email_address or self.email_address, "includetrackingpreference": include_tracking_preference, } response = self._get("/subscribers/%s.json" % (list_id or self.list_id), params=params) return json_to_py(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 add(self, list_id, email_address, name, custom_fields, resubscribe, consent_to_track, restart_subscription_based_autoresponders=False): """Adds a subscriber ...
validate_consent_to_track(consent_to_track) body = { "EmailAddress": email_address, "Name": name, "CustomFields": custom_fields, "Resubscribe": resubscribe, "ConsentToTrack": consent_to_track, "RestartSubscriptionBasedAutoresponder...
<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, new_email_address, name, custom_fields, resubscribe, consent_to_track, restart_subscription_based_autoresponders=False): """Updates any aspect o...
validate_consent_to_track(consent_to_track) params = {"email": self.email_address} body = { "EmailAddress": new_email_address, "Name": name, "CustomFields": custom_fields, "Resubscribe": resubscribe, "ConsentToTrack": consent_to_track,...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def import_subscribers(self, list_id, subscribers, resubscribe, queue_subscription_based_autoresponders=False, restart_subscription_based_autoresponders=False): ...
body = { "Subscribers": subscribers, "Resubscribe": resubscribe, "QueueSubscriptionBasedAutoresponders": queue_subscription_based_autoresponders, "RestartSubscriptionBasedAutoresponders": restart_subscription_based_autoresponders} try: respons...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def unsubscribe(self): """Unsubscribes this subscriber from the associated list."""
body = { "EmailAddress": self.email_address} response = self._post("/subscribers/%s/unsubscribe.json" % self.list_id, json.dumps(body))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def history(self): """Gets the historical record of this subscriber's trackable actions."""
params = {"email": self.email_address} response = self._get("/subscribers/%s/history.json" % self.list_id, params=params) return json_to_py(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 set_input(self): """Returns form input field of Field. """
name = self.attrs.get("_override", self.widget.__class__.__name__) self.values["field"] = str(FIELDS.get(name, FIELDS.get(None))(self.field, self.attrs))
<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_label(self): """Set label markup. """
if not self.field.label or self.attrs.get("_no_label"): return self.values["label"] = format_html( LABEL_TEMPLATE, self.field.html_name, mark_safe(self.field.label) )
<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_help(self): """Set help text markup. """
if not (self.field.help_text and self.attrs.get("_help")): return self.values["help"] = HELP_TEMPLATE.format(self.field.help_text)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_errors(self): """Set errors markup. """
if not self.field.errors or self.attrs.get("_no_errors"): return self.values["class"].append("error") for error in self.field.errors: self.values["errors"] += ERROR_WRAPPER % {"message": error}
<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_icon(self): """Wrap current field with icon wrapper. This setter must be the last setter called. """
if not self.attrs.get("_icon"): return if "Date" in self.field.field.__class__.__name__: return self.values["field"] = INPUT_WRAPPER % { "field": self.values["field"], "help": self.values["help"], "style": "%sicon " % escape(pad(self.attrs.get("_align", ""))), "icon": format_html(...
<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_classes(self): """Set field properties and custom classes. """
# Custom field classes on field wrapper if self.attrs.get("_field_class"): self.values["class"].append(escape(self.attrs.get("_field_class"))) # Inline class if self.attrs.get("_inline"): self.values["class"].append("inline") # Disabled class if self.field.field.disabled: self.values[...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def render(self): """Render field as HTML. """
self.widget.attrs = { k: v for k, v in self.attrs.items() if k[0] != "_" } self.set_input() if not self.attrs.get("_no_wrapper"): self.set_label() self.set_help() self.set_errors() self.set_classes() self.set_icon() # Must be the bottom-most setter self.values["class"] = pad...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ready(self): """ Create test friends for displaying. """
from .models import Friend # Requires migrations, not necessary try: Friend.objects.get_or_create(first_name="Michael", last_name="1", age=22) Friend.objects.get_or_create(first_name="Joe", last_name="2", age=21) Friend.objects.get_or_create(first_name="Bill", last_name="3", age=20) 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 render_booleanfield(field, attrs): """ Render BooleanField with label next to instead of above. """
attrs.setdefault("_no_label", True) # No normal label for booleanfields attrs.setdefault("_inline", True) # Checkbox should be inline field.field.widget.attrs["style"] = "display:hidden" # Hidden field return wrappers.CHECKBOX_WRAPPER % { "style": pad(attrs.get("_style", "")), "field": field, "label": fo...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def render_choicefield(field, attrs, choices=None): """ Render ChoiceField as 'div' dropdown rather than select for more customization. """
# Allow custom choice list, but if no custom choice list then wrap all # choices into the `wrappers.CHOICE_TEMPLATE` if not choices: choices = format_html_join("", wrappers.CHOICE_TEMPLATE, get_choices(field)) # Accessing the widget attrs directly saves them for a new use after # a POST request field.field.wi...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def render_countryfield(field, attrs): """ Render a custom ChoiceField specific for CountryFields. """
choices = ((k, k.lower(), v) for k, v in field.field._choices[1:]) # Render a `ChoiceField` with all countries return render_choicefield( field, attrs, format_html_join("", wrappers.COUNTRY_TEMPLATE, choices) )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def render_multiplechoicefield(field, attrs, choices=None): """ MultipleChoiceField uses its own field, but also uses a queryset. """
choices = format_html_join("", wrappers.CHOICE_TEMPLATE, get_choices(field)) return wrappers.MULTIPLE_DROPDOWN_WRAPPER % { "name": field.html_name, "field": field, "choices": choices, "placeholder": attrs.get("placeholder") or get_placeholder_text(), "style": pad(attrs.get("_style", "")), "icon": format_...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def render_datefield(field, attrs, style="date"): """ DateField that uses wrappers.CALENDAR_WRAPPER. """
return wrappers.CALENDAR_WRAPPER % { "field": field, "style": pad(style), "align": pad(attrs.get("_align", "")), "icon": format_html(wrappers.ICON_TEMPLATE, attrs.get("_icon")), }
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def render_filefield(field, attrs): """ Render a typical File Field. """
field.field.widget.attrs["style"] = "display:none" if not "_no_label" in attrs: attrs["_no_label"] = True return wrappers.FILE_WRAPPER % { "field": field, "id": "id_" + field.name, "style": pad(attrs.get("_style", "")), "text": escape(attrs.get("_text", "Select File")), "icon": format_html(wrappers.IC...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _repeat_iter(input_iter): """Iterate over the input iter values. Then repeat the last value indefinitely. This is useful to repeat seed values when an insuff...
last_value = None for value in input_iter: last_value = value yield value if last_value is not None: while True: yield last_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 seed(self, x=None, *args): """For consistent cross-platform seeding, provide an integer seed. """
if x is None: # Use same random seed code copied from Python's random.Random try: x = long(_hexlify(_urandom(16)), 16) except NotImplementedError: import time x = long(time.time() * 256) # use fractional seconds elif no...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def setbpf(self, bpf): """Set number of bits per float output"""
self._bpf = min(bpf, self.BPF) self._rng_n = int((self._bpf + self.RNG_RANGE_BITS - 1) / self.RNG_RANGE_BITS)
<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_info(cls): """Return information about backend and its availability. :return: A BackendInfo tuple if the import worked, none otherwise. """
mod = try_import(cls.mod_name) if not mod: return None version = getattr(mod, '__version__', None) or getattr(mod, 'version', None) return BackendInfo(version or 'deprecated', '')
<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_choices(field): """ Find choices of a field, whether it has choices or has a queryset. Args: field (BoundField): Django form boundfield Returns: ...
empty_label = getattr(field.field, "empty_label", False) needs_empty_value = False choices = [] # Data is the choices if hasattr(field.field, "_choices"): choices = field.field._choices # Data is a queryset elif hasattr(field.field, "_queryset"): queryset = field.field._queryset field_name = getattr(fi...
<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_class_list(cls) -> DOMTokenList: """Get class-level class list, including all super class's."""
cl = [] cl.append(DOMTokenList(cls, cls.class_)) if cls.inherit_class: for base_cls in cls.__bases__: if issubclass(base_cls, WdomElement): cl.append(base_cls.get_class_list()) # Reverse order so that parent's class comes to front <- why?...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def appendChild(self, child: 'WdomElement') -> Node: """Append child node at the last of child nodes. If this instance is connected to the node on browser, the ch...
if self.connected: self._append_child_web(child) return self._append_child(child)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def insertBefore(self, child: Node, ref_node: Node) -> Node: """Insert new child node before the reference child node. If the reference node is not a child of thi...
if self.connected: self._insert_before_web(child, ref_node) return self._insert_before(child, ref_node)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def removeChild(self, child: Node) -> Node: """Remove the child node from this node. If the node is not a child of this node, raise ValueError. """
if self.connected: self._remove_child_web(child) return self._remove_child(child)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def replaceChild(self, new_child: 'WdomElement', old_child: 'WdomElement' ) -> Node: """Replace child nodes."""
if self.connected: self._replace_child_web(new_child, old_child) return self._replace_child(new_child, old_child)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def textContent(self, text: str) -> None: # type: ignore """Set textContent both on this node and related browser node."""
self._set_text_content(text) if self.connected: self._set_text_content_web(text)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def innerHTML(self, html: str) -> None: # type: ignore """Set innerHTML both on this node and related browser node."""
df = self._parse_html(html) if self.connected: self._set_inner_html_web(df.html) self._empty() self._append_child(df)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def click(self) -> None: """Send click event."""
if self.connected: self.js_exec('click') else: # Web上に表示されてれば勝手にブラウザ側からクリックイベント発生する # のでローカルのクリックイベント不要 msg = {'proto': '', 'type': 'click', 'currentTarget': {'id': self.wdom_id}, 'target': {'id': self.wdom_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 getElementById(id: str) -> Optional[Node]: """Get element with ``id``."""
elm = Element._elements_with_id.get(id) return elm
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getElementByWdomId(id: str) -> Optional[WebEventTarget]: """Get element with ``wdom_id``."""
if not id: return None elif id == 'document': return get_document() elif id == 'window': return get_document().defaultView elm = WdomElement._elements_with_wdom_id.get(id) return elm
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _cleanup(path: str) -> None: """Cleanup temporary directory."""
if os.path.isdir(path): shutil.rmtree(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_element(tag: str, name: str = None, base: type = None, attr: dict = None) -> Node: """Create element with a tag of ``name``. :arg str name: html tag. :...
from wdom.web_node import WdomElement from wdom.tag import Tag from wdom.window import customElements if attr is None: attr = {} if name: base_class = customElements.get((name, tag)) else: base_class = customElements.get((tag, None)) if base_class is None: at...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def characterSet(self, charset: str) -> None: """Set character set of this document."""
charset_node = self._find_charset_node() or Meta(parent=self.head) charset_node.setAttribute('charset', charset)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getElementsBy(self, cond: Callable[[Element], bool]) -> NodeList: """Get elements in this document which matches condition."""
return getElementsBy(self, cond)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getElementById(self, id: str) -> Optional[Node]: """Get element by ``id``. If this document does not have the element with the id, return None. """
elm = getElementById(id) if elm and elm.ownerDocument is self: return elm return None