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 dispatch_event(self, event):
""" Takes an event dict. Logs the event if needed and cleans up the dict such as setting the index needed for composits. """ |
if self.config["debug"]:
self.py3_wrapper.log("received event {}".format(event))
# usage variables
event["index"] = event.get("index", "")
instance = event.get("instance", "")
name = event.get("name", "")
# composites have an index which is passed to i3bar with
# the instance. We need to separate this out here and
# clean up the event. If index
# is an integer type then cast it as such.
if " " in instance:
instance, index = instance.split(" ", 1)
try:
index = int(index)
except ValueError:
pass
event["index"] = index
event["instance"] = instance
if self.config["debug"]:
self.py3_wrapper.log(
'trying to dispatch event to module "{}"'.format(
"{} {}".format(name, instance).strip()
)
)
# guess the module config name
module_name = "{} {}".format(name, instance).strip()
default_event = False
module_info = self.output_modules.get(module_name)
module = module_info["module"]
# execute any configured i3-msg command
# we do not do this for containers
# modules that have failed do not execute their config on_click
if module.allow_config_clicks:
button = event.get("button", 0)
on_click = self.on_click.get(module_name, {}).get(str(button))
if on_click:
task = EventClickTask(module_name, event, self, on_click)
self.py3_wrapper.timeout_queue_add(task)
# otherwise setup default action on button 2 press
elif button == 2:
default_event = True
# do the work
task = EventTask(module_name, event, default_event, self)
self.py3_wrapper.timeout_queue_add(task) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def run(self):
""" Wait for an i3bar JSON event, then find the right module to dispatch the message to based on the 'name' and 'instance' of the event. In case the module does NOT support click_events, the default implementation is to clear the module's cache when the MIDDLE button (2) is pressed on it. Example event: {'y': 13, 'x': 1737, 'button': 1, 'name': 'empty', 'instance': 'first'} """ |
try:
while self.py3_wrapper.running:
event_str = self.poller_inp.readline()
if not event_str:
continue
try:
# remove leading comma if present
if event_str[0] == ",":
event_str = event_str[1:]
event = loads(event_str)
self.dispatch_event(event)
except Exception:
self.py3_wrapper.report_exception("Event failed")
except: # noqa e722
err = "Events thread died, click events are disabled."
self.py3_wrapper.report_exception(err, notify_user=False)
self.py3_wrapper.notify_user(err, level="warning") |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _start_handler_thread(self):
"""Called once to start the event handler thread.""" |
# Create handler thread
t = Thread(target=self._start_loop)
t.daemon = True
# Start handler thread
t.start()
self.thread_started = 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 _start_loop(self):
"""Starts main event handler loop, run in handler thread t.""" |
# Create our main loop, get our bus, and add the signal handler
loop = GObject.MainLoop()
bus = SystemBus()
manager = bus.get(".NetworkManager")
manager.onPropertiesChanged = self._vpn_signal_handler
# Loop forever
loop.run() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _vpn_signal_handler(self, args):
"""Called on NetworkManager PropertiesChanged signal""" |
# Args is a dictionary of changed properties
# We only care about changes in ActiveConnections
active = "ActiveConnections"
# Compare current ActiveConnections to last seen ActiveConnections
if active in args.keys() and sorted(self.active) != sorted(args[active]):
self.active = args[active]
self.py3.update() |
<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_vpn_status(self):
"""Returns None if no VPN active, Id if active.""" |
# Sleep for a bit to let any changes in state finish
sleep(0.3)
# Check if any active connections are a VPN
bus = SystemBus()
ids = []
for name in self.active:
conn = bus.get(".NetworkManager", name)
if conn.Vpn:
ids.append(conn.Id)
# No active VPN
return ids |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def vpn_status(self):
"""Returns response dict""" |
# Start signal handler thread if it should be running
if not self.check_pid and not self.thread_started:
self._start_handler_thread()
# Set color_bad as default output. Replaced if VPN active.
name = None
color = self.py3.COLOR_BAD
# If we are acting like the default i3status module
if self.check_pid:
if self._check_pid():
name = "yes"
color = self.py3.COLOR_GOOD
# Otherwise, find the VPN name, if it is active
else:
vpn = self._get_vpn_status()
if vpn:
name = ", ".join(vpn)
color = self.py3.COLOR_GOOD
# Format and create the response dict
full_text = self.py3.safe_format(self.format, {"name": name})
response = {
"full_text": full_text,
"color": color,
"cached_until": self.py3.CACHE_FOREVER,
}
# Cache forever unless in check_pid mode
if self.check_pid:
response["cached_until"] = self.py3.time_in(self.cache_timeout)
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 append(self, item):
""" Add an item to the Composite. Item can be a Composite, list etc """ |
if isinstance(item, Composite):
self._content += item.get_content()
elif isinstance(item, list):
self._content += item
elif isinstance(item, dict):
self._content.append(item)
elif isinstance(item, basestring):
self._content.append({"full_text": item})
else:
msg = "{!r} not suitable to append to Composite"
raise Exception(msg.format(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 simplify(self):
""" Simplify the content of a Composite merging any parts that can be and returning the new Composite as well as updating itself internally """ |
final_output = []
diff_last = None
item_last = None
for item in self._content:
# remove any undefined colors
if hasattr(item.get("color"), "none_setting"):
del item["color"]
# ignore empty items
if not item.get("full_text") and not item.get("separator"):
continue
# merge items if we can
diff = item.copy()
del diff["full_text"]
if diff == diff_last or (item["full_text"].strip() == "" and item_last):
item_last["full_text"] += item["full_text"]
else:
diff_last = diff
item_last = item.copy() # copy item as we may change it
final_output.append(item_last)
self._content = final_output
return self |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def composite_join(separator, items):
""" Join a list of items with a separator. This is used in joining strings, responses and Composites. The output will be a Composite. """ |
output = Composite()
first_item = True
for item in items:
# skip empty items
if not item:
continue
# skip separator on first item
if first_item:
first_item = False
else:
output.append(separator)
output.append(item)
return output |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _init_dbus(self):
""" Get the device id """ |
_bus = SessionBus()
if self.device_id is None:
self.device_id = self._get_device_id(_bus)
if self.device_id is None:
return False
try:
self._dev = _bus.get(SERVICE_BUS, DEVICE_PATH + "/%s" % self.device_id)
except Exception:
return False
return True |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _get_device_id(self, bus):
""" Find the device id """ |
_dbus = bus.get(SERVICE_BUS, PATH)
devices = _dbus.devices()
if self.device is None and self.device_id is None and len(devices) == 1:
return devices[0]
for id in devices:
self._dev = bus.get(SERVICE_BUS, DEVICE_PATH + "/%s" % id)
if self.device == self._dev.name:
return id
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 _get_device(self):
""" Get the device """ |
try:
device = {
"name": self._dev.name,
"isReachable": self._dev.isReachable,
"isTrusted": self._get_isTrusted(),
}
except Exception:
return None
return device |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _get_battery(self):
""" Get the battery """ |
try:
battery = {
"charge": self._dev.charge(),
"isCharging": self._dev.isCharging() == 1,
}
except Exception:
return None
return battery |
<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_battery_status(self, battery):
""" Get the battery status """ |
if battery["charge"] == -1:
return (UNKNOWN_SYMBOL, UNKNOWN, "#FFFFFF")
if battery["isCharging"]:
status = self.status_chr
color = self.py3.COLOR_GOOD
else:
status = self.status_bat
color = self.py3.COLOR_DEGRADED
if not battery["isCharging"] and battery["charge"] <= self.low_threshold:
color = self.py3.COLOR_BAD
if battery["charge"] > 99:
status = self.status_full
return (battery["charge"], status, color) |
<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_notifications_status(self, notifications):
""" Get the notifications status """ |
if notifications:
size = len(notifications["activeNotifications"])
else:
size = 0
status = self.status_notif if size > 0 else self.status_no_notif
return (size, status) |
<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_text(self):
""" Get the current metadatas """ |
device = self._get_device()
if device is None:
return (UNKNOWN_DEVICE, self.py3.COLOR_BAD)
if not device["isReachable"] or not device["isTrusted"]:
return (
self.py3.safe_format(
self.format_disconnected, {"name": device["name"]}
),
self.py3.COLOR_BAD,
)
battery = self._get_battery()
(charge, bat_status, color) = self._get_battery_status(battery)
notif = self._get_notifications()
(notif_size, notif_status) = self._get_notifications_status(notif)
return (
self.py3.safe_format(
self.format,
dict(
name=device["name"],
charge=charge,
bat_status=bat_status,
notif_size=notif_size,
notif_status=notif_status,
),
),
color,
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def kdeconnector(self):
""" Get the current state and return it. """ |
if self._init_dbus():
(text, color) = self._get_text()
else:
text = UNKNOWN_DEVICE
color = self.py3.COLOR_BAD
response = {
"cached_until": self.py3.time_in(self.cache_timeout),
"full_text": text,
"color": color,
}
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 dpms(self):
""" Display a colorful state of DPMS. """ |
if "DPMS is Enabled" in self.py3.command_output("xset -q"):
_format = self.icon_on
color = self.color_on
else:
_format = self.icon_off
color = self.color_off
icon = self.py3.safe_format(_format)
return {
"cached_until": self.py3.time_in(self.cache_timeout),
"full_text": self.py3.safe_format(self.format, {"icon": icon}),
"color": color,
} |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def on_click(self, event):
""" Control DPMS with mouse clicks. """ |
if event["button"] == self.button_toggle:
if "DPMS is Enabled" in self.py3.command_output("xset -q"):
self.py3.command_run("xset -dpms s off")
else:
self.py3.command_run("xset +dpms s on")
if event["button"] == self.button_off:
self.py3.command_run("xset dpms force off") |
<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_progress(self):
""" Get current progress of emerge. Returns a dict containing current and total value. """ |
input_data = []
ret = {}
# traverse emerge.log from bottom up to get latest information
last_lines = self.py3.command_output(["tail", "-50", self.emerge_log_file])
input_data = last_lines.split("\n")
input_data.reverse()
for line in input_data:
if "*** terminating." in line:
# copy content of ret_default, not only the references
ret = copy.deepcopy(self.ret_default)
break
else:
status_re = re.compile(
"\((?P<cu>[\d]+) of (?P<t>[\d]+)\) "
"(?P<a>[a-zA-Z\/]+( [a-zA-Z]+)?) "
"\((?P<ca>[\w\-]+)\/(?P<p>[\w\.]+)"
)
res = status_re.search(line)
if res is not None:
ret["action"] = res.group("a").lower()
ret["category"] = res.group("ca")
ret["current"] = res.group("cu")
ret["pkg"] = res.group("p")
ret["total"] = res.group("t")
break
return ret |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _idle(self):
""" since imaplib doesn't support IMAP4r1 IDLE, we'll do it by hand """ |
socket = None
try:
# build a new command tag (Xnnn) as bytes:
self.command_tag = (self.command_tag + 1) % 1000
command_tag = b"X" + bytes(str(self.command_tag).zfill(3), "ascii")
# make sure we have selected anything before idling:
directories = self.mailbox.split(",")
self.connection.select(directories[0])
socket = self.connection.socket()
# send IDLE command and check response:
socket.write(command_tag + b" IDLE\r\n")
try:
response = socket.read(4096).decode("ascii")
except socket_error:
raise imaplib.IMAP4.abort("Server didn't respond to 'IDLE' in time")
if not response.lower().startswith("+ idling"):
raise imaplib.IMAP4.abort("While initializing IDLE: " + str(response))
# wait for changes (EXISTS, EXPUNGE, etc.):
socket.settimeout(self.cache_timeout)
while True:
try:
response = socket.read(4096).decode("ascii")
if response.upper().startswith("* OK"):
continue # ignore '* OK Still here'
else:
break
except socket_error: # IDLE timed out
break
finally: # terminate IDLE command gracefully
if socket is None:
return
socket.settimeout(self.read_timeout)
socket.write(b"DONE\r\n") # important! Can't query IMAP again otherwise
try:
response = socket.read(4096).decode("ascii")
except socket_error:
raise imaplib.IMAP4.abort("Server didn't respond to 'DONE' in time")
# sometimes, more messages come in between reading and DONEing; so read them again:
if response.startswith("* "):
try:
response = socket.read(4096).decode("ascii")
except socket_error:
raise imaplib.IMAP4.abort(
"Server sent more continuations, but no 'DONE' ack"
)
expected_response = (command_tag + b" OK").decode("ascii")
if not response.lower().startswith(expected_response.lower()):
raise imaplib.IMAP4.abort("While terminating IDLE: " + 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 _get_cputemp_with_lmsensors(self, zone=None):
""" Tries to determine CPU temperature using the 'sensors' command. Searches for the CPU temperature by looking for a value prefixed by either "CPU Temp" or "Core 0" - does not look for or average out temperatures of all codes if more than one. """ |
sensors = None
command = ["sensors"]
if zone:
try:
sensors = self.py3.command_output(command + [zone])
except self.py3.CommandError:
pass
if not sensors:
sensors = self.py3.command_output(command)
m = re.search("(Core 0|CPU Temp).+\+(.+).+\(.+", sensors)
if m:
cpu_temp = float(m.groups()[1].strip()[:-2])
else:
cpu_temp = "?"
return cpu_temp |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def tokens(self, format_string):
""" Get the tokenized format_string. Tokenizing is resource intensive so we only do it once and cache it """ |
if format_string not in self.format_string_cache:
if python2 and isinstance(format_string, str):
format_string = format_string.decode("utf-8")
tokens = list(re.finditer(self.reg_ex, format_string))
self.format_string_cache[format_string] = tokens
return self.format_string_cache[format_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 get_color_names(self, format_string):
""" Parses the format_string and returns a set of color names. """ |
names = set()
# Tokenize the format string and process them
for token in self.tokens(format_string):
if token.group("command"):
name = dict(parse_qsl(token.group("command"))).get("color")
if (
not name
or name in COLOR_NAMES_EXCLUDED
or name in COLOR_NAMES
or name[0] == "#"
):
continue
names.add(name)
return names |
<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_placeholders(self, format_string):
""" Parses the format_string and returns a set of placeholders. """ |
placeholders = set()
# Tokenize the format string and process them
for token in self.tokens(format_string):
if token.group("placeholder"):
placeholders.add(token.group("key"))
elif token.group("command"):
# get any placeholders used in commands
commands = dict(parse_qsl(token.group("command")))
# placeholders only used in `if`
if_ = commands.get("if")
if if_:
placeholders.add(Condition(if_).variable)
return placeholders |
<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_placeholders(self, format_string, placeholders):
""" Update a format string renaming placeholders. """ |
# Tokenize the format string and process them
output = []
for token in self.tokens(format_string):
if token.group("key") in placeholders:
output.append(
"{%s%s}" % (placeholders[token.group("key")], token.group("format"))
)
continue
elif token.group("command"):
# update any placeholders used in commands
commands = parse_qsl(token.group("command"), keep_blank_values=True)
# placeholders only used in `if`
if "if" in [x[0] for x in commands]:
items = []
for key, value in commands:
if key == "if":
# we have to rebuild from the parts we have
condition = Condition(value)
variable = condition.variable
if variable in placeholders:
variable = placeholders[variable]
# negation via `!`
not_ = "!" if not condition.default else ""
condition_ = condition.condition or ""
# if there is no condition then there is no
# value
if condition_:
value_ = condition.value
else:
value_ = ""
value = "{}{}{}{}".format(
not_, variable, condition_, value_
)
if value:
items.append("{}={}".format(key, value))
else:
items.append(key)
# we cannot use urlencode because it will escape things
# like `!`
output.append(r"\?{} ".format("&".join(items)))
continue
value = token.group(0)
output.append(value)
return u"".join(output) |
<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_placeholder_formats(self, format_string, placeholder_formats):
""" Update a format string adding formats if they are not already present. """ |
# Tokenize the format string and process them
output = []
for token in self.tokens(format_string):
if (
token.group("placeholder")
and (not token.group("format"))
and token.group("key") in placeholder_formats
):
output.append(
"{%s%s}"
% (token.group("key"), placeholder_formats[token.group("key")])
)
continue
value = token.group(0)
output.append(value)
return u"".join(output) |
<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_block(self, format_string):
""" Parse the format string into blocks containing Literals, Placeholders etc that we can cache and reuse. """ |
first_block = Block(None, py3_wrapper=self.py3_wrapper)
block = first_block
# Tokenize the format string and process them
for token in self.tokens(format_string):
value = token.group(0)
if token.group("block_start"):
# Create new block
block = block.new_block()
elif token.group("block_end"):
# Close block setting any valid state as needed
# and return to parent block to continue
if not block.parent:
raise Exception("Too many `]`")
block = block.parent
elif token.group("switch"):
# a new option has been created
block = block.switch()
elif token.group("placeholder"):
# Found a {placeholder}
key = token.group("key")
format = token.group("format")
block.add(Placeholder(key, format))
elif token.group("literal"):
block.add(Literal(value))
elif token.group("lost_brace"):
# due to how parsing happens we can get a lonesome }
# eg in format_string '{{something}' this fixes that issue
block.add(Literal(value))
elif token.group("command"):
# a block command has been found
block.set_commands(token.group("command"))
elif token.group("escaped"):
# escaped characters add unescaped values
if value[0] in ["\\", "{", "}"]:
value = value[1:]
block.add(Literal(value))
if block.parent:
raise Exception("Block not closed")
# add to the cache
self.block_cache[format_string] = first_block |
<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( self, format_string, module=None, param_dict=None, force_composite=False, attr_getter=None, ):
""" Format a string, substituting place holders which can be found in param_dict, attributes of the supplied module, or provided via calls to the attr_getter function. """ |
# fix python 2 unicode issues
if python2 and isinstance(format_string, str):
format_string = format_string.decode("utf-8")
if param_dict is None:
param_dict = {}
# if the processed format string is not in the cache then create it.
if format_string not in self.block_cache:
self.build_block(format_string)
first_block = self.block_cache[format_string]
def get_parameter(key):
"""
function that finds and returns the value for a placeholder.
"""
if key in param_dict:
# was a supplied parameter
param = param_dict.get(key)
elif module and hasattr(module, key):
param = getattr(module, key)
if hasattr(param, "__call__"):
# we don't allow module methods
raise Exception()
elif attr_getter:
# get value from attr_getter function
try:
param = attr_getter(key)
except: # noqa e722
raise Exception()
else:
raise Exception()
if isinstance(param, Composite):
if param.text():
param = param.copy()
else:
param = u""
elif python2 and isinstance(param, str):
param = param.decode("utf-8")
return param
# render our processed format
valid, output = first_block.render(get_parameter, module)
# clean things up a little
if isinstance(output, list):
output = Composite(output)
if not output:
if force_composite:
output = Composite()
else:
output = ""
return output |
<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, get_params, block):
""" return the correct value for the placeholder """ |
value = "{%s}" % self.key
try:
value = value_ = get_params(self.key)
if self.format.startswith(":"):
# if a parameter has been set to be formatted as a numeric
# type then we see if we can coerce it to be. This allows
# the user to format types that normally would not be
# allowed eg '123' it also allows {:d} to be used as a
# shorthand for {:.0f}. Use {:g} to remove insignificant
# trailing zeroes and the decimal point too if there are
# no remaining digits following it. If the parameter cannot
# be successfully converted then the format will be removed.
try:
if "ceil" in self.format:
value = int(ceil(float(value)))
if "f" in self.format:
value = float(value)
if "g" in self.format:
value = float(value)
if "d" in self.format:
value = int(float(value))
output = u"{[%s]%s}" % (self.key, self.format)
value = output.format({self.key: value})
value_ = float(value)
except ValueError:
pass
elif self.format.startswith("!"):
output = u"{%s%s}" % (self.key, self.format)
value = value_ = output.format(**{self.key: value})
if block.commands.not_zero:
valid = value_ not in ["", None, False, "0", "0.0", 0, 0.0]
else:
# '', None, and False are ignored
# numbers like 0 and 0.0 are not.
valid = not (value_ in ["", None] or value_ is False)
enough = False
except: # noqa e722
# Exception raised when we don't have the param
enough = True
valid = False
return valid, value, enough |
<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_valid_condition(self, get_params):
""" Check if the condition has been met. We need to make sure that we are of the correct type. """ |
try:
variable = get_params(self.variable)
except: # noqa e722
variable = None
value = self.value
# if None, return oppositely
if variable is None:
return not self.default
# convert the value to a correct type
if isinstance(variable, bool):
value = bool(self.value)
elif isinstance(variable, Number):
try:
value = int(self.value)
except: # noqa e722
try:
value = float(self.value)
except: # noqa e722
# could not parse
return not self.default
# compare and return the result
if self.condition == "=":
return (variable == value) == self.default
elif self.condition == ">":
return (variable > value) == self.default
elif self.condition == "<":
return (variable < value) == self.default |
<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_valid_basic(self, get_params):
""" Simple check that the variable is set """ |
try:
if get_params(self.variable):
return self.default
except: # noqa e722
pass
return not self.default |
<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_commands(self, commands_str):
""" update with commands from the block """ |
commands = dict(parse_qsl(commands_str, keep_blank_values=True))
_if = commands.get("if", self._if)
if _if:
self._if = Condition(_if)
self._set_int(commands, "max_length")
self._set_int(commands, "min_length")
self.color = self._check_color(commands.get("color"))
self.not_zero = "not_zero" in commands or self.not_zero
self.show = "show" in commands or self.show
self.soft = "soft" in commands or self.soft |
<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_int(self, commands, name):
""" set integer value from commands """ |
if name in commands:
try:
value = int(commands[name])
setattr(self, name, value)
except ValueError:
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 new_block(self):
""" create a new sub block to the current block and return it. the sub block is added to the current block. """ |
child = Block(self, py3_wrapper=self.py3_wrapper)
self.add(child)
return 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 switch(self):
""" block has been split via | so we need to start a new block for that option and return it to the user. """ |
base_block = self.base_block or self
self.next_block = Block(
self.parent, base_block=base_block, py3_wrapper=self.py3_wrapper
)
return self.next_block |
<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_valid(self, get_params):
""" see if the if condition for a block is valid """ |
if self.commands._if:
return self.commands._if.check_valid(get_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 _content_function(self):
""" This returns a set containing the actively shown module. This is so we only get update events triggered for these modules. """ |
# ensure that active is valid
self.active = self.active % len(self.items)
return set([self.items[self.active]]) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _urgent_function(self, module_list):
""" A contained module has become urgent. We want to display it to the user. """ |
for module in module_list:
if module in self.items:
self.active = self.items.index(module)
self.urgent = 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 get_backends():
""" Get backends info so that we can find the correct one. We just look in the directory structure to find modules. """ |
IGNORE_DIRS = ["core", "tools", "utils"]
global backends
if backends is None:
backends = {}
i3pystatus_dir = os.path.dirname(i3pystatus.__file__)
subdirs = [
x
for x in next(os.walk(i3pystatus_dir))[1]
if not x.startswith("_") and x not in IGNORE_DIRS
]
for subdir in subdirs:
dirs = next(os.walk(os.path.join(i3pystatus_dir, subdir)))[2]
backends.update(
{
x[:-3]: "i3pystatus.%s.%s" % (subdir, x[:-3])
for x in dirs
if not x.startswith("_") and x.endswith(".py")
}
)
return backends |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def trigger(self):
""" Actually trigger the event """ |
if self.last_button:
button_index = min(self.last_button, len(self.callbacks)) - 1
click_style = 0 if self.clicks == 1 else 1
callback = self.callbacks[button_index][click_style]
if callback:
# we can do test for str as only python > 3 is supported
if isinstance(callback, str):
# no parameters
callback_name = callback
callback_args = []
else:
# has parameters
callback_name = callback[0]
callback_args = callback[1:]
callback_function = getattr(self.parent.module, callback_name)
callback_function(*callback_args)
# We want to ensure that the module has the latest output. The
# best way is to call the run method of the module
self.parent.module.run()
else:
self.parent.py3.prevent_refresh()
self.last_button = None
self.clicks = 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 event(self, button):
""" button has been clicked """ |
# cancel any pending timer
if self.timer:
self.timer.cancel()
if self.last_button != button:
if self.last_button:
# new button clicked process the one before.
self.trigger()
self.clicks = 1
else:
self.clicks += 1
# do we accept double clicks on this button?
# if not then just process the click
button_index = min(button, len(self.callbacks)) - 1
if not self.callbacks[button_index][1]:
# set things up correctly for the trigger
self.clicks = 1
self.last_button = button
self.trigger()
else:
# set a timeout to trigger the click
# this will be cancelled if we click again before it runs
self.last_button = button
self.timer = Timer(self.click_time, self.trigger)
self.timer.start() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _get_stat(self):
""" Get statistics from devfile in list of lists of words """ |
def dev_filter(x):
# get first word and remove trailing interface number
x = x.strip().split(" ")[0][:-1]
if x in self.interfaces_blacklist:
return False
if self.all_interfaces:
return True
if x in self.interfaces:
return True
return False
# read devfile, skip two header files
x = filter(dev_filter, open(self.devfile).readlines()[2:])
try:
# split info into words, filter empty ones
return [list(filter(lambda x: x, _x.split(" "))) for _x in x]
except StopIteration:
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 _format_value(self, value):
""" Return formatted string """ |
value, unit = self.py3.format_units(value, unit=self.unit, si=self.si_units)
return self.py3.safe_format(self.format_value, {"value": value, "unit": unit}) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _persist(self):
""" Run the command inside a thread so that we can catch output for each line as it comes in and display it. """ |
# run the block/command
for command in self.commands:
try:
process = Popen(
[command],
stdout=PIPE,
stderr=PIPE,
universal_newlines=True,
env=self.env,
shell=True,
)
except Exception as e:
retcode = process.poll()
msg = "Command '{cmd}' {error} retcode {retcode}"
self.py3.log(msg.format(cmd=command, error=e, retcode=retcode))
# persistent blocklet output can be of two forms. Either each row
# of the output is on a new line this is much easier to deal with)
# or else the output can be continuous and just flushed when ready.
# The second form is more tricky, if we find newlines then we
# switch to easy parsing of the output.
# When we have output we store in self.persistent_output and then
# trigger the module to update.
fd = process.stdout.fileno()
fl = fcntl.fcntl(fd, fcntl.F_GETFL)
has_newlines = False
while True:
line = process.stdout.read(1)
# switch to a non-blocking read as we do not know the output
# length
fcntl.fcntl(fd, fcntl.F_SETFL, fl | os.O_NONBLOCK)
line += process.stdout.read(1024)
# switch back to blocking so we can wait for the next output
fcntl.fcntl(fd, fcntl.F_SETFL, fl)
if process.poll():
break
if self.py3.is_python_2():
line = line.decode("utf-8")
self.persistent_output = line
self.py3.update()
if line[-1] == "\n":
has_newlines = True
break
if line == "":
break
if has_newlines:
msg = "Switch to newline persist method {cmd}"
self.py3.log(msg.format(cmd=command))
# just read the output in a sane manner
for line in iter(process.stdout.readline, b""):
if process.poll():
break
if self.py3.is_python_2():
line = line.decode("utf-8")
self.persistent_output = line
self.py3.update()
self.py3.log("command exited {cmd}".format(cmd=command))
self.persistent_output = "Error\nError\n{}".format(
self.py3.COLOR_ERROR or self.py3.COLOR_BAD
)
self.py3.update() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def markdown_2_rst(lines):
""" Convert markdown to restructured text """ |
out = []
code = False
for line in lines:
# code blocks
if line.strip() == "```":
code = not code
space = " " * (len(line.rstrip()) - 3)
if code:
out.append("\n\n%s.. code-block:: none\n\n" % space)
else:
out.append("\n")
else:
if code and line.strip():
line = " " + line
else:
# escape any backslashes
line = line.replace("\\", "\\\\")
out.append(line)
return out |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def file_sort(my_list):
""" Sort a list of files in a nice way. eg item-10 will be after item-9 """ |
def alphanum_key(key):
"""
Split the key into str/int parts
"""
return [int(s) if s.isdigit() else s for s in re.split("([0-9]+)", key)]
my_list.sort(key=alphanum_key)
return my_list |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def screenshots(screenshots_data, module_name):
""" Create .rst output for any screenshots a module may have. """ |
shots = screenshots_data.get(module_name)
if not shots:
return ""
out = []
for shot in file_sort(shots):
if not os.path.exists("../doc/screenshots/%s.png" % shot):
continue
out.append(u"\n.. image:: screenshots/{}.png\n\n".format(shot))
return u"".join(out) |
<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_module_docs():
""" Create documentation for modules. """ |
data = core_module_docstrings(format="rst")
# get screenshot data
screenshots_data = {}
samples = get_samples()
for sample in samples.keys():
module = sample.split("-")[0]
if module not in screenshots_data:
screenshots_data[module] = []
screenshots_data[module].append(sample)
out = []
# details
for module in sorted(data.keys()):
out.append("\n.. _module_%s:\n" % module) # reference for linking
out.append(
"\n{name}\n{underline}\n\n{screenshots}{details}\n".format(
name=module,
screenshots=screenshots(screenshots_data, module),
underline="-" * len(module),
details="".join(markdown_2_rst(data[module])).strip(),
)
)
# write include file
with open("../doc/modules-info.inc", "w") as f:
f.write("".join(out)) |
<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_variable_docstrings(filename):
""" Go through the file and find all documented variables. That is ones that have a literal expression following them. Also get a dict of assigned values so that we can substitute constants. """ |
def walk_node(parent, values=None, prefix=""):
"""
walk the ast searching for docstrings/values
"""
docstrings = {}
if values is None:
values = {}
key = None
for node in ast.iter_child_nodes(parent):
if isinstance(node, ast.ClassDef):
# We are in a class so walk the class
docs = walk_node(node, values, prefix + node.name + ".")[0]
docstrings[node.name] = docs
elif isinstance(node, ast.Assign):
key = node.targets[0].id
if isinstance(node.value, ast.Num):
values[key] = node.value.n
if isinstance(node.value, ast.Str):
values[key] = node.value.s
if isinstance(node.value, ast.Name):
if node.value.id in values:
values[prefix + key] = values[node.value.id]
elif isinstance(node, ast.Expr) and key:
docstrings[key] = node.value.s
else:
key = None
return docstrings, values
with open(filename, "r") as f:
source = f.read()
return walk_node(ast.parse(source)) |
<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_py3_info():
""" Inspect Py3 class and get constants, exceptions, methods along with their docstrings. """ |
# get all documented constants and their values
constants, values = get_variable_docstrings("../py3status/py3.py")
# we only care about ones defined in Py3
constants = constants["Py3"]
# sort them alphabetically
constants = [(k, v) for k, v in sorted(constants.items())]
# filter values as we only care about values defined in Py3
values = dict([(v, k[4:]) for k, v in values.items() if k.startswith("Py3.")])
def make_value(attr, arg, default):
"""
If the methods parameter is defined as a constant then do a
replacement. Otherwise return the values representation.
"""
if (attr, arg) in CONSTANT_PARAMS and default in values:
return values[default]
return repr(default)
# inspect Py3 to find it's methods etc
py3 = Py3()
# no private ones
attrs = [x for x in dir(py3) if not x.startswith("_")]
exceptions = []
methods = []
for attr in attrs:
item = getattr(py3, attr)
if "method" in str(item):
# a method so we need to get the call parameters
args, vargs, kw, defaults = inspect.getargspec(item)
args = args[1:]
len_defaults = len(defaults) if defaults else 0
len_args = len(args)
sig = []
for index, arg in enumerate(args):
# default values set?
if len_args - index <= len_defaults:
default = defaults[len_defaults - len_args + index]
sig.append("%s=%s" % (arg, make_value(attr, arg, default)))
else:
sig.append(arg)
definition = "%s(%s)" % (attr, ", ".join(sig))
methods.append((definition, item.__doc__))
continue
try:
# find any exceptions
if isinstance(item(), Exception):
exceptions.append((attr, item.__doc__))
continue
except: # noqa e722
pass
return {"methods": methods, "exceptions": exceptions, "constants": constants} |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def auto_undent(string):
""" Unindent a docstring. """ |
lines = string.splitlines()
while lines[0].strip() == "":
lines = lines[1:]
if not lines:
return []
spaces = len(lines[0]) - len(lines[0].lstrip(" "))
out = []
for line in lines:
num_spaces = len(line) - len(line.lstrip(" "))
out.append(line[min(spaces, num_spaces) :])
return out |
<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_py3_docs():
""" Create the include files for py3 documentation. """ |
# we want the correct .rst 'type' for our data
trans = {"methods": "function", "exceptions": "exception", "constants": "attribute"}
data = get_py3_info()
for k, v in data.items():
output = []
for name, desc in v:
output.append("")
output.append(".. _%s:" % name) # reference for linking
output.append("")
output.append(".. py:%s:: %s" % (trans[k], name))
output.append("")
output.extend(auto_undent(desc))
with open("../doc/py3-%s-info.inc" % k, "w") as f:
f.write("\n".join(output)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _time_up(self):
""" Called when the timer expires """ |
self.running = False
self.color = self.py3.COLOR_BAD
self.time_left = 0
self.done = True
if self.sound:
self.py3.play_sound(self.sound)
self.alarm = True
self.timer() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def status_code(self):
""" Get the http status code for the response """ |
try:
return self._status_code
except AttributeError:
self._status_code = self._response.getcode()
return self._status_code |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def text(self):
""" Get the raw text for the response """ |
try:
return self._text
except AttributeError:
if IS_PYTHON_3:
encoding = self._response.headers.get_content_charset("utf-8")
else:
encoding = self._response.headers.getparam("charset")
self._text = self._response.read().decode(encoding or "utf-8")
return self._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 json(self):
""" Return an object representing the return json for the request """ |
try:
return self._json
except AttributeError:
try:
self._json = json.loads(self.text)
return self._json
except: # noqa e722
raise RequestInvalidJSON("Invalid JSON received") |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def headers(self):
""" Get the headers from the response. """ |
try:
return self._headers
except AttributeError:
self._headers = self._response.headers
return self._headers |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def modules_directory():
""" Get the core modules directory. """ |
return os.path.join(os.path.dirname(os.path.abspath(__file__)), "modules") |
<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_readme(data):
""" Create README.md text for the given module data. """ |
out = ['<a name="top"></a>Modules\n========\n\n']
# Links
for module in sorted(data.keys()):
desc = "".join(data[module]).strip().split("\n")[0]
format_str = "\n**[{name}](#{name})** — {desc}\n"
out.append(format_str.format(name=module, desc=desc))
# details
for module in sorted(data.keys()):
out.append(
'\n---\n\n### <a name="{name}"></a>{name}\n\n{details}\n'.format(
name=module, details="".join(data[module]).strip()
)
)
return "".join(out) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _reformat_docstring(doc, format_fn, code_newline=""):
""" Go through lines of file and reformat using format_fn """ |
out = []
status = {"listing": False, "add_line": False, "eat_line": False}
code = False
for line in doc:
if status["add_line"]:
out.append("\n")
status["add_line"] = False
if status["eat_line"]:
status["eat_line"] = False
if line.strip() == "":
continue
# check for start/end of code block
if line.strip() == "```":
code = not code
out.append(line + code_newline)
continue
if not code:
# if we are in a block listing a blank line ends it
if line.rstrip() == "":
status["listing"] = False
# format the line
line = format_fn(line, status)
# see if block start
if re_listing.match(line):
status["listing"] = True
out.append(line.rstrip() + "\n")
return out |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _to_docstring(doc):
""" format from Markdown to docstring """ |
def format_fn(line, status):
""" format function """
# swap < > to < >
line = re_to_tag.sub(r"<\1>", line)
if re_to_data.match(line):
line = re_to_data.sub(r"@\1 ", line)
status["eat_line"] = True
line = re_to_defaults.sub(r"\1", line)
if status["listing"]:
# parameters
if re_to_param.match(line):
line = re_to_param.sub(r" \1: ", line)
# status items
elif re_to_status.match(line):
line = re_to_status.sub(r" \1 ", line)
# bullets
elif re_to_item.match(line):
line = re_to_item.sub(r" -", line)
# is continuation line
else:
line = " " * 8 + line.lstrip()
return line
return _reformat_docstring(doc, format_fn) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _from_docstring_md(doc):
""" format from docstring to Markdown """ |
def format_fn(line, status):
""" format function """
def fix_tags(line):
# In markdown we need to escape < > and & for display
# but we don't want to do this is the value is quoted
# by backticks ``
def fn(match):
# swap matched chars
found = match.group(1)
if found == "<":
return "<"
if found == ">":
return ">"
if found == "&":
return "&"
return match.group(0)
return re_from_tag.sub(fn, line)
if re_from_data.match(line):
line = re_from_data.sub(r"**\1** ", line)
status["add_line"] = True
line = re_from_defaults.sub(r"*\1*", line)
if status["listing"]:
# parameters
if re_from_param.match(line):
m = re_from_param.match(line)
line = " - `{}` {}".format(m.group(1), fix_tags(m.group(3)))
# status items
elif re_from_status.match(line):
m = re_from_status.match(line)
line = " - `{}` {}".format(m.group(1), fix_tags(m.group(3)))
# bullets
elif re_from_item.match(line):
line = re_from_item.sub(r" -", fix_tags(line))
# is continuation line
else:
line = fix_tags(line)
line = " " * 4 + line.lstrip()
else:
line = fix_tags(line)
return line
return _reformat_docstring(doc, format_fn, code_newline="\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 _from_docstring_rst(doc):
""" format from docstring to ReStructured Text """ |
def format_fn(line, status):
""" format function """
if re_from_data.match(line):
line = re_from_data.sub(r"**\1** ", line)
status["add_line"] = True
line = re_from_defaults.sub(r"*\1*", line)
if status["listing"]:
# parameters
if re_from_param.match(line):
m = re_from_param.match(line)
line = " - ``{}`` {}".format(m.group(1), m.group(3))
# status items
elif re_from_status.match(line):
m = re_from_status.match(line)
line = " - ``{}`` {}".format(m.group(1), m.group(3))
# bullets
elif re_from_item.match(line):
line = re_from_item.sub(r" -", line)
# is continuation line
else:
line = " " * 4 + line.lstrip()
# in .rst format code samples use double backticks vs single ones for
# .md This converts them.
line = re_lone_backtick.sub("``", line)
return line
return _reformat_docstring(doc, format_fn, code_newline="\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 check_docstrings(show_diff=False, config=None, mods=None):
""" Check docstrings in module match the README.md """ |
readme = parse_readme()
modules_readme = core_module_docstrings(config=config)
warned = False
if create_readme(readme) != create_readme(modules_readme):
for module in sorted(readme):
if mods and module not in mods:
continue
err = None
if module not in modules_readme:
err = "Module {} in README but not in /modules".format(module)
elif (
"".join(readme[module]).strip()
!= "".join(modules_readme[module]).strip()
):
err = "Module {} docstring does not match README".format(module)
if err:
if not warned:
print_stderr("Documentation does not match!\n")
warned = True
print_stderr(err)
for module in modules_readme:
if mods and module not in mods:
continue
if module not in readme:
print_stderr("Module {} in /modules but not in README".format(module))
if show_diff:
print_stderr(
"\n".join(
difflib.unified_diff(
create_readme(readme).split("\n"),
create_readme(modules_readme).split("\n"),
)
)
)
else:
if warned:
print_stderr("\nUse `py3-cmd docstring --diff` to view diff.") |
<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_readme_for_modules(modules):
""" Update README.md updating the sections for the module names listed. """ |
readme = parse_readme()
module_docstrings = core_module_docstrings()
if modules == ["__all__"]:
modules = core_module_docstrings().keys()
for module in modules:
if module in module_docstrings:
print_stderr("Updating README.md for module {}".format(module))
readme[module] = module_docstrings[module]
else:
print_stderr("Module {} not in core modules".format(module))
# write the file
readme_file = os.path.join(modules_directory(), "README.md")
with open(readme_file, "w") as f:
f.write(create_readme(readme)) |
<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_modules(config, modules_list):
""" List modules available optionally with details. """ |
details = config["full"]
core_mods = not config["user"]
user_mods = not config["core"]
modules = core_module_docstrings(
include_core=core_mods, include_user=user_mods, config=config
)
new_modules = []
if modules_list:
from fnmatch import fnmatch
for _filter in modules_list:
for name in modules.keys():
if fnmatch(name, _filter):
if name not in new_modules:
new_modules.append(name)
else:
new_modules = modules.keys()
for name in sorted(new_modules):
module = _to_docstring(modules[name])
desc = module[0][:-1]
if details:
dash_len = len(name) + 4
print("#" * dash_len)
print("# {} #".format(name))
print("#" * dash_len)
for description in module:
print(description[:-1])
else:
print("%-22s %s" % (name, desc)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def new(self, injection_site_fn):
"""Creates a _InjectionContext. Args: injection_site_fn: the initial function being injected into Returns: a new empty _InjectionContext in the default scope """ |
return _InjectionContext(
injection_site_fn, binding_stack=[], scope_id=scoping.UNSCOPED,
is_scope_usable_from_scope_fn=self._is_scope_usable_from_scope_fn) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_child(self, injection_site_fn, binding):
"""Creates a child injection context. A "child" injection context is a context for a binding used to inject something into the current binding's provided value. Args: injection_site_fn: the child function being injected into binding: a Binding Returns: a new _InjectionContext """ |
child_scope_id = binding.scope_id
new_binding_stack = self._binding_stack + [binding]
if binding in self._binding_stack:
raise errors.CyclicInjectionError(new_binding_stack)
if not self._is_scope_usable_from_scope_fn(
child_scope_id, self._scope_id):
raise errors.BadDependencyScopeError(
self.get_injection_site_desc(),
self._scope_id, child_scope_id, binding.binding_key)
return _InjectionContext(
injection_site_fn, new_binding_stack, child_scope_id,
self._is_scope_usable_from_scope_fn) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def provide(self, cls):
"""Provides an instance of the given class. Args: cls: a class (not an instance) Returns: an instance of cls Raises: Error: an instance of cls is not providable """ |
support.verify_class_type(cls, 'cls')
if not self._is_injectable_fn(cls):
provide_loc = locations.get_back_frame_loc()
raise errors.NonExplicitlyBoundClassError(provide_loc, cls)
try:
return self._obj_provider.provide_class(
cls, self._injection_context_factory.new(cls.__init__),
direct_init_pargs=[], direct_init_kwargs={})
except errors.Error as e:
if self._use_short_stack_traces:
raise e
else:
raise |
<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_type_name(target_thing):
""" Functions, bound methods and unbound methods change significantly in Python 3. For instance: class SomeObject(object):
def method():
pass In Python 2: - Unbound method inspect.ismethod(SomeObject.method) returns True - Unbound inspect.isfunction(SomeObject.method) returns False - Unbound hasattr(SomeObject.method, 'im_class') returns True - Bound method inspect.ismethod(SomeObject().method) returns True - Bound method inspect.isfunction(SomeObject().method) returns False - Bound hasattr(SomeObject().method, 'im_class') returns True In Python 3: - Unbound method inspect.ismethod(SomeObject.method) returns False - Unbound inspect.isfunction(SomeObject.method) returns True - Unbound hasattr(SomeObject.method, 'im_class') returns False - Bound method inspect.ismethod(SomeObject().method) returns True - Bound method inspect.isfunction(SomeObject().method) returns False - Bound hasattr(SomeObject().method, 'im_class') returns False This method tries to consolidate the approach for retrieving the enclosing type of a bound/unbound method and functions. """ |
thing = target_thing
if hasattr(thing, 'im_class'):
# only works in Python 2
return thing.im_class.__name__
if inspect.ismethod(thing):
for cls in inspect.getmro(thing.__self__.__class__):
if cls.__dict__.get(thing.__name__) is thing:
return cls.__name__
thing = thing.__func__
if inspect.isfunction(thing) and hasattr(thing, '__qualname__'):
qualifier = thing.__qualname__
if LOCALS_TOKEN in qualifier:
return _get_local_type_name(thing)
return _get_external_type_name(thing)
return inspect.getmodule(target_thing).__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 get_unbound_arg_names(arg_names, arg_binding_keys):
"""Determines which args have no arg binding keys. Args: arg_names: a sequence of the names of possibly bound args arg_binding_keys: a sequence of ArgBindingKey each of whose arg names is in arg_names Returns: a sequence of arg names that is a (possibly empty, possibly non-proper) subset of arg_names """ |
bound_arg_names = [abk._arg_name for abk in arg_binding_keys]
return [arg_name for arg_name in arg_names
if arg_name not in bound_arg_names] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def new(arg_name, annotated_with=None):
"""Creates an ArgBindingKey. Args: arg_name: the name of the bound arg annotation: an Annotation, or None to create an unannotated arg binding key Returns: a new ArgBindingKey """ |
if arg_name.startswith(_PROVIDE_PREFIX):
binding_key_name = arg_name[_PROVIDE_PREFIX_LEN:]
provider_indirection = provider_indirections.INDIRECTION
else:
binding_key_name = arg_name
provider_indirection = provider_indirections.NO_INDIRECTION
binding_key = binding_keys.new(binding_key_name, annotated_with)
return ArgBindingKey(arg_name, binding_key, provider_indirection) |
<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_overall_binding_key_to_binding_maps(bindings_lists):
"""bindings_lists from lowest to highest priority. Last item in bindings_lists is assumed explicit. """ |
binding_key_to_binding = {}
collided_binding_key_to_bindings = {}
for index, bindings in enumerate(bindings_lists):
is_final_index = (index == (len(bindings_lists) - 1))
handle_binding_collision_fn = {
True: _handle_explicit_binding_collision,
False: _handle_implicit_binding_collision}[is_final_index]
this_binding_key_to_binding, this_collided_binding_key_to_bindings = (
_get_binding_key_to_binding_maps(
bindings, handle_binding_collision_fn))
for good_binding_key in this_binding_key_to_binding:
collided_binding_key_to_bindings.pop(good_binding_key, None)
binding_key_to_binding.update(this_binding_key_to_binding)
collided_binding_key_to_bindings.update(
this_collided_binding_key_to_bindings)
return binding_key_to_binding, collided_binding_key_to_bindings |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def default_get_arg_names_from_class_name(class_name):
"""Converts normal class names into normal arg names. Normal class names are assumed to be CamelCase with an optional leading underscore. Normal arg names are assumed to be lower_with_underscores. Args: class_name: a class name, e.g., "FooBar" or "_FooBar" Returns: all likely corresponding arg names, e.g., ["foo_bar"] """ |
parts = []
rest = class_name
if rest.startswith('_'):
rest = rest[1:]
while True:
m = re.match(r'([A-Z][a-z]+)(.*)', rest)
if m is None:
break
parts.append(m.group(1))
rest = m.group(2)
if not parts:
return []
return ['_'.join(part.lower() for part in parts)] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def annotate_arg(arg_name, with_annotation):
"""Adds an annotation to an injected arg. arg_name must be one of the named args of the decorated function, i.e., @annotate_arg('foo', with_annotation='something') is OK, but @annotate_arg('foo', with_annotation='something') is not. The same arg (on the same function) may not be annotated twice. Args: arg_name: the name of the arg to annotate on the decorated function with_annotation: an annotation object Returns: a function that will decorate functions passed to it """ |
arg_binding_key = arg_binding_keys.new(arg_name, with_annotation)
return _get_pinject_wrapper(locations.get_back_frame_loc(),
arg_binding_key=arg_binding_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 inject(arg_names=None, all_except=None):
"""Marks an initializer explicitly as injectable. An initializer marked with @inject will be usable even when setting only_use_explicit_bindings=True when calling new_object_graph(). This decorator can be used on an initializer or provider method to separate the injectable args from the args that will be passed directly. If arg_names is specified, then it must be a sequence, and only those args are injected (and the rest must be passed directly). If all_except is specified, then it must be a sequence, and only those args are passed directly (and the rest must be specified). If neither arg_names nor all_except are specified, then all args are injected (and none may be passed directly). arg_names or all_except, when specified, must not be empty and must contain a (possibly empty, possibly non-proper) subset of the named args of the decorated function. all_except may not be all args of the decorated function (because then why call that provider method or initialzer via Pinject?). At most one of arg_names and all_except may be specified. A function may be decorated by @inject at most once. """ |
back_frame_loc = locations.get_back_frame_loc()
if arg_names is not None and all_except is not None:
raise errors.TooManyArgsToInjectDecoratorError(back_frame_loc)
for arg, arg_value in [('arg_names', arg_names), ('all_except', all_except)]:
if arg_value is not None:
if not arg_value:
raise errors.EmptySequenceArgError(back_frame_loc, arg)
if (not support.is_sequence(arg_value) or
support.is_string(arg_value)):
raise errors.WrongArgTypeError(
arg, 'sequence (of arg names)', type(arg_value).__name__)
if arg_names is None and all_except is None:
all_except = []
return _get_pinject_wrapper(
back_frame_loc, inject_arg_names=arg_names,
inject_all_except_arg_names=all_except) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def provides(arg_name=None, annotated_with=None, in_scope=None):
"""Modifies the binding of a provider method. If arg_name is specified, then the created binding is for that arg name instead of the one gotten from the provider method name (e.g., 'foo' from 'provide_foo'). If annotated_with is specified, then the created binding includes that annotation object. If in_scope is specified, then the created binding is in the scope with that scope ID. At least one of the args must be specified. A provider method may not be decorated with @provides() twice. Args: arg_name: the name of the arg to annotate on the decorated function annotated_with: an annotation object in_scope: a scope ID Returns: a function that will decorate functions passed to it """ |
if arg_name is None and annotated_with is None and in_scope is None:
raise errors.EmptyProvidesDecoratorError(locations.get_back_frame_loc())
return _get_pinject_wrapper(locations.get_back_frame_loc(),
provider_arg_name=arg_name,
provider_annotated_with=annotated_with,
provider_in_scope_id=in_scope) |
<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_provider_fn_decorations(provider_fn, default_arg_names):
"""Retrieves the provider method-relevant info set by decorators. If any info wasn't set by decorators, then defaults are returned. Args: provider_fn: a (possibly decorated) provider function default_arg_names: the (possibly empty) arg names to use if none were specified via @provides() Returns: a sequence of ProviderDecoration """ |
if hasattr(provider_fn, _IS_WRAPPER_ATTR):
provider_decorations = getattr(provider_fn, _PROVIDER_DECORATIONS_ATTR)
if provider_decorations:
expanded_provider_decorations = []
for provider_decoration in provider_decorations:
# TODO(kurts): seems like default scope should be done at
# ProviderDecoration instantiation time.
if provider_decoration.in_scope_id is None:
provider_decoration.in_scope_id = scoping.DEFAULT_SCOPE
if provider_decoration.arg_name is not None:
expanded_provider_decorations.append(provider_decoration)
else:
expanded_provider_decorations.extend(
[ProviderDecoration(default_arg_name,
provider_decoration.annotated_with,
provider_decoration.in_scope_id)
for default_arg_name in default_arg_names])
return expanded_provider_decorations
return [ProviderDecoration(default_arg_name,
annotated_with=None,
in_scope_id=scoping.DEFAULT_SCOPE)
for default_arg_name in default_arg_names] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def new(arg_name, annotated_with=None):
"""Creates a BindingKey. Args: arg_name: the name of the bound arg annotation: an Annotation, or None to create an unannotated binding key Returns: a new BindingKey """ |
if annotated_with is not None:
annotation = annotations.Annotation(annotated_with)
else:
annotation = annotations.NO_ANNOTATION
return BindingKey(arg_name, annotation) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def __setkey(key):
""" Set up the key schedule from the encryption key. """ |
global C, D, KS, E
shifts = (1, 1, 2, 2, 2, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 1)
# First, generate C and D by permuting the key. The lower order bit of each
# 8-bit char is not used, so C and D are only 28 bits apiece.
for i in range(28):
C[i] = key[PC1_C[i] - 1]
D[i] = key[PC1_D[i] - 1]
for i in range(16):
# rotate
for k in range(shifts[i]):
temp = C[0]
for j in range(27):
C[j] = C[j + 1]
C[27] = temp
temp = D[0]
for j in range(27):
D[j] = D[j + 1]
D[27] = temp
# get Ki. Note C and D are concatenated
for j in range(24):
KS[i][j] = C[PC2_C[j] - 1]
KS[i][j + 24] = D[PC2_D[j] - 28 - 1]
# load E with the initial E bit selections
for i in range(48):
E[i] = e2[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 nextset(self):
""" Skip to the next available result set, discarding any remaining rows from the current result set. If there are no more result sets, this method returns False. Otherwise, it returns a True and subsequent calls to the fetch*() methods will return rows from the next result set. """ |
# skip any data for this set if exists
self.flush_to_end_of_result()
if self._message is None:
return False
elif isinstance(self._message, END_OF_RESULT_RESPONSES):
# there might be another set, read next message to find out
self._message = self.connection.read_message()
if isinstance(self._message, messages.RowDescription):
self.description = [Column(fd, self.unicode_error) for fd in self._message.fields]
self._message = self.connection.read_message()
return True
elif isinstance(self._message, messages.BindComplete):
self._message = self.connection.read_message()
return True
elif isinstance(self._message, messages.ReadyForQuery):
return False
elif isinstance(self._message, END_OF_RESULT_RESPONSES):
# result of a DDL/transaction
return True
elif isinstance(self._message, messages.ErrorResponse):
raise errors.QueryError.from_error_response(self._message, self.operation)
else:
raise errors.MessageError(
'Unexpected nextset() state after END_OF_RESULT_RESPONSES: {0}'.format(self._message))
elif isinstance(self._message, messages.ReadyForQuery):
# no more sets left to be read
return False
else:
raise errors.MessageError('Unexpected nextset() state: {0}'.format(self._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 _prepare(self, query):
""" Send the query to be prepared to the server. The server will parse the query and return some metadata. """ |
self._logger.info(u'Prepare a statement: [{}]'.format(query))
# Send Parse message to server
# We don't need to tell the server the parameter types yet
self.connection.write(messages.Parse(self.prepared_name, query, param_types=()))
# Send Describe message to server
self.connection.write(messages.Describe('prepared_statement', self.prepared_name))
self.connection.write(messages.Flush())
# Read expected message: ParseComplete
self._message = self.connection.read_expected_message(messages.ParseComplete, self._error_handler)
# Read expected message: ParameterDescription
self._message = self.connection.read_expected_message(messages.ParameterDescription, self._error_handler)
self._param_metadata = self._message.parameters
# Read expected message: RowDescription or NoData
self._message = self.connection.read_expected_message(
(messages.RowDescription, messages.NoData), self._error_handler)
if isinstance(self._message, messages.NoData):
self.description = None # response was NoData for a DDL/transaction PreparedStatement
else:
self.description = [Column(fd, self.unicode_error) for fd in self._message.fields]
# Read expected message: CommandDescription
self._message = self.connection.read_expected_message(messages.CommandDescription, self._error_handler)
if len(self._message.command_tag) == 0:
msg = 'The statement being prepared is empty'
self._logger.error(msg)
self.connection.write(messages.Sync())
raise errors.EmptyQueryError(msg)
self._logger.info('Finish preparing the statement') |
<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_prepared_statement(self, list_of_parameter_values):
""" Send multiple statement parameter sets to the server using the extended query protocol. The server would bind and execute each set of parameter values. This function should not be called without first calling _prepare() to prepare a statement. """ |
portal_name = ""
parameter_type_oids = [metadata['data_type_oid'] for metadata in self._param_metadata]
parameter_count = len(self._param_metadata)
try:
if len(list_of_parameter_values) == 0:
raise ValueError("Empty list/tuple, nothing to execute")
for parameter_values in list_of_parameter_values:
if parameter_values is None:
parameter_values = ()
self._logger.info(u'Bind parameters: {}'.format(parameter_values))
if len(parameter_values) != parameter_count:
msg = ("Invalid number of parameters for {}: {} given, {} expected"
.format(parameter_values, len(parameter_values), parameter_count))
raise ValueError(msg)
self.connection.write(messages.Bind(portal_name, self.prepared_name,
parameter_values, parameter_type_oids))
self.connection.write(messages.Execute(portal_name, 0))
self.connection.write(messages.Sync())
except Exception as e:
self._logger.error(str(e))
# the server will not send anything until we issue a sync
self.connection.write(messages.Sync())
self._message = self.connection.read_message()
raise
self.connection.write(messages.Flush())
# Read expected message: BindComplete
self.connection.read_expected_message(messages.BindComplete)
self._message = self.connection.read_message()
if isinstance(self._message, messages.ErrorResponse):
raise errors.QueryError.from_error_response(self._message, self.prepared_sql) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _close_prepared_statement(self):
""" Close the prepared statement on the server. """ |
self.prepared_sql = None
self.flush_to_query_ready()
self.connection.write(messages.Close('prepared_statement', self.prepared_name))
self.connection.write(messages.Flush())
self._message = self.connection.read_expected_message(messages.CloseComplete)
self.connection.write(messages.Sync()) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def ensure_dir_exists(cls, filepath):
"""Ensure that a directory exists If it doesn't exist, try to create it and protect against a race condition if another process is doing the same. """ |
directory = os.path.dirname(filepath)
if directory != '' and not os.path.exists(directory):
try:
os.makedirs(directory)
except OSError as e:
if e.errno != errno.EEXIST:
raise |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def getTypeName(data_type_oid, type_modifier):
"""Returns the base type name according to data_type_oid and type_modifier""" |
if data_type_oid == VerticaType.BOOL:
return "Boolean"
elif data_type_oid == VerticaType.INT8:
return "Integer"
elif data_type_oid == VerticaType.FLOAT8:
return "Float"
elif data_type_oid == VerticaType.CHAR:
return "Char"
elif data_type_oid in (VerticaType.VARCHAR, VerticaType.UNKNOWN):
return "Varchar"
elif data_type_oid == VerticaType.LONGVARCHAR:
return "Long Varchar"
elif data_type_oid == VerticaType.DATE:
return "Date"
elif data_type_oid == VerticaType.TIME:
return "Time"
elif data_type_oid == VerticaType.TIMETZ:
return "TimeTz"
elif data_type_oid == VerticaType.TIMESTAMP:
return "Timestamp"
elif data_type_oid == VerticaType.TIMESTAMPTZ:
return "TimestampTz"
elif data_type_oid in (VerticaType.INTERVAL, VerticaType.INTERVALYM):
return "Interval " + getIntervalRange(data_type_oid, type_modifier)
elif data_type_oid == VerticaType.BINARY:
return "Binary"
elif data_type_oid == VerticaType.VARBINARY:
return "Varbinary"
elif data_type_oid == VerticaType.LONGVARBINARY:
return "Long Varbinary"
elif data_type_oid == VerticaType.NUMERIC:
return "Numeric"
elif data_type_oid == VerticaType.UUID:
return "Uuid"
else:
return "Unknown" |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def getIntervalRange(data_type_oid, type_modifier):
"""Extracts an interval's range from the bits set in its type_modifier""" |
if data_type_oid not in (VerticaType.INTERVAL, VerticaType.INTERVALYM):
raise ValueError("Invalid data type OID: {}".format(data_type_oid))
if type_modifier == -1: # assume the default
if data_type_oid == VerticaType.INTERVALYM:
return "Year to Month"
elif data_type_oid == VerticaType.INTERVAL:
return "Day to Second"
if data_type_oid == VerticaType.INTERVALYM: # Year/Month intervals
if (type_modifier & INTERVAL_MASK_YEAR2MONTH) == INTERVAL_MASK_YEAR2MONTH:
return "Year to Month"
elif (type_modifier & INTERVAL_MASK_YEAR) == INTERVAL_MASK_YEAR:
return "Year"
elif (type_modifier & INTERVAL_MASK_MONTH) == INTERVAL_MASK_MONTH:
return "Month"
else:
return "Year to Month"
if data_type_oid == VerticaType.INTERVAL: # Day/Time intervals
if (type_modifier & INTERVAL_MASK_DAY2SEC) == INTERVAL_MASK_DAY2SEC:
return "Day to Second"
elif (type_modifier & INTERVAL_MASK_DAY2MIN) == INTERVAL_MASK_DAY2MIN:
return "Day to Minute"
elif (type_modifier & INTERVAL_MASK_DAY2HOUR) == INTERVAL_MASK_DAY2HOUR:
return "Day to Hour"
elif (type_modifier & INTERVAL_MASK_DAY) == INTERVAL_MASK_DAY:
return "Day"
elif (type_modifier & INTERVAL_MASK_HOUR2SEC) == INTERVAL_MASK_HOUR2SEC:
return "Hour to Second"
elif (type_modifier & INTERVAL_MASK_HOUR2MIN) == INTERVAL_MASK_HOUR2MIN:
return "Hour to Minute"
elif (type_modifier & INTERVAL_MASK_HOUR) == INTERVAL_MASK_HOUR:
return "Hour"
elif (type_modifier & INTERVAL_MASK_MIN2SEC) == INTERVAL_MASK_MIN2SEC:
return "Minute to Second"
elif (type_modifier & INTERVAL_MASK_MINUTE) == INTERVAL_MASK_MINUTE:
return "Minute"
elif (type_modifier & INTERVAL_MASK_SECOND) == INTERVAL_MASK_SECOND:
return "Second"
else:
return "Day to Second" |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def getIntervalLeadingPrecision(data_type_oid, type_modifier):
""" Returns the leading precision for an interval, which is the largest number of digits that can fit in the leading field of the interval. All Year/Month intervals are defined in terms of months, even if the type_modifier forbids months to be specified (i.e. INTERVAL YEAR). Similarly, all Day/Time intervals are defined as a number of microseconds. Because of this, interval types with shorter ranges will have a larger leading precision. For example, an INTERVAL DAY's leading precision is ((2^63)-1)/MICROSECS_PER_DAY, while an INTERVAL HOUR's leading precision is ((2^63)-1)/MICROSECS_PER_HOUR """ |
interval_range = getIntervalRange(data_type_oid, type_modifier)
if interval_range in ("Year", "Year to Month"):
return 18
elif interval_range == "Month":
return 19
elif interval_range in ("Day", "Day to Hour", "Day to Minute", "Day to Second"):
return 9
elif interval_range in ("Hour", "Hour to Minute", "Hour to Second"):
return 10
elif interval_range in ("Minute", "Minute to Second"):
return 12
elif interval_range == "Second":
return 13
else:
raise ValueError("Invalid interval range: {}".format(interval_range)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def getPrecision(data_type_oid, type_modifier):
""" Returns the precision for the given Vertica type with consideration of the type modifier. For numerics, precision is the total number of digits (in base 10) that can fit in the type. For intervals, time and timestamps, precision is the number of digits to the right of the decimal point in the seconds portion of the time. The type modifier of -1 is used when the size of a type is unknown. In those cases we assume the maximum possible size. """ |
if data_type_oid == VerticaType.NUMERIC:
if type_modifier == -1:
return 1024
return ((type_modifier - 4) >> 16) & 0xFFFF
elif data_type_oid in (VerticaType.TIME, VerticaType.TIMETZ,
VerticaType.TIMESTAMP, VerticaType.TIMESTAMPTZ,
VerticaType.INTERVAL, VerticaType.INTERVALYM):
if type_modifier == -1:
return 6
return type_modifier & 0xF
else:
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 getDisplaySize(data_type_oid, type_modifier):
""" Returns the column display size for the given Vertica type with consideration of the type modifier. The display size of a column is the maximum number of characters needed to display data in character form. """ |
if data_type_oid == VerticaType.BOOL:
# T or F
return 1
elif data_type_oid == VerticaType.INT8:
# a sign and 19 digits if signed or 20 digits if unsigned
return 20
elif data_type_oid == VerticaType.FLOAT8:
# a sign, 15 digits, a decimal point, the letter E, a sign, and 3 digits
return 22
elif data_type_oid == VerticaType.NUMERIC:
# a sign, precision digits, and a decimal point
return getPrecision(data_type_oid, type_modifier) + 2
elif data_type_oid == VerticaType.DATE:
# yyyy-mm-dd, a space, and the calendar era (BC)
return 13
elif data_type_oid == VerticaType.TIME:
seconds_precision = getPrecision(data_type_oid, type_modifier)
if seconds_precision == 0:
# hh:mm:ss
return 8
else:
# hh:mm:ss.[fff...]
return 9 + seconds_precision
elif data_type_oid == VerticaType.TIMETZ:
seconds_precision = getPrecision(data_type_oid, type_modifier)
if seconds_precision == 0:
# hh:mm:ss, a sign, hh:mm
return 14
else:
# hh:mm:ss.[fff...], a sign, hh:mm
return 15 + seconds_precision
elif data_type_oid == VerticaType.TIMESTAMP:
seconds_precision = getPrecision(data_type_oid, type_modifier)
if seconds_precision == 0:
# yyyy-mm-dd hh:mm:ss, a space, and the calendar era (BC)
return 22
else:
# yyyy-mm-dd hh:mm:ss[.fff...], a space, and the calendar era (BC)
return 23 + seconds_precision
elif data_type_oid == VerticaType.TIMESTAMPTZ:
seconds_precision = getPrecision(data_type_oid, type_modifier)
if seconds_precision == 0:
# yyyy-mm-dd hh:mm:ss, a sign, hh:mm, a space, and the calendar era (BC)
return 28
else:
# yyyy-mm-dd hh:mm:ss.[fff...], a sign, hh:mm, a space, and the calendar era (BC)
return 29 + seconds_precision
elif data_type_oid in (VerticaType.INTERVAL, VerticaType.INTERVALYM):
leading_precision = getIntervalLeadingPrecision(data_type_oid, type_modifier)
seconds_precision = getPrecision(data_type_oid, type_modifier)
interval_range = getIntervalRange(data_type_oid, type_modifier)
if interval_range in ("Year", "Month", "Day", "Hour", "Minute"):
# a sign, [range...]
return 1 + leading_precision
elif interval_range in ("Day to Hour", "Year to Month", "Hour to Minute"):
# a sign, [dd...] hh; a sign, [yy...]-mm; a sign, [hh...]:mm
return 1 + leading_precision + 3
elif interval_range == "Day to Minute":
# a sign, [dd...] hh:mm
return 1 + leading_precision + 6
elif interval_range == "Second":
if seconds_precision == 0:
# a sign, [ss...]
return 1 + leading_precision
else:
# a sign, [ss...].[fff...]
return 1 + leading_precision + 1 + seconds_precision
elif interval_range == "Day to Second":
if seconds_precision == 0:
# a sign, [dd...] hh:mm:ss
return 1 + leading_precision + 9
else:
# a sign, [dd...] hh:mm:ss.[fff...]
return 1 + leading_precision + 10 + seconds_precision
elif interval_range == "Hour to Second":
if seconds_precision == 0:
# a sign, [hh...]:mm:ss
return 1 + leading_precision + 6
else:
# a sign, [hh...]:mm:ss.[fff...]
return 1 + leading_precision + 7 + seconds_precision
elif interval_range == "Minute to Second":
if seconds_precision == 0:
# a sign, [mm...]:ss
return 1 + leading_precision + 3
else:
# a sign, [mm...]:ss.[fff...]
return 1 + leading_precision + 4 + seconds_precision
elif data_type_oid == VerticaType.UUID:
# aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee
return 36
elif data_type_oid in (VerticaType.CHAR,
VerticaType.VARCHAR,
VerticaType.BINARY,
VerticaType.VARBINARY,
VerticaType.UNKNOWN):
# the defined maximum octet length of the column
return MAX_STRING_LEN if type_modifier <= -1 else (type_modifier - 4)
elif data_type_oid in (VerticaType.LONGVARCHAR,
VerticaType.LONGVARBINARY):
return MAX_LONG_STRING_LEN if type_modifier <= -1 else (type_modifier - 4)
else:
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 _get_classpath():
"""Extract CLASSPATH from system environment as JPype doesn't seem to respect that variable. """ |
try:
orig_cp = os.environ['CLASSPATH']
except KeyError:
return []
expanded_cp = []
for i in orig_cp.split(os.path.pathsep):
expanded_cp.extend(_jar_glob(i))
return expanded_cp |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _close_last(self):
"""Close the resultset and reset collected meta data. """ |
if self._rs:
self._rs.close()
self._rs = None
if self._prep:
self._prep.close()
self._prep = None
self._meta = None
self._description = None |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_global_tracer(value):
"""Sets the global tracer. It is an error to pass ``None``. :param value: the :class:`Tracer` used as global instance. :type value: :class:`Tracer` """ |
if value is None:
raise ValueError('The global Tracer tracer cannot be None')
global tracer, is_tracer_registered
tracer = value
is_tracer_registered = 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 inject(self, span_context, format, carrier):
"""Injects `span_context` into `carrier`. The type of `carrier` is determined by `format`. See the :class:`Format` class/namespace for the built-in OpenTracing formats. Implementations *must* raise :exc:`UnsupportedFormatException` if `format` is unknown or disallowed. :param span_context: the :class:`SpanContext` instance to inject :type span_context: SpanContext :param format: a python object instance that represents a given carrier format. `format` may be of any type, and `format` equality is defined by python ``==`` equality. :type format: Format :param carrier: the format-specific carrier object to inject into """ |
if format in Tracer._supported_formats:
return
raise UnsupportedFormatException(format) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def __analizar_controles(self, ret):
"Comprueba y extrae controles si existen en la respuesta XML"
if 'arrayControles' in ret:
controles = ret['arrayControles']
self.Controles = ["%(tipo)s: %(descripcion)s" % ctl['control']
for ctl in controles] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def Dummy(self):
"Obtener el estado de los servidores de la AFIP"
results = self.client.dummy()['response']
self.AppServerStatus = str(results['appserver'])
self.DbServerStatus = str(results['dbserver'])
self.AuthServerStatus = str(results['authserver']) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def SolicitarCTGInicial(self, numero_carta_de_porte, codigo_especie,
cuit_canjeador, cuit_destino, cuit_destinatario, codigo_localidad_origen,
codigo_localidad_destino, codigo_cosecha, peso_neto_carga,
cant_horas=None, patente_vehiculo=None, cuit_transportista=None,
km_a_recorrer=None, remitente_comercial_como_canjeador=None,
cuit_corredor=None, remitente_comercial_como_productor=None,
turno=None,
**kwargs):
"Solicitar CTG Desde el Inicio"
# ajusto parámetros según validaciones de AFIP:
if not cuit_canjeador or int(cuit_canjeador) == 0:
cuit_canjeador = None # nulo
if not cuit_corredor or int(cuit_corredor) == 0:
cuit_corredor = None # nulo
if not remitente_comercial_como_canjeador:
remitente_comercial_como_canjeador = None
if not remitente_comercial_como_productor:
remitente_comercial_como_productor = None
if turno == '':
turno = None # nulo
ret = self.client.solicitarCTGInicial(request=dict(
auth={
'token': self.Token, 'sign': self.Sign,
'cuitRepresentado': self.Cuit, },
datosSolicitarCTGInicial=dict(
cartaPorte=numero_carta_de_porte,
codigoEspecie=codigo_especie,
cuitCanjeador=cuit_canjeador or None,
remitenteComercialComoCanjeador=remitente_comercial_como_canjeador,
cuitDestino=cuit_destino,
cuitDestinatario=cuit_destinatario,
codigoLocalidadOrigen=codigo_localidad_origen,
codigoLocalidadDestino=codigo_localidad_destino,
codigoCosecha=codigo_cosecha,
pesoNeto=peso_neto_carga,
cuitTransportista=cuit_transportista,
cantHoras=cant_horas,
patente=patente_vehiculo,
kmARecorrer=km_a_recorrer,
cuitCorredor=cuit_corredor,
remitenteComercialcomoProductor=remitente_comercial_como_productor,
turno=turno,
)))['response']
self.__analizar_errores(ret)
self.Observaciones = ret['observacion']
datos = ret.get('datosSolicitarCTGResponse')
if datos:
self.CartaPorte = str(datos['cartaPorte'])
datos_ctg = datos.get('datosSolicitarCTG')
if datos_ctg:
self.NumeroCTG = str(datos_ctg['ctg'])
self.FechaHora = str(datos_ctg['fechaEmision'])
self.VigenciaDesde = str(datos_ctg['fechaVigenciaDesde'])
self.VigenciaHasta = str(datos_ctg['fechaVigenciaHasta'])
self.TarifaReferencia = str(datos_ctg.get('tarifaReferencia'))
self.__analizar_controles(datos)
return self.NumeroCTG or 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 SolicitarCTGDatoPendiente(self, numero_carta_de_porte, cant_horas,
patente_vehiculo, cuit_transportista, patente=None, turno=None):
"Solicitud que permite completar los datos faltantes de un Pre-CTG "
"generado anteriormente a través de la operación solicitarCTGInicial"
ret = self.client.solicitarCTGDatoPendiente(request=dict(
auth={
'token': self.Token, 'sign': self.Sign,
'cuitRepresentado': self.Cuit, },
datosSolicitarCTGDatoPendiente=dict(
cartaPorte=numero_carta_de_porte,
cuitTransportista=cuit_transportista,
cantHoras=cant_horas,
patente=patente,
turno=turno,
)))['response']
self.__analizar_errores(ret)
self.Observaciones = ret['observacion']
datos = ret.get('datosSolicitarCTGResponse')
if datos:
self.CartaPorte = str(datos['cartaPorte'])
datos_ctg = datos.get('datosSolicitarCTG')
if datos_ctg:
self.NumeroCTG = str(datos_ctg['ctg'])
self.FechaHora = str(datos_ctg['fechaEmision'])
self.VigenciaDesde = str(datos_ctg['fechaVigenciaDesde'])
self.VigenciaHasta = str(datos_ctg['fechaVigenciaHasta'])
self.TarifaReferencia = str(datos_ctg.get('tarifaReferencia'))
self.__analizar_controles(datos)
return self.NumeroCTG |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.