_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q35000 | Py3statusWrapper.log | train | def log(self, msg, level="info"):
"""
log this information to syslog or user provided logfile.
"""
if not self.config.get("log_file"):
# If level was given as a str then convert to actual level
level = LOG_LEVELS.get(level, level)
syslog(level, u"{}".f... | python | {
"resource": ""
} |
q35001 | Py3statusWrapper.create_output_modules | train | def create_output_modules(self):
"""
Setup our output modules to allow easy updating of py3modules and
i3status modules allows the same module to be used multiple times.
"""
py3_config = self.config["py3_config"]
i3modules = self.i3status_thread.i3modules
output_m... | python | {
"resource": ""
} |
q35002 | Py3statusWrapper.create_mappings | train | def create_mappings(self, config):
"""
Create any mappings needed for global substitutions eg. colors
"""
mappings = {}
for name, cfg in config.items():
# Ignore special config sections.
if name in CONFIG_SPECIAL_SECTIONS:
continue
... | python | {
"resource": ""
} |
q35003 | Py3statusWrapper.process_module_output | train | def process_module_output(self, module):
"""
Process the output for a module and return a json string representing it.
Color processing occurs here.
"""
outputs = module["module"].get_latest()
color = module["color"]
if color:
for output in outputs:
... | python | {
"resource": ""
} |
q35004 | Py3statusWrapper.run | train | def run(self):
"""
Main py3status loop, continuously read from i3status and modules
and output it to i3bar for displaying.
"""
# SIGUSR1 forces a refresh of the bar both for py3status and i3status,
# this mimics the USR1 signal handling of i3status (see man i3status)
... | python | {
"resource": ""
} |
q35005 | Gradients.hex_2_rgb | train | def hex_2_rgb(self, color):
"""
convert a hex color to rgb
"""
if not self.RE_HEX.match(color):
color = "#FFF"
if len(color) == 7:
return (int(color[i : i + 2], 16) / 255 for i in [1, 3, 5])
return (int(c, 16) / 15 for c in color) | python | {
"resource": ""
} |
q35006 | Gradients.rgb_2_hex | train | def rgb_2_hex(self, r, g, b):
"""
convert a rgb color to hex
"""
return "#{:02X}{:02X}{:02X}".format(int(r * 255), int(g * 255), int(b * 255)) | python | {
"resource": ""
} |
q35007 | Gradients.hsv_2_hex | train | def hsv_2_hex(self, h, s, v):
"""
convert a hsv color to hex
"""
return self.rgb_2_hex(*hsv_to_rgb(h, s, v)) | python | {
"resource": ""
} |
q35008 | Gradients.make_threshold_gradient | train | def make_threshold_gradient(self, py3, thresholds, size=100):
"""
Given a thresholds list, creates a gradient list that covers the range
of the thresholds.
The number of colors in the gradient is limited by size.
Because of how the range is split the exact number of colors in th... | python | {
"resource": ""
} |
q35009 | Events.get_module_text | train | def get_module_text(self, module_name, event):
"""
Get the full text for the module as well as the partial text if the
module is a composite. Partial text is the text for just the single
section of a composite.
"""
index = event.get("index")
module_info = self.py... | python | {
"resource": ""
} |
q35010 | Events.wm_msg | train | def wm_msg(self, module_name, command):
"""
Execute the message with i3-msg or swaymsg and log its output.
"""
wm_msg = self.config["wm"]["msg"]
pipe = Popen([wm_msg, command], stdout=PIPE)
self.py3_wrapper.log(
'{} module="{}" command="{}" stdout={}'.format(
... | python | {
"resource": ""
} |
q35011 | Events.dispatch_event | train | 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
... | python | {
"resource": ""
} |
q35012 | Events.run | train | 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 MI... | python | {
"resource": ""
} |
q35013 | Py3status._start_handler_thread | train | 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 | python | {
"resource": ""
} |
q35014 | Py3status._start_loop | train | 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_s... | python | {
"resource": ""
} |
q35015 | Py3status._vpn_signal_handler | train | 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 ActiveConnecti... | python | {
"resource": ""
} |
q35016 | Py3status._get_vpn_status | train | 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... | python | {
"resource": ""
} |
q35017 | Py3status.vpn_status | train | 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
col... | python | {
"resource": ""
} |
q35018 | Composite.append | train | 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):
... | python | {
"resource": ""
} |
q35019 | Composite.simplify | train | 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:
#... | python | {
"resource": ""
} |
q35020 | Composite.composite_join | train | 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 emp... | python | {
"resource": ""
} |
q35021 | Py3status._init_dbus | train | 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, D... | python | {
"resource": ""
} |
q35022 | Py3status._get_device_id | train | 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... | python | {
"resource": ""
} |
q35023 | Py3status._get_device | train | 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
... | python | {
"resource": ""
} |
q35024 | Py3status._get_battery | train | def _get_battery(self):
"""
Get the battery
"""
try:
battery = {
"charge": self._dev.charge(),
"isCharging": self._dev.isCharging() == 1,
}
except Exception:
return None
return battery | python | {
"resource": ""
} |
q35025 | Py3status._get_battery_status | train | 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:
... | python | {
"resource": ""
} |
q35026 | Py3status._get_notifications_status | train | 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
ret... | python | {
"resource": ""
} |
q35027 | Py3status._get_text | train | 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_forma... | python | {
"resource": ""
} |
q35028 | Py3status.kdeconnector | train | 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_i... | python | {
"resource": ""
} |
q35029 | Py3status.dpms | train | 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 = ... | python | {
"resource": ""
} |
q35030 | Py3status.on_click | train | 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... | python | {
"resource": ""
} |
q35031 | Py3status._get_progress | train | 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"... | python | {
"resource": ""
} |
q35032 | Py3status._idle | train | 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... | python | {
"resource": ""
} |
q35033 | Py3status._get_cputemp_with_lmsensors | train | 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 ... | python | {
"resource": ""
} |
q35034 | Formatter.tokens | train | 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... | python | {
"resource": ""
} |
q35035 | Formatter.get_color_names | train | 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 = ... | python | {
"resource": ""
} |
q35036 | Formatter.get_placeholders | train | 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"):
... | python | {
"resource": ""
} |
q35037 | Formatter.update_placeholders | train | 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:
... | python | {
"resource": ""
} |
q35038 | Formatter.update_placeholder_formats | train | 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 (
... | python | {
"resource": ""
} |
q35039 | Formatter.build_block | train | 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 proce... | python | {
"resource": ""
} |
q35040 | Formatter.format | train | 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 call... | python | {
"resource": ""
} |
q35041 | Placeholder.get | train | 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 n... | python | {
"resource": ""
} |
q35042 | Condition._check_valid_condition | train | 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.val... | python | {
"resource": ""
} |
q35043 | Condition._check_valid_basic | train | 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 | python | {
"resource": ""
} |
q35044 | BlockConfig.update_commands | train | 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_leng... | python | {
"resource": ""
} |
q35045 | BlockConfig._set_int | train | 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 | python | {
"resource": ""
} |
q35046 | Block.new_block | train | 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 | python | {
"resource": ""
} |
q35047 | Block.switch | train | 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
... | python | {
"resource": ""
} |
q35048 | Block.check_valid | train | 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) | python | {
"resource": ""
} |
q35049 | Py3status._content_function | train | 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.a... | python | {
"resource": ""
} |
q35050 | Py3status._urgent_function | train | 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 | python | {
"resource": ""
} |
q35051 | get_backends | train | 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... | python | {
"resource": ""
} |
q35052 | ClickTimer.trigger | train | 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 call... | python | {
"resource": ""
} |
q35053 | ClickTimer.event | train | 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.
... | python | {
"resource": ""
} |
q35054 | Py3status._get_stat | train | 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 Fal... | python | {
"resource": ""
} |
q35055 | Py3status._format_value | train | 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}) | python | {
"resource": ""
} |
q35056 | Py3status._persist | train | 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],
... | python | {
"resource": ""
} |
q35057 | markdown_2_rst | train | 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... | python | {
"resource": ""
} |
q35058 | file_sort | train | 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... | python | {
"resource": ""
} |
q35059 | screenshots | train | 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... | python | {
"resource": ""
} |
q35060 | create_module_docs | train | 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_dat... | python | {
"resource": ""
} |
q35061 | get_variable_docstrings | train | 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=""):
"""
... | python | {
"resource": ""
} |
q35062 | get_py3_info | train | 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 = consta... | python | {
"resource": ""
} |
q35063 | auto_undent | train | 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(l... | python | {
"resource": ""
} |
q35064 | create_py3_docs | train | 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 n... | python | {
"resource": ""
} |
q35065 | Py3status._time_up | train | 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() | python | {
"resource": ""
} |
q35066 | HttpResponse.status_code | train | 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 | python | {
"resource": ""
} |
q35067 | HttpResponse.text | train | 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._respon... | python | {
"resource": ""
} |
q35068 | HttpResponse.json | train | 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
... | python | {
"resource": ""
} |
q35069 | HttpResponse.headers | train | def headers(self):
"""
Get the headers from the response.
"""
try:
return self._headers
except AttributeError:
self._headers = self._response.headers
return self._headers | python | {
"resource": ""
} |
q35070 | modules_directory | train | def modules_directory():
"""
Get the core modules directory.
"""
return os.path.join(os.path.dirname(os.path.abspath(__file__)), "modules") | python | {
"resource": ""
} |
q35071 | create_readme | train | 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"
... | python | {
"resource": ""
} |
q35072 | _reformat_docstring | train | 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")
... | python | {
"resource": ""
} |
q35073 | _to_docstring | train | 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)
stat... | python | {
"resource": ""
} |
q35074 | _from_docstring_md | train | 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
... | python | {
"resource": ""
} |
q35075 | _from_docstring_rst | train | 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... | python | {
"resource": ""
} |
q35076 | check_docstrings | train | 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 i... | python | {
"resource": ""
} |
q35077 | update_readme_for_modules | train | 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:
... | python | {
"resource": ""
} |
q35078 | show_modules | train | 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
... | python | {
"resource": ""
} |
q35079 | InjectionContextFactory.new | train | 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, bindin... | python | {
"resource": ""
} |
q35080 | _InjectionContext.get_child | train | 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
... | python | {
"resource": ""
} |
q35081 | ObjectGraph.provide | train | 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... | python | {
"resource": ""
} |
q35082 | _get_type_name | train | 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 insp... | python | {
"resource": ""
} |
q35083 | get_unbound_arg_names | train | 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... | python | {
"resource": ""
} |
q35084 | new | train | 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):
bi... | python | {
"resource": ""
} |
q35085 | get_overall_binding_key_to_binding_maps | train | 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_... | python | {
"resource": ""
} |
q35086 | default_get_arg_names_from_class_name | train | 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., "FooB... | python | {
"resource": ""
} |
q35087 | annotate_arg | train | 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')
def a_function(foo): # ...
is OK, but
@annotate_arg('foo', with_annotation='som... | python | {
"resource": ""
} |
q35088 | inject | train | 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
sep... | python | {
"resource": ""
} |
q35089 | provides | train | 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 spec... | python | {
"resource": ""
} |
q35090 | get_provider_fn_decorations | train | 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 empt... | python | {
"resource": ""
} |
q35091 | new | train | 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.Annotati... | python | {
"resource": ""
} |
q35092 | __setkey | train | 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.... | python | {
"resource": ""
} |
q35093 | Cursor.nextset | train | 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 row... | python | {
"resource": ""
} |
q35094 | Cursor._prepare | train | 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 serv... | python | {
"resource": ""
} |
q35095 | Cursor._execute_prepared_statement | train | 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 _... | python | {
"resource": ""
} |
q35096 | Cursor._close_prepared_statement | train | 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())
... | python | {
"resource": ""
} |
q35097 | VerticaLogging.ensure_dir_exists | train | 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(di... | python | {
"resource": ""
} |
q35098 | getTypeName | train | 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:
... | python | {
"resource": ""
} |
q35099 | getIntervalRange | train | 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: # assu... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.