code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
'''
Use geolocation to get the station ID
'''
extra_opts = '/pws:0' if not self.use_pws else ''
api_url = GEOLOOKUP_URL % (self.api_key,
extra_opts,
self.location_code)
response = self.api_request(api_u... | def get_station_id(self) | Use geolocation to get the station ID | 3.518897 | 3.273939 | 1.07482 |
'''
Query the configured/queried station and return the weather data
'''
if self.station_id is None:
# Failed to get the nearest station ID when first launched, so
# retry it.
self.get_station_id()
self.data['update_error'] = ''
try:
... | def check_weather(self) | Query the configured/queried station and return the weather data | 2.238503 | 2.140733 | 1.045671 |
'''
Figure out the date to use for API requests. Assumes yesterday's date
if between midnight and 10am Eastern time. Override this function in a
subclass to change how the API date is calculated.
'''
# NOTE: If you are writing your own function to get the date, make sure
... | def get_api_date(self) | Figure out the date to use for API requests. Assumes yesterday's date
if between midnight and 10am Eastern time. Override this function in a
subclass to change how the API date is calculated. | 4.141969 | 3.008043 | 1.376965 |
'''
Sometimes the weather data is set under an attribute of the "window"
DOM object. Sometimes it appears as part of a javascript function.
Catch either possibility.
'''
if self.weather_data is not None:
# We've already found weather data, no need to continue ... | def handle_data(self, content) | Sometimes the weather data is set under an attribute of the "window"
DOM object. Sometimes it appears as part of a javascript function.
Catch either possibility. | 3.907178 | 3.197824 | 1.221824 |
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
port = int(getattr(self, 'port', 1738))
sock.bind(('127.0.0.1', port))
while True:
data, addr = sock.recvfrom(512)
color = data.decode().strip()
self.color = self.colors.get(color, color) | def main_loop(self) | Mainloop blocks so we thread it. | 2.71327 | 2.661764 | 1.01935 |
if not self._suspended.is_set():
return True
workload = unwrap_workload(workload)
return hasattr(workload, 'keep_alive') and getattr(workload, 'keep_alive') | def should_execute(self, workload) | If we have been suspended by i3bar, only execute those modules that set the keep_alive flag to a truthy
value. See the docs on the suspend_signal_handler method of the io module for more information. | 6.195977 | 3.498252 | 1.771164 |
import sensors
found_sensors = list()
def get_subfeature_value(feature, subfeature_type):
subfeature = chip.get_subfeature(feature, subfeature_type)
if subfeature:
return chip.get_value(subfeature.number)
for chip in sensors.get_detected_chips():
for feature in... | def get_sensors() | Detect and return a list of Sensor objects | 3.166288 | 3.053921 | 1.036795 |
with open(self.file, "r") as f:
temp = float(f.read().strip()) / 1000
if self.dynamic_color:
perc = int(self.percentage(int(temp), self.alert_temp))
if (perc > 99):
perc = 99
color = self.colors[perc]
else:
col... | def get_output_original(self) | Build the output the original way. Requires no third party libraries. | 3.995537 | 3.825988 | 1.044315 |
data = dict()
found_sensors = get_sensors()
if len(found_sensors) == 0:
raise Exception("No sensors detected! "
"Ensure lm-sensors is installed and check the output of the `sensors` command.")
for sensor in found_sensors:
data[... | def get_output_sensors(self) | Build the output using lm_sensors. Requires sensors Python module (see docs). | 4.768729 | 4.27314 | 1.115978 |
if self.urgent_on not in ('warning', 'critical'):
raise Exception("urgent_on must be one of (warning, critical)")
for sensor in sensors:
if self.urgent_on == 'warning' and sensor.is_warning():
return True
elif self.urgent_on == 'critical' and ... | def get_urgent(self, sensors) | Determine if any sensors should set the urgent flag. | 2.592646 | 2.396363 | 1.081909 |
current_val = sensor.current
if self.pango_enabled:
percentage = self.percentage(sensor.current, sensor.critical)
if self.dynamic_color:
color = self.colors[int(percentage)]
return self.format_pango(color, current_val)
return curre... | def format_sensor(self, sensor) | Format a sensor value. If pango is enabled color is per sensor. | 6.361612 | 4.395571 | 1.447278 |
percentage = self.percentage(sensor.current, sensor.critical)
bar = make_vertical_bar(int(percentage))
if self.pango_enabled:
if self.dynamic_color:
color = self.colors[int(percentage)]
return self.format_pango(color, bar)
return bar | def format_sensor_bar(self, sensor) | Build and format a sensor bar. If pango is enabled bar color is per sensor. | 6.744357 | 4.970742 | 1.356811 |
unread = 0
current_unread = 0
for id, backend in enumerate(self.backends):
temp = backend.unread or 0
unread = unread + temp
if id == self.current_backend:
current_unread = temp
if not unread:
color = self.color
... | def run(self) | Returns the sum of unread messages across all registered backends | 3.846626 | 3.625942 | 1.060862 |
try:
key, value = line.split(":")
self.update_value(key.strip(), value.strip())
except ValueError:
pass | def parse_output(self, line) | Convert output to key value pairs | 3.813903 | 3.23348 | 1.179504 |
if key == "Status":
self._inhibited = value != "Enabled"
elif key == "Color temperature":
self._temperature = int(value.rstrip("K"), 10)
elif key == "Period":
self._period = value
elif key == "Brightness":
self._brightness = value... | def update_value(self, key, value) | Parse key value pairs to update their values | 3.979069 | 4.001741 | 0.994334 |
if self._pid and inhibit != self._inhibited:
os.kill(self._pid, signal.SIGUSR1)
self._inhibited = inhibit | def set_inhibit(self, inhibit) | Set inhibition state | 4.05702 | 4.768843 | 0.850735 |
if self.inhibit:
self._controller.set_inhibit(False)
self.inhibit = False
else:
self._controller.set_inhibit(True)
self.inhibit = True | def toggle_inhibit(self) | Enable/disable redshift | 2.12097 | 2.253587 | 0.941153 |
if not enable_shell and isinstance(command, str):
command = shlex.split(command)
returncode = None
stderr = None
try:
proc = subprocess.Popen(command, stderr=subprocess.PIPE,
stdout=subprocess.PIPE, shell=enable_shell)
out, stderr = proc.com... | def run_through_shell(command, enable_shell=False) | Retrieve output of a command.
Returns a named tuple with three elements:
* ``rc`` (integer) Return code of command.
* ``out`` (string) Everything that was printed to stdout.
* ``err`` (string) Everything that was printed to stderr.
Don't use this function with programs that outputs lots of data si... | 2.234398 | 2.255664 | 0.990572 |
if detach:
if not isinstance(command, str):
msg = "Detached mode expects a string as command, not {}".format(
command)
logging.getLogger("i3pystatus.core.command").error(msg)
raise AttributeError(msg)
command = ["i3-msg", "exec", command]
... | def execute(command, detach=False) | Runs a command in background. No output is retrieved. Useful for running GUI
applications that would block click events.
:param command: A string or a list of strings containing the name and
arguments of the program.
:param detach: If set to `True` the program will be executed using the
`i3-msg` ... | 2.579935 | 2.266894 | 1.138092 |
raw_colors = [c.hex for c in list(Color(start_color).range_to(Color(end_color), quantity))]
colors = []
for color in raw_colors:
# i3bar expects the full Hex value but for some colors the colour
# module only returns partial values. So we need to convert these c... | def get_hex_color_range(start_color, end_color, quantity) | Generates a list of quantity Hex colors from start_color to end_color.
:param start_color: Hex or plain English color for start of range
:param end_color: Hex or plain English color for end of range
:param quantity: Number of colours to return
:return: A list of Hex color values | 4.689645 | 4.766494 | 0.983877 |
index = int(self.percentage(value, upper_limit))
if index >= len(colors):
return colors[-1]
elif index < 0:
return colors[0]
else:
return colors[index] | def get_gradient(self, value, colors, upper_limit=100) | Map a value to a color
:param value: Some value
:return: A Hex color code | 2.729441 | 3.000662 | 0.909613 |
if not callable(method) or not hasattr(method, "__name__"):
return False
if inspect.ismethod(method):
return method.__self__ is object
for cls in inspect.getmro(object.__class__):
if cls.__dict__.get(method.__name__, None) is method:
return True
return False | def is_method_of(method, object) | Decide whether ``method`` is contained within the MRO of ``object``. | 2.084105 | 1.980882 | 1.052109 |
actions = ['leftclick', 'middleclick', 'rightclick',
'upscroll', 'downscroll']
try:
action = actions[button - 1]
except (TypeError, IndexError):
self.__log_button_event(button, None, None, "Other button")
action = "otherclick"
... | def on_click(self, button, **kwargs) | Maps a click event with its associated callback.
Currently implemented events are:
============ ================ =========
Event Callback setting Button ID
============ ================ =========
Left click on_leftclick 1
Middle click on_middleclic... | 4.692181 | 4.181059 | 1.122247 |
def replace(s):
s = s.split("&")
out = s[0]
for i in range(len(s) - 1):
if s[i + 1].startswith("amp;"):
out += "&" + s[i + 1]
else:
out += "&" + s[i + 1]
return out
if "f... | def text_to_pango(self) | Replaces all ampersands in `full_text` and `short_text` attributes of
`self.output` with `&`.
It is called internally when pango markup is used.
Can be called multiple times (`&` won't change to `&amp;`). | 2.2605 | 1.873642 | 1.206474 |
unit = 'bps'
kilo = 1000
mega = 1000000
giga = 1000000000
bps = 0
if self.units == 'bytes' or self.units == 'B':
unit = 'Bps'
kilo = 8000
mega = 8000000
giga = 8000000000
if n < kilo:
bps = flo... | def form_b(self, n: float)->tuple | formats a bps as bps/kbps/mbps/gbps etc
handles whether its meant to be in bytes
:param n: input float
:rtype tuple:
:return: tuple of float-number of mbps etc, str-units | 1.816188 | 1.707698 | 1.06353 |
user_backend = settings_source.get('keyring_backend')
found_settings = dict()
for setting_name in self.__PROTECTED_SETTINGS:
# Nothing to do if the setting is already defined.
if settings_source.get(setting_name):
continue
setting = N... | def get_protected_settings(self, settings_source) | Attempt to retrieve protected settings from keyring if they are not already set. | 3.098937 | 2.923457 | 1.060025 |
# If a custom keyring backend has been defined, use it.
if keyring_backend:
return keyring_backend.get_password(setting_identifier, getpass.getuser())
# Otherwise try and use default keyring.
try:
import keyring
except ImportError:
pa... | def get_setting_from_keyring(self, setting_identifier, keyring_backend=None) | Retrieves a protected setting from keyring
:param setting_identifier: must be in the format package.module.Class.setting | 2.472275 | 2.615744 | 0.945152 |
from i3pystatus.text import Text
if not module:
return
# Merge the module's hints with the default hints
# and overwrite any duplicates with the hint from the module
hints = self.default_hints.copy() if self.default_hints else {}
hints.update(kwargs... | def register(self, module, *args, **kwargs) | Register a new module.
:param module: Either a string module name, or a module class,
or a module instance (in which case args and kwargs are
invalid).
:param kwargs: Settings for the module.
:returns: module instance | 3.944804 | 4.095493 | 0.963206 |
if self.click_events:
self.command_endpoint.start()
for j in io.JSONIO(self.io).read():
for module in self.modules:
module.inject(j) | def run(self) | Run main loop. | 16.34692 | 15.580559 | 1.049187 |
cpus_offline = 0
if self.file == '/sys':
with open('/sys/devices/system/cpu/online') as f:
line = f.readline()
cpus_online = [int(cpu) for cpu in line.split(',') if cpu.find('-') < 0]
cpus_online_range = [cpu_range for cpu_range in lin... | def createvaluesdict(self) | function processes the /proc/cpuinfo file, use file=/sys to use kernel >=4.13 location
:return: dictionary used as the full-text output for the module | 2.020411 | 1.933139 | 1.045145 |
self.url = self.url.format(host=self.host, port=self.port,
api_key=self.api_key) | def init(self) | Initialize the URL used to connect to SABnzbd. | 3.874202 | 3.019638 | 1.283002 |
try:
answer = urlopen(self.url + "&mode=queue").read().decode()
except (HTTPError, URLError) as error:
self.output = {
"full_text": str(error.reason),
"color": "#FF0000"
}
return
answer = json.loads(answer)... | def run(self) | Connect to SABnzbd and get the data. | 2.600592 | 2.45015 | 1.061401 |
if self.is_paused():
urlopen(self.url + "&mode=resume")
else:
urlopen(self.url + "&mode=pause") | def pause_resume(self) | Toggle between pausing or resuming downloading. | 4.211478 | 3.484768 | 1.208539 |
webbrowser.open(
"http://{host}:{port}/".format(host=self.host, port=self.port)) | def open_browser(self) | Open the URL of SABnzbd inside a browser. | 3.841782 | 3.770305 | 1.018958 |
params = ["memory.total", "memory.free", "memory.used",
"temperature.gpu", "fan.speed",
"utilization.gpu", "utilization.memory"]
try:
output = subprocess.check_output(["nvidia-smi",
"--query-gpu={}".format(','.join(params)),
... | def query_nvidia_smi(gpu_number) -> GPUUsageInfo | :return:
all memory fields are in megabytes,
temperature in degrees celsius,
fan speed is integer percent from 0 to 100 inclusive,
usage_gpu and usage_mem are integer percents from 0 to 100 inclusive
(usage_mem != used_mem, usage_mem is about read/write access load)
read ... | 3.45948 | 3.250893 | 1.064163 |
if button in (4, 5):
return super().on_click(button, **kwargs)
else:
activemodule = self.get_active_module()
if not activemodule:
return
return activemodule.on_click(button, **kwargs) | def on_click(self, button, **kwargs) | Capture scrollup and scorlldown to move in groups
Pass everthing else to the module itself | 3.445566 | 2.834815 | 1.215446 |
'''
Get the system timezone for use when no timezone is explicitly provided
Requires pytz, if not available then no timezone will be set when not
explicitly provided.
'''
if not HAS_PYTZ:
return None
def _etc_localtime():
try:
... | def _get_system_tz(self) | Get the system timezone for use when no timezone is explicitly provided
Requires pytz, if not available then no timezone will be set when not
explicitly provided. | 2.484309 | 1.961627 | 1.266453 |
'''
Check the weather using the configured backend
'''
self.output['full_text'] = \
self.refresh_icon + self.output.get('full_text', '')
self.backend.check_weather()
self.refresh_display() | def check_weather(self) | Check the weather using the configured backend | 10.200718 | 6.597403 | 1.546172 |
'''
Disambiguate similarly-named weather conditions, and return the icon
and color that match.
'''
if condition not in self.color_icons:
# Check for similarly-named conditions if no exact match found
condition_lc = condition.lower()
if 'cloudy'... | def get_color_data(self, condition) | Disambiguate similarly-named weather conditions, and return the icon
and color that match. | 2.660882 | 2.157565 | 1.23328 |
timings = {}
with open('/proc/stat', 'r') as file_obj:
for line in file_obj:
if 'cpu' in line:
line = line.strip().split()
timings[line[0]] = [int(x) for x in line[1:]]
return timings | def get_cpu_timings(self) | reads and parses /proc/stat
returns dictionary with all available cores including global average | 2.450121 | 2.269473 | 1.079599 |
diff_total = total - self.prev_total[cpu]
diff_busy = busy - self.prev_busy[cpu]
self.prev_total[cpu] = total
self.prev_busy[cpu] = busy
if diff_total == 0:
return 0
else:
return int(diff_busy / diff_total * 100) | def calculate_usage(self, cpu, total, busy) | calculates usage | 1.995601 | 2.002212 | 0.996699 |
format_string = " "
core_strings = []
for core, usage in usage.items():
if core == 'usage_cpu' and self.exclude_average:
continue
elif core == 'usage':
continue
core = core.replace('usage_', '')
string = se... | def gen_format_all(self, usage) | generates string for format all | 4.676499 | 4.591169 | 1.018586 |
usage = {}
for cpu, timings in self.get_cpu_timings().items():
cpu_total = sum(timings)
del timings[3:5]
cpu_busy = sum(timings)
cpu_usage = self.calculate_usage(cpu, cpu_total, cpu_busy)
usage['usage_' + cpu] = cpu_usage
# ... | def get_usage(self) | parses /proc/stat and calcualtes total and busy time
(more specific USER_HZ see man 5 proc for further informations ) | 4.189617 | 3.528592 | 1.187334 |
now = datetime.datetime.now(tz=pytz.UTC)
try:
now, later = self.get_timerange_formatted(now)
events_result = self.service.events().list(
calendarId='primary',
timeMin=now,
timeMax=later,
maxResults=10,
... | def refresh_events(self) | Retrieve the next N events from Google. | 2.673429 | 2.587193 | 1.033332 |
later = now + datetime.timedelta(days=self.days)
return now.isoformat(), later.isoformat() | def get_timerange_formatted(self, now) | Return two ISO8601 formatted date strings, one for timeMin, the other for timeMax (to be consumed by get_events) | 5.049756 | 3.611017 | 1.39843 |
if string.startswith(prefix):
return string[len(prefix):]
return string | def lchop(string, prefix) | Removes a prefix from string
:param string: String, possibly prefixed with prefix
:param prefix: Prefix to remove from string
:returns: string without the prefix | 2.425826 | 3.89094 | 0.623455 |
while iterable:
item = iterable.pop()
if predicate(item):
yield item
else:
break | def popwhile(predicate, iterable) | Generator function yielding items of iterable while predicate holds for each item
:param predicate: function taking an item returning bool
:param iterable: iterable
:returns: iterable (generator function) | 2.788182 | 4.657202 | 0.598682 |
if places is None:
for key, value in dic.items():
dic[key] = round(value)
else:
for key, value in dic.items():
dic[key] = round(value, places) | def round_dict(dic, places) | Rounds all values in a dict containing only numeric types to `places` decimal places.
If places is None, round to INT. | 1.757688 | 1.66704 | 1.054377 |
l = list(l)
i = 0
while i < len(l):
while isinstance(l[i], list):
if not l[i]:
l.pop(i)
i -= 1
break
else:
l[i:i + 1] = l[i]
i += 1
return l | def flatten(l) | Flattens a hierarchy of nested lists into a single list containing all elements in order
:param l: list of arbitrary types and lists
:returns: list of arbitrary types | 1.841384 | 2.382604 | 0.772845 |
def build_stack(string):
class Token:
string = ""
class OpeningBracket(Token):
pass
class ClosingBracket(Token):
pass
class String(Token):
def __init__(self, str):
self.string = str
TOKENS = {... | def formatp(string, **kwargs) | Function for advanced format strings with partial formatting
This function consumes format strings with groups enclosed in brackets. A
group enclosed in brackets will only become part of the result if all fields
inside the group evaluate True in boolean contexts.
Groups can be nested. The fields in a ... | 2.711257 | 2.662728 | 1.018226 |
def decorator(method):
@functools.wraps(method)
def wrapper(*args, **kwargs):
if predicate():
return method(*args, **kwargs)
return None
return wrapper
return decorator | def require(predicate) | Decorator factory for methods requiring a predicate. If the
predicate is not fulfilled during a method call, the method call
is skipped and None is returned.
:param predicate: A callable returning a truth value
:returns: Method decorator
.. seealso::
:py:class:`internet` | 2.68141 | 2.900826 | 0.924361 |
values = [float(n) for n in values]
mn, mx = min(values), max(values)
mn = mn if lower_limit is None else min(mn, float(lower_limit))
mx = mx if upper_limit is None else max(mx, float(upper_limit))
extent = mx - mn
if style == 'blocks':
bar = '_▁▂▃▄▅▆▇█'
bar_count = len(ba... | def make_graph(values, lower_limit=0.0, upper_limit=100.0, style="blocks") | Draws a graph made of unicode characters.
:param values: An array of values to graph.
:param lower_limit: Minimum value for the y axis (or None for dynamic).
:param upper_limit: Maximum value for the y axis (or None for dynamic).
:param style: Drawing style ('blocks', 'braille-fill', 'braille-peak', or... | 3.306405 | 3.101898 | 1.06593 |
bar = ' _▁▂▃▄▅▆▇█'
percentage //= 10
percentage = int(percentage)
if percentage < 0:
output = bar[0]
elif percentage >= len(bar):
output = bar[-1]
else:
output = bar[percentage]
return output * width | def make_vertical_bar(percentage, width=1) | Draws a vertical bar made of unicode characters.
:param value: A value between 0 and 100
:param width: How many characters wide the bar should be.
:returns: Bar as a String | 3.11636 | 3.617886 | 0.861376 |
bars = [' ', '▏', '▎', '▍', '▌', '▋', '▋', '▊', '▊', '█']
tens = int(percentage / 10)
ones = int(percentage) - tens * 10
result = tens * '█'
if(ones >= 1):
result = result + bars[ones]
result = result + (10 - len(result)) * ' '
return result | def make_bar(percentage) | Draws a bar made of unicode box characters.
:param percentage: A value between 0 and 100
:returns: Bar as a string | 2.920274 | 2.880047 | 1.013968 |
# Handle edge cases first
if lower_bound >= upper_bound:
raise Exception("Invalid upper/lower bounds")
elif number <= lower_bound:
return glyphs[0]
elif number >= upper_bound:
return glyphs[-1]
if enable_boundary_glyphs:
# Trim first and last items from glyphs ... | def make_glyph(number, glyphs="▁▂▃▄▅▆▇█", lower_bound=0, upper_bound=100, enable_boundary_glyphs=False) | Returns a single glyph from the list of glyphs provided relative to where
the number is in the range (by default a percentage value is expected).
This can be used to create an icon based representation of a value with an
arbitrary number of glyphs (e.g. 4 different battery status glyphs for
battery per... | 4.201514 | 4.236536 | 0.991733 |
from urllib.parse import urlparse
scheme = urlparse(url_or_command).scheme
if scheme == 'http' or scheme == 'https':
import webbrowser
import os
# webbrowser.open() sometimes prints a message for some reason and confuses i3
# Redirect stdout briefly to prevent this from ... | def user_open(url_or_command) | Open the specified paramater in the web browser if a URL is detected,
othewrise pass the paramater to the shell as a subprocess. This function
is inteded to bu used in on_leftclick/on_rightclick callbacks.
:param url_or_command: String containing URL or command | 3.008421 | 3.20529 | 0.93858 |
@functools.wraps(function)
def call_wrapper(*args, **kwargs):
stack = inspect.stack()
caller_frame_info = stack[1]
self = caller_frame_info[0].f_locals["self"]
# not completly sure whether this is necessary
# see note in Python docs about stack frames
del sta... | def get_module(function) | Function decorator for retrieving the ``self`` argument from the stack.
Intended for use with callbacks that need access to a modules variables, for example:
.. code:: python
from i3pystatus import Status, get_module
from i3pystatus.core.command import execute
status = Status(...)
... | 4.165334 | 4.118412 | 1.011393 |
for _id in range(2, 25):
setattr(self, TypeKind.from_id(_id).name,
self._handle_fundamental_types) | def init_fundamental_types(self) | Registers all fundamental typekind handlers | 9.771449 | 5.863558 | 1.666471 |
ctypesname = self.get_ctypes_name(typ.kind)
if typ.kind == TypeKind.VOID:
size = align = 1
else:
size = typ.get_size()
align = typ.get_align()
return typedesc.FundamentalType(ctypesname, size, align) | def _handle_fundamental_types(self, typ) | Handles POD types nodes.
see init_fundamental_types for the registration. | 4.739443 | 4.443765 | 1.066538 |
_decl = _cursor_type.get_declaration()
name = self.get_unique_name(_decl)
if self.is_registered(name):
obj = self.get_registered(name)
else:
log.debug('Was in TYPEDEF but had to parse record declaration for %s', name)
obj = self.parse_cursor(_... | def TYPEDEF(self, _cursor_type) | Handles TYPEDEF statement. | 6.171538 | 6.103506 | 1.011146 |
_decl = _cursor_type.get_declaration()
name = self.get_unique_name(_decl)
if self.is_registered(name):
obj = self.get_registered(name)
else:
log.warning('Was in ENUM but had to parse record declaration ')
obj = self.parse_cursor(_decl)
... | def ENUM(self, _cursor_type) | Handles ENUM typedef. | 7.347728 | 7.289503 | 1.007988 |
#
# FIXME catch InvalidDefinitionError and return a void *
#
#
# we shortcut to canonical typedefs and to pointee canonical defs
comment = None
_type = _cursor_type.get_pointee().get_canonical()
_p_type_name = self.get_unique_name(_type)
#... | def POINTER(self, _cursor_type) | Handles POINTER types. | 4.359155 | 4.355593 | 1.000818 |
# The element type has been previously declared
# we need to get the canonical typedef, in some cases
_type = _cursor_type.get_canonical()
size = _type.get_array_size()
if size == -1 and _type.kind == TypeKind.INCOMPLETEARRAY:
size = 0
# FIXME: In... | def _array_handler(self, _cursor_type) | Handles all array types.
Resolves it's element type and makes a Array typedesc. | 5.118005 | 4.968554 | 1.030079 |
# id, returns, attributes
returns = _cursor_type.get_result()
# if self.is_fundamental_type(returns):
returns = self.parse_cursor_type(returns)
attributes = []
obj = typedesc.FunctionType(returns, attributes)
for i, _attr_type in enumerate(_cursor_type.ar... | def FUNCTIONPROTO(self, _cursor_type) | Handles function prototype. | 4.93395 | 4.865825 | 1.014001 |
# id, returns, attributes
returns = _cursor_type.get_result()
# if self.is_fundamental_type(returns):
returns = self.parse_cursor_type(returns)
attributes = []
obj = typedesc.FunctionType(returns, attributes)
# argument_types cant be asked. no arguments.
... | def FUNCTIONNOPROTO(self, _cursor_type) | Handles function with no prototype. | 11.115332 | 10.86456 | 1.023082 |
_decl = _cursor_type.get_declaration()
name = self.get_unique_name(_decl) # _cursor)
if self.is_registered(name):
obj = self.get_registered(name)
else:
obj = self.parse_cursor(_decl)
return obj | def UNEXPOSED(self, _cursor_type) | Handles unexposed types.
Returns the canonical type instead. | 5.574167 | 5.580581 | 0.998851 |
values = [self.parse_cursor(child)
for child in list(cursor.get_children())]
return values | def INIT_LIST_EXPR(self, cursor) | Returns a list of literal values. | 7.559251 | 6.211029 | 1.217069 |
name = cursor.displayname
value = cursor.enum_value
pname = self.get_unique_name(cursor.semantic_parent)
parent = self.get_registered(pname)
obj = typedesc.EnumValue(name, value, parent)
parent.add_value(obj)
return obj | def ENUM_CONSTANT_DECL(self, cursor) | Gets the enumeration values | 5.742336 | 6.121973 | 0.937988 |
name = self.get_unique_name(cursor)
if self.is_registered(name):
return self.get_registered(name)
align = cursor.type.get_align()
size = cursor.type.get_size()
obj = self.register(name, typedesc.Enumeration(name, size, align))
self.set_location(obj, c... | def ENUM_DECL(self, cursor) | Gets the enumeration declaration. | 4.880236 | 4.606656 | 1.059388 |
# FIXME to UT
name = self.get_unique_name(cursor)
if self.is_registered(name):
return self.get_registered(name)
returns = self.parse_cursor_type(cursor.type.get_result())
attributes = []
extern = False
obj = typedesc.Function(name, returns, at... | def FUNCTION_DECL(self, cursor) | Handles function declaration | 3.814564 | 3.772104 | 1.011256 |
# try and get the type. If unexposed, The canonical type will work.
_type = cursor.type
_name = cursor.spelling
if (self.is_array_type(_type) or
self.is_fundamental_type(_type) or
self.is_pointer_type(_type) or
self.is_unexposed_ty... | def PARM_DECL(self, cursor) | Handles parameter declarations. | 4.518559 | 4.527758 | 0.997968 |
name = self.get_unique_name(cursor)
# if the typedef is known, get it from cache
if self.is_registered(name):
return self.get_registered(name)
# use the canonical type directly.
_type = cursor.type.get_canonical()
log.debug("TYPEDEF_DECL: name:%s", na... | def TYPEDEF_DECL(self, cursor) | Handles typedef statements.
Gets Type from cache if we known it. Add it to cache otherwise.
# typedef of an enum | 5.106736 | 4.88504 | 1.045383 |
# get the name
name = self.get_unique_name(cursor)
log.debug('VAR_DECL: name: %s', name)
# Check for a previous declaration in the register
if self.is_registered(name):
return self.get_registered(name)
# get the typedesc object
_type = self._V... | def VAR_DECL(self, cursor) | Handles Variable declaration. | 4.430629 | 4.437717 | 0.998403 |
# Get the type
_ctype = cursor.type.get_canonical()
log.debug('VAR_DECL: _ctype: %s ', _ctype.kind)
# FIXME: Need working int128, long_double, etc.
if self.is_fundamental_type(_ctype):
ctypesname = self.get_ctypes_name(_ctype.kind)
_type = typedes... | def _VAR_DECL_type(self, cursor) | Generates a typedesc object from a Variable declaration. | 4.09681 | 4.08815 | 1.002119 |
# always expect list [(k,v)] as init value.from list(cursor.get_children())
# get the init_value and special cases
init_value = self._get_var_decl_init_value(cursor.type,
list(cursor.get_children()))
_ctype = cursor.type.get_can... | def _VAR_DECL_value(self, cursor, _type) | Handles Variable value initialization. | 6.162146 | 6.012398 | 1.024906 |
# FIXME TU for INIT_LIST_EXPR
# FIXME: always return [(child.kind,child.value),...]
# FIXME: simplify this redondant code.
init_value = []
children = list(children) # weird requirement, list iterator error.
log.debug('_get_var_decl_init_value: children #: %d', ... | def _get_var_decl_init_value(self, _ctype, children) | Gathers initialisation values by parsing children nodes of a VAR_DECL. | 6.565611 | 6.196085 | 1.059639 |
init_value = None
# FIXME: always return (child.kind, child.value)
log.debug(
'_get_var_decl_init_value_single: _ctype: %s Child.kind: %s',
_ctype.kind,
child.kind)
# shorcuts.
if not child.kind.is_expression() and not child.kind.is_de... | def _get_var_decl_init_value_single(self, _ctype, child) | Handling of a single child for initialization value.
Accepted types are expressions and declarations | 4.312562 | 4.273625 | 1.009111 |
values = self._literal_handling(cursor)
retval = ''.join([str(val) for val in values])
return retval | def _operator_handling(self, cursor) | Returns a string with the literal that are part of the operation. | 7.641662 | 5.59537 | 1.365712 |
return self._record_decl(cursor, typedesc.Structure, num) | def STRUCT_DECL(self, cursor, num=None) | Handles Structure declaration.
Its a wrapper to _record_decl. | 14.450234 | 7.380996 | 1.957762 |
return self._record_decl(cursor, typedesc.Union, num) | def UNION_DECL(self, cursor, num=None) | Handles Union declaration.
Its a wrapper to _record_decl. | 16.295851 | 8.082224 | 2.016258 |
log.debug('FIXUP_STRUCT: %s %d bits', s.name, s.size * 8)
if s.members is None:
log.debug('FIXUP_STRUCT: no members')
s.members = []
return
if s.size == 0:
log.debug('FIXUP_STRUCT: struct has size %d', s.size)
return
# ... | def _fixup_record(self, s) | Fixup padding on a record | 5.54805 | 5.474159 | 1.013498 |
name = 'PADDING_%d' % padding_nb
padding_nb += 1
log.debug("_make_padding: for %d bits", length)
if (length % 8) != 0 or (prev_member is not None and prev_member.is_bitfield):
# add a padding to align with the bitfield type
# then multiple bytes if requir... | def _make_padding(
self, members, padding_nb, offset, length, prev_member=None) | Make padding Fields for a specifed size. | 3.305482 | 3.264123 | 1.012671 |
# TODO: optionalize macro parsing. It takes a LOT of time.
# ignore system macro
if (not hasattr(cursor, 'location') or cursor.location is None or
cursor.location.file is None):
return False
name = self.get_unique_name(cursor)
# if name == 'A'... | def MACRO_DEFINITION(self, cursor) | Parse MACRO_DEFINITION, only present if the TranslationUnit is
used with TranslationUnit.PARSE_DETAILED_PROCESSING_RECORD. | 8.44255 | 8.230061 | 1.025819 |
if (hasattr(cursor, 'location') and cursor.location is not None and
cursor.location.file is not None):
obj.location = (cursor.location.file.name, cursor.location.line)
return | def set_location(self, obj, cursor) | Location is also used for codegeneration ordering. | 3.199654 | 2.625462 | 1.218701 |
if isinstance(obj, typedesc.T):
obj.comment = cursor.brief_comment
return | def set_comment(self, obj, cursor) | If a comment is available, add it to the typedesc. | 22.925632 | 10.692947 | 2.143996 |
# FIXME see cindex.SpellingCache
for k, v in [('<', '_'), ('>', '_'), ('::', '__'), (',', ''), (' ', ''),
("$", "DOLLAR"), (".", "DOT"), ("@", "_"), (":", "_"),
('-', '_')]:
if k in name: # template
name = name.replace(k, v)... | def make_python_name(self, name) | Transforms an USR into a valid python name. | 7.508698 | 7.461586 | 1.006314 |
'''Creates a name for unname type'''
parent = cursor.lexical_parent
pname = self.get_unique_name(parent)
log.debug('_make_unknown_name: Got parent get_unique_name %s',pname)
# we only look at types declarations
_cursor_decl = cursor.type.get_declaration()
# we had... | def _make_unknown_name(self, cursor) | Creates a name for unname type | 7.173289 | 6.797233 | 1.055325 |
name = ''
if cursor.kind in [CursorKind.UNEXPOSED_DECL]:
return ''
# covers most cases
name = cursor.spelling
# if its a record decl or field decl and its type is unnamed
if cursor.spelling == '':
# a unnamed object at the root TU
... | def get_unique_name(self, cursor) | get the spelling or create a unique name for a cursor | 3.831498 | 3.668438 | 1.044449 |
''' return the list of fundamental types that are adequate for which
this literal_kind is adequate'''
if literal_kind == CursorKind.INTEGER_LITERAL:
return [TypeKind.USHORT, TypeKind.UINT, TypeKind.ULONG,
TypeKind.ULONGLONG, TypeKind.UINT128,
T... | def get_literal_kind_affinity(self, literal_kind) | return the list of fundamental types that are adequate for which
this literal_kind is adequate | 2.642451 | 2.156956 | 1.225083 |
compilerflags = compilerflags or ["-c"]
# create a hash for the code, and use that as basename for the
# files we have to create
fullcode = "/* compilerflags: %r */\n%s" % (compilerflags, code)
hashval = md5(fullcode).hexdigest()
fnm = os.path.abspath(os.path.join(gen_dir, hashval))
h_... | def include(code, persist=True, compilerflags=None) | This function replaces the *calling module* with a dynamic
module that generates code on demand. The code is generated from
type descriptions that are created by gccxml compiling the C code
'code'.
If <persist> is True, generated code is appended to the module's
source code, otherwise the generate... | 4.114164 | 4.146528 | 0.992195 |
if not os.path.exists(source):
raise ValueError("file '%s' does not exist" % source)
if not os.path.exists(target):
return 1
from stat import ST_MTIME
mtime1 = os.stat(source)[ST_MTIME]
mtime2 = os.stat(target)[ST_MTIME]
return mtime1 > mtime2 | def is_newer(source, target) | Return true if 'source' exists and is more recently modified than
'target', or if 'source' exists and 'target' doesn't. Return false if
both exist and 'target' is the same age or younger than 'source'.
Raise ValueError if 'source' does not exist. | 1.992587 | 2.020712 | 0.986082 |
index = Index.create()
self.tu = index.parse(filename, self.flags, options=self.tu_options)
if not self.tu:
log.warning("unable to load input")
return
if len(self.tu.diagnostics) > 0:
for x in self.tu.diagnostics:
log.warning(x... | def parse(self, filename) | . reads 1 file
. if there is a compilation error, print a warning
. get root cursor and recurse
. for each STRUCT_DECL, register a new struct type
. for each UNION_DECL, register a new union type
. for each TYPEDEF_DECL, register a new alias/typdef to the underlying type
... | 4.289901 | 4.447412 | 0.964584 |
if node is None:
return
if self.__filter_location is not None:
# dont even parse includes.
# FIXME: go back on dependencies ?
if node.location.file is None:
return
elif node.location.file.name not in self.__filter_loca... | def startElement(self, node) | Recurses in children of this node | 7.781415 | 7.530344 | 1.033341 |
if name in self.all:
log.debug('register: %s already existed: %s', name, obj.name)
# code.interact(local=locals())
raise DuplicateDefinitionException(
'register: %s already existed: %s' % (name, obj.name))
log.debug('register: %s ', name)
... | def register(self, name, obj) | Registers an unique type description | 3.385272 | 3.383429 | 1.000545 |
tu = util.get_tu('''
typedef short short_t;
typedef int int_t;
typedef long long_t;
typedef long long longlong_t;
typedef float float_t;
typedef double double_t;
typedef long double longdouble_t;
typedef void* pointer_t;''', flags=_flags)
size = util.get_cursor(tu, 'short_t').type.get_size() * ... | def make_ctypes_convertor(self, _flags) | Fix clang types to ctypes convertion for this parsing isntance.
Some architecture dependent size types ahve to be changed if the target
architecture is not the same as local | 2.09172 | 2.072943 | 1.009058 |
args = list(flags or [])
name = 't.c'
if lang == 'cpp':
name = 't.cpp'
args.append('-std=c++11')
elif lang == 'objc':
name = 't.m'
elif lang != 'c':
raise Exception('Unknown language: %s' % lang)
if all_warnings:
args += ['-Wall', '-Wextra']
ret... | def get_tu(source, lang='c', all_warnings=False, flags=None) | Obtain a translation unit from source and language.
By default, the translation unit is created from source file "t.<ext>"
where <ext> is the default file extension for the specified language. By
default it is C, so "t.c" is the default file name.
Supported languages are {c, cpp, objc}.
all_warni... | 3.142241 | 3.088861 | 1.017282 |
children = []
if isinstance(source, Cursor):
children = source.get_children()
else:
# Assume TU
children = source.cursor.get_children()
for cursor in children:
if cursor.spelling == spelling:
return cursor
# Recurse into children.
result... | def get_cursor(source, spelling) | Obtain a cursor from a source object.
This provides a convenient search mechanism to find a cursor with specific
spelling within a source. The first argument can be either a
TranslationUnit or Cursor instance.
If the cursor is not found, None is returned. | 2.779969 | 2.425363 | 1.146207 |
cursors = []
children = []
if isinstance(source, Cursor):
children = source.get_children()
else:
# Assume TU
children = source.cursor.get_children()
for cursor in children:
if cursor.spelling == spelling:
cursors.append(cursor)
# Recurse int... | def get_cursors(source, spelling) | Obtain all cursors from a source object with a specific spelling.
This provides a convenient search mechanism to find all cursors with specific
spelling within a source. The first argument can be either a
TranslationUnit or Cursor instance.
If no cursors are found, an empty list is returned. | 2.745132 | 2.520334 | 1.089194 |
# 2015-01 reactivating header templates
#log.warning('enable_fundamental_type_wrappers deprecated - replaced by generate_headers')
# return # FIXME ignore
self.enable_fundamental_type_wrappers = lambda: True
import pkgutil
headers = pkgutil.get_data(
... | def enable_fundamental_type_wrappers(self) | If a type is a int128, a long_double_t or a void, some placeholders need
to be in the generated code to be valid. | 8.465102 | 7.738235 | 1.093932 |
# 2015-01 reactivating header templates
#log.warning('enable_pointer_type deprecated - replaced by generate_headers')
# return # FIXME ignore
self.enable_pointer_type = lambda: True
import pkgutil
headers = pkgutil.get_data('ctypeslib', 'data/pointer_type.tpl').d... | def enable_pointer_type(self) | If a type is a pointer, a platform-independent POINTER_T type needs
to be in the generated code. | 6.830453 | 6.498297 | 1.051114 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.