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
self.__nxgraph.node[name]['nodeobj'] = cls()
self.__nxgraph.node[name]['type'] = cls.__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.__addNode(name, Host)
return 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 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 for building a link".format(n))
macs = [None,None]
if self.__auto_macs:
for i in range(len(macs)):
macstr = '{:012x}'.format(self.__ifnum)
self.__ifnum += 1
macaddr = ':'.join([ macstr[j:(j+2)] for j in range(0,len(macstr),2)])
macs[i] = macaddr
node1if = self.__nxgraph.node[node1]['nodeobj'].addInterface(ethaddr=macs[0])
node2if = self.__nxgraph.node[node2]['nodeobj'].addInterface(ethaddr=macs[1])
self.__nxgraph.add_edge(node1, node2)
self.__nxgraph[node1][node2][node1] = node1if
self.__nxgraph[node1][node2][node2] = node2if
self.setLinkCharacteristics(node1, node2, capacity, delay)
|
<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:
raise Exception("Required type information is not present in serialized node {} :{}".format(n, ndict))
nobj = ndict['nodeobj']
cls = eval(ndict['type'])
ndict['nodeobj'] = cls(**dict(nobj))
t = Topology(nxgraph=G)
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 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-defined.
'''
nxgraph = Topology.__relabel_graph(self.__nxgraph, prefix)
if copy:
newtopo = copy.deepcopy(self)
newtopo.nxgraph = nxgraph
return newtopo
else:
# looks like it was done in place
self.__nxgraph = nxgraph
|
<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('=I', raw[:4])
self._af = fields[0]
return raw[4:]
|
<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.
'''
if isinstance(ph, bytes):
ph = RawPacketContents(ph)
if isinstance(ph, PacketHeaderBase):
self._headers.append(ph)
return self
raise Exception("Payload for a packet header must be an object that is a subclass of PacketHeaderBase, or a bytes object.")
|
<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:
if isinstance(hdr, hdrclass):
return hdr
return returnval
|
<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 to handle next header value {}".format(key))
return rv
|
<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.id):
return Response(int(request.query_params.get('hub.challenge')))
return Response('Error, wrong validation token')
|
<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, redirect_uri, scope, and optional state data."""
|
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 refresh token."""
|
params = [
('grant_type', 'authorization_code'),
('client_id', client_id),
('client_secret', client_secret),
('redirect_uri', redirect_uri),
('code', code),
]
response = self._post('', urlencode(params),
CreateSend.oauth_token_uri, "application/x-www-form-urlencoded")
access_token, expires_in, refresh_token = None, None, None
r = json_to_py(response)
if hasattr(r, 'error') and hasattr(r, 'error_description'):
err = "Error exchanging code for access token: "
err += "%s - %s" % (r.error, r.error_description)
raise Exception(err)
access_token, expires_in, refresh_token = r.access_token, r.expires_in, r.refresh_token
return [access_token, expires_in, refresh_token]
|
<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_token']
params = [
('grant_type', 'refresh_token'),
('refresh_token', refresh_token)
]
response = self._post('', urlencode(params),
CreateSend.oauth_token_uri, "application/x-www-form-urlencoded")
new_access_token, new_expires_in, new_refresh_token = None, None, None
r = json_to_py(response)
new_access_token, new_expires_in, new_refresh_token = r.access_token, r.expires_in, r.refresh_token
self.auth({
'access_token': new_access_token,
'refresh_token': new_refresh_token})
return [new_access_token, new_expires_in, new_refresh_token]
|
<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 be emailed to the person"""
|
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=json.dumps(body), params=params)
# Update self.email_address, so this object can continue to be used
# reliably
self.email_address = new_email_address
|
<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. :param client_id: String representing the ID of the client for whom the campaign will be created. :param subject: String representing the subject of the campaign. :param name: String representing the name of the campaign. :param from_name: String representing the from name for the campaign. :param from_email: String representing the from address for the campaign. :param reply_to: String representing the reply-to address for the campaign. :param html_url: String representing the URL for the campaign HTML content. :param text_url: String representing the URL for the campaign text content. Note that text_url is optional and if None or an empty string, text content will be automatically generated from the HTML content. :param list_ids: Array of Strings representing the IDs of the lists to which the campaign will be sent. :param segment_ids: Array of Strings representing the IDs of the segments to which the campaign will be sent. :returns String representing the ID of the newly created campaign. """
|
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}
response = self._post("/campaigns/%s.json" %
client_id, json.dumps(body))
self.campaign_id = json_to_py(response)
return self.campaign_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 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 campaign for a client, from a template. :param client_id: String representing the ID of the client for whom the campaign will be created. :param subject: String representing the subject of the campaign. :param name: String representing the name of the campaign. :param from_name: String representing the from name for the campaign. :param from_email: String representing the from address for the campaign. :param reply_to: String representing the reply-to address for the campaign. :param list_ids: Array of Strings representing the IDs of the lists to which the campaign will be sent. :param segment_ids: Array of Strings representing the IDs of the segments to which the campaign will be sent. :param template_id: String representing the ID of the template on which the campaign will be based. :param template_content: Hash representing the content to be used for the editable areas of the template. See documentation at campaignmonitor.com/api/campaigns/#creating_a_campaign_from_template for full details of template content format. :returns String representing the ID of the newly created campaign. """
|
body = {
"Subject": subject,
"Name": name,
"FromName": from_name,
"FromEmail": from_email,
"ReplyTo": reply_to,
"ListIDs": list_ids,
"SegmentIDs": segment_ids,
"TemplateID": template_id,
"TemplateContent": template_content}
response = self._post("/campaigns/%s/fromtemplate.json" %
client_id, json.dumps(body))
self.campaign_id = json_to_py(response)
return self.campaign_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 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_test=0):
"""Sets the PAYG billing settings for this client."""
|
body = {
"Currency": currency,
"CanPurchaseCredits": can_purchase_credits,
"ClientPays": client_pays,
"MarkupPercentage": markup_percentage,
"MarkupOnDelivery": markup_on_delivery,
"MarkupPerRecipient": markup_per_recipient,
"MarkupOnDesignSpamTest": markup_on_design_spam_test}
response = self._put(self.uri_for('setpaygbilling'), 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 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.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 transfer_credits(self, credits, can_use_my_credits_when_they_run_out):
"""Transfer credits to or from this client. :param credits: An Integer representing the number of credits to transfer. This value may be either positive if you want to allocate credits from your account to the client, or negative if you want to deduct credits from the client back into your account. :param can_use_my_credits_when_they_run_out: A Boolean value representing which, if set to true, will allow the client to continue sending using your credits or payment details once they run out of credits, and if set to false, will prevent the client from using your credits to continue sending until you allocate more credits to them. :returns: An object of the following form representing the result: { AccountCredits # Integer representing credits in your account now ClientCredits # Integer representing credits in this client's account now } """
|
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 email."""
|
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,
}
response = self._post("/transactional/smartEmail/%s/send" %
smart_email_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 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=True, track_clicks=True, inline_css=True, group=None, add_recipients_to_list=None):
"""Sends a classic email."""
|
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": track_opens,
"TrackClicks": track_clicks,
"InlineCSS": inline_css,
"Group": group,
"AddRecipientsToList": add_recipients_to_list,
"ConsentToTrack": consent_to_track,
}
if client_id is None:
response = self._post(
"/transactional/classicEmail/send", json.dumps(body))
else:
response = self._post(
"/transactional/classicEmail/send?clientID=%s" % 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 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 subscribers in this segment."""
|
params = {
"date": date,
"page": page,
"pagesize": page_size,
"orderfield": order_field,
"orderdirection": order_direction,
"includetrackinginformation": include_tracking_information
}
response = self._get(self.uri_for("active"), 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, 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 used
# reliably
self.email_address = new_email_address
|
<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 for a client."""
|
body = {
"Title": title,
"UnsubscribePage": unsubscribe_page,
"ConfirmedOptIn": confirmed_opt_in,
"ConfirmationSuccessPage": confirmation_success_page,
"UnsubscribeSetting": unsubscribe_setting}
response = self._post("/lists/%s.json" % client_id, json.dumps(body))
self.list_id = json_to_py(response)
return self.list_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 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))
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 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 for this list."""
|
params = {
"date": date,
"page": page,
"pagesize": page_size,
"orderfield": order_field,
"orderdirection": order_direction,
"includetrackingpreference": include_tracking_preference,
}
response = self._get(self.uri_for("active"), 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 update(self, title, unsubscribe_page, confirmed_opt_in, confirmation_success_page, unsubscribe_setting="AllClientLists", add_unsubscribes_to_supp_list=False, scrub_active_with_supp_list=False):
"""Updates this list."""
|
body = {
"Title": title,
"UnsubscribePage": unsubscribe_page,
"ConfirmedOptIn": confirmed_opt_in,
"ConfirmationSuccessPage": confirmation_success_page,
"UnsubscribeSetting": unsubscribe_setting,
"AddUnsubscribesToSuppList": add_unsubscribes_to_supp_list,
"ScrubActiveWithSuppList": scrub_active_with_supp_list}
response = self._put("/lists/%s.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 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 to a subscriber list."""
|
validate_consent_to_track(consent_to_track)
body = {
"EmailAddress": email_address,
"Name": name,
"CustomFields": custom_fields,
"Resubscribe": resubscribe,
"ConsentToTrack": consent_to_track,
"RestartSubscriptionBasedAutoresponders": restart_subscription_based_autoresponders}
response = self._post("/subscribers/%s.json" %
list_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, custom_fields, resubscribe, consent_to_track, restart_subscription_based_autoresponders=False):
"""Updates any aspect of a subscriber, including email address, name, and custom field data if supplied."""
|
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,
"RestartSubscriptionBasedAutoresponders": restart_subscription_based_autoresponders}
response = self._put("/subscribers/%s.json" % self.list_id,
body=json.dumps(body), params=params)
# Update self.email_address, so this object can continue to be used
# reliably
self.email_address = new_email_address
|
<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):
"""Imports subscribers into a subscriber list."""
|
body = {
"Subscribers": subscribers,
"Resubscribe": resubscribe,
"QueueSubscriptionBasedAutoresponders": queue_subscription_based_autoresponders,
"RestartSubscriptionBasedAutoresponders": restart_subscription_based_autoresponders}
try:
response = self._post("/subscribers/%s/import.json" %
list_id, json.dumps(body))
except BadRequest as br:
# Subscriber import will throw BadRequest if some subscribers are not imported
# successfully. If this occurs, we want to return the ResultData property of
# the BadRequest exception (which is of the same "form" as the response we'd
# receive upon a completely successful import)
if hasattr(br.data, 'ResultData'):
return br.data.ResultData
else:
raise br
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 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(ICON_TEMPLATE, self.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 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["class"].append("disabled")
# Required class
if self.field.field.required and not self.attrs.get("_no_required"):
self.values["class"].append("required")
elif self.attrs.get("_required") and not self.field.field.required:
self.values["class"].append("required")
|
<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(" ".join(self.values["class"])).lstrip()
result = mark_safe(FIELD_WRAPPER % self.values)
self.widget.attrs = self.attrs # Re-assign variables
return result
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def 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": format_html(
wrappers.LABEL_TEMPLATE, field.html_name, mark_safe(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 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.widget.attrs["value"] = field.value() or attrs.get("value", "")
return wrappers.DROPDOWN_WRAPPER % {
"name": field.html_name,
"attrs": pad(flatatt(field.field.widget.attrs)),
"placeholder": attrs.get("placeholder") or get_placeholder_text(),
"style": pad(attrs.get("_style", "")),
"icon": format_html(wrappers.ICON_TEMPLATE, attrs.get("_dropdown_icon") or "dropdown"),
"choices": 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_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_html(wrappers.ICON_TEMPLATE, attrs.get("_dropdown_icon") or "dropdown"),
}
|
<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.ICON_TEMPLATE, attrs.get("_icon", "file outline"))
}
|
<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 insufficient number of seeds are provided. E.g. KISS(1) effectively becomes KISS(1, 1, 1, 1), rather than (if we just used default values) KISS(1, default-value, default-value, default-value) It is better to repeat the last seed value, rather than just using default values. Given two generators seeded with an insufficient number of seeds, repeating the last seed value means their states are more different from each other, with less correlation between their generated outputs. """
|
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 not isinstance(x, _Integral):
# Use the hash of the input seed object. Note this does not give
# consistent results cross-platform--between Python versions or
# between 32-bit and 64-bit systems.
x = hash(x)
self.rng_iterator.seed(x, *args, mix_extras=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 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: list: List of choices """
|
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(field.field, "to_field_name") or "pk"
choices += ((getattr(obj, field_name), str(obj)) for obj in queryset)
# Determine if an empty value is needed
if choices and (choices[0][1] == BLANK_CHOICE_DASH[0][1] or choices[0][0]):
needs_empty_value = True
# Delete empty option
if not choices[0][0]:
del choices[0]
# Remove dashed empty choice
if empty_label == BLANK_CHOICE_DASH[0][1]:
empty_label = None
# Add custom empty value
if empty_label or not field.field.required:
if needs_empty_value:
choices.insert(0, ("", empty_label or BLANK_CHOICE_DASH[0][1]))
return 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 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?
cl.reverse()
return DOMTokenList(cls, *cl)
|
<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 child node is also added to it. """
|
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 this node, raise ValueError. If this instance is connected to the node on browser, the child node is also added to it. """
|
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}}
e = create_event(msg)
self._dispatch_event(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 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. :arg type base: Base class of the created element (defatlt: ``WdomElement``) :arg dict attr: Attributes (key-value pairs dict) of the new element. """
|
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:
attr['_registered'] = False
base_class = base or WdomElement
if issubclass(base_class, Tag):
return base_class(**attr)
return base_class(tag, **attr)
|
<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
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.