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 dump(self):
"""Print packet content.""" |
print "-----MqttPkt------"
print "command = ", self.command
print "have_remaining = ", self.have_remaining
print "remaining_count = ", self.remaining_count
print "mid = ", self.mid
print "remaining_mult = ", self.remaining_mult
print "remaining_length = ", self.r... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def alloc(self):
"""from _mosquitto_packet_alloc.""" |
byte = 0
remaining_bytes = bytearray(5)
i = 0
remaining_length = self.remaining_length
self.payload = None
self.remaining_count = 0
loop_flag = True
#self.dump()
while loop_flag:
byte = remaining_length % 128... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def connect_build(self, nyamuk, keepalive, clean_session, retain = 0, dup = 0, version = 3):
"""Build packet for CONNECT command.""" |
will = 0; will_topic = None
byte = 0
client_id = utf8encode(nyamuk.client_id)
username = utf8encode(nyamuk.username) if nyamuk.username is not None else None
password = utf8encode(nyamuk.password) if nyamuk.password is not None else None
#payload len
payload_... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def write_string(self, string):
"""Write a string to this packet.""" |
self.write_uint16(len(string))
self.write_bytes(string, len(string)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def write_uint16(self, word):
"""Write 2 bytes.""" |
self.write_byte(nyamuk_net.MOSQ_MSB(word))
self.write_byte(nyamuk_net.MOSQ_LSB(word)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def write_byte(self, byte):
"""Write one byte.""" |
self.payload[self.pos] = byte
self.pos = self.pos + 1 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def write_bytes(self, data, n):
"""Write n number of bytes to this packet.""" |
for pos in xrange(0, n):
self.payload[self.pos + pos] = data[pos]
self.pos += n |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def read_byte(self):
"""Read a byte.""" |
if self.pos + 1 > self.remaining_length:
return NC.ERR_PROTOCOL, None
byte = self.payload[self.pos]
self.pos += 1
return NC.ERR_SUCCESS, byte |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def read_uint16(self):
"""Read 2 bytes.""" |
if self.pos + 2 > self.remaining_length:
return NC.ERR_PROTOCOL
msb = self.payload[self.pos]
self.pos += 1
lsb = self.payload[self.pos]
self.pos += 1
word = (msb << 8) + lsb
return NC.ERR_SUCCESS, word |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def read_bytes(self, count):
"""Read count number of bytes.""" |
if self.pos + count > self.remaining_length:
return NC.ERR_PROTOCOL, None
ba = bytearray(count)
for x in xrange(0, count):
ba[x] = self.payload[self.pos]
self.pos += 1
return NC.ERR_SUCCESS, ba |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def read_string(self):
"""Read string.""" |
rc, length = self.read_uint16()
if rc != NC.ERR_SUCCESS:
return rc, None
if self.pos + length > self.remaining_length:
return NC.ERR_PROTOCOL, None
ba = bytearray(length)
if ba is None:
return NC.ERR_NO_MEM, 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 pop_event(self):
"""Pop an event from event_list.""" |
if len(self.event_list) > 0:
evt = self.event_list.pop(0)
return evt
return None |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def packet_queue(self, pkt):
"""Enqueue packet to out_packet queue.""" |
pkt.pos = 0
pkt.to_process = pkt.packet_length
self.out_packet.append(pkt)
return NC.ERR_SUCCESS |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def packet_write(self):
"""Write packet to network.""" |
bytes_written = 0
if self.sock == NC.INVALID_SOCKET:
return NC.ERR_NO_CONN, bytes_written
while len(self.out_packet) > 0:
pkt = self.out_packet[0]
write_length, status = nyamuk_net.write(self.sock, pkt.payload)
if write_length > ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def socket_close(self):
"""Close our socket.""" |
if self.sock != NC.INVALID_SOCKET:
self.sock.close()
self.sock = NC.INVALID_SOCKET |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def build_publish_pkt(self, mid, topic, payload, qos, retain, dup):
"""Build PUBLISH packet.""" |
pkt = MqttPkt()
payloadlen = len(payload)
packetlen = 2 + len(topic) + payloadlen
if qos > 0:
packetlen += 2
pkt.mid = mid
pkt.command = NC.CMD_PUBLISH | ((dup & 0x1) << 3) | (qos << 1) | retain
pkt.remaining_length = packetlen
... |
<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_simple_command(self, cmd):
"""Send simple mqtt commands.""" |
pkt = MqttPkt()
pkt.command = cmd
pkt.remaining_length = 0
ret = pkt.alloc()
if ret != NC.ERR_SUCCESS:
return ret
return self.packet_queue(pkt) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def real_ip(self):
""" The actual public IP of this host. """ |
if self._real_ip is None:
response = get(ICANHAZIP)
self._real_ip = self._get_response_text(response)
return self._real_ip |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_current_ip(self):
""" Get the current IP Tor is using. :returns str :raises TorIpError """ |
response = get(ICANHAZIP, proxies={"http": self.local_http_proxy})
if response.ok:
return self._get_response_text(response)
raise TorIpError("Failed to get the current Tor IP") |
<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_new_ip(self):
""" Try to obtain new a usable TOR IP. :returns bool :raises TorIpError """ |
attempts = 0
while True:
if attempts == self.new_ip_max_attempts:
raise TorIpError("Failed to obtain a new usable Tor IP")
attempts += 1
try:
current_ip = self.get_current_ip()
except (RequestException, TorIpError):
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _ip_is_usable(self, current_ip):
""" Check if the current Tor's IP is usable. :argument current_ip: current Tor IP :type current_ip: str :returns bool """ |
# Consider IP addresses only.
try:
ipaddress.ip_address(current_ip)
except ValueError:
return False
# Never use real IP.
if current_ip == self.real_ip:
return False
# Do dot allow IP reuse.
if not self._ip_is_safe(current_ip)... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _manage_used_ips(self, current_ip):
""" Handle registering and releasing used Tor IPs. :argument current_ip: current Tor IP :type current_ip: str """ |
# Register current IP.
self.used_ips.append(current_ip)
# Release the oldest registred IP.
if self.reuse_threshold:
if len(self.used_ips) > self.reuse_threshold:
del self.used_ips[0] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _obtain_new_ip(self):
""" Change Tor's IP. """ |
with Controller.from_port(
address=self.tor_address, port=self.tor_port
) as controller:
controller.authenticate(password=self.tor_password)
controller.signal(Signal.NEWNYM)
# Wait till the IP 'settles in'.
sleep(0.5) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def is_local_subsection(command_dict):
"""Returns True if command dict is "local subsection", meaning that it is "if", "else" or "for" (not a real call, but call... |
for local_com in ['if ', 'for ', 'else ']:
if list(command_dict.keys())[0].startswith(local_com):
return True
return False |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _process_req_txt(req):
'''Returns a processed request or raises an exception'''
if req.status_code == 404:
return ''
if req.status_code != 200:
raise DapiCommError('Response of the server was {code}'.format(code=req.status_code))
return req.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 _get_from_dapi_or_mirror(link):
'''Tries to get the link form DAPI or the mirror'''
exception = False
try:
req = requests.get(_api_url() + link, timeout=5)
except requests.exceptions.RequestException:
exception = True
attempts = 1
while exception or str(req.status_code).star... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _remove_api_url_from_link(link):
'''Remove the API URL from the link if it is there'''
if link.startswith(_api_url()):
link = link[len(_api_url()):]
if link.startswith(_api_url(mirror=True)):
link = link[len(_api_url(mirror=True)):]
return link |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def data(link):
'''Returns a dictionary from requested link'''
link = _remove_api_url_from_link(link)
req = _get_from_dapi_or_mirror(link)
return _process_req(req) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def search(q, **kwargs):
'''Returns a dictionary with the search results'''
data = {'q': q}
for key, value in kwargs.items():
if value:
if type(value) == bool:
data[key] = 'on'
else:
data[key] = value
return _unpaginated('search/?' + urlenc... |
<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_users():
'''Formats a list of users available on Dapi'''
lines = []
u = users()
count = u['count']
if not count:
raise DapiCommError('Could not find any users on DAPI.')
for user in u['results']:
line = user['username']
if user['full_name']:
line +=... |
<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_daps(simple=False, skip_installed=False):
'''Formats a list of metadaps available on Dapi'''
lines= []
m = metadaps()
if not m['count']:
logger.info('Could not find any daps')
return
for mdap in sorted(m['results'], key=lambda mdap: mdap['package_name']):
if skip_i... |
<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_metadap_dap(name, version=''):
'''Return data for dap of given or latest version.'''
m = metadap(name)
if not m:
raise DapiCommError('DAP {dap} not found.'.format(dap=name))
if not version:
d = m['latest_stable'] or m['latest']
if d:
d = data(d)
else:
... |
<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_dap_from_dapi(name, version='', full=False):
'''Formats information about given DAP from DAPI in a human readable form to list of lines'''
lines = []
m, d = _get_metadap_dap(name, version)
if d:
# Determining label width
labels = BASIC_LABELS + ['average_rank'] # average_rank... |
<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_local_dap(dap, full=False, **kwargs):
'''Formaqts information about the given local DAP in a human readable form to list of lines'''
lines = []
# Determining label width
label_width = dapi.DapFormatter.calculate_offset(BASIC_LABELS)
# Metadata
lines.append(dapi.DapFormatter.format_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 format_installed_dap(name, full=False):
'''Formats information about an installed DAP in a human readable form to list of lines'''
dap_data = get_installed_daps_detailed().get(name)
if not dap_data:
raise DapiLocalError('DAP "{dap}" is not installed, can not query for info.'.format(dap=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 format_installed_dap_list(simple=False):
'''Formats all installed DAPs in a human readable form to list of lines'''
lines = []
if simple:
for pkg in sorted(get_installed_daps()):
lines.append(pkg)
else:
for pkg, instances in sorted(get_installed_daps_detailed().items()):
... |
<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_assistants_snippets(path, name):
'''Get Assistants and Snippets for a given DAP name on a given path'''
result = []
subdirs = {'assistants': 2, 'snippets': 1} # Values used for stripping leading path tokens
for loc in subdirs:
for root, dirs, files in os.walk(os.path.join(path, loc)):
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def format_search(q, **kwargs):
'''Formats the results of a search'''
m = search(q, **kwargs)
count = m['count']
if not count:
raise DapiCommError('Could not find any DAP packages for your query.')
return
for mdap in m['results']:
mdap = mdap['content_object']
return ... |
<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_installed_daps(location=None, skip_distro=False):
'''Returns a set of all installed daps
Either in the given location or in all of them'''
if location:
locations = [location]
else:
locations = _data_dirs()
s = set()
for loc in locations:
if skip_distro and loc == ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def get_installed_daps_detailed():
'''Returns a dictionary with all installed daps and their versions and locations
First version and location in the dap's list is the one that is preferred'''
daps = {}
for loc in _data_dirs():
s = get_installed_daps(loc)
for dap in s:
if dap... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def download_dap(name, version='', d='', directory=''):
'''Download a dap to a given or temporary directory
Return a path to that file together with information if the directory should be later deleted
'''
if not d:
m, d = _get_metadap_dap(name, version)
if directory:
_dir = director... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _strip_version_from_dependency(dep):
'''For given dependency string, return only the package name'''
usedmark = ''
for mark in '< > ='.split():
split = dep.split(mark)
if len(split) > 1:
usedmark = mark
break
if usedmark:
return split[0].strip()
el... |
<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_installed_version_of(name, location=None):
'''Gets the installed version of the given dap or None if not installed
Searches in all dirs by default, otherwise in the given one'''
if location:
locations = [location]
else:
locations = _data_dirs()
for loc in locations:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _get_all_dependencies_of(name, deps=set(), force=False):
'''Returns list of dependencies of the given dap from Dapi recursively'''
first_deps = _get_api_dependencies_of(name, force=force)
for dep in first_deps:
dep = _strip_version_from_dependency(dep)
if dep in deps:
continu... |
<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_api_dependencies_of(name, version='', force=False):
'''Returns list of first level dependencies of the given dap from Dapi'''
m, d = _get_metadap_dap(name, version=version)
# We need the dependencies to install the dap,
# if the dap is unsupported, raise an exception here
if not force and n... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def install_dap(name, version='', update=False, update_allpaths=False, first=True,
force=False, nodeps=False, reinstall=False, __ui__=''):
'''Install a dap from dapi
If update is True, it will remove previously installed daps of the same name'''
m, d = _get_metadap_dap(name, version)
if ... |
<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_dependency_metadata():
'''Returns list of strings with dependency metadata from Dapi'''
link = os.path.join(_api_url(), 'meta.txt')
return _process_req_txt(requests.get(link)).split('\n') |
<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_frame(self):
""" This function creates a frame """ |
frame = Gtk.Frame()
frame.set_shadow_type(Gtk.ShadowType.IN)
return frame |
<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_box(self, orientation=Gtk.Orientation.HORIZONTAL, spacing=0):
""" Function creates box. Based on orientation it can be either HORIZONTAL or VERTICAL "... |
h_box = Gtk.Box(orientation=orientation, spacing=spacing)
h_box.set_homogeneous(False)
return h_box |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def button_with_label(self, description, assistants=None):
""" Function creates a button with lave. If assistant is specified then text is aligned """ |
btn = self.create_button()
label = self.create_label(description)
if assistants is not None:
h_box = self.create_box(orientation=Gtk.Orientation.VERTICAL)
h_box.pack_start(label, False, False, 0)
label_ass = self.create_label(
assistants, just... |
<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_image(self, image_name=None, scale_ratio=1, window=None):
""" The function creates a image from name defined in image_name """ |
size = 48 * scale_ratio
pixbuf = GdkPixbuf.Pixbuf.new_from_file_at_scale(image_name, -1, size, True)
image = Gtk.Image()
# Creating the cairo surface is necessary for proper scaling on HiDPI
try:
surface = Gdk.cairo_surface_create_from_pixbuf(pixbuf, scale_ratio, 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 button_with_image(self, description, image=None, sensitive=True):
""" The function creates a button with image """ |
btn = self.create_button()
btn.set_sensitive(sensitive)
h_box = self.create_box()
try:
img = self.create_image(image_name=image,
scale_ratio=btn.get_scale_factor(),
window=btn.get_window())
excep... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def checkbutton_with_label(self, description):
""" The function creates a checkbutton with label """ |
act_btn = Gtk.CheckButton(description)
align = self.create_alignment()
act_btn.add(align)
return align |
<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_checkbox(self, name, margin=10):
""" Function creates a checkbox with his name """ |
chk_btn = Gtk.CheckButton(name)
chk_btn.set_margin_right(margin)
return chk_btn |
<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_entry(self, text="", sensitive="False"):
""" Function creates an Entry with corresponding text """ |
text_entry = Gtk.Entry()
text_entry.set_sensitive(sensitive)
text_entry.set_text(text)
return text_entry |
<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_link_button(self, text="None", uri="None"):
""" Function creates a link button with corresponding text and URI reference """ |
link_btn = Gtk.LinkButton(uri, text)
return link_btn |
<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_button(self, style=Gtk.ReliefStyle.NORMAL):
""" This is generalized method for creating Gtk.Button """ |
btn = Gtk.Button()
btn.set_relief(style)
return btn |
<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_image_menu_item(self, text, image_name):
""" Function creates a menu item with an image """ |
menu_item = Gtk.ImageMenuItem(text)
img = self.create_image(image_name)
menu_item.set_image(img)
return menu_item |
<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_label(self, name, justify=Gtk.Justification.CENTER, wrap_mode=True, tooltip=None):
""" The function is used for creating lable with HTML text """ |
label = Gtk.Label()
name = name.replace('|', '\n')
label.set_markup(name)
label.set_justify(justify)
label.set_line_wrap(wrap_mode)
if tooltip is not None:
label.set_has_tooltip(True)
label.connect("query-tooltip", self.parent.tooltip_queries, too... |
<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_button(self, grid_lang, ass, row, column):
""" The function is used for creating button with all features like signal on tooltip and signal on clicked Th... |
#print "gui_helper add_button"
image_name = ass[0].icon_path
label = "<b>" + ass[0].fullname + "</b>"
if not image_name:
btn = self.button_with_label(label)
else:
btn = self.button_with_image(label, image=ass[0].icon_path)
#print "Dependencies but... |
<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_install_button(self, grid_lang, row, column):
""" Add button that opens the window for installing more assistants """ |
btn = self.button_with_label('<b>Install more...</b>')
if row == 0 and column == 0:
grid_lang.add(btn)
else:
grid_lang.attach(btn, column, row, 1, 1)
btn.connect("clicked", self.parent.install_btn_clicked)
return btn |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def menu_item(self, sub_assistant, path):
""" The function creates a menu item and assigns signal like select and button-press-event for manipulation with menu_i... |
if not sub_assistant[0].icon_path:
menu_item = self.create_menu_item(sub_assistant[0].fullname)
else:
menu_item = self.create_image_menu_item(
sub_assistant[0].fullname, sub_assistant[0].icon_path
)
if sub_assistant[0].description:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def generate_menu(self, ass, text, path=None, level=0):
""" Function generates menu from based on ass parameter """ |
menu = self.create_menu()
for index, sub in enumerate(sorted(ass[1], key=lambda y: y[0].fullname.lower())):
if index != 0:
text += "|"
text += "- " + sub[0].fullname
new_path = list(path)
if level == 0:
new_path.append(ass[... |
<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_submenu(self, grid_lang, ass, row, column):
""" The function is used for creating button with menu and submenu. Also signal on tooltip and signal on clic... |
text = "Available subassistants:\n"
# Generate menus
path = []
(menu, text) = self.generate_menu(ass, text, path=path)
menu.show_all()
if ass[0].description:
description = self.get_formatted_description(ass[0].description) + "\n\n"
else:
d... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def create_scrolled_window(self, layout_manager, horizontal=Gtk.PolicyType.NEVER, vertical=Gtk.PolicyType.ALWAYS):
""" Function creates a scrolled window with la... |
scrolled_window = Gtk.ScrolledWindow()
scrolled_window.add(layout_manager)
scrolled_window.set_policy(horizontal, vertical)
return scrolled_window |
<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_gtk_grid(self, row_spacing=6, col_spacing=6, row_homogenous=False, col_homogenous=True):
""" Function creates a Gtk Grid with spacing and homogeous ta... |
grid_lang = Gtk.Grid()
grid_lang.set_column_spacing(row_spacing)
grid_lang.set_row_spacing(col_spacing)
grid_lang.set_border_width(12)
grid_lang.set_row_homogeneous(row_homogenous)
grid_lang.set_column_homogeneous(col_homogenous)
return grid_lang |
<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_notebook(self, position=Gtk.PositionType.TOP):
""" Function creates a notebook """ |
notebook = Gtk.Notebook()
notebook.set_tab_pos(position)
notebook.set_show_border(True)
return notebook |
<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_message_dialog(self, text, buttons=Gtk.ButtonsType.CLOSE, icon=Gtk.MessageType.WARNING):
""" Function creates a message dialog with text and relevant ... |
dialog = Gtk.MessageDialog(None,
Gtk.DialogFlags.DESTROY_WITH_PARENT,
icon,
buttons,
text
)
return dialog |
<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_question_dialog(self, text, second_text):
""" Function creates a question dialog with title text and second_text """ |
dialog = self.create_message_dialog(
text, buttons=Gtk.ButtonsType.YES_NO, icon=Gtk.MessageType.QUESTION
)
dialog.format_secondary_text(second_text)
response = dialog.run()
dialog.destroy()
return 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 execute_dialog(self, title):
""" Function executes a dialog """ |
msg_dlg = self.create_message_dialog(title)
msg_dlg.run()
msg_dlg.destroy()
return |
<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_file_chooser_dialog(self, text, parent, name=Gtk.STOCK_OPEN):
""" Function creates a file chooser dialog with title text """ |
text = None
dialog = Gtk.FileChooserDialog(
text, parent,
Gtk.FileChooserAction.SELECT_FOLDER,
(Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL, name, Gtk.ResponseType.OK)
)
response = dialog.run()
if response == Gtk.ResponseType.OK:
tex... |
<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_alignment(self, x_align=0, y_align=0, x_scale=0, y_scale=0):
""" Function creates an alignment """ |
align = Gtk.Alignment()
align.set(x_align, y_align, x_scale, y_scale)
return align |
<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_textview(self, wrap_mode=Gtk.WrapMode.WORD_CHAR, justify=Gtk.Justification.LEFT, visible=True, editable=True):
""" Function creates a text view with w... |
text_view = Gtk.TextView()
text_view.set_wrap_mode(wrap_mode)
text_view.set_editable(editable)
if not editable:
text_view.set_cursor_visible(False)
else:
text_view.set_cursor_visible(visible)
text_view.set_justification(justify)
return tex... |
<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_tree_view(self, model=None):
""" Function creates a tree_view with model """ |
tree_view = Gtk.TreeView()
if model is not None:
tree_view.set_model(model)
return tree_view |
<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_cell_renderer_text(self, tree_view, title="title", assign=0, editable=False):
""" Function creates a CellRendererText with title """ |
renderer = Gtk.CellRendererText()
renderer.set_property('editable', editable)
column = Gtk.TreeViewColumn(title, renderer, text=assign)
tree_view.append_column(column) |
<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_cell_renderer_combo(self, tree_view, title="title", assign=0, editable=False, model=None, function=None):
"""' Function creates a CellRendererCombo wi... |
renderer_combo = Gtk.CellRendererCombo()
renderer_combo.set_property('editable', editable)
if model:
renderer_combo.set_property('model', model)
if function:
renderer_combo.connect("edited", function)
renderer_combo.set_property("text-column", 0)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def create_clipboard(self, text, selection=Gdk.SELECTION_CLIPBOARD):
""" Function creates a clipboard """ |
clipboard = Gtk.Clipboard.get(selection)
clipboard.set_text('\n'.join(text), -1)
clipboard.store()
return clipboard |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def ask_for_confirm_with_message(cls, ui, prompt='Do you agree?', message='', **options):
"""Returns True if user agrees, False otherwise""" |
return cls.get_appropriate_helper(ui).ask_for_confirm_with_message(prompt, message) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def ask_for_input_with_prompt(cls, ui, prompt='', **options):
"""Ask user for written input with prompt""" |
return cls.get_appropriate_helper(ui).ask_for_input_with_prompt(prompt=prompt, **options) |
<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_argument_to(self, parser):
"""Used by cli to add this as an argument to argparse parser. Args: parser: parser to add this argument to """ |
from devassistant.cli.devassistant_argparse import DefaultIffUsedActionFactory
if isinstance(self.kwargs.get('action', ''), list):
# see documentation of DefaultIffUsedActionFactory to see why this is necessary
if self.kwargs['action'][0] == 'default_iff_used':
s... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_subassistants(self):
"""Return list of instantiated subassistants. Usually, this needs not be overriden in subclasses, you should just override get_subas... |
if not hasattr(self, '_subassistants'):
self._subassistants = []
# we want to know, if type(self) defines 'get_subassistant_classes',
# we don't want to inherit it from superclass (would cause recursion)
if 'get_subassistant_classes' in vars(type(self)):
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_subassistant_tree(self):
"""Returns a tree-like structure representing the assistant hierarchy going down from this assistant to leaf assistants. For exa... |
if '_tree' not in dir(self):
subassistant_tree = []
subassistants = self.get_subassistants()
for subassistant in subassistants:
subassistant_tree.append(subassistant.get_subassistant_tree())
self._tree = (self, subassistant_tree)
return 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 is_run_as_leaf(self, **kwargs):
"""Returns True if this assistant was run as last in path, False otherwise.""" |
# find the last subassistant_N
i = 0
while i < len(kwargs): # len(kwargs) is maximum of subassistant_N keys
if settings.SUBASSISTANT_N_STRING.format(i) in kwargs:
leaf_name = kwargs[settings.SUBASSISTANT_N_STRING.format(i)]
i += 1
return self.na... |
<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_all_yamls(cls, directories):
"""Loads yaml files from all given directories. Args: directories: list of directories to search Returns: dict of {fullpath... |
yaml_files = []
loaded_yamls = {}
for d in directories:
if d.startswith('/home') and not os.path.exists(d):
os.makedirs(d)
for dirname, subdirs, files in os.walk(d):
yaml_files.extend(map(lambda x: os.path.join(dirname, x),
... |
<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_yaml_by_relpath(cls, directories, rel_path, log_debug=False):
"""Load a yaml file with path that is relative to one of given directories. Args: director... |
for d in directories:
if d.startswith(os.path.expanduser('~')) and not os.path.exists(d):
os.makedirs(d)
possible_path = os.path.join(d, rel_path)
if os.path.exists(possible_path):
loaded = cls.load_yaml_by_path(possible_path, log_debug=log_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 load_yaml_by_path(cls, path, log_debug=False):
"""Load a yaml file that is at given path, if the path is not a string, it is assumed it's a file-like object"... |
try:
if isinstance(path, six.string_types):
return yaml.load(open(path, 'r'), Loader=Loader) or {}
else:
return yaml.load(path, Loader=Loader) or {}
except (yaml.scanner.ScannerError, yaml.parser.ParserError) as e:
log_level = logging.... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def calculate_offset(cls, labels):
'''Return the maximum length of the provided strings that have a nice
variant in DapFormatter._nice_strings'''
used_strings = set(cls._nice_strings.keys()) & set(labels)
return max([len(cls._nice_strings[s]) for s in used_strings]) |
<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_dapi_score(cls, meta, offset):
'''Format the line with DAPI user rating and number of votes'''
if 'average_rank' and 'rank_count' in meta:
label = (cls._nice_strings['average_rank'] + ':').ljust(offset + 2)
score = cls._format_field(meta['average_rank'])
vo... |
<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_meta_lines(cls, meta, labels, offset, **kwargs):
'''Return all information from a given meta dictionary in a list of lines'''
lines = []
# Name and underline
name = meta['package_name']
if 'version' in meta:
name += '-' + meta['version']
if 'custom... |
<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_assistants_lines(cls, assistants):
'''Return formatted assistants from the given list in human readable form.'''
lines = cls._format_files(assistants, 'assistants')
# Assistant help
if assistants:
lines.append('')
assistant = strip_prefix(random.choice... |
<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_platforms(cls, platforms):
'''Formats supported platforms in human readable form'''
lines = []
if platforms:
lines.append('This DAP is only supported on the following platforms:')
lines.extend([' * ' + platform for platform in platforms])
return lines |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def check(cls, dap, network=False, yamls=True, raises=False, logger=logger):
'''Checks if the dap is valid, reports problems
Parameters:
network -- whether to run checks that requires network connection
output -- where to write() problems, might be None
raises -- whe... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def check_meta(cls, dap):
'''Check the meta.yaml in the dap.
Return a list of DapProblems.'''
problems = list()
# Check for non array-like metadata
for datatype in (Dap._required_meta | Dap._optional_meta) - Dap._array_meta:
if not dap._isvalid(datatype):
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def check_topdir(cls, dap):
'''Check that everything is in the correct top-level directory.
Return a list of DapProblems'''
problems = list()
dirname = os.path.dirname(dap._meta_location)
if not dirname:
msg = 'meta.yaml is not in top-level directory'
pr... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def check_no_self_dependency(cls, dap):
'''Check that the package does not depend on itself.
Return a list of problems.'''
problems = list()
if 'package_name' in dap.meta and 'dependencies' in dap.meta:
dependencies = set()
for dependency in dap.meta['dependenc... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def check_name_not_on_dapi(cls, dap):
'''Check that the package_name is not registered on Dapi.
Return list of problems.'''
problems = list()
if dap.meta['package_name']:
from . import dapicli
d = dapicli.metadap(dap.meta['package_name'])
if d:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def check_yamls(cls, dap):
'''Check that all assistants and snippets are valid.
Return list of DapProblems.'''
problems = list()
for yaml in dap.assistants_and_snippets:
path = yaml + '.yaml'
parsed_yaml = YamlLoader.load_yaml_by_path(dap._get_file(path, prepend... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _strip_leading_dirname(self, path):
'''Strip leading directory name from the given path'''
return os.path.sep.join(path.split(os.path.sep)[1:]) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def assistants(self):
'''Get all assistants in this DAP'''
return [strip_suffix(f, '.yaml') for f in self._stripped_files if self._assistants_pattern.match(f)] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def snippets(self):
'''Get all snippets in this DAP'''
return [strip_suffix(f, '.yaml') for f in self._stripped_files if self._snippets_pattern.match(f)] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.