repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 75 19.8k | code_tokens listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1
value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
NetEaseGame/aircv | aircv/__init__.py | imread | def imread(filename):
'''
Like cv2.imread
This function will make sure filename exists
'''
im = cv2.imread(filename)
if im is None:
raise RuntimeError("file: '%s' not exists" % filename)
return im | python | def imread(filename):
'''
Like cv2.imread
This function will make sure filename exists
'''
im = cv2.imread(filename)
if im is None:
raise RuntimeError("file: '%s' not exists" % filename)
return im | [
"def",
"imread",
"(",
"filename",
")",
":",
"im",
"=",
"cv2",
".",
"imread",
"(",
"filename",
")",
"if",
"im",
"is",
"None",
":",
"raise",
"RuntimeError",
"(",
"\"file: '%s' not exists\"",
"%",
"filename",
")",
"return",
"im"
] | Like cv2.imread
This function will make sure filename exists | [
"Like",
"cv2",
".",
"imread",
"This",
"function",
"will",
"make",
"sure",
"filename",
"exists"
] | d479e49ef98347bbbe6ac2e4aa9119cecc15c8ca | https://github.com/NetEaseGame/aircv/blob/d479e49ef98347bbbe6ac2e4aa9119cecc15c8ca/aircv/__init__.py#L80-L88 | train | 203,700 |
NetEaseGame/aircv | aircv/__init__.py | find_all_template | def find_all_template(im_source, im_search, threshold=0.5, maxcnt=0, rgb=False, bgremove=False):
'''
Locate image position with cv2.templateFind
Use pixel match to find pictures.
Args:
im_source(string): 图像、素材
im_search(string): 需要查找的图片
threshold: 阈值,当相识度小于该阈值的时候,就忽略掉
Returns:
A tuple of found [(point, score), ...]
Raises:
IOError: when file read error
'''
# method = cv2.TM_CCORR_NORMED
# method = cv2.TM_SQDIFF_NORMED
method = cv2.TM_CCOEFF_NORMED
if rgb:
s_bgr = cv2.split(im_search) # Blue Green Red
i_bgr = cv2.split(im_source)
weight = (0.3, 0.3, 0.4)
resbgr = [0, 0, 0]
for i in range(3): # bgr
resbgr[i] = cv2.matchTemplate(i_bgr[i], s_bgr[i], method)
res = resbgr[0]*weight[0] + resbgr[1]*weight[1] + resbgr[2]*weight[2]
else:
s_gray = cv2.cvtColor(im_search, cv2.COLOR_BGR2GRAY)
i_gray = cv2.cvtColor(im_source, cv2.COLOR_BGR2GRAY)
# 边界提取(来实现背景去除的功能)
if bgremove:
s_gray = cv2.Canny(s_gray, 100, 200)
i_gray = cv2.Canny(i_gray, 100, 200)
res = cv2.matchTemplate(i_gray, s_gray, method)
w, h = im_search.shape[1], im_search.shape[0]
result = []
while True:
min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res)
if method in [cv2.TM_SQDIFF, cv2.TM_SQDIFF_NORMED]:
top_left = min_loc
else:
top_left = max_loc
if DEBUG:
print('templmatch_value(thresh:%.1f) = %.3f' %(threshold, max_val)) # not show debug
if max_val < threshold:
break
# calculator middle point
middle_point = (top_left[0]+w/2, top_left[1]+h/2)
result.append(dict(
result=middle_point,
rectangle=(top_left, (top_left[0], top_left[1] + h), (top_left[0] + w, top_left[1]), (top_left[0] + w, top_left[1] + h)),
confidence=max_val
))
if maxcnt and len(result) >= maxcnt:
break
# floodfill the already found area
cv2.floodFill(res, None, max_loc, (-1000,), max_val-threshold+0.1, 1, flags=cv2.FLOODFILL_FIXED_RANGE)
return result | python | def find_all_template(im_source, im_search, threshold=0.5, maxcnt=0, rgb=False, bgremove=False):
'''
Locate image position with cv2.templateFind
Use pixel match to find pictures.
Args:
im_source(string): 图像、素材
im_search(string): 需要查找的图片
threshold: 阈值,当相识度小于该阈值的时候,就忽略掉
Returns:
A tuple of found [(point, score), ...]
Raises:
IOError: when file read error
'''
# method = cv2.TM_CCORR_NORMED
# method = cv2.TM_SQDIFF_NORMED
method = cv2.TM_CCOEFF_NORMED
if rgb:
s_bgr = cv2.split(im_search) # Blue Green Red
i_bgr = cv2.split(im_source)
weight = (0.3, 0.3, 0.4)
resbgr = [0, 0, 0]
for i in range(3): # bgr
resbgr[i] = cv2.matchTemplate(i_bgr[i], s_bgr[i], method)
res = resbgr[0]*weight[0] + resbgr[1]*weight[1] + resbgr[2]*weight[2]
else:
s_gray = cv2.cvtColor(im_search, cv2.COLOR_BGR2GRAY)
i_gray = cv2.cvtColor(im_source, cv2.COLOR_BGR2GRAY)
# 边界提取(来实现背景去除的功能)
if bgremove:
s_gray = cv2.Canny(s_gray, 100, 200)
i_gray = cv2.Canny(i_gray, 100, 200)
res = cv2.matchTemplate(i_gray, s_gray, method)
w, h = im_search.shape[1], im_search.shape[0]
result = []
while True:
min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res)
if method in [cv2.TM_SQDIFF, cv2.TM_SQDIFF_NORMED]:
top_left = min_loc
else:
top_left = max_loc
if DEBUG:
print('templmatch_value(thresh:%.1f) = %.3f' %(threshold, max_val)) # not show debug
if max_val < threshold:
break
# calculator middle point
middle_point = (top_left[0]+w/2, top_left[1]+h/2)
result.append(dict(
result=middle_point,
rectangle=(top_left, (top_left[0], top_left[1] + h), (top_left[0] + w, top_left[1]), (top_left[0] + w, top_left[1] + h)),
confidence=max_val
))
if maxcnt and len(result) >= maxcnt:
break
# floodfill the already found area
cv2.floodFill(res, None, max_loc, (-1000,), max_val-threshold+0.1, 1, flags=cv2.FLOODFILL_FIXED_RANGE)
return result | [
"def",
"find_all_template",
"(",
"im_source",
",",
"im_search",
",",
"threshold",
"=",
"0.5",
",",
"maxcnt",
"=",
"0",
",",
"rgb",
"=",
"False",
",",
"bgremove",
"=",
"False",
")",
":",
"# method = cv2.TM_CCORR_NORMED",
"# method = cv2.TM_SQDIFF_NORMED",
"method",... | Locate image position with cv2.templateFind
Use pixel match to find pictures.
Args:
im_source(string): 图像、素材
im_search(string): 需要查找的图片
threshold: 阈值,当相识度小于该阈值的时候,就忽略掉
Returns:
A tuple of found [(point, score), ...]
Raises:
IOError: when file read error | [
"Locate",
"image",
"position",
"with",
"cv2",
".",
"templateFind"
] | d479e49ef98347bbbe6ac2e4aa9119cecc15c8ca | https://github.com/NetEaseGame/aircv/blob/d479e49ef98347bbbe6ac2e4aa9119cecc15c8ca/aircv/__init__.py#L98-L160 | train | 203,701 |
NetEaseGame/aircv | aircv/__init__.py | find | def find(im_source, im_search):
'''
Only find maximum one object
'''
r = find_all(im_source, im_search, maxcnt=1)
return r[0] if r else None | python | def find(im_source, im_search):
'''
Only find maximum one object
'''
r = find_all(im_source, im_search, maxcnt=1)
return r[0] if r else None | [
"def",
"find",
"(",
"im_source",
",",
"im_search",
")",
":",
"r",
"=",
"find_all",
"(",
"im_source",
",",
"im_search",
",",
"maxcnt",
"=",
"1",
")",
"return",
"r",
"[",
"0",
"]",
"if",
"r",
"else",
"None"
] | Only find maximum one object | [
"Only",
"find",
"maximum",
"one",
"object"
] | d479e49ef98347bbbe6ac2e4aa9119cecc15c8ca | https://github.com/NetEaseGame/aircv/blob/d479e49ef98347bbbe6ac2e4aa9119cecc15c8ca/aircv/__init__.py#L285-L290 | train | 203,702 |
enkore/i3pystatus | i3pystatus/pulseaudio/__init__.py | PulseAudio.init | def init(self):
"""Creates context, when context is ready context_notify_cb is called"""
# Wrap callback methods in appropriate ctypefunc instances so
# that the Pulseaudio C API can call them
self._context_notify_cb = pa_context_notify_cb_t(
self.context_notify_cb)
self._sink_info_cb = pa_sink_info_cb_t(self.sink_info_cb)
self._update_cb = pa_context_subscribe_cb_t(self.update_cb)
self._success_cb = pa_context_success_cb_t(self.success_cb)
self._server_info_cb = pa_server_info_cb_t(self.server_info_cb)
# Create the mainloop thread and set our context_notify_cb
# method to be called when there's updates relating to the
# connection to Pulseaudio
_mainloop = pa_threaded_mainloop_new()
_mainloop_api = pa_threaded_mainloop_get_api(_mainloop)
context = pa_context_new(_mainloop_api, "i3pystatus_pulseaudio".encode("ascii"))
pa_context_set_state_callback(context, self._context_notify_cb, None)
pa_context_connect(context, None, 0, None)
pa_threaded_mainloop_start(_mainloop)
self.colors = self.get_hex_color_range(self.color_muted, self.color_unmuted, 100)
self.sinks = [] | python | def init(self):
"""Creates context, when context is ready context_notify_cb is called"""
# Wrap callback methods in appropriate ctypefunc instances so
# that the Pulseaudio C API can call them
self._context_notify_cb = pa_context_notify_cb_t(
self.context_notify_cb)
self._sink_info_cb = pa_sink_info_cb_t(self.sink_info_cb)
self._update_cb = pa_context_subscribe_cb_t(self.update_cb)
self._success_cb = pa_context_success_cb_t(self.success_cb)
self._server_info_cb = pa_server_info_cb_t(self.server_info_cb)
# Create the mainloop thread and set our context_notify_cb
# method to be called when there's updates relating to the
# connection to Pulseaudio
_mainloop = pa_threaded_mainloop_new()
_mainloop_api = pa_threaded_mainloop_get_api(_mainloop)
context = pa_context_new(_mainloop_api, "i3pystatus_pulseaudio".encode("ascii"))
pa_context_set_state_callback(context, self._context_notify_cb, None)
pa_context_connect(context, None, 0, None)
pa_threaded_mainloop_start(_mainloop)
self.colors = self.get_hex_color_range(self.color_muted, self.color_unmuted, 100)
self.sinks = [] | [
"def",
"init",
"(",
"self",
")",
":",
"# Wrap callback methods in appropriate ctypefunc instances so",
"# that the Pulseaudio C API can call them",
"self",
".",
"_context_notify_cb",
"=",
"pa_context_notify_cb_t",
"(",
"self",
".",
"context_notify_cb",
")",
"self",
".",
"_sin... | Creates context, when context is ready context_notify_cb is called | [
"Creates",
"context",
"when",
"context",
"is",
"ready",
"context_notify_cb",
"is",
"called"
] | 14cfde967cecf79b40e223e35a04600f4c875af7 | https://github.com/enkore/i3pystatus/blob/14cfde967cecf79b40e223e35a04600f4c875af7/i3pystatus/pulseaudio/__init__.py#L67-L90 | train | 203,703 |
enkore/i3pystatus | i3pystatus/pulseaudio/__init__.py | PulseAudio.server_info_cb | def server_info_cb(self, context, server_info_p, userdata):
"""Retrieves the default sink and calls request_update"""
server_info = server_info_p.contents
self.request_update(context) | python | def server_info_cb(self, context, server_info_p, userdata):
"""Retrieves the default sink and calls request_update"""
server_info = server_info_p.contents
self.request_update(context) | [
"def",
"server_info_cb",
"(",
"self",
",",
"context",
",",
"server_info_p",
",",
"userdata",
")",
":",
"server_info",
"=",
"server_info_p",
".",
"contents",
"self",
".",
"request_update",
"(",
"context",
")"
] | Retrieves the default sink and calls request_update | [
"Retrieves",
"the",
"default",
"sink",
"and",
"calls",
"request_update"
] | 14cfde967cecf79b40e223e35a04600f4c875af7 | https://github.com/enkore/i3pystatus/blob/14cfde967cecf79b40e223e35a04600f4c875af7/i3pystatus/pulseaudio/__init__.py#L119-L122 | train | 203,704 |
enkore/i3pystatus | i3pystatus/pulseaudio/__init__.py | PulseAudio.context_notify_cb | def context_notify_cb(self, context, _):
"""Checks wether the context is ready
-Queries server information (server_info_cb is called)
-Subscribes to property changes on all sinks (update_cb is called)
"""
state = pa_context_get_state(context)
if state == PA_CONTEXT_READY:
pa_operation_unref(
pa_context_get_server_info(context, self._server_info_cb, None))
pa_context_set_subscribe_callback(context, self._update_cb, None)
pa_operation_unref(pa_context_subscribe(
context, PA_SUBSCRIPTION_EVENT_CHANGE | PA_SUBSCRIPTION_MASK_SINK | PA_SUBSCRIPTION_MASK_SERVER, self._success_cb, None)) | python | def context_notify_cb(self, context, _):
"""Checks wether the context is ready
-Queries server information (server_info_cb is called)
-Subscribes to property changes on all sinks (update_cb is called)
"""
state = pa_context_get_state(context)
if state == PA_CONTEXT_READY:
pa_operation_unref(
pa_context_get_server_info(context, self._server_info_cb, None))
pa_context_set_subscribe_callback(context, self._update_cb, None)
pa_operation_unref(pa_context_subscribe(
context, PA_SUBSCRIPTION_EVENT_CHANGE | PA_SUBSCRIPTION_MASK_SINK | PA_SUBSCRIPTION_MASK_SERVER, self._success_cb, None)) | [
"def",
"context_notify_cb",
"(",
"self",
",",
"context",
",",
"_",
")",
":",
"state",
"=",
"pa_context_get_state",
"(",
"context",
")",
"if",
"state",
"==",
"PA_CONTEXT_READY",
":",
"pa_operation_unref",
"(",
"pa_context_get_server_info",
"(",
"context",
",",
"s... | Checks wether the context is ready
-Queries server information (server_info_cb is called)
-Subscribes to property changes on all sinks (update_cb is called) | [
"Checks",
"wether",
"the",
"context",
"is",
"ready"
] | 14cfde967cecf79b40e223e35a04600f4c875af7 | https://github.com/enkore/i3pystatus/blob/14cfde967cecf79b40e223e35a04600f4c875af7/i3pystatus/pulseaudio/__init__.py#L124-L139 | train | 203,705 |
enkore/i3pystatus | i3pystatus/pulseaudio/__init__.py | PulseAudio.update_cb | def update_cb(self, context, t, idx, userdata):
"""A sink property changed, calls request_update"""
if t & PA_SUBSCRIPTION_EVENT_FACILITY_MASK == PA_SUBSCRIPTION_EVENT_SERVER:
pa_operation_unref(
pa_context_get_server_info(context, self._server_info_cb, None))
self.request_update(context) | python | def update_cb(self, context, t, idx, userdata):
"""A sink property changed, calls request_update"""
if t & PA_SUBSCRIPTION_EVENT_FACILITY_MASK == PA_SUBSCRIPTION_EVENT_SERVER:
pa_operation_unref(
pa_context_get_server_info(context, self._server_info_cb, None))
self.request_update(context) | [
"def",
"update_cb",
"(",
"self",
",",
"context",
",",
"t",
",",
"idx",
",",
"userdata",
")",
":",
"if",
"t",
"&",
"PA_SUBSCRIPTION_EVENT_FACILITY_MASK",
"==",
"PA_SUBSCRIPTION_EVENT_SERVER",
":",
"pa_operation_unref",
"(",
"pa_context_get_server_info",
"(",
"context... | A sink property changed, calls request_update | [
"A",
"sink",
"property",
"changed",
"calls",
"request_update"
] | 14cfde967cecf79b40e223e35a04600f4c875af7 | https://github.com/enkore/i3pystatus/blob/14cfde967cecf79b40e223e35a04600f4c875af7/i3pystatus/pulseaudio/__init__.py#L141-L148 | train | 203,706 |
enkore/i3pystatus | i3pystatus/pulseaudio/__init__.py | PulseAudio.sink_info_cb | def sink_info_cb(self, context, sink_info_p, _, __):
"""Updates self.output"""
if sink_info_p:
sink_info = sink_info_p.contents
volume_percent = round(100 * sink_info.volume.values[0] / 0x10000)
volume_db = pa_sw_volume_to_dB(sink_info.volume.values[0])
self.currently_muted = sink_info.mute
if volume_db == float('-Infinity'):
volume_db = "-∞"
else:
volume_db = int(volume_db)
muted = self.muted if sink_info.mute else self.unmuted
if self.multi_colors and not sink_info.mute:
color = self.get_gradient(volume_percent, self.colors)
else:
color = self.color_muted if sink_info.mute else self.color_unmuted
if muted and self.format_muted is not None:
output_format = self.format_muted
else:
output_format = self.format
if self.bar_type == 'vertical':
volume_bar = make_vertical_bar(volume_percent, self.vertical_bar_width)
elif self.bar_type == 'horizontal':
volume_bar = make_bar(volume_percent)
else:
raise Exception("bar_type must be 'vertical' or 'horizontal'")
selected = ""
dump = subprocess.check_output("pacmd dump".split(), universal_newlines=True)
for line in dump.split("\n"):
if line.startswith("set-default-sink"):
default_sink = line.split()[1]
if default_sink == self.current_sink:
selected = self.format_selected
self.output = {
"color": color,
"full_text": output_format.format(
muted=muted,
volume=volume_percent,
db=volume_db,
volume_bar=volume_bar,
selected=selected),
}
self.send_output() | python | def sink_info_cb(self, context, sink_info_p, _, __):
"""Updates self.output"""
if sink_info_p:
sink_info = sink_info_p.contents
volume_percent = round(100 * sink_info.volume.values[0] / 0x10000)
volume_db = pa_sw_volume_to_dB(sink_info.volume.values[0])
self.currently_muted = sink_info.mute
if volume_db == float('-Infinity'):
volume_db = "-∞"
else:
volume_db = int(volume_db)
muted = self.muted if sink_info.mute else self.unmuted
if self.multi_colors and not sink_info.mute:
color = self.get_gradient(volume_percent, self.colors)
else:
color = self.color_muted if sink_info.mute else self.color_unmuted
if muted and self.format_muted is not None:
output_format = self.format_muted
else:
output_format = self.format
if self.bar_type == 'vertical':
volume_bar = make_vertical_bar(volume_percent, self.vertical_bar_width)
elif self.bar_type == 'horizontal':
volume_bar = make_bar(volume_percent)
else:
raise Exception("bar_type must be 'vertical' or 'horizontal'")
selected = ""
dump = subprocess.check_output("pacmd dump".split(), universal_newlines=True)
for line in dump.split("\n"):
if line.startswith("set-default-sink"):
default_sink = line.split()[1]
if default_sink == self.current_sink:
selected = self.format_selected
self.output = {
"color": color,
"full_text": output_format.format(
muted=muted,
volume=volume_percent,
db=volume_db,
volume_bar=volume_bar,
selected=selected),
}
self.send_output() | [
"def",
"sink_info_cb",
"(",
"self",
",",
"context",
",",
"sink_info_p",
",",
"_",
",",
"__",
")",
":",
"if",
"sink_info_p",
":",
"sink_info",
"=",
"sink_info_p",
".",
"contents",
"volume_percent",
"=",
"round",
"(",
"100",
"*",
"sink_info",
".",
"volume",
... | Updates self.output | [
"Updates",
"self",
".",
"output"
] | 14cfde967cecf79b40e223e35a04600f4c875af7 | https://github.com/enkore/i3pystatus/blob/14cfde967cecf79b40e223e35a04600f4c875af7/i3pystatus/pulseaudio/__init__.py#L150-L200 | train | 203,707 |
enkore/i3pystatus | i3pystatus/network.py | Network.cycle_interface | def cycle_interface(self, increment=1):
"""Cycle through available interfaces in `increment` steps. Sign indicates direction."""
interfaces = [i for i in netifaces.interfaces() if i not in self.ignore_interfaces]
if self.interface in interfaces:
next_index = (interfaces.index(self.interface) + increment) % len(interfaces)
self.interface = interfaces[next_index]
elif len(interfaces) > 0:
self.interface = interfaces[0]
if self.network_traffic:
self.network_traffic.clear_counters()
self.kbs_arr = [0.0] * self.graph_width | python | def cycle_interface(self, increment=1):
"""Cycle through available interfaces in `increment` steps. Sign indicates direction."""
interfaces = [i for i in netifaces.interfaces() if i not in self.ignore_interfaces]
if self.interface in interfaces:
next_index = (interfaces.index(self.interface) + increment) % len(interfaces)
self.interface = interfaces[next_index]
elif len(interfaces) > 0:
self.interface = interfaces[0]
if self.network_traffic:
self.network_traffic.clear_counters()
self.kbs_arr = [0.0] * self.graph_width | [
"def",
"cycle_interface",
"(",
"self",
",",
"increment",
"=",
"1",
")",
":",
"interfaces",
"=",
"[",
"i",
"for",
"i",
"in",
"netifaces",
".",
"interfaces",
"(",
")",
"if",
"i",
"not",
"in",
"self",
".",
"ignore_interfaces",
"]",
"if",
"self",
".",
"i... | Cycle through available interfaces in `increment` steps. Sign indicates direction. | [
"Cycle",
"through",
"available",
"interfaces",
"in",
"increment",
"steps",
".",
"Sign",
"indicates",
"direction",
"."
] | 14cfde967cecf79b40e223e35a04600f4c875af7 | https://github.com/enkore/i3pystatus/blob/14cfde967cecf79b40e223e35a04600f4c875af7/i3pystatus/network.py#L394-L405 | train | 203,708 |
enkore/i3pystatus | i3pystatus/timer.py | Timer.start | def start(self, seconds=300):
"""
Starts timer.
If timer is already running it will increase remaining time instead.
:param int seconds: Initial time.
"""
if self.state is TimerState.stopped:
self.compare = time.time() + abs(seconds)
self.state = TimerState.running
elif self.state is TimerState.running:
self.increase(seconds) | python | def start(self, seconds=300):
"""
Starts timer.
If timer is already running it will increase remaining time instead.
:param int seconds: Initial time.
"""
if self.state is TimerState.stopped:
self.compare = time.time() + abs(seconds)
self.state = TimerState.running
elif self.state is TimerState.running:
self.increase(seconds) | [
"def",
"start",
"(",
"self",
",",
"seconds",
"=",
"300",
")",
":",
"if",
"self",
".",
"state",
"is",
"TimerState",
".",
"stopped",
":",
"self",
".",
"compare",
"=",
"time",
".",
"time",
"(",
")",
"+",
"abs",
"(",
"seconds",
")",
"self",
".",
"sta... | Starts timer.
If timer is already running it will increase remaining time instead.
:param int seconds: Initial time. | [
"Starts",
"timer",
".",
"If",
"timer",
"is",
"already",
"running",
"it",
"will",
"increase",
"remaining",
"time",
"instead",
"."
] | 14cfde967cecf79b40e223e35a04600f4c875af7 | https://github.com/enkore/i3pystatus/blob/14cfde967cecf79b40e223e35a04600f4c875af7/i3pystatus/timer.py#L147-L158 | train | 203,709 |
enkore/i3pystatus | i3pystatus/timer.py | Timer.increase | def increase(self, seconds):
"""
Change remainig time value.
:param int seconds: Seconds to add. Negative value substracts from
remaining time.
"""
if self.state is TimerState.running:
new_compare = self.compare + seconds
if new_compare > time.time():
self.compare = new_compare | python | def increase(self, seconds):
"""
Change remainig time value.
:param int seconds: Seconds to add. Negative value substracts from
remaining time.
"""
if self.state is TimerState.running:
new_compare = self.compare + seconds
if new_compare > time.time():
self.compare = new_compare | [
"def",
"increase",
"(",
"self",
",",
"seconds",
")",
":",
"if",
"self",
".",
"state",
"is",
"TimerState",
".",
"running",
":",
"new_compare",
"=",
"self",
".",
"compare",
"+",
"seconds",
"if",
"new_compare",
">",
"time",
".",
"time",
"(",
")",
":",
"... | Change remainig time value.
:param int seconds: Seconds to add. Negative value substracts from
remaining time. | [
"Change",
"remainig",
"time",
"value",
"."
] | 14cfde967cecf79b40e223e35a04600f4c875af7 | https://github.com/enkore/i3pystatus/blob/14cfde967cecf79b40e223e35a04600f4c875af7/i3pystatus/timer.py#L160-L170 | train | 203,710 |
enkore/i3pystatus | i3pystatus/timer.py | Timer.reset | def reset(self):
"""
Stop timer and execute ``on_reset`` if overflow occured.
"""
if self.state is not TimerState.stopped:
if self.on_reset and self.state is TimerState.overflow:
if callable(self.on_reset):
self.on_reset()
else:
execute(self.on_reset)
self.state = TimerState.stopped | python | def reset(self):
"""
Stop timer and execute ``on_reset`` if overflow occured.
"""
if self.state is not TimerState.stopped:
if self.on_reset and self.state is TimerState.overflow:
if callable(self.on_reset):
self.on_reset()
else:
execute(self.on_reset)
self.state = TimerState.stopped | [
"def",
"reset",
"(",
"self",
")",
":",
"if",
"self",
".",
"state",
"is",
"not",
"TimerState",
".",
"stopped",
":",
"if",
"self",
".",
"on_reset",
"and",
"self",
".",
"state",
"is",
"TimerState",
".",
"overflow",
":",
"if",
"callable",
"(",
"self",
".... | Stop timer and execute ``on_reset`` if overflow occured. | [
"Stop",
"timer",
"and",
"execute",
"on_reset",
"if",
"overflow",
"occured",
"."
] | 14cfde967cecf79b40e223e35a04600f4c875af7 | https://github.com/enkore/i3pystatus/blob/14cfde967cecf79b40e223e35a04600f4c875af7/i3pystatus/timer.py#L172-L182 | train | 203,711 |
enkore/i3pystatus | i3pystatus/core/io.py | IOHandler.write_line | def write_line(self, message):
"""Unbuffered printing to stdout."""
self.out.write(message + "\n")
self.out.flush() | python | def write_line(self, message):
"""Unbuffered printing to stdout."""
self.out.write(message + "\n")
self.out.flush() | [
"def",
"write_line",
"(",
"self",
",",
"message",
")",
":",
"self",
".",
"out",
".",
"write",
"(",
"message",
"+",
"\"\\n\"",
")",
"self",
".",
"out",
".",
"flush",
"(",
")"
] | Unbuffered printing to stdout. | [
"Unbuffered",
"printing",
"to",
"stdout",
"."
] | 14cfde967cecf79b40e223e35a04600f4c875af7 | https://github.com/enkore/i3pystatus/blob/14cfde967cecf79b40e223e35a04600f4c875af7/i3pystatus/core/io.py#L16-L20 | train | 203,712 |
enkore/i3pystatus | i3pystatus/core/io.py | IOHandler.read_line | def read_line(self):
"""
Interrupted respecting reader for stdin.
Raises EOFError if the end of stream has been reached
"""
try:
line = self.inp.readline().strip()
except KeyboardInterrupt:
raise EOFError()
# i3status sends EOF, or an empty line
if not line:
raise EOFError()
return line | python | def read_line(self):
"""
Interrupted respecting reader for stdin.
Raises EOFError if the end of stream has been reached
"""
try:
line = self.inp.readline().strip()
except KeyboardInterrupt:
raise EOFError()
# i3status sends EOF, or an empty line
if not line:
raise EOFError()
return line | [
"def",
"read_line",
"(",
"self",
")",
":",
"try",
":",
"line",
"=",
"self",
".",
"inp",
".",
"readline",
"(",
")",
".",
"strip",
"(",
")",
"except",
"KeyboardInterrupt",
":",
"raise",
"EOFError",
"(",
")",
"# i3status sends EOF, or an empty line",
"if",
"n... | Interrupted respecting reader for stdin.
Raises EOFError if the end of stream has been reached | [
"Interrupted",
"respecting",
"reader",
"for",
"stdin",
"."
] | 14cfde967cecf79b40e223e35a04600f4c875af7 | https://github.com/enkore/i3pystatus/blob/14cfde967cecf79b40e223e35a04600f4c875af7/i3pystatus/core/io.py#L31-L46 | train | 203,713 |
enkore/i3pystatus | i3pystatus/core/io.py | StandaloneIO.compute_treshold_interval | def compute_treshold_interval(self):
"""
Current method is to compute average from all intervals.
"""
intervals = [m.interval for m in self.modules if hasattr(m, "interval")]
if len(intervals) > 0:
self.treshold_interval = round(sum(intervals) / len(intervals)) | python | def compute_treshold_interval(self):
"""
Current method is to compute average from all intervals.
"""
intervals = [m.interval for m in self.modules if hasattr(m, "interval")]
if len(intervals) > 0:
self.treshold_interval = round(sum(intervals) / len(intervals)) | [
"def",
"compute_treshold_interval",
"(",
"self",
")",
":",
"intervals",
"=",
"[",
"m",
".",
"interval",
"for",
"m",
"in",
"self",
".",
"modules",
"if",
"hasattr",
"(",
"m",
",",
"\"interval\"",
")",
"]",
"if",
"len",
"(",
"intervals",
")",
">",
"0",
... | Current method is to compute average from all intervals. | [
"Current",
"method",
"is",
"to",
"compute",
"average",
"from",
"all",
"intervals",
"."
] | 14cfde967cecf79b40e223e35a04600f4c875af7 | https://github.com/enkore/i3pystatus/blob/14cfde967cecf79b40e223e35a04600f4c875af7/i3pystatus/core/io.py#L108-L115 | train | 203,714 |
enkore/i3pystatus | i3pystatus/core/io.py | StandaloneIO.refresh_signal_handler | def refresh_signal_handler(self, signo, frame):
"""
This callback is called when SIGUSR1 signal is received.
It updates outputs of all modules by calling their `run` method.
Interval modules are updated in separate threads if their interval is
above a certain treshold value.
This treshold is computed by :func:`compute_treshold_interval` class
method.
The reasoning is that modules with larger intervals also usually take
longer to refresh their output and that their output is not required in
'real time'.
This also prevents possible lag when updating all modules in a row.
"""
if signo != signal.SIGUSR1:
return
for module in self.modules:
if hasattr(module, "interval"):
if module.interval > self.treshold_interval:
thread = Thread(target=module.run)
thread.start()
else:
module.run()
else:
module.run()
self.async_refresh() | python | def refresh_signal_handler(self, signo, frame):
"""
This callback is called when SIGUSR1 signal is received.
It updates outputs of all modules by calling their `run` method.
Interval modules are updated in separate threads if their interval is
above a certain treshold value.
This treshold is computed by :func:`compute_treshold_interval` class
method.
The reasoning is that modules with larger intervals also usually take
longer to refresh their output and that their output is not required in
'real time'.
This also prevents possible lag when updating all modules in a row.
"""
if signo != signal.SIGUSR1:
return
for module in self.modules:
if hasattr(module, "interval"):
if module.interval > self.treshold_interval:
thread = Thread(target=module.run)
thread.start()
else:
module.run()
else:
module.run()
self.async_refresh() | [
"def",
"refresh_signal_handler",
"(",
"self",
",",
"signo",
",",
"frame",
")",
":",
"if",
"signo",
"!=",
"signal",
".",
"SIGUSR1",
":",
"return",
"for",
"module",
"in",
"self",
".",
"modules",
":",
"if",
"hasattr",
"(",
"module",
",",
"\"interval\"",
")"... | This callback is called when SIGUSR1 signal is received.
It updates outputs of all modules by calling their `run` method.
Interval modules are updated in separate threads if their interval is
above a certain treshold value.
This treshold is computed by :func:`compute_treshold_interval` class
method.
The reasoning is that modules with larger intervals also usually take
longer to refresh their output and that their output is not required in
'real time'.
This also prevents possible lag when updating all modules in a row. | [
"This",
"callback",
"is",
"called",
"when",
"SIGUSR1",
"signal",
"is",
"received",
"."
] | 14cfde967cecf79b40e223e35a04600f4c875af7 | https://github.com/enkore/i3pystatus/blob/14cfde967cecf79b40e223e35a04600f4c875af7/i3pystatus/core/io.py#L127-L156 | train | 203,715 |
enkore/i3pystatus | i3pystatus/core/io.py | JSONIO.parse_line | def parse_line(self, line):
"""Parse a single line of JSON and write modified JSON back."""
prefix = ""
# ignore comma at start of lines
if line.startswith(","):
line, prefix = line[1:], ","
j = json.loads(line)
yield j
self.io.write_line(prefix + json.dumps(j)) | python | def parse_line(self, line):
"""Parse a single line of JSON and write modified JSON back."""
prefix = ""
# ignore comma at start of lines
if line.startswith(","):
line, prefix = line[1:], ","
j = json.loads(line)
yield j
self.io.write_line(prefix + json.dumps(j)) | [
"def",
"parse_line",
"(",
"self",
",",
"line",
")",
":",
"prefix",
"=",
"\"\"",
"# ignore comma at start of lines",
"if",
"line",
".",
"startswith",
"(",
"\",\"",
")",
":",
"line",
",",
"prefix",
"=",
"line",
"[",
"1",
":",
"]",
",",
"\",\"",
"j",
"=",... | Parse a single line of JSON and write modified JSON back. | [
"Parse",
"a",
"single",
"line",
"of",
"JSON",
"and",
"write",
"modified",
"JSON",
"back",
"."
] | 14cfde967cecf79b40e223e35a04600f4c875af7 | https://github.com/enkore/i3pystatus/blob/14cfde967cecf79b40e223e35a04600f4c875af7/i3pystatus/core/io.py#L193-L203 | train | 203,716 |
enkore/i3pystatus | i3pystatus/calendar/__init__.py | CalendarBackend.on_click | def on_click(self, event):
""" Override this method to do more interesting things with the event. """
DesktopNotification(
title=event.title,
body="{} until {}!".format(event.time_remaining, event.title),
icon='dialog-information',
urgency=1,
timeout=0,
).display() | python | def on_click(self, event):
""" Override this method to do more interesting things with the event. """
DesktopNotification(
title=event.title,
body="{} until {}!".format(event.time_remaining, event.title),
icon='dialog-information',
urgency=1,
timeout=0,
).display() | [
"def",
"on_click",
"(",
"self",
",",
"event",
")",
":",
"DesktopNotification",
"(",
"title",
"=",
"event",
".",
"title",
",",
"body",
"=",
"\"{} until {}!\"",
".",
"format",
"(",
"event",
".",
"time_remaining",
",",
"event",
".",
"title",
")",
",",
"icon... | Override this method to do more interesting things with the event. | [
"Override",
"this",
"method",
"to",
"do",
"more",
"interesting",
"things",
"with",
"the",
"event",
"."
] | 14cfde967cecf79b40e223e35a04600f4c875af7 | https://github.com/enkore/i3pystatus/blob/14cfde967cecf79b40e223e35a04600f4c875af7/i3pystatus/calendar/__init__.py#L103-L111 | train | 203,717 |
enkore/i3pystatus | i3pystatus/calendar/__init__.py | Calendar.is_urgent | def is_urgent(self):
"""
Determine whether or not to set the urgent flag. If urgent_blink is set, toggles urgent flag
on and off every second.
"""
if not self.current_event:
return False
now = datetime.now(tz=self.current_event.start.tzinfo)
alert_time = now + timedelta(seconds=self.urgent_seconds)
urgent = alert_time > self.current_event.start
if urgent and self.urgent_blink:
urgent = now.second % 2 == 0 and not self.urgent_acknowledged
return urgent | python | def is_urgent(self):
"""
Determine whether or not to set the urgent flag. If urgent_blink is set, toggles urgent flag
on and off every second.
"""
if not self.current_event:
return False
now = datetime.now(tz=self.current_event.start.tzinfo)
alert_time = now + timedelta(seconds=self.urgent_seconds)
urgent = alert_time > self.current_event.start
if urgent and self.urgent_blink:
urgent = now.second % 2 == 0 and not self.urgent_acknowledged
return urgent | [
"def",
"is_urgent",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"current_event",
":",
"return",
"False",
"now",
"=",
"datetime",
".",
"now",
"(",
"tz",
"=",
"self",
".",
"current_event",
".",
"start",
".",
"tzinfo",
")",
"alert_time",
"=",
"now",
... | Determine whether or not to set the urgent flag. If urgent_blink is set, toggles urgent flag
on and off every second. | [
"Determine",
"whether",
"or",
"not",
"to",
"set",
"the",
"urgent",
"flag",
".",
"If",
"urgent_blink",
"is",
"set",
"toggles",
"urgent",
"flag",
"on",
"and",
"off",
"every",
"second",
"."
] | 14cfde967cecf79b40e223e35a04600f4c875af7 | https://github.com/enkore/i3pystatus/blob/14cfde967cecf79b40e223e35a04600f4c875af7/i3pystatus/calendar/__init__.py#L234-L246 | train | 203,718 |
enkore/i3pystatus | i3pystatus/weather/wunderground.py | Wunderground.init | def init(self):
'''
Use the location_code to perform a geolookup and find the closest
station. If the location is a pws or icao station ID, no lookup will be
peformed.
'''
try:
for no_lookup in ('pws', 'icao'):
sid = self.location_code.partition(no_lookup + ':')[-1]
if sid:
self.station_id = self.location_code
return
except AttributeError:
# Numeric or some other type, either way we'll just stringify
# it below and perform a lookup.
pass
self.get_station_id() | python | def init(self):
'''
Use the location_code to perform a geolookup and find the closest
station. If the location is a pws or icao station ID, no lookup will be
peformed.
'''
try:
for no_lookup in ('pws', 'icao'):
sid = self.location_code.partition(no_lookup + ':')[-1]
if sid:
self.station_id = self.location_code
return
except AttributeError:
# Numeric or some other type, either way we'll just stringify
# it below and perform a lookup.
pass
self.get_station_id() | [
"def",
"init",
"(",
"self",
")",
":",
"try",
":",
"for",
"no_lookup",
"in",
"(",
"'pws'",
",",
"'icao'",
")",
":",
"sid",
"=",
"self",
".",
"location_code",
".",
"partition",
"(",
"no_lookup",
"+",
"':'",
")",
"[",
"-",
"1",
"]",
"if",
"sid",
":"... | Use the location_code to perform a geolookup and find the closest
station. If the location is a pws or icao station ID, no lookup will be
peformed. | [
"Use",
"the",
"location_code",
"to",
"perform",
"a",
"geolookup",
"and",
"find",
"the",
"closest",
"station",
".",
"If",
"the",
"location",
"is",
"a",
"pws",
"or",
"icao",
"station",
"ID",
"no",
"lookup",
"will",
"be",
"peformed",
"."
] | 14cfde967cecf79b40e223e35a04600f4c875af7 | https://github.com/enkore/i3pystatus/blob/14cfde967cecf79b40e223e35a04600f4c875af7/i3pystatus/weather/wunderground.py#L110-L127 | train | 203,719 |
enkore/i3pystatus | i3pystatus/weather/wunderground.py | Wunderground.get_station_id | def get_station_id(self):
'''
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_url)
station_type = 'pws' if self.use_pws else 'airport'
try:
stations = response['location']['nearby_weather_stations']
nearest = stations[station_type]['station'][0]
except (KeyError, IndexError):
raise Exception(
'No locations matched location_code %s' % self.location_code)
self.logger.error('nearest = %s', nearest)
if self.use_pws:
nearest_pws = nearest.get('id', '')
if not nearest_pws:
raise Exception('No id entry for nearest PWS')
self.station_id = 'pws:%s' % nearest_pws
else:
nearest_airport = nearest.get('icao', '')
if not nearest_airport:
raise Exception('No icao entry for nearest airport')
self.station_id = 'icao:%s' % nearest_airport | python | def get_station_id(self):
'''
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_url)
station_type = 'pws' if self.use_pws else 'airport'
try:
stations = response['location']['nearby_weather_stations']
nearest = stations[station_type]['station'][0]
except (KeyError, IndexError):
raise Exception(
'No locations matched location_code %s' % self.location_code)
self.logger.error('nearest = %s', nearest)
if self.use_pws:
nearest_pws = nearest.get('id', '')
if not nearest_pws:
raise Exception('No id entry for nearest PWS')
self.station_id = 'pws:%s' % nearest_pws
else:
nearest_airport = nearest.get('icao', '')
if not nearest_airport:
raise Exception('No icao entry for nearest airport')
self.station_id = 'icao:%s' % nearest_airport | [
"def",
"get_station_id",
"(",
"self",
")",
":",
"extra_opts",
"=",
"'/pws:0'",
"if",
"not",
"self",
".",
"use_pws",
"else",
"''",
"api_url",
"=",
"GEOLOOKUP_URL",
"%",
"(",
"self",
".",
"api_key",
",",
"extra_opts",
",",
"self",
".",
"location_code",
")",
... | Use geolocation to get the station ID | [
"Use",
"geolocation",
"to",
"get",
"the",
"station",
"ID"
] | 14cfde967cecf79b40e223e35a04600f4c875af7 | https://github.com/enkore/i3pystatus/blob/14cfde967cecf79b40e223e35a04600f4c875af7/i3pystatus/weather/wunderground.py#L158-L185 | train | 203,720 |
enkore/i3pystatus | i3pystatus/scores/__init__.py | ScoresBackend.get_api_date | 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.
'''
# NOTE: If you are writing your own function to get the date, make sure
# to include the first if block below to allow for the ``date``
# parameter to hard-code a date.
api_date = None
if self.date is not None and not isinstance(self.date, datetime):
try:
api_date = datetime.strptime(self.date, '%Y-%m-%d')
except (TypeError, ValueError):
self.logger.warning('Invalid date \'%s\'', self.date)
if api_date is None:
utc_time = pytz.utc.localize(datetime.utcnow())
eastern = pytz.timezone('US/Eastern')
api_date = eastern.normalize(utc_time.astimezone(eastern))
if api_date.hour < 10:
# The scores on NHL.com change at 10am Eastern, if it's before
# that time of day then we will use yesterday's date.
api_date -= timedelta(days=1)
self.date = api_date | python | 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.
'''
# NOTE: If you are writing your own function to get the date, make sure
# to include the first if block below to allow for the ``date``
# parameter to hard-code a date.
api_date = None
if self.date is not None and not isinstance(self.date, datetime):
try:
api_date = datetime.strptime(self.date, '%Y-%m-%d')
except (TypeError, ValueError):
self.logger.warning('Invalid date \'%s\'', self.date)
if api_date is None:
utc_time = pytz.utc.localize(datetime.utcnow())
eastern = pytz.timezone('US/Eastern')
api_date = eastern.normalize(utc_time.astimezone(eastern))
if api_date.hour < 10:
# The scores on NHL.com change at 10am Eastern, if it's before
# that time of day then we will use yesterday's date.
api_date -= timedelta(days=1)
self.date = api_date | [
"def",
"get_api_date",
"(",
"self",
")",
":",
"# NOTE: If you are writing your own function to get the date, make sure",
"# to include the first if block below to allow for the ``date``",
"# parameter to hard-code a date.",
"api_date",
"=",
"None",
"if",
"self",
".",
"date",
"is",
... | 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. | [
"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... | 14cfde967cecf79b40e223e35a04600f4c875af7 | https://github.com/enkore/i3pystatus/blob/14cfde967cecf79b40e223e35a04600f4c875af7/i3pystatus/scores/__init__.py#L83-L107 | train | 203,721 |
enkore/i3pystatus | i3pystatus/weather/weathercom.py | WeathercomHTMLParser.handle_data | 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.
'''
if self.weather_data is not None:
# We've already found weather data, no need to continue parsing
return
content = content.strip().rstrip(';')
try:
tag_text = self.get_starttag_text().lower()
except AttributeError:
tag_text = ''
if tag_text.startswith('<script'):
# Look for feed information embedded as a javascript variable
begin = content.find('window.__data')
if begin != -1:
self.logger.debug('Located window.__data')
# Look for end of JSON dict and end of javascript statement
end = content.find('};', begin)
if end == -1:
self.logger.debug('Failed to locate end of javascript statement')
else:
# Strip the "window.__data=" from the beginning
json_data = self.load_json(
content[begin:end + 1].split('=', 1)[1].lstrip()
)
if json_data is not None:
def _find_weather_data(data):
'''
Helper designed to minimize impact of potential
structural changes to this data.
'''
if isinstance(data, dict):
if 'Observation' in data and 'DailyForecast' in data:
return data
else:
for key in data:
ret = _find_weather_data(data[key])
if ret is not None:
return ret
return None
weather_data = _find_weather_data(json_data)
if weather_data is None:
self.logger.debug(
'Failed to locate weather data in the '
'following data structure: %s', json_data
)
else:
self.weather_data = weather_data
return
for line in content.splitlines():
line = line.strip().rstrip(';')
if line.startswith('var adaptorParams'):
# Strip off the "var adaptorParams = " from the beginning,
# and the javascript semicolon from the end. This will give
# us JSON that we can load.
weather_data = self.load_json(line.split('=', 1)[1].lstrip())
if weather_data is not None:
self.weather_data = weather_data
return | python | 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.
'''
if self.weather_data is not None:
# We've already found weather data, no need to continue parsing
return
content = content.strip().rstrip(';')
try:
tag_text = self.get_starttag_text().lower()
except AttributeError:
tag_text = ''
if tag_text.startswith('<script'):
# Look for feed information embedded as a javascript variable
begin = content.find('window.__data')
if begin != -1:
self.logger.debug('Located window.__data')
# Look for end of JSON dict and end of javascript statement
end = content.find('};', begin)
if end == -1:
self.logger.debug('Failed to locate end of javascript statement')
else:
# Strip the "window.__data=" from the beginning
json_data = self.load_json(
content[begin:end + 1].split('=', 1)[1].lstrip()
)
if json_data is not None:
def _find_weather_data(data):
'''
Helper designed to minimize impact of potential
structural changes to this data.
'''
if isinstance(data, dict):
if 'Observation' in data and 'DailyForecast' in data:
return data
else:
for key in data:
ret = _find_weather_data(data[key])
if ret is not None:
return ret
return None
weather_data = _find_weather_data(json_data)
if weather_data is None:
self.logger.debug(
'Failed to locate weather data in the '
'following data structure: %s', json_data
)
else:
self.weather_data = weather_data
return
for line in content.splitlines():
line = line.strip().rstrip(';')
if line.startswith('var adaptorParams'):
# Strip off the "var adaptorParams = " from the beginning,
# and the javascript semicolon from the end. This will give
# us JSON that we can load.
weather_data = self.load_json(line.split('=', 1)[1].lstrip())
if weather_data is not None:
self.weather_data = weather_data
return | [
"def",
"handle_data",
"(",
"self",
",",
"content",
")",
":",
"if",
"self",
".",
"weather_data",
"is",
"not",
"None",
":",
"# We've already found weather data, no need to continue parsing",
"return",
"content",
"=",
"content",
".",
"strip",
"(",
")",
".",
"rstrip",... | 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. | [
"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",
"."
] | 14cfde967cecf79b40e223e35a04600f4c875af7 | https://github.com/enkore/i3pystatus/blob/14cfde967cecf79b40e223e35a04600f4c875af7/i3pystatus/weather/weathercom.py#L49-L112 | train | 203,722 |
enkore/i3pystatus | i3pystatus/anybar.py | AnyBar.main_loop | def main_loop(self):
""" Mainloop blocks so we thread it."""
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) | python | def main_loop(self):
""" Mainloop blocks so we thread it."""
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",
")",
":",
"sock",
"=",
"socket",
".",
"socket",
"(",
"socket",
".",
"AF_INET",
",",
"socket",
".",
"SOCK_DGRAM",
")",
"port",
"=",
"int",
"(",
"getattr",
"(",
"self",
",",
"'port'",
",",
"1738",
")",
")",
"sock",
".... | Mainloop blocks so we thread it. | [
"Mainloop",
"blocks",
"so",
"we",
"thread",
"it",
"."
] | 14cfde967cecf79b40e223e35a04600f4c875af7 | https://github.com/enkore/i3pystatus/blob/14cfde967cecf79b40e223e35a04600f4c875af7/i3pystatus/anybar.py#L41-L49 | train | 203,723 |
enkore/i3pystatus | i3pystatus/core/threading.py | Thread.should_execute | 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.
"""
if not self._suspended.is_set():
return True
workload = unwrap_workload(workload)
return hasattr(workload, 'keep_alive') and getattr(workload, 'keep_alive') | python | 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.
"""
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",
"not",
"self",
".",
"_suspended",
".",
"is_set",
"(",
")",
":",
"return",
"True",
"workload",
"=",
"unwrap_workload",
"(",
"workload",
")",
"return",
"hasattr",
"(",
"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. | [
"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",
... | 14cfde967cecf79b40e223e35a04600f4c875af7 | https://github.com/enkore/i3pystatus/blob/14cfde967cecf79b40e223e35a04600f4c875af7/i3pystatus/core/threading.py#L51-L59 | train | 203,724 |
enkore/i3pystatus | i3pystatus/temp.py | get_sensors | def get_sensors():
""" Detect and return a list of Sensor objects """
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 chip.get_features():
if feature.type == sensors.FEATURE_TEMP:
try:
name = chip.get_label(feature)
max = get_subfeature_value(feature, sensors.SUBFEATURE_TEMP_MAX)
current = get_subfeature_value(feature, sensors.SUBFEATURE_TEMP_INPUT)
critical = get_subfeature_value(feature, sensors.SUBFEATURE_TEMP_CRIT)
if critical:
found_sensors.append(Sensor(name=name, current=current, maximum=max, critical=critical))
except sensors.SensorsException:
continue
return found_sensors | python | def get_sensors():
""" Detect and return a list of Sensor objects """
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 chip.get_features():
if feature.type == sensors.FEATURE_TEMP:
try:
name = chip.get_label(feature)
max = get_subfeature_value(feature, sensors.SUBFEATURE_TEMP_MAX)
current = get_subfeature_value(feature, sensors.SUBFEATURE_TEMP_INPUT)
critical = get_subfeature_value(feature, sensors.SUBFEATURE_TEMP_CRIT)
if critical:
found_sensors.append(Sensor(name=name, current=current, maximum=max, critical=critical))
except sensors.SensorsException:
continue
return found_sensors | [
"def",
"get_sensors",
"(",
")",
":",
"import",
"sensors",
"found_sensors",
"=",
"list",
"(",
")",
"def",
"get_subfeature_value",
"(",
"feature",
",",
"subfeature_type",
")",
":",
"subfeature",
"=",
"chip",
".",
"get_subfeature",
"(",
"feature",
",",
"subfeatur... | Detect and return a list of Sensor objects | [
"Detect",
"and",
"return",
"a",
"list",
"of",
"Sensor",
"objects"
] | 14cfde967cecf79b40e223e35a04600f4c875af7 | https://github.com/enkore/i3pystatus/blob/14cfde967cecf79b40e223e35a04600f4c875af7/i3pystatus/temp.py#L32-L54 | train | 203,725 |
enkore/i3pystatus | i3pystatus/temp.py | Temperature.get_output_original | def get_output_original(self):
"""
Build the output the original way. Requires no third party libraries.
"""
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:
color = self.color if temp < self.alert_temp else self.alert_color
return {
"full_text": self.format.format(temp=temp),
"color": color,
} | python | def get_output_original(self):
"""
Build the output the original way. Requires no third party libraries.
"""
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:
color = self.color if temp < self.alert_temp else self.alert_color
return {
"full_text": self.format.format(temp=temp),
"color": color,
} | [
"def",
"get_output_original",
"(",
"self",
")",
":",
"with",
"open",
"(",
"self",
".",
"file",
",",
"\"r\"",
")",
"as",
"f",
":",
"temp",
"=",
"float",
"(",
"f",
".",
"read",
"(",
")",
".",
"strip",
"(",
")",
")",
"/",
"1000",
"if",
"self",
"."... | Build the output the original way. Requires no third party libraries. | [
"Build",
"the",
"output",
"the",
"original",
"way",
".",
"Requires",
"no",
"third",
"party",
"libraries",
"."
] | 14cfde967cecf79b40e223e35a04600f4c875af7 | https://github.com/enkore/i3pystatus/blob/14cfde967cecf79b40e223e35a04600f4c875af7/i3pystatus/temp.py#L184-L201 | train | 203,726 |
enkore/i3pystatus | i3pystatus/temp.py | Temperature.get_urgent | def get_urgent(self, sensors):
""" Determine if any sensors should set the urgent flag. """
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 sensor.is_critical():
return True
return False | python | def get_urgent(self, sensors):
""" Determine if any sensors should set the urgent flag. """
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 sensor.is_critical():
return True
return False | [
"def",
"get_urgent",
"(",
"self",
",",
"sensors",
")",
":",
"if",
"self",
".",
"urgent_on",
"not",
"in",
"(",
"'warning'",
",",
"'critical'",
")",
":",
"raise",
"Exception",
"(",
"\"urgent_on must be one of (warning, critical)\"",
")",
"for",
"sensor",
"in",
"... | Determine if any sensors should set the urgent flag. | [
"Determine",
"if",
"any",
"sensors",
"should",
"set",
"the",
"urgent",
"flag",
"."
] | 14cfde967cecf79b40e223e35a04600f4c875af7 | https://github.com/enkore/i3pystatus/blob/14cfde967cecf79b40e223e35a04600f4c875af7/i3pystatus/temp.py#L222-L231 | train | 203,727 |
enkore/i3pystatus | i3pystatus/temp.py | Temperature.format_sensor | def format_sensor(self, sensor):
""" Format a sensor value. If pango is enabled color is per sensor. """
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 current_val | python | def format_sensor(self, sensor):
""" Format a sensor value. If pango is enabled color is per sensor. """
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 current_val | [
"def",
"format_sensor",
"(",
"self",
",",
"sensor",
")",
":",
"current_val",
"=",
"sensor",
".",
"current",
"if",
"self",
".",
"pango_enabled",
":",
"percentage",
"=",
"self",
".",
"percentage",
"(",
"sensor",
".",
"current",
",",
"sensor",
".",
"critical"... | Format a sensor value. If pango is enabled color is per sensor. | [
"Format",
"a",
"sensor",
"value",
".",
"If",
"pango",
"is",
"enabled",
"color",
"is",
"per",
"sensor",
"."
] | 14cfde967cecf79b40e223e35a04600f4c875af7 | https://github.com/enkore/i3pystatus/blob/14cfde967cecf79b40e223e35a04600f4c875af7/i3pystatus/temp.py#L233-L241 | train | 203,728 |
enkore/i3pystatus | i3pystatus/temp.py | Temperature.format_sensor_bar | def format_sensor_bar(self, sensor):
""" Build and format a sensor bar. If pango is enabled bar color is per sensor."""
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 | python | def format_sensor_bar(self, sensor):
""" Build and format a sensor bar. If pango is enabled bar color is per sensor."""
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",
")",
":",
"percentage",
"=",
"self",
".",
"percentage",
"(",
"sensor",
".",
"current",
",",
"sensor",
".",
"critical",
")",
"bar",
"=",
"make_vertical_bar",
"(",
"int",
"(",
"percentage",
")",
")",
... | Build and format a sensor bar. If pango is enabled bar color is per sensor. | [
"Build",
"and",
"format",
"a",
"sensor",
"bar",
".",
"If",
"pango",
"is",
"enabled",
"bar",
"color",
"is",
"per",
"sensor",
"."
] | 14cfde967cecf79b40e223e35a04600f4c875af7 | https://github.com/enkore/i3pystatus/blob/14cfde967cecf79b40e223e35a04600f4c875af7/i3pystatus/temp.py#L243-L251 | train | 203,729 |
enkore/i3pystatus | i3pystatus/mail/__init__.py | Mail.run | def run(self):
"""
Returns the sum of unread messages across all registered backends
"""
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
urgent = "false"
if self.hide_if_null:
self.output = None
return
else:
color = self.color_unread
urgent = "true"
format = self.format
if unread > 1:
format = self.format_plural
account_name = getattr(self.backends[self.current_backend], "account", "No name")
self.output = {
"full_text": format.format(unread=unread, current_unread=current_unread, account=account_name),
"urgent": urgent,
"color": color,
} | python | def run(self):
"""
Returns the sum of unread messages across all registered backends
"""
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
urgent = "false"
if self.hide_if_null:
self.output = None
return
else:
color = self.color_unread
urgent = "true"
format = self.format
if unread > 1:
format = self.format_plural
account_name = getattr(self.backends[self.current_backend], "account", "No name")
self.output = {
"full_text": format.format(unread=unread, current_unread=current_unread, account=account_name),
"urgent": urgent,
"color": color,
} | [
"def",
"run",
"(",
"self",
")",
":",
"unread",
"=",
"0",
"current_unread",
"=",
"0",
"for",
"id",
",",
"backend",
"in",
"enumerate",
"(",
"self",
".",
"backends",
")",
":",
"temp",
"=",
"backend",
".",
"unread",
"or",
"0",
"unread",
"=",
"unread",
... | Returns the sum of unread messages across all registered backends | [
"Returns",
"the",
"sum",
"of",
"unread",
"messages",
"across",
"all",
"registered",
"backends"
] | 14cfde967cecf79b40e223e35a04600f4c875af7 | https://github.com/enkore/i3pystatus/blob/14cfde967cecf79b40e223e35a04600f4c875af7/i3pystatus/mail/__init__.py#L55-L87 | train | 203,730 |
enkore/i3pystatus | i3pystatus/redshift.py | RedshiftController.parse_output | def parse_output(self, line):
"""Convert output to key value pairs"""
try:
key, value = line.split(":")
self.update_value(key.strip(), value.strip())
except ValueError:
pass | python | def parse_output(self, line):
"""Convert output to key value pairs"""
try:
key, value = line.split(":")
self.update_value(key.strip(), value.strip())
except ValueError:
pass | [
"def",
"parse_output",
"(",
"self",
",",
"line",
")",
":",
"try",
":",
"key",
",",
"value",
"=",
"line",
".",
"split",
"(",
"\":\"",
")",
"self",
".",
"update_value",
"(",
"key",
".",
"strip",
"(",
")",
",",
"value",
".",
"strip",
"(",
")",
")",
... | Convert output to key value pairs | [
"Convert",
"output",
"to",
"key",
"value",
"pairs"
] | 14cfde967cecf79b40e223e35a04600f4c875af7 | https://github.com/enkore/i3pystatus/blob/14cfde967cecf79b40e223e35a04600f4c875af7/i3pystatus/redshift.py#L42-L49 | train | 203,731 |
enkore/i3pystatus | i3pystatus/redshift.py | RedshiftController.update_value | def update_value(self, key, value):
"""Parse key value pairs to update their values"""
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
elif key == "Location":
location = []
for x in value.split(", "):
v, d = x.split(" ")
location.append(float(v) * (1 if d in "NE" else -1))
self._location = (location) | python | def update_value(self, key, value):
"""Parse key value pairs to update their values"""
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
elif key == "Location":
location = []
for x in value.split(", "):
v, d = x.split(" ")
location.append(float(v) * (1 if d in "NE" else -1))
self._location = (location) | [
"def",
"update_value",
"(",
"self",
",",
"key",
",",
"value",
")",
":",
"if",
"key",
"==",
"\"Status\"",
":",
"self",
".",
"_inhibited",
"=",
"value",
"!=",
"\"Enabled\"",
"elif",
"key",
"==",
"\"Color temperature\"",
":",
"self",
".",
"_temperature",
"=",... | Parse key value pairs to update their values | [
"Parse",
"key",
"value",
"pairs",
"to",
"update",
"their",
"values"
] | 14cfde967cecf79b40e223e35a04600f4c875af7 | https://github.com/enkore/i3pystatus/blob/14cfde967cecf79b40e223e35a04600f4c875af7/i3pystatus/redshift.py#L51-L67 | train | 203,732 |
enkore/i3pystatus | i3pystatus/redshift.py | RedshiftController.set_inhibit | def set_inhibit(self, inhibit):
"""Set inhibition state"""
if self._pid and inhibit != self._inhibited:
os.kill(self._pid, signal.SIGUSR1)
self._inhibited = inhibit | python | def set_inhibit(self, inhibit):
"""Set inhibition state"""
if self._pid and inhibit != self._inhibited:
os.kill(self._pid, signal.SIGUSR1)
self._inhibited = inhibit | [
"def",
"set_inhibit",
"(",
"self",
",",
"inhibit",
")",
":",
"if",
"self",
".",
"_pid",
"and",
"inhibit",
"!=",
"self",
".",
"_inhibited",
":",
"os",
".",
"kill",
"(",
"self",
".",
"_pid",
",",
"signal",
".",
"SIGUSR1",
")",
"self",
".",
"_inhibited"... | Set inhibition state | [
"Set",
"inhibition",
"state"
] | 14cfde967cecf79b40e223e35a04600f4c875af7 | https://github.com/enkore/i3pystatus/blob/14cfde967cecf79b40e223e35a04600f4c875af7/i3pystatus/redshift.py#L94-L98 | train | 203,733 |
enkore/i3pystatus | i3pystatus/core/command.py | execute | 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` command. As a result the program is executed independent of
i3pystatus as a child of i3 process. Because of how i3-msg parses its
arguments the type of `command` is limited to string in this mode.
"""
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]
else:
if isinstance(command, str):
command = shlex.split(command)
try:
subprocess.Popen(command, stdin=subprocess.DEVNULL,
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
except OSError:
logging.getLogger("i3pystatus.core.command").exception("")
except subprocess.CalledProcessError:
logging.getLogger("i3pystatus.core.command").exception("") | python | 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` command. As a result the program is executed independent of
i3pystatus as a child of i3 process. Because of how i3-msg parses its
arguments the type of `command` is limited to string in this mode.
"""
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]
else:
if isinstance(command, str):
command = shlex.split(command)
try:
subprocess.Popen(command, stdin=subprocess.DEVNULL,
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
except OSError:
logging.getLogger("i3pystatus.core.command").exception("")
except subprocess.CalledProcessError:
logging.getLogger("i3pystatus.core.command").exception("") | [
"def",
"execute",
"(",
"command",
",",
"detach",
"=",
"False",
")",
":",
"if",
"detach",
":",
"if",
"not",
"isinstance",
"(",
"command",
",",
"str",
")",
":",
"msg",
"=",
"\"Detached mode expects a string as command, not {}\"",
".",
"format",
"(",
"command",
... | 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` command. As a result the program is executed independent of
i3pystatus as a child of i3 process. Because of how i3-msg parses its
arguments the type of `command` is limited to string in this mode. | [
"Runs",
"a",
"command",
"in",
"background",
".",
"No",
"output",
"is",
"retrieved",
".",
"Useful",
"for",
"running",
"GUI",
"applications",
"that",
"would",
"block",
"click",
"events",
"."
] | 14cfde967cecf79b40e223e35a04600f4c875af7 | https://github.com/enkore/i3pystatus/blob/14cfde967cecf79b40e223e35a04600f4c875af7/i3pystatus/core/command.py#L53-L83 | train | 203,734 |
enkore/i3pystatus | i3pystatus/core/color.py | ColorRangeModule.get_hex_color_range | 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
"""
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 colors to the full
# Hex value.
if len(color) == 4:
fixed_color = "#"
for c in color[1:]:
fixed_color += c * 2
colors.append(fixed_color)
else:
colors.append(color)
return colors | python | 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
"""
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 colors to the full
# Hex value.
if len(color) == 4:
fixed_color = "#"
for c in color[1:]:
fixed_color += c * 2
colors.append(fixed_color)
else:
colors.append(color)
return colors | [
"def",
"get_hex_color_range",
"(",
"start_color",
",",
"end_color",
",",
"quantity",
")",
":",
"raw_colors",
"=",
"[",
"c",
".",
"hex",
"for",
"c",
"in",
"list",
"(",
"Color",
"(",
"start_color",
")",
".",
"range_to",
"(",
"Color",
"(",
"end_color",
")",... | 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 | [
"Generates",
"a",
"list",
"of",
"quantity",
"Hex",
"colors",
"from",
"start_color",
"to",
"end_color",
"."
] | 14cfde967cecf79b40e223e35a04600f4c875af7 | https://github.com/enkore/i3pystatus/blob/14cfde967cecf79b40e223e35a04600f4c875af7/i3pystatus/core/color.py#L15-L38 | train | 203,735 |
enkore/i3pystatus | i3pystatus/core/modules.py | is_method_of | def is_method_of(method, object):
"""Decide whether ``method`` is contained within the MRO of ``object``."""
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 | python | def is_method_of(method, object):
"""Decide whether ``method`` is contained within the MRO of ``object``."""
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",
")",
":",
"if",
"not",
"callable",
"(",
"method",
")",
"or",
"not",
"hasattr",
"(",
"method",
",",
"\"__name__\"",
")",
":",
"return",
"False",
"if",
"inspect",
".",
"ismethod",
"(",
"method",
")",
"... | Decide whether ``method`` is contained within the MRO of ``object``. | [
"Decide",
"whether",
"method",
"is",
"contained",
"within",
"the",
"MRO",
"of",
"object",
"."
] | 14cfde967cecf79b40e223e35a04600f4c875af7 | https://github.com/enkore/i3pystatus/blob/14cfde967cecf79b40e223e35a04600f4c875af7/i3pystatus/core/modules.py#L11-L20 | train | 203,736 |
enkore/i3pystatus | i3pystatus/core/modules.py | Module.on_click | 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_middleclick 2
Right click on_rightclick 3
Scroll up on_upscroll 4
Scroll down on_downscroll 5
Others on_otherclick > 5
============ ================ =========
The action is determined by the nature (type and value) of the callback
setting in the following order:
1. If null callback (``None``), no action is taken.
2. If it's a `python function`, call it and pass any additional
arguments.
3. If it's name of a `member method` of current module (string), call
it and pass any additional arguments.
4. If the name does not match with `member method` name execute program
with such name.
.. seealso:: :ref:`callbacks` for more information about
callback settings and examples.
:param button: The ID of button event received from i3bar.
:param kwargs: Further information received from i3bar like the
positions of the mouse where the click occured.
:return: Returns ``True`` if a valid callback action was executed.
``False`` otherwise.
"""
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"
m_click = self.__multi_click
with m_click.lock:
double = m_click.check_double(button)
double_action = 'double%s' % action
if double:
action = double_action
# Get callback function
cb = getattr(self, 'on_%s' % action, None)
double_handler = getattr(self, 'on_%s' % double_action, None)
delay_execution = (not double and double_handler)
if delay_execution:
m_click.set_timer(button, cb, **kwargs)
else:
self.__button_callback_handler(button, cb, **kwargs) | python | 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_middleclick 2
Right click on_rightclick 3
Scroll up on_upscroll 4
Scroll down on_downscroll 5
Others on_otherclick > 5
============ ================ =========
The action is determined by the nature (type and value) of the callback
setting in the following order:
1. If null callback (``None``), no action is taken.
2. If it's a `python function`, call it and pass any additional
arguments.
3. If it's name of a `member method` of current module (string), call
it and pass any additional arguments.
4. If the name does not match with `member method` name execute program
with such name.
.. seealso:: :ref:`callbacks` for more information about
callback settings and examples.
:param button: The ID of button event received from i3bar.
:param kwargs: Further information received from i3bar like the
positions of the mouse where the click occured.
:return: Returns ``True`` if a valid callback action was executed.
``False`` otherwise.
"""
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"
m_click = self.__multi_click
with m_click.lock:
double = m_click.check_double(button)
double_action = 'double%s' % action
if double:
action = double_action
# Get callback function
cb = getattr(self, 'on_%s' % action, None)
double_handler = getattr(self, 'on_%s' % double_action, None)
delay_execution = (not double and double_handler)
if delay_execution:
m_click.set_timer(button, cb, **kwargs)
else:
self.__button_callback_handler(button, cb, **kwargs) | [
"def",
"on_click",
"(",
"self",
",",
"button",
",",
"*",
"*",
"kwargs",
")",
":",
"actions",
"=",
"[",
"'leftclick'",
",",
"'middleclick'",
",",
"'rightclick'",
",",
"'upscroll'",
",",
"'downscroll'",
"]",
"try",
":",
"action",
"=",
"actions",
"[",
"butt... | 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_middleclick 2
Right click on_rightclick 3
Scroll up on_upscroll 4
Scroll down on_downscroll 5
Others on_otherclick > 5
============ ================ =========
The action is determined by the nature (type and value) of the callback
setting in the following order:
1. If null callback (``None``), no action is taken.
2. If it's a `python function`, call it and pass any additional
arguments.
3. If it's name of a `member method` of current module (string), call
it and pass any additional arguments.
4. If the name does not match with `member method` name execute program
with such name.
.. seealso:: :ref:`callbacks` for more information about
callback settings and examples.
:param button: The ID of button event received from i3bar.
:param kwargs: Further information received from i3bar like the
positions of the mouse where the click occured.
:return: Returns ``True`` if a valid callback action was executed.
``False`` otherwise. | [
"Maps",
"a",
"click",
"event",
"with",
"its",
"associated",
"callback",
"."
] | 14cfde967cecf79b40e223e35a04600f4c875af7 | https://github.com/enkore/i3pystatus/blob/14cfde967cecf79b40e223e35a04600f4c875af7/i3pystatus/core/modules.py#L184-L248 | train | 203,737 |
enkore/i3pystatus | i3pystatus/core/modules.py | Module.text_to_pango | 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;`).
"""
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 "full_text" in self.output.keys():
self.output["full_text"] = replace(self.output["full_text"])
if "short_text" in self.output.keys():
self.output["short_text"] = replace(self.output["short_text"]) | python | 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;`).
"""
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 "full_text" in self.output.keys():
self.output["full_text"] = replace(self.output["full_text"])
if "short_text" in self.output.keys():
self.output["short_text"] = replace(self.output["short_text"]) | [
"def",
"text_to_pango",
"(",
"self",
")",
":",
"def",
"replace",
"(",
"s",
")",
":",
"s",
"=",
"s",
".",
"split",
"(",
"\"&\"",
")",
"out",
"=",
"s",
"[",
"0",
"]",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"s",
")",
"-",
"1",
")",
":",
... | 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;`). | [
"Replaces",
"all",
"ampersands",
"in",
"full_text",
"and",
"short_text",
"attributes",
"of",
"self",
".",
"output",
"with",
"&",
";",
"."
] | 14cfde967cecf79b40e223e35a04600f4c875af7 | https://github.com/enkore/i3pystatus/blob/14cfde967cecf79b40e223e35a04600f4c875af7/i3pystatus/core/modules.py#L254-L276 | train | 203,738 |
enkore/i3pystatus | i3pystatus/core/settings.py | SettingsBase.get_protected_settings | def get_protected_settings(self, settings_source):
"""
Attempt to retrieve protected settings from keyring if they are not already set.
"""
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 = None
identifier = "%s.%s" % (self.__name__, setting_name)
if hasattr(self, 'required') and setting_name in getattr(self, 'required'):
setting = self.get_setting_from_keyring(identifier, user_backend)
elif hasattr(self, setting_name):
setting = self.get_setting_from_keyring(identifier, user_backend)
if setting:
found_settings.update({setting_name: setting})
return found_settings | python | def get_protected_settings(self, settings_source):
"""
Attempt to retrieve protected settings from keyring if they are not already set.
"""
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 = None
identifier = "%s.%s" % (self.__name__, setting_name)
if hasattr(self, 'required') and setting_name in getattr(self, 'required'):
setting = self.get_setting_from_keyring(identifier, user_backend)
elif hasattr(self, setting_name):
setting = self.get_setting_from_keyring(identifier, user_backend)
if setting:
found_settings.update({setting_name: setting})
return found_settings | [
"def",
"get_protected_settings",
"(",
"self",
",",
"settings_source",
")",
":",
"user_backend",
"=",
"settings_source",
".",
"get",
"(",
"'keyring_backend'",
")",
"found_settings",
"=",
"dict",
"(",
")",
"for",
"setting_name",
"in",
"self",
".",
"__PROTECTED_SETTI... | Attempt to retrieve protected settings from keyring if they are not already set. | [
"Attempt",
"to",
"retrieve",
"protected",
"settings",
"from",
"keyring",
"if",
"they",
"are",
"not",
"already",
"set",
"."
] | 14cfde967cecf79b40e223e35a04600f4c875af7 | https://github.com/enkore/i3pystatus/blob/14cfde967cecf79b40e223e35a04600f4c875af7/i3pystatus/core/settings.py#L111-L130 | train | 203,739 |
enkore/i3pystatus | i3pystatus/core/__init__.py | Status.register | 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
"""
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.get('hints', {}))
if hints:
kwargs['hints'] = hints
try:
return self.modules.append(module, *args, **kwargs)
except Exception as e:
log.exception(e)
return self.modules.append(Text(
color="#FF0000",
text="{i3py_mod}: Fatal Error - {ex}({msg})".format(
i3py_mod=module,
ex=e.__class__.__name__,
msg=e
)
)) | python | 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
"""
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.get('hints', {}))
if hints:
kwargs['hints'] = hints
try:
return self.modules.append(module, *args, **kwargs)
except Exception as e:
log.exception(e)
return self.modules.append(Text(
color="#FF0000",
text="{i3py_mod}: Fatal Error - {ex}({msg})".format(
i3py_mod=module,
ex=e.__class__.__name__,
msg=e
)
)) | [
"def",
"register",
"(",
"self",
",",
"module",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"from",
"i3pystatus",
".",
"text",
"import",
"Text",
"if",
"not",
"module",
":",
"return",
"# Merge the module's hints with the default hints",
"# and overwrite a... | 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 | [
"Register",
"a",
"new",
"module",
"."
] | 14cfde967cecf79b40e223e35a04600f4c875af7 | https://github.com/enkore/i3pystatus/blob/14cfde967cecf79b40e223e35a04600f4c875af7/i3pystatus/core/__init__.py#L99-L132 | train | 203,740 |
enkore/i3pystatus | i3pystatus/core/__init__.py | Status.run | def run(self):
"""
Run main loop.
"""
if self.click_events:
self.command_endpoint.start()
for j in io.JSONIO(self.io).read():
for module in self.modules:
module.inject(j) | python | def run(self):
"""
Run main loop.
"""
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",
")",
":",
"if",
"self",
".",
"click_events",
":",
"self",
".",
"command_endpoint",
".",
"start",
"(",
")",
"for",
"j",
"in",
"io",
".",
"JSONIO",
"(",
"self",
".",
"io",
")",
".",
"read",
"(",
")",
":",
"for",
"module",... | Run main loop. | [
"Run",
"main",
"loop",
"."
] | 14cfde967cecf79b40e223e35a04600f4c875af7 | https://github.com/enkore/i3pystatus/blob/14cfde967cecf79b40e223e35a04600f4c875af7/i3pystatus/core/__init__.py#L134-L142 | train | 203,741 |
enkore/i3pystatus | i3pystatus/sabnzbd.py | sabnzbd.init | def init(self):
"""Initialize the URL used to connect to SABnzbd."""
self.url = self.url.format(host=self.host, port=self.port,
api_key=self.api_key) | python | def init(self):
"""Initialize the URL used to connect to SABnzbd."""
self.url = self.url.format(host=self.host, port=self.port,
api_key=self.api_key) | [
"def",
"init",
"(",
"self",
")",
":",
"self",
".",
"url",
"=",
"self",
".",
"url",
".",
"format",
"(",
"host",
"=",
"self",
".",
"host",
",",
"port",
"=",
"self",
".",
"port",
",",
"api_key",
"=",
"self",
".",
"api_key",
")"
] | Initialize the URL used to connect to SABnzbd. | [
"Initialize",
"the",
"URL",
"used",
"to",
"connect",
"to",
"SABnzbd",
"."
] | 14cfde967cecf79b40e223e35a04600f4c875af7 | https://github.com/enkore/i3pystatus/blob/14cfde967cecf79b40e223e35a04600f4c875af7/i3pystatus/sabnzbd.py#L47-L50 | train | 203,742 |
enkore/i3pystatus | i3pystatus/sabnzbd.py | sabnzbd.run | def run(self):
"""Connect to SABnzbd and get the data."""
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)
# if answer["status"] exists and is False, an error occured
if not answer.get("status", True):
self.output = {
"full_text": answer["error"],
"color": "#FF0000"
}
return
queue = answer["queue"]
self.status = queue["status"]
if self.is_paused():
color = self.color_paused
elif self.is_downloading():
color = self.color_downloading
else:
color = self.color
if self.is_downloading():
full_text = self.format.format(**queue)
else:
full_text = self.format_paused.format(**queue)
self.output = {
"full_text": full_text,
"color": color
} | python | def run(self):
"""Connect to SABnzbd and get the data."""
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)
# if answer["status"] exists and is False, an error occured
if not answer.get("status", True):
self.output = {
"full_text": answer["error"],
"color": "#FF0000"
}
return
queue = answer["queue"]
self.status = queue["status"]
if self.is_paused():
color = self.color_paused
elif self.is_downloading():
color = self.color_downloading
else:
color = self.color
if self.is_downloading():
full_text = self.format.format(**queue)
else:
full_text = self.format_paused.format(**queue)
self.output = {
"full_text": full_text,
"color": color
} | [
"def",
"run",
"(",
"self",
")",
":",
"try",
":",
"answer",
"=",
"urlopen",
"(",
"self",
".",
"url",
"+",
"\"&mode=queue\"",
")",
".",
"read",
"(",
")",
".",
"decode",
"(",
")",
"except",
"(",
"HTTPError",
",",
"URLError",
")",
"as",
"error",
":",
... | Connect to SABnzbd and get the data. | [
"Connect",
"to",
"SABnzbd",
"and",
"get",
"the",
"data",
"."
] | 14cfde967cecf79b40e223e35a04600f4c875af7 | https://github.com/enkore/i3pystatus/blob/14cfde967cecf79b40e223e35a04600f4c875af7/i3pystatus/sabnzbd.py#L52-L91 | train | 203,743 |
enkore/i3pystatus | i3pystatus/sabnzbd.py | sabnzbd.pause_resume | def pause_resume(self):
"""Toggle between pausing or resuming downloading."""
if self.is_paused():
urlopen(self.url + "&mode=resume")
else:
urlopen(self.url + "&mode=pause") | python | def pause_resume(self):
"""Toggle between pausing or resuming downloading."""
if self.is_paused():
urlopen(self.url + "&mode=resume")
else:
urlopen(self.url + "&mode=pause") | [
"def",
"pause_resume",
"(",
"self",
")",
":",
"if",
"self",
".",
"is_paused",
"(",
")",
":",
"urlopen",
"(",
"self",
".",
"url",
"+",
"\"&mode=resume\"",
")",
"else",
":",
"urlopen",
"(",
"self",
".",
"url",
"+",
"\"&mode=pause\"",
")"
] | Toggle between pausing or resuming downloading. | [
"Toggle",
"between",
"pausing",
"or",
"resuming",
"downloading",
"."
] | 14cfde967cecf79b40e223e35a04600f4c875af7 | https://github.com/enkore/i3pystatus/blob/14cfde967cecf79b40e223e35a04600f4c875af7/i3pystatus/sabnzbd.py#L93-L98 | train | 203,744 |
enkore/i3pystatus | i3pystatus/sabnzbd.py | sabnzbd.open_browser | def open_browser(self):
"""Open the URL of SABnzbd inside a browser."""
webbrowser.open(
"http://{host}:{port}/".format(host=self.host, port=self.port)) | python | def open_browser(self):
"""Open the URL of SABnzbd inside a browser."""
webbrowser.open(
"http://{host}:{port}/".format(host=self.host, port=self.port)) | [
"def",
"open_browser",
"(",
"self",
")",
":",
"webbrowser",
".",
"open",
"(",
"\"http://{host}:{port}/\"",
".",
"format",
"(",
"host",
"=",
"self",
".",
"host",
",",
"port",
"=",
"self",
".",
"port",
")",
")"
] | Open the URL of SABnzbd inside a browser. | [
"Open",
"the",
"URL",
"of",
"SABnzbd",
"inside",
"a",
"browser",
"."
] | 14cfde967cecf79b40e223e35a04600f4c875af7 | https://github.com/enkore/i3pystatus/blob/14cfde967cecf79b40e223e35a04600f4c875af7/i3pystatus/sabnzbd.py#L108-L111 | train | 203,745 |
enkore/i3pystatus | i3pystatus/group.py | Group.on_click | def on_click(self, button, **kwargs):
"""
Capture scrollup and scorlldown to move in groups
Pass everthing else to the module itself
"""
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) | python | def on_click(self, button, **kwargs):
"""
Capture scrollup and scorlldown to move in groups
Pass everthing else to the module itself
"""
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",
")",
":",
"if",
"button",
"in",
"(",
"4",
",",
"5",
")",
":",
"return",
"super",
"(",
")",
".",
"on_click",
"(",
"button",
",",
"*",
"*",
"kwargs",
")",
"else",
":",
"activ... | Capture scrollup and scorlldown to move in groups
Pass everthing else to the module itself | [
"Capture",
"scrollup",
"and",
"scorlldown",
"to",
"move",
"in",
"groups",
"Pass",
"everthing",
"else",
"to",
"the",
"module",
"itself"
] | 14cfde967cecf79b40e223e35a04600f4c875af7 | https://github.com/enkore/i3pystatus/blob/14cfde967cecf79b40e223e35a04600f4c875af7/i3pystatus/group.py#L62-L73 | train | 203,746 |
enkore/i3pystatus | i3pystatus/clock.py | Clock._get_system_tz | 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.
'''
if not HAS_PYTZ:
return None
def _etc_localtime():
try:
with open('/etc/localtime', 'rb') as fp:
return pytz.tzfile.build_tzinfo('system', fp)
except OSError as exc:
if exc.errno != errno.ENOENT:
self.logger.error(
'Unable to read from /etc/localtime: %s', exc.strerror
)
except pytz.UnknownTimeZoneError:
self.logger.error(
'/etc/localtime contains unrecognized tzinfo'
)
return None
def _etc_timezone():
try:
with open('/etc/timezone', 'r') as fp:
tzname = fp.read().strip()
return pytz.timezone(tzname)
except OSError as exc:
if exc.errno != errno.ENOENT:
self.logger.error(
'Unable to read from /etc/localtime: %s', exc.strerror
)
except pytz.UnknownTimeZoneError:
self.logger.error(
'/etc/timezone contains unrecognized timezone \'%s\'',
tzname
)
return None
return _etc_localtime() or _etc_timezone() | python | 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.
'''
if not HAS_PYTZ:
return None
def _etc_localtime():
try:
with open('/etc/localtime', 'rb') as fp:
return pytz.tzfile.build_tzinfo('system', fp)
except OSError as exc:
if exc.errno != errno.ENOENT:
self.logger.error(
'Unable to read from /etc/localtime: %s', exc.strerror
)
except pytz.UnknownTimeZoneError:
self.logger.error(
'/etc/localtime contains unrecognized tzinfo'
)
return None
def _etc_timezone():
try:
with open('/etc/timezone', 'r') as fp:
tzname = fp.read().strip()
return pytz.timezone(tzname)
except OSError as exc:
if exc.errno != errno.ENOENT:
self.logger.error(
'Unable to read from /etc/localtime: %s', exc.strerror
)
except pytz.UnknownTimeZoneError:
self.logger.error(
'/etc/timezone contains unrecognized timezone \'%s\'',
tzname
)
return None
return _etc_localtime() or _etc_timezone() | [
"def",
"_get_system_tz",
"(",
"self",
")",
":",
"if",
"not",
"HAS_PYTZ",
":",
"return",
"None",
"def",
"_etc_localtime",
"(",
")",
":",
"try",
":",
"with",
"open",
"(",
"'/etc/localtime'",
",",
"'rb'",
")",
"as",
"fp",
":",
"return",
"pytz",
".",
"tzfi... | 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. | [
"Get",
"the",
"system",
"timezone",
"for",
"use",
"when",
"no",
"timezone",
"is",
"explicitly",
"provided"
] | 14cfde967cecf79b40e223e35a04600f4c875af7 | https://github.com/enkore/i3pystatus/blob/14cfde967cecf79b40e223e35a04600f4c875af7/i3pystatus/clock.py#L110-L152 | train | 203,747 |
enkore/i3pystatus | i3pystatus/weather/__init__.py | Weather.check_weather | def check_weather(self):
'''
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() | python | def check_weather(self):
'''
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",
")",
":",
"self",
".",
"output",
"[",
"'full_text'",
"]",
"=",
"self",
".",
"refresh_icon",
"+",
"self",
".",
"output",
".",
"get",
"(",
"'full_text'",
",",
"''",
")",
"self",
".",
"backend",
".",
"check_weather",
"... | Check the weather using the configured backend | [
"Check",
"the",
"weather",
"using",
"the",
"configured",
"backend"
] | 14cfde967cecf79b40e223e35a04600f4c875af7 | https://github.com/enkore/i3pystatus/blob/14cfde967cecf79b40e223e35a04600f4c875af7/i3pystatus/weather/__init__.py#L267-L274 | train | 203,748 |
enkore/i3pystatus | i3pystatus/weather/__init__.py | Weather.get_color_data | def get_color_data(self, condition):
'''
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' in condition_lc or 'clouds' in condition_lc:
if 'partly' in condition_lc:
condition = 'Partly Cloudy'
else:
condition = 'Cloudy'
elif condition_lc == 'overcast':
condition = 'Cloudy'
elif 'thunder' in condition_lc or 't-storm' in condition_lc:
condition = 'Thunderstorm'
elif 'snow' in condition_lc:
condition = 'Snow'
elif 'rain' in condition_lc or 'showers' in condition_lc:
condition = 'Rainy'
elif 'sunny' in condition_lc:
condition = 'Sunny'
elif 'clear' in condition_lc or 'fair' in condition_lc:
condition = 'Fair'
elif 'fog' in condition_lc:
condition = 'Fog'
return self.color_icons['default'] \
if condition not in self.color_icons \
else self.color_icons[condition] | python | def get_color_data(self, condition):
'''
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' in condition_lc or 'clouds' in condition_lc:
if 'partly' in condition_lc:
condition = 'Partly Cloudy'
else:
condition = 'Cloudy'
elif condition_lc == 'overcast':
condition = 'Cloudy'
elif 'thunder' in condition_lc or 't-storm' in condition_lc:
condition = 'Thunderstorm'
elif 'snow' in condition_lc:
condition = 'Snow'
elif 'rain' in condition_lc or 'showers' in condition_lc:
condition = 'Rainy'
elif 'sunny' in condition_lc:
condition = 'Sunny'
elif 'clear' in condition_lc or 'fair' in condition_lc:
condition = 'Fair'
elif 'fog' in condition_lc:
condition = 'Fog'
return self.color_icons['default'] \
if condition not in self.color_icons \
else self.color_icons[condition] | [
"def",
"get_color_data",
"(",
"self",
",",
"condition",
")",
":",
"if",
"condition",
"not",
"in",
"self",
".",
"color_icons",
":",
"# Check for similarly-named conditions if no exact match found",
"condition_lc",
"=",
"condition",
".",
"lower",
"(",
")",
"if",
"'clo... | Disambiguate similarly-named weather conditions, and return the icon
and color that match. | [
"Disambiguate",
"similarly",
"-",
"named",
"weather",
"conditions",
"and",
"return",
"the",
"icon",
"and",
"color",
"that",
"match",
"."
] | 14cfde967cecf79b40e223e35a04600f4c875af7 | https://github.com/enkore/i3pystatus/blob/14cfde967cecf79b40e223e35a04600f4c875af7/i3pystatus/weather/__init__.py#L276-L306 | train | 203,749 |
enkore/i3pystatus | i3pystatus/cpu_usage.py | CpuUsage.gen_format_all | def gen_format_all(self, usage):
"""
generates string for format all
"""
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 = self.formatter.format(self.format_all,
core=core,
usage=usage)
core_strings.append(string)
core_strings = sorted(core_strings)
return format_string.join(core_strings) | python | def gen_format_all(self, usage):
"""
generates string for format all
"""
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 = self.formatter.format(self.format_all,
core=core,
usage=usage)
core_strings.append(string)
core_strings = sorted(core_strings)
return format_string.join(core_strings) | [
"def",
"gen_format_all",
"(",
"self",
",",
"usage",
")",
":",
"format_string",
"=",
"\" \"",
"core_strings",
"=",
"[",
"]",
"for",
"core",
",",
"usage",
"in",
"usage",
".",
"items",
"(",
")",
":",
"if",
"core",
"==",
"'usage_cpu'",
"and",
"self",
".",
... | generates string for format all | [
"generates",
"string",
"for",
"format",
"all"
] | 14cfde967cecf79b40e223e35a04600f4c875af7 | https://github.com/enkore/i3pystatus/blob/14cfde967cecf79b40e223e35a04600f4c875af7/i3pystatus/cpu_usage.py#L94-L114 | train | 203,750 |
enkore/i3pystatus | i3pystatus/calendar/google.py | Google.refresh_events | def refresh_events(self):
"""
Retrieve the next N events from Google.
"""
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,
singleEvents=True,
orderBy='startTime',
timeZone='utc'
).execute()
self.events.clear()
for event in events_result.get('items', []):
self.events.append(GoogleCalendarEvent(event))
except HttpError as e:
if e.resp.status in (500, 503):
self.logger.warn("GoogleCalendar received %s while retrieving events" % e.resp.status)
else:
raise | python | def refresh_events(self):
"""
Retrieve the next N events from Google.
"""
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,
singleEvents=True,
orderBy='startTime',
timeZone='utc'
).execute()
self.events.clear()
for event in events_result.get('items', []):
self.events.append(GoogleCalendarEvent(event))
except HttpError as e:
if e.resp.status in (500, 503):
self.logger.warn("GoogleCalendar received %s while retrieving events" % e.resp.status)
else:
raise | [
"def",
"refresh_events",
"(",
"self",
")",
":",
"now",
"=",
"datetime",
".",
"datetime",
".",
"now",
"(",
"tz",
"=",
"pytz",
".",
"UTC",
")",
"try",
":",
"now",
",",
"later",
"=",
"self",
".",
"get_timerange_formatted",
"(",
"now",
")",
"events_result"... | Retrieve the next N events from Google. | [
"Retrieve",
"the",
"next",
"N",
"events",
"from",
"Google",
"."
] | 14cfde967cecf79b40e223e35a04600f4c875af7 | https://github.com/enkore/i3pystatus/blob/14cfde967cecf79b40e223e35a04600f4c875af7/i3pystatus/calendar/google.py#L105-L128 | train | 203,751 |
enkore/i3pystatus | i3pystatus/core/util.py | lchop | 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
"""
if string.startswith(prefix):
return string[len(prefix):]
return string | python | 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
"""
if string.startswith(prefix):
return string[len(prefix):]
return string | [
"def",
"lchop",
"(",
"string",
",",
"prefix",
")",
":",
"if",
"string",
".",
"startswith",
"(",
"prefix",
")",
":",
"return",
"string",
"[",
"len",
"(",
"prefix",
")",
":",
"]",
"return",
"string"
] | Removes a prefix from string
:param string: String, possibly prefixed with prefix
:param prefix: Prefix to remove from string
:returns: string without the prefix | [
"Removes",
"a",
"prefix",
"from",
"string"
] | 14cfde967cecf79b40e223e35a04600f4c875af7 | https://github.com/enkore/i3pystatus/blob/14cfde967cecf79b40e223e35a04600f4c875af7/i3pystatus/core/util.py#L12-L21 | train | 203,752 |
enkore/i3pystatus | i3pystatus/core/util.py | popwhile | 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)
"""
while iterable:
item = iterable.pop()
if predicate(item):
yield item
else:
break | python | 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)
"""
while iterable:
item = iterable.pop()
if predicate(item):
yield item
else:
break | [
"def",
"popwhile",
"(",
"predicate",
",",
"iterable",
")",
":",
"while",
"iterable",
":",
"item",
"=",
"iterable",
".",
"pop",
"(",
")",
"if",
"predicate",
"(",
"item",
")",
":",
"yield",
"item",
"else",
":",
"break"
] | 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) | [
"Generator",
"function",
"yielding",
"items",
"of",
"iterable",
"while",
"predicate",
"holds",
"for",
"each",
"item"
] | 14cfde967cecf79b40e223e35a04600f4c875af7 | https://github.com/enkore/i3pystatus/blob/14cfde967cecf79b40e223e35a04600f4c875af7/i3pystatus/core/util.py#L24-L36 | train | 203,753 |
enkore/i3pystatus | i3pystatus/core/util.py | round_dict | 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.
"""
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) | python | 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.
"""
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",
")",
":",
"if",
"places",
"is",
"None",
":",
"for",
"key",
",",
"value",
"in",
"dic",
".",
"items",
"(",
")",
":",
"dic",
"[",
"key",
"]",
"=",
"round",
"(",
"value",
")",
"else",
":",
"for",
"key... | Rounds all values in a dict containing only numeric types to `places` decimal places.
If places is None, round to INT. | [
"Rounds",
"all",
"values",
"in",
"a",
"dict",
"containing",
"only",
"numeric",
"types",
"to",
"places",
"decimal",
"places",
".",
"If",
"places",
"is",
"None",
"round",
"to",
"INT",
"."
] | 14cfde967cecf79b40e223e35a04600f4c875af7 | https://github.com/enkore/i3pystatus/blob/14cfde967cecf79b40e223e35a04600f4c875af7/i3pystatus/core/util.py#L54-L64 | train | 203,754 |
enkore/i3pystatus | i3pystatus/core/util.py | flatten | 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
"""
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 | python | 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
"""
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",
")",
":",
"l",
"=",
"list",
"(",
"l",
")",
"i",
"=",
"0",
"while",
"i",
"<",
"len",
"(",
"l",
")",
":",
"while",
"isinstance",
"(",
"l",
"[",
"i",
"]",
",",
"list",
")",
":",
"if",
"not",
"l",
"[",
"i",
"]",
... | 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 | [
"Flattens",
"a",
"hierarchy",
"of",
"nested",
"lists",
"into",
"a",
"single",
"list",
"containing",
"all",
"elements",
"in",
"order"
] | 14cfde967cecf79b40e223e35a04600f4c875af7 | https://github.com/enkore/i3pystatus/blob/14cfde967cecf79b40e223e35a04600f4c875af7/i3pystatus/core/util.py#L153-L171 | train | 203,755 |
enkore/i3pystatus | i3pystatus/core/util.py | formatp | 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 nested group do not count as fields in
the enclosing group, i.e. the enclosing group will evaluate to an empty
string even if a nested group would be eligible for formatting. Nesting is
thus equivalent to a logical or of all enclosing groups with the enclosed
group.
Escaped brackets, i.e. \\\\[ and \\\\] are copied verbatim to output.
:param string: Format string
:param kwargs: keyword arguments providing data for the format string
:returns: Formatted string
"""
def build_stack(string):
"""
Builds a stack with OpeningBracket, ClosingBracket and String tokens.
Tokens have a level property denoting their nesting level.
They also have a string property containing associated text (empty for
all tokens but String tokens).
"""
class Token:
string = ""
class OpeningBracket(Token):
pass
class ClosingBracket(Token):
pass
class String(Token):
def __init__(self, str):
self.string = str
TOKENS = {
"[": OpeningBracket,
"]": ClosingBracket,
}
stack = []
# Index of next unconsumed char
next = 0
# Last consumed char
prev = ""
# Current char
char = ""
# Current level
level = 0
while next < len(string):
prev = char
char = string[next]
next += 1
if prev != "\\" and char in TOKENS:
token = TOKENS[char]()
token.index = next
if char == "]":
level -= 1
token.level = level
if char == "[":
level += 1
stack.append(token)
else:
if stack and isinstance(stack[-1], String):
stack[-1].string += char
else:
token = String(char)
token.level = level
stack.append(token)
return stack
def build_tree(items, level=0):
"""
Builds a list-of-lists tree (in forward order) from a stack (reversed order),
and formats the elements on the fly, discarding everything not eligible for
inclusion.
"""
subtree = []
while items:
nested = []
while items[0].level > level:
nested.append(items.pop(0))
if nested:
subtree.append(build_tree(nested, level + 1))
item = items.pop(0)
if item.string:
string = item.string
if level == 0:
subtree.append(string.format(**kwargs))
else:
fields = re.findall(r"({(\w+)[^}]*})", string)
successful_fields = 0
for fieldspec, fieldname in fields:
if kwargs.get(fieldname, False):
successful_fields += 1
if successful_fields == len(fields):
subtree.append(string.format(**kwargs))
else:
return []
return subtree
def merge_tree(items):
return "".join(flatten(items)).replace(r"\]", "]").replace(r"\[", "[")
stack = build_stack(string)
tree = build_tree(stack, 0)
return merge_tree(tree) | python | 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 nested group do not count as fields in
the enclosing group, i.e. the enclosing group will evaluate to an empty
string even if a nested group would be eligible for formatting. Nesting is
thus equivalent to a logical or of all enclosing groups with the enclosed
group.
Escaped brackets, i.e. \\\\[ and \\\\] are copied verbatim to output.
:param string: Format string
:param kwargs: keyword arguments providing data for the format string
:returns: Formatted string
"""
def build_stack(string):
"""
Builds a stack with OpeningBracket, ClosingBracket and String tokens.
Tokens have a level property denoting their nesting level.
They also have a string property containing associated text (empty for
all tokens but String tokens).
"""
class Token:
string = ""
class OpeningBracket(Token):
pass
class ClosingBracket(Token):
pass
class String(Token):
def __init__(self, str):
self.string = str
TOKENS = {
"[": OpeningBracket,
"]": ClosingBracket,
}
stack = []
# Index of next unconsumed char
next = 0
# Last consumed char
prev = ""
# Current char
char = ""
# Current level
level = 0
while next < len(string):
prev = char
char = string[next]
next += 1
if prev != "\\" and char in TOKENS:
token = TOKENS[char]()
token.index = next
if char == "]":
level -= 1
token.level = level
if char == "[":
level += 1
stack.append(token)
else:
if stack and isinstance(stack[-1], String):
stack[-1].string += char
else:
token = String(char)
token.level = level
stack.append(token)
return stack
def build_tree(items, level=0):
"""
Builds a list-of-lists tree (in forward order) from a stack (reversed order),
and formats the elements on the fly, discarding everything not eligible for
inclusion.
"""
subtree = []
while items:
nested = []
while items[0].level > level:
nested.append(items.pop(0))
if nested:
subtree.append(build_tree(nested, level + 1))
item = items.pop(0)
if item.string:
string = item.string
if level == 0:
subtree.append(string.format(**kwargs))
else:
fields = re.findall(r"({(\w+)[^}]*})", string)
successful_fields = 0
for fieldspec, fieldname in fields:
if kwargs.get(fieldname, False):
successful_fields += 1
if successful_fields == len(fields):
subtree.append(string.format(**kwargs))
else:
return []
return subtree
def merge_tree(items):
return "".join(flatten(items)).replace(r"\]", "]").replace(r"\[", "[")
stack = build_stack(string)
tree = build_tree(stack, 0)
return merge_tree(tree) | [
"def",
"formatp",
"(",
"string",
",",
"*",
"*",
"kwargs",
")",
":",
"def",
"build_stack",
"(",
"string",
")",
":",
"\"\"\"\n Builds a stack with OpeningBracket, ClosingBracket and String tokens.\n Tokens have a level property denoting their nesting level.\n They ... | 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 nested group do not count as fields in
the enclosing group, i.e. the enclosing group will evaluate to an empty
string even if a nested group would be eligible for formatting. Nesting is
thus equivalent to a logical or of all enclosing groups with the enclosed
group.
Escaped brackets, i.e. \\\\[ and \\\\] are copied verbatim to output.
:param string: Format string
:param kwargs: keyword arguments providing data for the format string
:returns: Formatted string | [
"Function",
"for",
"advanced",
"format",
"strings",
"with",
"partial",
"formatting"
] | 14cfde967cecf79b40e223e35a04600f4c875af7 | https://github.com/enkore/i3pystatus/blob/14cfde967cecf79b40e223e35a04600f4c875af7/i3pystatus/core/util.py#L174-L292 | train | 203,756 |
enkore/i3pystatus | i3pystatus/core/util.py | require | 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`
"""
def decorator(method):
@functools.wraps(method)
def wrapper(*args, **kwargs):
if predicate():
return method(*args, **kwargs)
return None
return wrapper
return decorator | python | 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`
"""
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",
")",
":",
"def",
"decorator",
"(",
"method",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"method",
")",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"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` | [
"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",
"."
] | 14cfde967cecf79b40e223e35a04600f4c875af7 | https://github.com/enkore/i3pystatus/blob/14cfde967cecf79b40e223e35a04600f4c875af7/i3pystatus/core/util.py#L346-L369 | train | 203,757 |
enkore/i3pystatus | i3pystatus/core/util.py | make_graph | 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 'braille-snake').
:returns: Bar as a string
"""
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(bar) - 1
if extent == 0:
graph = '_' * len(values)
else:
graph = ''.join(bar[int((n - mn) / extent * bar_count)] for n in values)
elif style in ['braille-fill', 'braille-peak', 'braille-snake']:
# idea from https://github.com/asciimoo/drawille
# unicode values from http://en.wikipedia.org/wiki/Braille
vpad = values if len(values) % 2 == 0 else values + [mn]
vscale = [round(4 * (vp - mn) / extent) for vp in vpad]
l = len(vscale) // 2
# do the 2-character collapse separately for clarity
if 'fill' in style:
vbits = [[0, 0x40, 0x44, 0x46, 0x47][vs] for vs in vscale]
elif 'peak' in style:
vbits = [[0, 0x40, 0x04, 0x02, 0x01][vs] for vs in vscale]
else:
assert('snake' in style)
# there are a few choices for what to put last in vb2.
# arguable vscale[-1] from the _previous_ call is best.
vb2 = [vscale[0]] + vscale + [0]
vbits = []
for i in range(1, l + 1):
c = 0
for j in range(min(vb2[i - 1], vb2[i], vb2[i + 1]), vb2[i] + 1):
c |= [0, 0x40, 0x04, 0x02, 0x01][j]
vbits.append(c)
# 2-character collapse
graph = ''
for i in range(0, l, 2):
b1 = vbits[i]
b2 = vbits[i + 1]
if b2 & 0x40:
b2 = b2 - 0x30
b2 = b2 << 3
graph += chr(0x2800 + b1 + b2)
else:
raise NotImplementedError("Graph drawing style '%s' unimplemented." % style)
return graph | python | 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 'braille-snake').
:returns: Bar as a string
"""
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(bar) - 1
if extent == 0:
graph = '_' * len(values)
else:
graph = ''.join(bar[int((n - mn) / extent * bar_count)] for n in values)
elif style in ['braille-fill', 'braille-peak', 'braille-snake']:
# idea from https://github.com/asciimoo/drawille
# unicode values from http://en.wikipedia.org/wiki/Braille
vpad = values if len(values) % 2 == 0 else values + [mn]
vscale = [round(4 * (vp - mn) / extent) for vp in vpad]
l = len(vscale) // 2
# do the 2-character collapse separately for clarity
if 'fill' in style:
vbits = [[0, 0x40, 0x44, 0x46, 0x47][vs] for vs in vscale]
elif 'peak' in style:
vbits = [[0, 0x40, 0x04, 0x02, 0x01][vs] for vs in vscale]
else:
assert('snake' in style)
# there are a few choices for what to put last in vb2.
# arguable vscale[-1] from the _previous_ call is best.
vb2 = [vscale[0]] + vscale + [0]
vbits = []
for i in range(1, l + 1):
c = 0
for j in range(min(vb2[i - 1], vb2[i], vb2[i + 1]), vb2[i] + 1):
c |= [0, 0x40, 0x04, 0x02, 0x01][j]
vbits.append(c)
# 2-character collapse
graph = ''
for i in range(0, l, 2):
b1 = vbits[i]
b2 = vbits[i + 1]
if b2 & 0x40:
b2 = b2 - 0x30
b2 = b2 << 3
graph += chr(0x2800 + b1 + b2)
else:
raise NotImplementedError("Graph drawing style '%s' unimplemented." % style)
return graph | [
"def",
"make_graph",
"(",
"values",
",",
"lower_limit",
"=",
"0.0",
",",
"upper_limit",
"=",
"100.0",
",",
"style",
"=",
"\"blocks\"",
")",
":",
"values",
"=",
"[",
"float",
"(",
"n",
")",
"for",
"n",
"in",
"values",
"]",
"mn",
",",
"mx",
"=",
"min... | 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 'braille-snake').
:returns: Bar as a string | [
"Draws",
"a",
"graph",
"made",
"of",
"unicode",
"characters",
"."
] | 14cfde967cecf79b40e223e35a04600f4c875af7 | https://github.com/enkore/i3pystatus/blob/14cfde967cecf79b40e223e35a04600f4c875af7/i3pystatus/core/util.py#L440-L500 | train | 203,758 |
enkore/i3pystatus | i3pystatus/core/util.py | make_vertical_bar | 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
"""
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 | python | 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
"""
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",
")",
":",
"bar",
"=",
"' _▁▂▃▄▅▆▇█'",
"percentage",
"//=",
"10",
"percentage",
"=",
"int",
"(",
"percentage",
")",
"if",
"percentage",
"<",
"0",
":",
"output",
"=",
"bar",
"[",
"0",
... | 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 | [
"Draws",
"a",
"vertical",
"bar",
"made",
"of",
"unicode",
"characters",
"."
] | 14cfde967cecf79b40e223e35a04600f4c875af7 | https://github.com/enkore/i3pystatus/blob/14cfde967cecf79b40e223e35a04600f4c875af7/i3pystatus/core/util.py#L503-L520 | train | 203,759 |
enkore/i3pystatus | i3pystatus/core/util.py | get_module | 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(...)
# other modules etc.
@get_module
def display_ip_verbose(module):
execute('sh -c "ip addr show dev {dev} | xmessage -file -"'.format(dev=module.interface))
status.register("network", interface="wlan1", on_leftclick=display_ip_verbose)
"""
@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 stack
function(self, *args, **kwargs)
return call_wrapper | python | 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(...)
# other modules etc.
@get_module
def display_ip_verbose(module):
execute('sh -c "ip addr show dev {dev} | xmessage -file -"'.format(dev=module.interface))
status.register("network", interface="wlan1", on_leftclick=display_ip_verbose)
"""
@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 stack
function(self, *args, **kwargs)
return call_wrapper | [
"def",
"get_module",
"(",
"function",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"function",
")",
"def",
"call_wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"stack",
"=",
"inspect",
".",
"stack",
"(",
")",
"caller_frame_info",
"=",... | 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(...)
# other modules etc.
@get_module
def display_ip_verbose(module):
execute('sh -c "ip addr show dev {dev} | xmessage -file -"'.format(dev=module.interface))
status.register("network", interface="wlan1", on_leftclick=display_ip_verbose) | [
"Function",
"decorator",
"for",
"retrieving",
"the",
"self",
"argument",
"from",
"the",
"stack",
"."
] | 14cfde967cecf79b40e223e35a04600f4c875af7 | https://github.com/enkore/i3pystatus/blob/14cfde967cecf79b40e223e35a04600f4c875af7/i3pystatus/core/util.py#L673-L698 | train | 203,760 |
trolldbois/ctypeslib | ctypeslib/codegen/typehandler.py | TypeHandler.init_fundamental_types | def init_fundamental_types(self):
"""Registers all fundamental typekind handlers"""
for _id in range(2, 25):
setattr(self, TypeKind.from_id(_id).name,
self._handle_fundamental_types) | python | def init_fundamental_types(self):
"""Registers all fundamental typekind handlers"""
for _id in range(2, 25):
setattr(self, TypeKind.from_id(_id).name,
self._handle_fundamental_types) | [
"def",
"init_fundamental_types",
"(",
"self",
")",
":",
"for",
"_id",
"in",
"range",
"(",
"2",
",",
"25",
")",
":",
"setattr",
"(",
"self",
",",
"TypeKind",
".",
"from_id",
"(",
"_id",
")",
".",
"name",
",",
"self",
".",
"_handle_fundamental_types",
")... | Registers all fundamental typekind handlers | [
"Registers",
"all",
"fundamental",
"typekind",
"handlers"
] | 2aeb1942a5a32a5cc798c287cd0d9e684a0181a8 | https://github.com/trolldbois/ctypeslib/blob/2aeb1942a5a32a5cc798c287cd0d9e684a0181a8/ctypeslib/codegen/typehandler.py#L31-L35 | train | 203,761 |
trolldbois/ctypeslib | ctypeslib/codegen/typehandler.py | TypeHandler._handle_fundamental_types | def _handle_fundamental_types(self, typ):
"""
Handles POD types nodes.
see init_fundamental_types for the registration.
"""
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) | python | def _handle_fundamental_types(self, typ):
"""
Handles POD types nodes.
see init_fundamental_types for the registration.
"""
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",
")",
":",
"ctypesname",
"=",
"self",
".",
"get_ctypes_name",
"(",
"typ",
".",
"kind",
")",
"if",
"typ",
".",
"kind",
"==",
"TypeKind",
".",
"VOID",
":",
"size",
"=",
"align",
"=",
"1",
"else"... | Handles POD types nodes.
see init_fundamental_types for the registration. | [
"Handles",
"POD",
"types",
"nodes",
".",
"see",
"init_fundamental_types",
"for",
"the",
"registration",
"."
] | 2aeb1942a5a32a5cc798c287cd0d9e684a0181a8 | https://github.com/trolldbois/ctypeslib/blob/2aeb1942a5a32a5cc798c287cd0d9e684a0181a8/ctypeslib/codegen/typehandler.py#L37-L48 | train | 203,762 |
trolldbois/ctypeslib | ctypeslib/codegen/typehandler.py | TypeHandler.TYPEDEF | def TYPEDEF(self, _cursor_type):
"""
Handles TYPEDEF statement.
"""
_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(_decl)
return obj | python | def TYPEDEF(self, _cursor_type):
"""
Handles TYPEDEF statement.
"""
_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(_decl)
return obj | [
"def",
"TYPEDEF",
"(",
"self",
",",
"_cursor_type",
")",
":",
"_decl",
"=",
"_cursor_type",
".",
"get_declaration",
"(",
")",
"name",
"=",
"self",
".",
"get_unique_name",
"(",
"_decl",
")",
"if",
"self",
".",
"is_registered",
"(",
"name",
")",
":",
"obj"... | Handles TYPEDEF statement. | [
"Handles",
"TYPEDEF",
"statement",
"."
] | 2aeb1942a5a32a5cc798c287cd0d9e684a0181a8 | https://github.com/trolldbois/ctypeslib/blob/2aeb1942a5a32a5cc798c287cd0d9e684a0181a8/ctypeslib/codegen/typehandler.py#L74-L85 | train | 203,763 |
trolldbois/ctypeslib | ctypeslib/codegen/typehandler.py | TypeHandler.ENUM | def ENUM(self, _cursor_type):
"""
Handles ENUM typedef.
"""
_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)
return obj | python | def ENUM(self, _cursor_type):
"""
Handles ENUM typedef.
"""
_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)
return obj | [
"def",
"ENUM",
"(",
"self",
",",
"_cursor_type",
")",
":",
"_decl",
"=",
"_cursor_type",
".",
"get_declaration",
"(",
")",
"name",
"=",
"self",
".",
"get_unique_name",
"(",
"_decl",
")",
"if",
"self",
".",
"is_registered",
"(",
"name",
")",
":",
"obj",
... | Handles ENUM typedef. | [
"Handles",
"ENUM",
"typedef",
"."
] | 2aeb1942a5a32a5cc798c287cd0d9e684a0181a8 | https://github.com/trolldbois/ctypeslib/blob/2aeb1942a5a32a5cc798c287cd0d9e684a0181a8/ctypeslib/codegen/typehandler.py#L88-L99 | train | 203,764 |
trolldbois/ctypeslib | ctypeslib/codegen/typehandler.py | TypeHandler.POINTER | def POINTER(self, _cursor_type):
"""
Handles POINTER types.
"""
#
# 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)
# get pointer size
size = _cursor_type.get_size() # not size of pointee
align = _cursor_type.get_align()
log.debug(
"POINTER: size:%d align:%d typ:%s",
size, align, _type.kind)
if self.is_fundamental_type(_type):
p_type = self.parse_cursor_type(_type)
elif self.is_pointer_type(_type) or self.is_array_type(_type):
p_type = self.parse_cursor_type(_type)
elif _type.kind == TypeKind.FUNCTIONPROTO:
p_type = self.parse_cursor_type(_type)
elif _type.kind == TypeKind.FUNCTIONNOPROTO:
p_type = self.parse_cursor_type(_type)
else: # elif _type.kind == TypeKind.RECORD:
# check registration
decl = _type.get_declaration()
decl_name = self.get_unique_name(decl)
# Type is already defined OR will be defined later.
if self.is_registered(decl_name):
p_type = self.get_registered(decl_name)
else: # forward declaration, without looping
log.debug(
'POINTER: %s type was not previously declared',
decl_name)
try:
p_type = self.parse_cursor(decl)
except InvalidDefinitionError as e:
# no declaration in source file. Fake a void *
p_type = typedesc.FundamentalType('None', 1, 1)
comment = "InvalidDefinitionError"
log.debug("POINTER: pointee type_name:'%s'", _p_type_name)
# return the pointer
obj = typedesc.PointerType(p_type, size, align)
obj.location = p_type.location
if comment is not None:
obj.comment = comment
return obj | python | def POINTER(self, _cursor_type):
"""
Handles POINTER types.
"""
#
# 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)
# get pointer size
size = _cursor_type.get_size() # not size of pointee
align = _cursor_type.get_align()
log.debug(
"POINTER: size:%d align:%d typ:%s",
size, align, _type.kind)
if self.is_fundamental_type(_type):
p_type = self.parse_cursor_type(_type)
elif self.is_pointer_type(_type) or self.is_array_type(_type):
p_type = self.parse_cursor_type(_type)
elif _type.kind == TypeKind.FUNCTIONPROTO:
p_type = self.parse_cursor_type(_type)
elif _type.kind == TypeKind.FUNCTIONNOPROTO:
p_type = self.parse_cursor_type(_type)
else: # elif _type.kind == TypeKind.RECORD:
# check registration
decl = _type.get_declaration()
decl_name = self.get_unique_name(decl)
# Type is already defined OR will be defined later.
if self.is_registered(decl_name):
p_type = self.get_registered(decl_name)
else: # forward declaration, without looping
log.debug(
'POINTER: %s type was not previously declared',
decl_name)
try:
p_type = self.parse_cursor(decl)
except InvalidDefinitionError as e:
# no declaration in source file. Fake a void *
p_type = typedesc.FundamentalType('None', 1, 1)
comment = "InvalidDefinitionError"
log.debug("POINTER: pointee type_name:'%s'", _p_type_name)
# return the pointer
obj = typedesc.PointerType(p_type, size, align)
obj.location = p_type.location
if comment is not None:
obj.comment = comment
return obj | [
"def",
"POINTER",
"(",
"self",
",",
"_cursor_type",
")",
":",
"#",
"# FIXME catch InvalidDefinitionError and return a void *",
"#",
"#",
"# we shortcut to canonical typedefs and to pointee canonical defs",
"comment",
"=",
"None",
"_type",
"=",
"_cursor_type",
".",
"get_pointe... | Handles POINTER types. | [
"Handles",
"POINTER",
"types",
"."
] | 2aeb1942a5a32a5cc798c287cd0d9e684a0181a8 | https://github.com/trolldbois/ctypeslib/blob/2aeb1942a5a32a5cc798c287cd0d9e684a0181a8/ctypeslib/codegen/typehandler.py#L102-L151 | train | 203,765 |
trolldbois/ctypeslib | ctypeslib/codegen/typehandler.py | TypeHandler._array_handler | def _array_handler(self, _cursor_type):
"""
Handles all array types.
Resolves it's element type and makes a Array typedesc.
"""
# 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: Incomplete Array handling at end of record.
# https://gcc.gnu.org/onlinedocs/gcc/Zero-Length.html
# FIXME VARIABLEARRAY DEPENDENTSIZEDARRAY
_array_type = _type.get_array_element_type() # .get_canonical()
if self.is_fundamental_type(_array_type):
_subtype = self.parse_cursor_type(_array_type)
elif self.is_pointer_type(_array_type):
# code.interact(local=locals())
# pointers to POD have no declaration ??
# FIXME test_struct_with_pointer x_n_t g[1]
_subtype = self.parse_cursor_type(_array_type)
elif self.is_array_type(_array_type):
_subtype = self.parse_cursor_type(_array_type)
else:
_subtype_decl = _array_type.get_declaration()
_subtype = self.parse_cursor(_subtype_decl)
# if _subtype_decl.kind == CursorKind.NO_DECL_FOUND:
# pass
#_subtype_name = self.get_unique_name(_subtype_decl)
#_subtype = self.get_registered(_subtype_name)
obj = typedesc.ArrayType(_subtype, size)
obj.location = _subtype.location
return obj | python | def _array_handler(self, _cursor_type):
"""
Handles all array types.
Resolves it's element type and makes a Array typedesc.
"""
# 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: Incomplete Array handling at end of record.
# https://gcc.gnu.org/onlinedocs/gcc/Zero-Length.html
# FIXME VARIABLEARRAY DEPENDENTSIZEDARRAY
_array_type = _type.get_array_element_type() # .get_canonical()
if self.is_fundamental_type(_array_type):
_subtype = self.parse_cursor_type(_array_type)
elif self.is_pointer_type(_array_type):
# code.interact(local=locals())
# pointers to POD have no declaration ??
# FIXME test_struct_with_pointer x_n_t g[1]
_subtype = self.parse_cursor_type(_array_type)
elif self.is_array_type(_array_type):
_subtype = self.parse_cursor_type(_array_type)
else:
_subtype_decl = _array_type.get_declaration()
_subtype = self.parse_cursor(_subtype_decl)
# if _subtype_decl.kind == CursorKind.NO_DECL_FOUND:
# pass
#_subtype_name = self.get_unique_name(_subtype_decl)
#_subtype = self.get_registered(_subtype_name)
obj = typedesc.ArrayType(_subtype, size)
obj.location = _subtype.location
return obj | [
"def",
"_array_handler",
"(",
"self",
",",
"_cursor_type",
")",
":",
"# 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_arr... | Handles all array types.
Resolves it's element type and makes a Array typedesc. | [
"Handles",
"all",
"array",
"types",
".",
"Resolves",
"it",
"s",
"element",
"type",
"and",
"makes",
"a",
"Array",
"typedesc",
"."
] | 2aeb1942a5a32a5cc798c287cd0d9e684a0181a8 | https://github.com/trolldbois/ctypeslib/blob/2aeb1942a5a32a5cc798c287cd0d9e684a0181a8/ctypeslib/codegen/typehandler.py#L154-L187 | train | 203,766 |
trolldbois/ctypeslib | ctypeslib/codegen/typehandler.py | TypeHandler.FUNCTIONPROTO | def FUNCTIONPROTO(self, _cursor_type):
"""Handles function prototype."""
# 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.argument_types()):
arg = typedesc.Argument(
"a%d" %
(i),
self.parse_cursor_type(_attr_type))
obj.add_argument(arg)
self.set_location(obj, None)
return obj | python | def FUNCTIONPROTO(self, _cursor_type):
"""Handles function prototype."""
# 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.argument_types()):
arg = typedesc.Argument(
"a%d" %
(i),
self.parse_cursor_type(_attr_type))
obj.add_argument(arg)
self.set_location(obj, None)
return obj | [
"def",
"FUNCTIONPROTO",
"(",
"self",
",",
"_cursor_type",
")",
":",
"# id, returns, attributes",
"returns",
"=",
"_cursor_type",
".",
"get_result",
"(",
")",
"# if self.is_fundamental_type(returns):",
"returns",
"=",
"self",
".",
"parse_cursor_type",
"(",
"returns",
"... | Handles function prototype. | [
"Handles",
"function",
"prototype",
"."
] | 2aeb1942a5a32a5cc798c287cd0d9e684a0181a8 | https://github.com/trolldbois/ctypeslib/blob/2aeb1942a5a32a5cc798c287cd0d9e684a0181a8/ctypeslib/codegen/typehandler.py#L195-L210 | train | 203,767 |
trolldbois/ctypeslib | ctypeslib/codegen/typehandler.py | TypeHandler.FUNCTIONNOPROTO | def FUNCTIONNOPROTO(self, _cursor_type):
"""Handles function with no prototype."""
# 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.
self.set_location(obj, None)
return obj | python | def FUNCTIONNOPROTO(self, _cursor_type):
"""Handles function with no prototype."""
# 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.
self.set_location(obj, None)
return obj | [
"def",
"FUNCTIONNOPROTO",
"(",
"self",
",",
"_cursor_type",
")",
":",
"# id, returns, attributes",
"returns",
"=",
"_cursor_type",
".",
"get_result",
"(",
")",
"# if self.is_fundamental_type(returns):",
"returns",
"=",
"self",
".",
"parse_cursor_type",
"(",
"returns",
... | Handles function with no prototype. | [
"Handles",
"function",
"with",
"no",
"prototype",
"."
] | 2aeb1942a5a32a5cc798c287cd0d9e684a0181a8 | https://github.com/trolldbois/ctypeslib/blob/2aeb1942a5a32a5cc798c287cd0d9e684a0181a8/ctypeslib/codegen/typehandler.py#L213-L223 | train | 203,768 |
trolldbois/ctypeslib | ctypeslib/codegen/typehandler.py | TypeHandler.UNEXPOSED | def UNEXPOSED(self, _cursor_type):
"""
Handles unexposed types.
Returns the canonical type instead.
"""
_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 | python | def UNEXPOSED(self, _cursor_type):
"""
Handles unexposed types.
Returns the canonical type instead.
"""
_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",
")",
":",
"_decl",
"=",
"_cursor_type",
".",
"get_declaration",
"(",
")",
"name",
"=",
"self",
".",
"get_unique_name",
"(",
"_decl",
")",
"# _cursor)",
"if",
"self",
".",
"is_registered",
"(",
"name",
"... | Handles unexposed types.
Returns the canonical type instead. | [
"Handles",
"unexposed",
"types",
".",
"Returns",
"the",
"canonical",
"type",
"instead",
"."
] | 2aeb1942a5a32a5cc798c287cd0d9e684a0181a8 | https://github.com/trolldbois/ctypeslib/blob/2aeb1942a5a32a5cc798c287cd0d9e684a0181a8/ctypeslib/codegen/typehandler.py#L247-L258 | train | 203,769 |
trolldbois/ctypeslib | ctypeslib/codegen/cursorhandler.py | CursorHandler.INIT_LIST_EXPR | def INIT_LIST_EXPR(self, cursor):
"""Returns a list of literal values."""
values = [self.parse_cursor(child)
for child in list(cursor.get_children())]
return values | python | def INIT_LIST_EXPR(self, cursor):
"""Returns a list of literal values."""
values = [self.parse_cursor(child)
for child in list(cursor.get_children())]
return values | [
"def",
"INIT_LIST_EXPR",
"(",
"self",
",",
"cursor",
")",
":",
"values",
"=",
"[",
"self",
".",
"parse_cursor",
"(",
"child",
")",
"for",
"child",
"in",
"list",
"(",
"cursor",
".",
"get_children",
"(",
")",
")",
"]",
"return",
"values"
] | Returns a list of literal values. | [
"Returns",
"a",
"list",
"of",
"literal",
"values",
"."
] | 2aeb1942a5a32a5cc798c287cd0d9e684a0181a8 | https://github.com/trolldbois/ctypeslib/blob/2aeb1942a5a32a5cc798c287cd0d9e684a0181a8/ctypeslib/codegen/cursorhandler.py#L85-L89 | train | 203,770 |
trolldbois/ctypeslib | ctypeslib/codegen/cursorhandler.py | CursorHandler.ENUM_CONSTANT_DECL | def ENUM_CONSTANT_DECL(self, cursor):
"""Gets the enumeration values"""
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 | python | def ENUM_CONSTANT_DECL(self, cursor):
"""Gets the enumeration values"""
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",
")",
":",
"name",
"=",
"cursor",
".",
"displayname",
"value",
"=",
"cursor",
".",
"enum_value",
"pname",
"=",
"self",
".",
"get_unique_name",
"(",
"cursor",
".",
"semantic_parent",
")",
"parent",
"=",
... | Gets the enumeration values | [
"Gets",
"the",
"enumeration",
"values"
] | 2aeb1942a5a32a5cc798c287cd0d9e684a0181a8 | https://github.com/trolldbois/ctypeslib/blob/2aeb1942a5a32a5cc798c287cd0d9e684a0181a8/ctypeslib/codegen/cursorhandler.py#L132-L140 | train | 203,771 |
trolldbois/ctypeslib | ctypeslib/codegen/cursorhandler.py | CursorHandler.ENUM_DECL | def ENUM_DECL(self, cursor):
"""Gets the enumeration declaration."""
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, cursor)
self.set_comment(obj, cursor)
# parse all children
for child in cursor.get_children():
self.parse_cursor(child) # FIXME, where is the starElement
return obj | python | def ENUM_DECL(self, cursor):
"""Gets the enumeration declaration."""
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, cursor)
self.set_comment(obj, cursor)
# parse all children
for child in cursor.get_children():
self.parse_cursor(child) # FIXME, where is the starElement
return obj | [
"def",
"ENUM_DECL",
"(",
"self",
",",
"cursor",
")",
":",
"name",
"=",
"self",
".",
"get_unique_name",
"(",
"cursor",
")",
"if",
"self",
".",
"is_registered",
"(",
"name",
")",
":",
"return",
"self",
".",
"get_registered",
"(",
"name",
")",
"align",
"=... | Gets the enumeration declaration. | [
"Gets",
"the",
"enumeration",
"declaration",
"."
] | 2aeb1942a5a32a5cc798c287cd0d9e684a0181a8 | https://github.com/trolldbois/ctypeslib/blob/2aeb1942a5a32a5cc798c287cd0d9e684a0181a8/ctypeslib/codegen/cursorhandler.py#L143-L156 | train | 203,772 |
trolldbois/ctypeslib | ctypeslib/codegen/cursorhandler.py | CursorHandler.FUNCTION_DECL | def FUNCTION_DECL(self, cursor):
"""Handles function declaration"""
# 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, attributes, extern)
for arg in cursor.get_arguments():
arg_obj = self.parse_cursor(arg)
# if arg_obj is None:
# code.interact(local=locals())
obj.add_argument(arg_obj)
# code.interact(local=locals())
self.register(name, obj)
self.set_location(obj, cursor)
self.set_comment(obj, cursor)
return obj | python | def FUNCTION_DECL(self, cursor):
"""Handles function declaration"""
# 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, attributes, extern)
for arg in cursor.get_arguments():
arg_obj = self.parse_cursor(arg)
# if arg_obj is None:
# code.interact(local=locals())
obj.add_argument(arg_obj)
# code.interact(local=locals())
self.register(name, obj)
self.set_location(obj, cursor)
self.set_comment(obj, cursor)
return obj | [
"def",
"FUNCTION_DECL",
"(",
"self",
",",
"cursor",
")",
":",
"# FIXME to UT",
"name",
"=",
"self",
".",
"get_unique_name",
"(",
"cursor",
")",
"if",
"self",
".",
"is_registered",
"(",
"name",
")",
":",
"return",
"self",
".",
"get_registered",
"(",
"name",... | Handles function declaration | [
"Handles",
"function",
"declaration"
] | 2aeb1942a5a32a5cc798c287cd0d9e684a0181a8 | https://github.com/trolldbois/ctypeslib/blob/2aeb1942a5a32a5cc798c287cd0d9e684a0181a8/ctypeslib/codegen/cursorhandler.py#L159-L178 | train | 203,773 |
trolldbois/ctypeslib | ctypeslib/codegen/cursorhandler.py | CursorHandler.PARM_DECL | def PARM_DECL(self, cursor):
"""Handles parameter declarations."""
# 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_type(_type)):
_argtype = self.parse_cursor_type(_type)
else: # FIXME: Which UT/case ? size_t in stdio.h for example.
_argtype_decl = _type.get_declaration()
_argtype_name = self.get_unique_name(_argtype_decl)
if not self.is_registered(_argtype_name):
log.info('This param type is not declared: %s', _argtype_name)
_argtype = self.parse_cursor_type(_type)
else:
_argtype = self.get_registered(_argtype_name)
obj = typedesc.Argument(_name, _argtype)
self.set_location(obj, cursor)
self.set_comment(obj, cursor)
return obj | python | def PARM_DECL(self, cursor):
"""Handles parameter declarations."""
# 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_type(_type)):
_argtype = self.parse_cursor_type(_type)
else: # FIXME: Which UT/case ? size_t in stdio.h for example.
_argtype_decl = _type.get_declaration()
_argtype_name = self.get_unique_name(_argtype_decl)
if not self.is_registered(_argtype_name):
log.info('This param type is not declared: %s', _argtype_name)
_argtype = self.parse_cursor_type(_type)
else:
_argtype = self.get_registered(_argtype_name)
obj = typedesc.Argument(_name, _argtype)
self.set_location(obj, cursor)
self.set_comment(obj, cursor)
return obj | [
"def",
"PARM_DECL",
"(",
"self",
",",
"cursor",
")",
":",
"# try and get the type. If unexposed, The canonical type will work.",
"_type",
"=",
"cursor",
".",
"type",
"_name",
"=",
"cursor",
".",
"spelling",
"if",
"(",
"self",
".",
"is_array_type",
"(",
"_type",
")... | Handles parameter declarations. | [
"Handles",
"parameter",
"declarations",
"."
] | 2aeb1942a5a32a5cc798c287cd0d9e684a0181a8 | https://github.com/trolldbois/ctypeslib/blob/2aeb1942a5a32a5cc798c287cd0d9e684a0181a8/ctypeslib/codegen/cursorhandler.py#L181-L202 | train | 203,774 |
trolldbois/ctypeslib | ctypeslib/codegen/cursorhandler.py | CursorHandler.VAR_DECL | def VAR_DECL(self, cursor):
"""Handles Variable declaration."""
# 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._VAR_DECL_type(cursor)
# transform the ctypes values into ctypeslib
init_value = self._VAR_DECL_value(cursor, _type)
# finished
log.debug('VAR_DECL: _type:%s', _type.name)
log.debug('VAR_DECL: _init:%s', init_value)
log.debug('VAR_DECL: location:%s', getattr(cursor, 'location'))
obj = self.register(name, typedesc.Variable(name, _type, init_value))
self.set_location(obj, cursor)
self.set_comment(obj, cursor)
return True | python | def VAR_DECL(self, cursor):
"""Handles Variable declaration."""
# 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._VAR_DECL_type(cursor)
# transform the ctypes values into ctypeslib
init_value = self._VAR_DECL_value(cursor, _type)
# finished
log.debug('VAR_DECL: _type:%s', _type.name)
log.debug('VAR_DECL: _init:%s', init_value)
log.debug('VAR_DECL: location:%s', getattr(cursor, 'location'))
obj = self.register(name, typedesc.Variable(name, _type, init_value))
self.set_location(obj, cursor)
self.set_comment(obj, cursor)
return True | [
"def",
"VAR_DECL",
"(",
"self",
",",
"cursor",
")",
":",
"# get the name",
"name",
"=",
"self",
".",
"get_unique_name",
"(",
"cursor",
")",
"log",
".",
"debug",
"(",
"'VAR_DECL: name: %s'",
",",
"name",
")",
"# Check for a previous declaration in the register",
"i... | Handles Variable declaration. | [
"Handles",
"Variable",
"declaration",
"."
] | 2aeb1942a5a32a5cc798c287cd0d9e684a0181a8 | https://github.com/trolldbois/ctypeslib/blob/2aeb1942a5a32a5cc798c287cd0d9e684a0181a8/ctypeslib/codegen/cursorhandler.py#L238-L257 | train | 203,775 |
trolldbois/ctypeslib | ctypeslib/codegen/cursorhandler.py | CursorHandler._VAR_DECL_type | def _VAR_DECL_type(self, cursor):
"""Generates a typedesc object from a Variable declaration."""
# 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 = typedesc.FundamentalType(ctypesname, 0, 0)
elif self.is_unexposed_type(_ctype):
st = 'PATCH NEEDED: %s type is not exposed by clang' % (
self.get_unique_name(cursor))
log.error(st)
raise RuntimeError(st)
elif self.is_array_type(_ctype) or _ctype.kind == TypeKind.RECORD:
_type = self.parse_cursor_type(_ctype)
elif self.is_pointer_type(_ctype):
# for example, extern Function pointer
if self.is_unexposed_type(_ctype.get_pointee()):
_type = self.parse_cursor_type(
_ctype.get_canonical().get_pointee())
elif _ctype.get_pointee().kind == TypeKind.FUNCTIONPROTO:
# Function pointers
# Arguments are handled in here
_type = self.parse_cursor_type(_ctype.get_pointee())
else: # Pointer to Fundamental types, structs....
_type = self.parse_cursor_type(_ctype)
else:
# What else ?
raise NotImplementedError(
'What other type of variable? %s' %
(_ctype.kind))
log.debug('VAR_DECL: _type: %s ', _type)
return _type | python | def _VAR_DECL_type(self, cursor):
"""Generates a typedesc object from a Variable declaration."""
# 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 = typedesc.FundamentalType(ctypesname, 0, 0)
elif self.is_unexposed_type(_ctype):
st = 'PATCH NEEDED: %s type is not exposed by clang' % (
self.get_unique_name(cursor))
log.error(st)
raise RuntimeError(st)
elif self.is_array_type(_ctype) or _ctype.kind == TypeKind.RECORD:
_type = self.parse_cursor_type(_ctype)
elif self.is_pointer_type(_ctype):
# for example, extern Function pointer
if self.is_unexposed_type(_ctype.get_pointee()):
_type = self.parse_cursor_type(
_ctype.get_canonical().get_pointee())
elif _ctype.get_pointee().kind == TypeKind.FUNCTIONPROTO:
# Function pointers
# Arguments are handled in here
_type = self.parse_cursor_type(_ctype.get_pointee())
else: # Pointer to Fundamental types, structs....
_type = self.parse_cursor_type(_ctype)
else:
# What else ?
raise NotImplementedError(
'What other type of variable? %s' %
(_ctype.kind))
log.debug('VAR_DECL: _type: %s ', _type)
return _type | [
"def",
"_VAR_DECL_type",
"(",
"self",
",",
"cursor",
")",
":",
"# Get the type",
"_ctype",
"=",
"cursor",
".",
"type",
".",
"get_canonical",
"(",
")",
"log",
".",
"debug",
"(",
"'VAR_DECL: _ctype: %s '",
",",
"_ctype",
".",
"kind",
")",
"# FIXME: Need working ... | Generates a typedesc object from a Variable declaration. | [
"Generates",
"a",
"typedesc",
"object",
"from",
"a",
"Variable",
"declaration",
"."
] | 2aeb1942a5a32a5cc798c287cd0d9e684a0181a8 | https://github.com/trolldbois/ctypeslib/blob/2aeb1942a5a32a5cc798c287cd0d9e684a0181a8/ctypeslib/codegen/cursorhandler.py#L259-L292 | train | 203,776 |
trolldbois/ctypeslib | ctypeslib/codegen/cursorhandler.py | CursorHandler._VAR_DECL_value | def _VAR_DECL_value(self, cursor, _type):
"""Handles Variable value initialization."""
# 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_canonical()
if self.is_unexposed_type(_ctype):
# string are not exposed
init_value = '%s # UNEXPOSED TYPE. PATCH NEEDED.' % (init_value)
elif (self.is_pointer_type(_ctype) and
_ctype.get_pointee().kind == TypeKind.FUNCTIONPROTO):
# Function pointers argument are handled at type creation time
# but we need to put a CFUNCTYPE as a value of the name variable
init_value = _type
elif self.is_array_type(_ctype):
# an integer litteral will be the size
# an string litteral will be the value
# any list member will be children of a init_list_expr
# FIXME Move that code into typedesc
def countof(k, l):
return [item[0] for item in l].count(k)
if (countof(CursorKind.INIT_LIST_EXPR, init_value) == 1):
init_value = dict(init_value)[CursorKind.INIT_LIST_EXPR]
elif (countof(CursorKind.STRING_LITERAL, init_value) == 1):
# we have a initialised c_array
init_value = dict(init_value)[CursorKind.STRING_LITERAL]
else:
# ignore size alone
init_value = []
# check the array size versus elements.
if _type.size < len(init_value):
_type.size = len(init_value)
elif init_value == []:
# catch case.
init_value = None
else:
log.debug('VAR_DECL: default init_value: %s', init_value)
if len(init_value) > 0:
init_value = init_value[0][1]
return init_value | python | def _VAR_DECL_value(self, cursor, _type):
"""Handles Variable value initialization."""
# 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_canonical()
if self.is_unexposed_type(_ctype):
# string are not exposed
init_value = '%s # UNEXPOSED TYPE. PATCH NEEDED.' % (init_value)
elif (self.is_pointer_type(_ctype) and
_ctype.get_pointee().kind == TypeKind.FUNCTIONPROTO):
# Function pointers argument are handled at type creation time
# but we need to put a CFUNCTYPE as a value of the name variable
init_value = _type
elif self.is_array_type(_ctype):
# an integer litteral will be the size
# an string litteral will be the value
# any list member will be children of a init_list_expr
# FIXME Move that code into typedesc
def countof(k, l):
return [item[0] for item in l].count(k)
if (countof(CursorKind.INIT_LIST_EXPR, init_value) == 1):
init_value = dict(init_value)[CursorKind.INIT_LIST_EXPR]
elif (countof(CursorKind.STRING_LITERAL, init_value) == 1):
# we have a initialised c_array
init_value = dict(init_value)[CursorKind.STRING_LITERAL]
else:
# ignore size alone
init_value = []
# check the array size versus elements.
if _type.size < len(init_value):
_type.size = len(init_value)
elif init_value == []:
# catch case.
init_value = None
else:
log.debug('VAR_DECL: default init_value: %s', init_value)
if len(init_value) > 0:
init_value = init_value[0][1]
return init_value | [
"def",
"_VAR_DECL_value",
"(",
"self",
",",
"cursor",
",",
"_type",
")",
":",
"# 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",
".",... | Handles Variable value initialization. | [
"Handles",
"Variable",
"value",
"initialization",
"."
] | 2aeb1942a5a32a5cc798c287cd0d9e684a0181a8 | https://github.com/trolldbois/ctypeslib/blob/2aeb1942a5a32a5cc798c287cd0d9e684a0181a8/ctypeslib/codegen/cursorhandler.py#L294-L335 | train | 203,777 |
trolldbois/ctypeslib | ctypeslib/codegen/cursorhandler.py | CursorHandler._get_var_decl_init_value | def _get_var_decl_init_value(self, _ctype, children):
"""
Gathers initialisation values by parsing children nodes of a VAR_DECL.
"""
# 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', len(children))
for child in children:
# early stop cases.
_tmp = None
try:
_tmp = self._get_var_decl_init_value_single(_ctype, child)
except CursorKindException:
log.debug(
'_get_var_decl_init_value: children init value skip on %s',
child.kind)
continue
if _tmp is not None:
init_value.append(_tmp)
return init_value | python | def _get_var_decl_init_value(self, _ctype, children):
"""
Gathers initialisation values by parsing children nodes of a VAR_DECL.
"""
# 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', len(children))
for child in children:
# early stop cases.
_tmp = None
try:
_tmp = self._get_var_decl_init_value_single(_ctype, child)
except CursorKindException:
log.debug(
'_get_var_decl_init_value: children init value skip on %s',
child.kind)
continue
if _tmp is not None:
init_value.append(_tmp)
return init_value | [
"def",
"_get_var_decl_init_value",
"(",
"self",
",",
"_ctype",
",",
"children",
")",
":",
"# FIXME TU for INIT_LIST_EXPR",
"# FIXME: always return [(child.kind,child.value),...]",
"# FIXME: simplify this redondant code.",
"init_value",
"=",
"[",
"]",
"children",
"=",
"list",
... | Gathers initialisation values by parsing children nodes of a VAR_DECL. | [
"Gathers",
"initialisation",
"values",
"by",
"parsing",
"children",
"nodes",
"of",
"a",
"VAR_DECL",
"."
] | 2aeb1942a5a32a5cc798c287cd0d9e684a0181a8 | https://github.com/trolldbois/ctypeslib/blob/2aeb1942a5a32a5cc798c287cd0d9e684a0181a8/ctypeslib/codegen/cursorhandler.py#L337-L360 | train | 203,778 |
trolldbois/ctypeslib | ctypeslib/codegen/cursorhandler.py | CursorHandler._get_var_decl_init_value_single | def _get_var_decl_init_value_single(self, _ctype, child):
"""
Handling of a single child for initialization value.
Accepted types are expressions and declarations
"""
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_declaration():
raise CursorKindException(child.kind)
if child.kind == CursorKind.CALL_EXPR:
raise CursorKindException(child.kind)
# POD init values handling.
# As of clang 3.3, int, double literals are exposed.
# float, long double, char , char* are not exposed directly in level1.
# but really it depends...
if child.kind.is_unexposed():
# recurse until we find a literal kind
init_value = self._get_var_decl_init_value(_ctype,
child.get_children())
if len(init_value) == 0:
init_value = None
elif len(init_value) == 1:
init_value = init_value[0]
else:
log.error('_get_var_decl_init_value_single: Unhandled case')
assert len(init_value) <= 1
else: # literal or others
_v = self.parse_cursor(child)
if isinstance(
_v, list) and child.kind not in [CursorKind.INIT_LIST_EXPR, CursorKind.STRING_LITERAL]:
log.warning(
'_get_var_decl_init_value_single: TOKENIZATION BUG CHECK: %s',
_v)
_v = _v[0]
init_value = (child.kind, _v)
log.debug(
'_get_var_decl_init_value_single: returns %s',
str(init_value))
return init_value | python | def _get_var_decl_init_value_single(self, _ctype, child):
"""
Handling of a single child for initialization value.
Accepted types are expressions and declarations
"""
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_declaration():
raise CursorKindException(child.kind)
if child.kind == CursorKind.CALL_EXPR:
raise CursorKindException(child.kind)
# POD init values handling.
# As of clang 3.3, int, double literals are exposed.
# float, long double, char , char* are not exposed directly in level1.
# but really it depends...
if child.kind.is_unexposed():
# recurse until we find a literal kind
init_value = self._get_var_decl_init_value(_ctype,
child.get_children())
if len(init_value) == 0:
init_value = None
elif len(init_value) == 1:
init_value = init_value[0]
else:
log.error('_get_var_decl_init_value_single: Unhandled case')
assert len(init_value) <= 1
else: # literal or others
_v = self.parse_cursor(child)
if isinstance(
_v, list) and child.kind not in [CursorKind.INIT_LIST_EXPR, CursorKind.STRING_LITERAL]:
log.warning(
'_get_var_decl_init_value_single: TOKENIZATION BUG CHECK: %s',
_v)
_v = _v[0]
init_value = (child.kind, _v)
log.debug(
'_get_var_decl_init_value_single: returns %s',
str(init_value))
return init_value | [
"def",
"_get_var_decl_init_value_single",
"(",
"self",
",",
"_ctype",
",",
"child",
")",
":",
"init_value",
"=",
"None",
"# FIXME: always return (child.kind, child.value)",
"log",
".",
"debug",
"(",
"'_get_var_decl_init_value_single: _ctype: %s Child.kind: %s'",
",",
"_ctype"... | Handling of a single child for initialization value.
Accepted types are expressions and declarations | [
"Handling",
"of",
"a",
"single",
"child",
"for",
"initialization",
"value",
".",
"Accepted",
"types",
"are",
"expressions",
"and",
"declarations"
] | 2aeb1942a5a32a5cc798c287cd0d9e684a0181a8 | https://github.com/trolldbois/ctypeslib/blob/2aeb1942a5a32a5cc798c287cd0d9e684a0181a8/ctypeslib/codegen/cursorhandler.py#L362-L405 | train | 203,779 |
trolldbois/ctypeslib | ctypeslib/codegen/cursorhandler.py | CursorHandler._literal_handling | def _literal_handling(self, cursor):
"""Parse all literal associated with this cursor.
Literal handling is usually useful only for initialization values.
We can't use a shortcut by getting tokens
# init_value = ' '.join([t.spelling for t in children[0].get_tokens()
# if t.spelling != ';'])
because some literal might need cleaning."""
# use a shortcut - does not work on unicode var_decl
# if cursor.kind == CursorKind.STRING_LITERAL:
# value = cursor.displayname
# value = self._clean_string_literal(cursor, value)
# return value
tokens = list(cursor.get_tokens())
log.debug('literal has %d tokens.[ %s ]', len(tokens),
str([str(t.spelling) for t in tokens]))
final_value = []
# code.interact(local=locals())
log.debug('cursor.type:%s', cursor.type.kind.name)
for i, token in enumerate(tokens):
value = token.spelling
log.debug('token:%s tk.kd:%11s tk.cursor.kd:%15s cursor.kd:%15s',
token.spelling, token.kind.name, token.cursor.kind.name,
cursor.kind.name)
# Punctuation is probably not part of the init_value,
# but only in specific case: ';' endl, or part of list_expr
if (token.kind == TokenKind.PUNCTUATION and
(token.cursor.kind == CursorKind.INVALID_FILE or
token.cursor.kind == CursorKind.INIT_LIST_EXPR)):
log.debug('IGNORE token %s', value)
continue
elif token.kind == TokenKind.COMMENT:
log.debug('Ignore comment %s', value)
continue
# elif token.cursor.kind == CursorKind.VAR_DECL:
elif token.location not in cursor.extent:
log.debug(
'FIXME BUG: token.location not in cursor.extent %s',
value)
# FIXME
# there is most probably a BUG in clang or python-clang
# when on #define with no value, a token is taken from
# next line. Which break stuff.
# example:
# #define A
# extern int i;
# // this will give "extern" the last token of Macro("A")
# Lexer is choking ?
# FIXME BUG: token.location not in cursor.extent
# code.interact(local=locals())
continue
# Cleanup specific c-lang or c++ prefix/suffix for POD types.
if token.cursor.kind == CursorKind.INTEGER_LITERAL:
# strip type suffix for constants
value = value.replace('L', '').replace('U', '')
value = value.replace('l', '').replace('u', '')
if value[:2] == '0x' or value[:2] == '0X':
value = '0x%s' % value[2:] # "int(%s,16)"%(value)
else:
value = int(value)
elif token.cursor.kind == CursorKind.FLOATING_LITERAL:
# strip type suffix for constants
value = value.replace('f', '').replace('F', '')
value = float(value)
elif (token.cursor.kind == CursorKind.CHARACTER_LITERAL or
token.cursor.kind == CursorKind.STRING_LITERAL):
value = self._clean_string_literal(token.cursor, value)
elif token.cursor.kind == CursorKind.MACRO_INSTANTIATION:
# get the macro value
value = self.get_registered(value).body
# already cleaned value = self._clean_string_literal(token.cursor, value)
elif token.cursor.kind == CursorKind.MACRO_DEFINITION:
if i == 0:
# ignore, macro name
pass
elif token.kind == TokenKind.LITERAL:
# and just clean it
value = self._clean_string_literal(token.cursor, value)
elif token.kind == TokenKind.IDENTIFIER:
# parse that, try to see if there is another Macro in there.
value = self.get_registered(value).body
# add token
final_value.append(value)
# return the EXPR
# code.interact(local=locals())
if len(final_value) == 1:
return final_value[0]
# Macro definition of a string using multiple macro
if isinstance(final_value, list) and cursor.kind == CursorKind.STRING_LITERAL:
final_value = ''.join(final_value)
return final_value | python | def _literal_handling(self, cursor):
"""Parse all literal associated with this cursor.
Literal handling is usually useful only for initialization values.
We can't use a shortcut by getting tokens
# init_value = ' '.join([t.spelling for t in children[0].get_tokens()
# if t.spelling != ';'])
because some literal might need cleaning."""
# use a shortcut - does not work on unicode var_decl
# if cursor.kind == CursorKind.STRING_LITERAL:
# value = cursor.displayname
# value = self._clean_string_literal(cursor, value)
# return value
tokens = list(cursor.get_tokens())
log.debug('literal has %d tokens.[ %s ]', len(tokens),
str([str(t.spelling) for t in tokens]))
final_value = []
# code.interact(local=locals())
log.debug('cursor.type:%s', cursor.type.kind.name)
for i, token in enumerate(tokens):
value = token.spelling
log.debug('token:%s tk.kd:%11s tk.cursor.kd:%15s cursor.kd:%15s',
token.spelling, token.kind.name, token.cursor.kind.name,
cursor.kind.name)
# Punctuation is probably not part of the init_value,
# but only in specific case: ';' endl, or part of list_expr
if (token.kind == TokenKind.PUNCTUATION and
(token.cursor.kind == CursorKind.INVALID_FILE or
token.cursor.kind == CursorKind.INIT_LIST_EXPR)):
log.debug('IGNORE token %s', value)
continue
elif token.kind == TokenKind.COMMENT:
log.debug('Ignore comment %s', value)
continue
# elif token.cursor.kind == CursorKind.VAR_DECL:
elif token.location not in cursor.extent:
log.debug(
'FIXME BUG: token.location not in cursor.extent %s',
value)
# FIXME
# there is most probably a BUG in clang or python-clang
# when on #define with no value, a token is taken from
# next line. Which break stuff.
# example:
# #define A
# extern int i;
# // this will give "extern" the last token of Macro("A")
# Lexer is choking ?
# FIXME BUG: token.location not in cursor.extent
# code.interact(local=locals())
continue
# Cleanup specific c-lang or c++ prefix/suffix for POD types.
if token.cursor.kind == CursorKind.INTEGER_LITERAL:
# strip type suffix for constants
value = value.replace('L', '').replace('U', '')
value = value.replace('l', '').replace('u', '')
if value[:2] == '0x' or value[:2] == '0X':
value = '0x%s' % value[2:] # "int(%s,16)"%(value)
else:
value = int(value)
elif token.cursor.kind == CursorKind.FLOATING_LITERAL:
# strip type suffix for constants
value = value.replace('f', '').replace('F', '')
value = float(value)
elif (token.cursor.kind == CursorKind.CHARACTER_LITERAL or
token.cursor.kind == CursorKind.STRING_LITERAL):
value = self._clean_string_literal(token.cursor, value)
elif token.cursor.kind == CursorKind.MACRO_INSTANTIATION:
# get the macro value
value = self.get_registered(value).body
# already cleaned value = self._clean_string_literal(token.cursor, value)
elif token.cursor.kind == CursorKind.MACRO_DEFINITION:
if i == 0:
# ignore, macro name
pass
elif token.kind == TokenKind.LITERAL:
# and just clean it
value = self._clean_string_literal(token.cursor, value)
elif token.kind == TokenKind.IDENTIFIER:
# parse that, try to see if there is another Macro in there.
value = self.get_registered(value).body
# add token
final_value.append(value)
# return the EXPR
# code.interact(local=locals())
if len(final_value) == 1:
return final_value[0]
# Macro definition of a string using multiple macro
if isinstance(final_value, list) and cursor.kind == CursorKind.STRING_LITERAL:
final_value = ''.join(final_value)
return final_value | [
"def",
"_literal_handling",
"(",
"self",
",",
"cursor",
")",
":",
"# use a shortcut - does not work on unicode var_decl",
"# if cursor.kind == CursorKind.STRING_LITERAL:",
"# value = cursor.displayname",
"# value = self._clean_string_literal(cursor, value)",
"# return value",
"... | Parse all literal associated with this cursor.
Literal handling is usually useful only for initialization values.
We can't use a shortcut by getting tokens
# init_value = ' '.join([t.spelling for t in children[0].get_tokens()
# if t.spelling != ';'])
because some literal might need cleaning. | [
"Parse",
"all",
"literal",
"associated",
"with",
"this",
"cursor",
"."
] | 2aeb1942a5a32a5cc798c287cd0d9e684a0181a8 | https://github.com/trolldbois/ctypeslib/blob/2aeb1942a5a32a5cc798c287cd0d9e684a0181a8/ctypeslib/codegen/cursorhandler.py#L447-L539 | train | 203,780 |
trolldbois/ctypeslib | ctypeslib/codegen/cursorhandler.py | CursorHandler._operator_handling | def _operator_handling(self, cursor):
"""Returns a string with the literal that are part of the operation."""
values = self._literal_handling(cursor)
retval = ''.join([str(val) for val in values])
return retval | python | def _operator_handling(self, cursor):
"""Returns a string with the literal that are part of the operation."""
values = self._literal_handling(cursor)
retval = ''.join([str(val) for val in values])
return retval | [
"def",
"_operator_handling",
"(",
"self",
",",
"cursor",
")",
":",
"values",
"=",
"self",
".",
"_literal_handling",
"(",
"cursor",
")",
"retval",
"=",
"''",
".",
"join",
"(",
"[",
"str",
"(",
"val",
")",
"for",
"val",
"in",
"values",
"]",
")",
"retur... | Returns a string with the literal that are part of the operation. | [
"Returns",
"a",
"string",
"with",
"the",
"literal",
"that",
"are",
"part",
"of",
"the",
"operation",
"."
] | 2aeb1942a5a32a5cc798c287cd0d9e684a0181a8 | https://github.com/trolldbois/ctypeslib/blob/2aeb1942a5a32a5cc798c287cd0d9e684a0181a8/ctypeslib/codegen/cursorhandler.py#L548-L552 | train | 203,781 |
trolldbois/ctypeslib | ctypeslib/codegen/cursorhandler.py | CursorHandler.STRUCT_DECL | def STRUCT_DECL(self, cursor, num=None):
"""
Handles Structure declaration.
Its a wrapper to _record_decl.
"""
return self._record_decl(cursor, typedesc.Structure, num) | python | def STRUCT_DECL(self, cursor, num=None):
"""
Handles Structure declaration.
Its a wrapper to _record_decl.
"""
return self._record_decl(cursor, typedesc.Structure, num) | [
"def",
"STRUCT_DECL",
"(",
"self",
",",
"cursor",
",",
"num",
"=",
"None",
")",
":",
"return",
"self",
".",
"_record_decl",
"(",
"cursor",
",",
"typedesc",
".",
"Structure",
",",
"num",
")"
] | Handles Structure declaration.
Its a wrapper to _record_decl. | [
"Handles",
"Structure",
"declaration",
".",
"Its",
"a",
"wrapper",
"to",
"_record_decl",
"."
] | 2aeb1942a5a32a5cc798c287cd0d9e684a0181a8 | https://github.com/trolldbois/ctypeslib/blob/2aeb1942a5a32a5cc798c287cd0d9e684a0181a8/ctypeslib/codegen/cursorhandler.py#L558-L563 | train | 203,782 |
trolldbois/ctypeslib | ctypeslib/codegen/cursorhandler.py | CursorHandler.UNION_DECL | def UNION_DECL(self, cursor, num=None):
"""
Handles Union declaration.
Its a wrapper to _record_decl.
"""
return self._record_decl(cursor, typedesc.Union, num) | python | def UNION_DECL(self, cursor, num=None):
"""
Handles Union declaration.
Its a wrapper to _record_decl.
"""
return self._record_decl(cursor, typedesc.Union, num) | [
"def",
"UNION_DECL",
"(",
"self",
",",
"cursor",
",",
"num",
"=",
"None",
")",
":",
"return",
"self",
".",
"_record_decl",
"(",
"cursor",
",",
"typedesc",
".",
"Union",
",",
"num",
")"
] | Handles Union declaration.
Its a wrapper to _record_decl. | [
"Handles",
"Union",
"declaration",
".",
"Its",
"a",
"wrapper",
"to",
"_record_decl",
"."
] | 2aeb1942a5a32a5cc798c287cd0d9e684a0181a8 | https://github.com/trolldbois/ctypeslib/blob/2aeb1942a5a32a5cc798c287cd0d9e684a0181a8/ctypeslib/codegen/cursorhandler.py#L566-L571 | train | 203,783 |
trolldbois/ctypeslib | ctypeslib/codegen/cursorhandler.py | CursorHandler._fixup_record_bitfields_type | def _fixup_record_bitfields_type(self, s):
"""Fix the bitfield packing issue for python ctypes, by changing the
bitfield type, and respecting compiler alignement rules.
This method should be called AFTER padding to have a perfect continuous
layout.
There is one very special case:
struct bytes3 {
unsigned int b1:23; // 0-23
// 1 bit padding
char a2; // 24-32
};
where we would need to actually put a2 in the int32 bitfield.
We also need to change the member type to the smallest type possible
that can contains the number of bits.
Otherwise ctypes has strange bitfield rules packing stuff to the biggest
type possible.
** but at the same time, if a bitfield member is from type x, we need to
respect that
"""
# phase 1, make bitfield, relying upon padding.
bitfields = []
bitfield_members = []
current_bits = 0
for m in s.members:
if m.is_bitfield:
bitfield_members.append(m)
if m.is_padding:
# compiler says this ends the bitfield
size = current_bits
bitfields.append((size, bitfield_members))
bitfield_members = []
current_bits = 0
else:
# size of padding is not included
current_bits += m.bits
elif len(bitfield_members) == 0:
# no opened bitfield
continue
else:
# we reach the end of the bitfield. Make calculations.
size = current_bits
bitfields.append((size, bitfield_members))
bitfield_members = []
current_bits = 0
if current_bits != 0:
size = current_bits
bitfields.append((size, bitfield_members))
# compilers tend to reduce the size of the bitfield
# to the bf_size
# set the proper type name for the bitfield.
for bf_size, members in bitfields:
name = members[0].type.name
pad_bits = 0
if bf_size <= 8: # use 1 byte - type = char
# prep the padding bitfield size
pad_bits = 8 - bf_size
elif bf_size <= 16: # use 2 byte
pad_bits = 16 - bf_size
elif bf_size <= 32: # use 2 byte
pad_bits = 32 - bf_size
elif bf_size <= 64: # use 2 byte
name = 'c_uint64' # also the 3 bytes + char thing
pad_bits = 64 - bf_size
else:
name = 'c_uint64'
pad_bits = bf_size % 64 - bf_size
# change the type to harmonise the bitfield
log.debug('_fixup_record_bitfield_size: fix type to %s', name)
# set the whole bitfield to the appropriate type size.
for m in members:
m.type.name = name
if m.is_padding:
# this is the last field.
# reduce the size of this padding field to the
m.bits = pad_bits
# and remove padding if the size is 0
if members[-1].is_padding and members[-1].bits == 0:
s.members.remove(members[-1])
# phase 2 - integrate the special 3 Bytes + char fix
for bf_size, members in bitfields:
if True or bf_size == 24:
# we need to check for a 3bytes + char corner case
m = members[-1]
i = s.members.index(m)
if len(s.members) > i + 1:
# has to exists, no arch is aligned on 24 bits.
next_member = s.members[i + 1]
if next_member.bits == 8:
# next_member field is a char.
# it will be aggregated in a 32 bits space
# we need to make it a member of 32bit bitfield
next_member.is_bitfield = True
next_member.comment = "Promoted to bitfield member and type (was char)"
next_member.type = m.type
log.info("%s.%s promoted to bitfield member and type", s.name, next_member.name)
continue
#
return | python | def _fixup_record_bitfields_type(self, s):
"""Fix the bitfield packing issue for python ctypes, by changing the
bitfield type, and respecting compiler alignement rules.
This method should be called AFTER padding to have a perfect continuous
layout.
There is one very special case:
struct bytes3 {
unsigned int b1:23; // 0-23
// 1 bit padding
char a2; // 24-32
};
where we would need to actually put a2 in the int32 bitfield.
We also need to change the member type to the smallest type possible
that can contains the number of bits.
Otherwise ctypes has strange bitfield rules packing stuff to the biggest
type possible.
** but at the same time, if a bitfield member is from type x, we need to
respect that
"""
# phase 1, make bitfield, relying upon padding.
bitfields = []
bitfield_members = []
current_bits = 0
for m in s.members:
if m.is_bitfield:
bitfield_members.append(m)
if m.is_padding:
# compiler says this ends the bitfield
size = current_bits
bitfields.append((size, bitfield_members))
bitfield_members = []
current_bits = 0
else:
# size of padding is not included
current_bits += m.bits
elif len(bitfield_members) == 0:
# no opened bitfield
continue
else:
# we reach the end of the bitfield. Make calculations.
size = current_bits
bitfields.append((size, bitfield_members))
bitfield_members = []
current_bits = 0
if current_bits != 0:
size = current_bits
bitfields.append((size, bitfield_members))
# compilers tend to reduce the size of the bitfield
# to the bf_size
# set the proper type name for the bitfield.
for bf_size, members in bitfields:
name = members[0].type.name
pad_bits = 0
if bf_size <= 8: # use 1 byte - type = char
# prep the padding bitfield size
pad_bits = 8 - bf_size
elif bf_size <= 16: # use 2 byte
pad_bits = 16 - bf_size
elif bf_size <= 32: # use 2 byte
pad_bits = 32 - bf_size
elif bf_size <= 64: # use 2 byte
name = 'c_uint64' # also the 3 bytes + char thing
pad_bits = 64 - bf_size
else:
name = 'c_uint64'
pad_bits = bf_size % 64 - bf_size
# change the type to harmonise the bitfield
log.debug('_fixup_record_bitfield_size: fix type to %s', name)
# set the whole bitfield to the appropriate type size.
for m in members:
m.type.name = name
if m.is_padding:
# this is the last field.
# reduce the size of this padding field to the
m.bits = pad_bits
# and remove padding if the size is 0
if members[-1].is_padding and members[-1].bits == 0:
s.members.remove(members[-1])
# phase 2 - integrate the special 3 Bytes + char fix
for bf_size, members in bitfields:
if True or bf_size == 24:
# we need to check for a 3bytes + char corner case
m = members[-1]
i = s.members.index(m)
if len(s.members) > i + 1:
# has to exists, no arch is aligned on 24 bits.
next_member = s.members[i + 1]
if next_member.bits == 8:
# next_member field is a char.
# it will be aggregated in a 32 bits space
# we need to make it a member of 32bit bitfield
next_member.is_bitfield = True
next_member.comment = "Promoted to bitfield member and type (was char)"
next_member.type = m.type
log.info("%s.%s promoted to bitfield member and type", s.name, next_member.name)
continue
#
return | [
"def",
"_fixup_record_bitfields_type",
"(",
"self",
",",
"s",
")",
":",
"# phase 1, make bitfield, relying upon padding.",
"bitfields",
"=",
"[",
"]",
"bitfield_members",
"=",
"[",
"]",
"current_bits",
"=",
"0",
"for",
"m",
"in",
"s",
".",
"members",
":",
"if",
... | Fix the bitfield packing issue for python ctypes, by changing the
bitfield type, and respecting compiler alignement rules.
This method should be called AFTER padding to have a perfect continuous
layout.
There is one very special case:
struct bytes3 {
unsigned int b1:23; // 0-23
// 1 bit padding
char a2; // 24-32
};
where we would need to actually put a2 in the int32 bitfield.
We also need to change the member type to the smallest type possible
that can contains the number of bits.
Otherwise ctypes has strange bitfield rules packing stuff to the biggest
type possible.
** but at the same time, if a bitfield member is from type x, we need to
respect that | [
"Fix",
"the",
"bitfield",
"packing",
"issue",
"for",
"python",
"ctypes",
"by",
"changing",
"the",
"bitfield",
"type",
"and",
"respecting",
"compiler",
"alignement",
"rules",
"."
] | 2aeb1942a5a32a5cc798c287cd0d9e684a0181a8 | https://github.com/trolldbois/ctypeslib/blob/2aeb1942a5a32a5cc798c287cd0d9e684a0181a8/ctypeslib/codegen/cursorhandler.py#L680-L784 | train | 203,784 |
trolldbois/ctypeslib | ctypeslib/codegen/cursorhandler.py | CursorHandler._fixup_record | def _fixup_record(self, s):
"""Fixup padding on a record"""
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
# try to fix bitfields without padding first
self._fixup_record_bitfields_type(s)
# No need to lookup members in a global var.
# Just fix the padding
members = []
member = None
offset = 0
padding_nb = 0
member = None
prev_member = None
# create padding fields
# DEBUG FIXME: why are s.members already typedesc objet ?
# fields = self.fields[s.name]
for m in s.members: # s.members are strings - NOT
# we need to check total size of bitfield, so to choose the right
# bitfield type
member = m
log.debug('Fixup_struct: Member:%s offsetbits:%d->%d expecting offset:%d',
member.name, member.offset, member.offset + member.bits, offset)
if member.offset < 0:
# FIXME INCOMPLETEARRAY (clang bindings?)
# All fields have offset == -2. No padding will be done.
# But the fields are ordered and code will be produces with typed info.
# so in most cases, it will work. if there is a structure with incompletearray
# and padding or alignement issue, it will produce wrong results
# just exit
return
if member.offset > offset:
# create padding
length = member.offset - offset
log.debug(
'Fixup_struct: create padding for %d bits %d bytes',
length, length // 8)
padding_nb = self._make_padding(
members,
padding_nb,
offset,
length,
prev_member)
if member.type is None:
log.error('FIXUP_STRUCT: %s.type is None', member.name)
members.append(member)
offset = member.offset + member.bits
prev_member = member
# tail padding if necessary
if s.size * 8 != offset:
length = s.size * 8 - offset
log.debug(
'Fixup_struct: s:%d create tail padding for %d bits %d bytes',
s.size, length, length // 8)
padding_nb = self._make_padding(
members,
padding_nb,
offset,
length,
prev_member)
if len(members) > 0:
offset = members[-1].offset + members[-1].bits
# go
s.members = members
log.debug("FIXUP_STRUCT: size:%d offset:%d", s.size * 8, offset)
# if member and not member.is_bitfield:
## self._fixup_record_bitfields_type(s)
# , assert that the last field stop at the size limit
assert offset == s.size * 8
return | python | def _fixup_record(self, s):
"""Fixup padding on a record"""
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
# try to fix bitfields without padding first
self._fixup_record_bitfields_type(s)
# No need to lookup members in a global var.
# Just fix the padding
members = []
member = None
offset = 0
padding_nb = 0
member = None
prev_member = None
# create padding fields
# DEBUG FIXME: why are s.members already typedesc objet ?
# fields = self.fields[s.name]
for m in s.members: # s.members are strings - NOT
# we need to check total size of bitfield, so to choose the right
# bitfield type
member = m
log.debug('Fixup_struct: Member:%s offsetbits:%d->%d expecting offset:%d',
member.name, member.offset, member.offset + member.bits, offset)
if member.offset < 0:
# FIXME INCOMPLETEARRAY (clang bindings?)
# All fields have offset == -2. No padding will be done.
# But the fields are ordered and code will be produces with typed info.
# so in most cases, it will work. if there is a structure with incompletearray
# and padding or alignement issue, it will produce wrong results
# just exit
return
if member.offset > offset:
# create padding
length = member.offset - offset
log.debug(
'Fixup_struct: create padding for %d bits %d bytes',
length, length // 8)
padding_nb = self._make_padding(
members,
padding_nb,
offset,
length,
prev_member)
if member.type is None:
log.error('FIXUP_STRUCT: %s.type is None', member.name)
members.append(member)
offset = member.offset + member.bits
prev_member = member
# tail padding if necessary
if s.size * 8 != offset:
length = s.size * 8 - offset
log.debug(
'Fixup_struct: s:%d create tail padding for %d bits %d bytes',
s.size, length, length // 8)
padding_nb = self._make_padding(
members,
padding_nb,
offset,
length,
prev_member)
if len(members) > 0:
offset = members[-1].offset + members[-1].bits
# go
s.members = members
log.debug("FIXUP_STRUCT: size:%d offset:%d", s.size * 8, offset)
# if member and not member.is_bitfield:
## self._fixup_record_bitfields_type(s)
# , assert that the last field stop at the size limit
assert offset == s.size * 8
return | [
"def",
"_fixup_record",
"(",
"self",
",",
"s",
")",
":",
"log",
".",
"debug",
"(",
"'FIXUP_STRUCT: %s %d bits'",
",",
"s",
".",
"name",
",",
"s",
".",
"size",
"*",
"8",
")",
"if",
"s",
".",
"members",
"is",
"None",
":",
"log",
".",
"debug",
"(",
... | Fixup padding on a record | [
"Fixup",
"padding",
"on",
"a",
"record"
] | 2aeb1942a5a32a5cc798c287cd0d9e684a0181a8 | https://github.com/trolldbois/ctypeslib/blob/2aeb1942a5a32a5cc798c287cd0d9e684a0181a8/ctypeslib/codegen/cursorhandler.py#L786-L861 | train | 203,785 |
trolldbois/ctypeslib | ctypeslib/codegen/cursorhandler.py | CursorHandler._make_padding | def _make_padding(
self, members, padding_nb, offset, length, prev_member=None):
"""Make padding Fields for a specifed size."""
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 required.
# pad_length = (length % 8)
typename = prev_member.type.name
padding = typedesc.Field(name,
typedesc.FundamentalType(typename, 1, 1),
# offset, pad_length, is_bitfield=True)
offset, length, is_bitfield=True, is_padding=True)
members.append(padding)
# check for multiple bytes
# if (length//8) > 0:
# padding_nb = self._make_padding(members, padding_nb, offset+pad_length,
# (length//8)*8, prev_member=padding)
return padding_nb
elif length > 8:
pad_bytes = length // 8
padding = typedesc.Field(name,
typedesc.ArrayType(
typedesc.FundamentalType(
self.get_ctypes_name(TypeKind.CHAR_U), length, 1),
pad_bytes),
offset, length, is_padding=True)
members.append(padding)
return padding_nb
# simple char padding
padding = typedesc.Field(name,
typedesc.FundamentalType(
self.get_ctypes_name(
TypeKind.CHAR_U),
1,
1),
offset, length, is_padding=True)
members.append(padding)
return padding_nb | python | def _make_padding(
self, members, padding_nb, offset, length, prev_member=None):
"""Make padding Fields for a specifed size."""
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 required.
# pad_length = (length % 8)
typename = prev_member.type.name
padding = typedesc.Field(name,
typedesc.FundamentalType(typename, 1, 1),
# offset, pad_length, is_bitfield=True)
offset, length, is_bitfield=True, is_padding=True)
members.append(padding)
# check for multiple bytes
# if (length//8) > 0:
# padding_nb = self._make_padding(members, padding_nb, offset+pad_length,
# (length//8)*8, prev_member=padding)
return padding_nb
elif length > 8:
pad_bytes = length // 8
padding = typedesc.Field(name,
typedesc.ArrayType(
typedesc.FundamentalType(
self.get_ctypes_name(TypeKind.CHAR_U), length, 1),
pad_bytes),
offset, length, is_padding=True)
members.append(padding)
return padding_nb
# simple char padding
padding = typedesc.Field(name,
typedesc.FundamentalType(
self.get_ctypes_name(
TypeKind.CHAR_U),
1,
1),
offset, length, is_padding=True)
members.append(padding)
return padding_nb | [
"def",
"_make_padding",
"(",
"self",
",",
"members",
",",
"padding_nb",
",",
"offset",
",",
"length",
",",
"prev_member",
"=",
"None",
")",
":",
"name",
"=",
"'PADDING_%d'",
"%",
"padding_nb",
"padding_nb",
"+=",
"1",
"log",
".",
"debug",
"(",
"\"_make_pad... | Make padding Fields for a specifed size. | [
"Make",
"padding",
"Fields",
"for",
"a",
"specifed",
"size",
"."
] | 2aeb1942a5a32a5cc798c287cd0d9e684a0181a8 | https://github.com/trolldbois/ctypeslib/blob/2aeb1942a5a32a5cc798c287cd0d9e684a0181a8/ctypeslib/codegen/cursorhandler.py#L866-L906 | train | 203,786 |
trolldbois/ctypeslib | ctypeslib/codegen/cursorhandler.py | CursorHandler.MACRO_DEFINITION | def MACRO_DEFINITION(self, cursor):
"""
Parse MACRO_DEFINITION, only present if the TranslationUnit is
used with TranslationUnit.PARSE_DETAILED_PROCESSING_RECORD.
"""
# 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':
# code.interact(local=locals())
# Tokens !!! .kind = {IDENTIFIER, KEYWORD, LITERAL, PUNCTUATION,
# COMMENT ? } etc. see TokenKinds.def
comment = None
tokens = self._literal_handling(cursor)
# Macro name is tokens[0]
# get Macro value(s)
value = True
if isinstance(tokens, list):
if len(tokens) == 2:
value = tokens[1]
else:
# just merge the list of tokens
value = ''.join(tokens[1:])
# macro comment maybe in tokens. Not in cursor.raw_comment
for t in cursor.get_tokens():
if t.kind == TokenKind.COMMENT:
comment = t.spelling
# special case. internal __null
# FIXME, there are probable a lot of others.
# why not Cursor.kind GNU_NULL_EXPR child instead of a token ?
if name == 'NULL' or value == '__null':
value = None
log.debug('MACRO: #define %s %s', tokens[0], value)
obj = typedesc.Macro(name, None, value)
try:
self.register(name, obj)
except DuplicateDefinitionException:
log.info(
'Redefinition of %s %s->%s',
name, self.parser.all[name].args, value)
# HACK
self.parser.all[name] = obj
self.set_location(obj, cursor)
# set the comment in the obj
obj.comment = comment
return True | python | def MACRO_DEFINITION(self, cursor):
"""
Parse MACRO_DEFINITION, only present if the TranslationUnit is
used with TranslationUnit.PARSE_DETAILED_PROCESSING_RECORD.
"""
# 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':
# code.interact(local=locals())
# Tokens !!! .kind = {IDENTIFIER, KEYWORD, LITERAL, PUNCTUATION,
# COMMENT ? } etc. see TokenKinds.def
comment = None
tokens = self._literal_handling(cursor)
# Macro name is tokens[0]
# get Macro value(s)
value = True
if isinstance(tokens, list):
if len(tokens) == 2:
value = tokens[1]
else:
# just merge the list of tokens
value = ''.join(tokens[1:])
# macro comment maybe in tokens. Not in cursor.raw_comment
for t in cursor.get_tokens():
if t.kind == TokenKind.COMMENT:
comment = t.spelling
# special case. internal __null
# FIXME, there are probable a lot of others.
# why not Cursor.kind GNU_NULL_EXPR child instead of a token ?
if name == 'NULL' or value == '__null':
value = None
log.debug('MACRO: #define %s %s', tokens[0], value)
obj = typedesc.Macro(name, None, value)
try:
self.register(name, obj)
except DuplicateDefinitionException:
log.info(
'Redefinition of %s %s->%s',
name, self.parser.all[name].args, value)
# HACK
self.parser.all[name] = obj
self.set_location(obj, cursor)
# set the comment in the obj
obj.comment = comment
return True | [
"def",
"MACRO_DEFINITION",
"(",
"self",
",",
"cursor",
")",
":",
"# TODO: optionalize macro parsing. It takes a LOT of time.",
"# ignore system macro",
"if",
"(",
"not",
"hasattr",
"(",
"cursor",
",",
"'location'",
")",
"or",
"cursor",
".",
"location",
"is",
"None",
... | Parse MACRO_DEFINITION, only present if the TranslationUnit is
used with TranslationUnit.PARSE_DETAILED_PROCESSING_RECORD. | [
"Parse",
"MACRO_DEFINITION",
"only",
"present",
"if",
"the",
"TranslationUnit",
"is",
"used",
"with",
"TranslationUnit",
".",
"PARSE_DETAILED_PROCESSING_RECORD",
"."
] | 2aeb1942a5a32a5cc798c287cd0d9e684a0181a8 | https://github.com/trolldbois/ctypeslib/blob/2aeb1942a5a32a5cc798c287cd0d9e684a0181a8/ctypeslib/codegen/cursorhandler.py#L1025-L1073 | train | 203,787 |
trolldbois/ctypeslib | ctypeslib/codegen/handler.py | ClangHandler.set_location | def set_location(self, obj, cursor):
""" Location is also used for codegeneration ordering."""
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 | python | def set_location(self, obj, cursor):
""" Location is also used for codegeneration ordering."""
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",
")",
":",
"if",
"(",
"hasattr",
"(",
"cursor",
",",
"'location'",
")",
"and",
"cursor",
".",
"location",
"is",
"not",
"None",
"and",
"cursor",
".",
"location",
".",
"file",
"is",
"not",
"... | Location is also used for codegeneration ordering. | [
"Location",
"is",
"also",
"used",
"for",
"codegeneration",
"ordering",
"."
] | 2aeb1942a5a32a5cc798c287cd0d9e684a0181a8 | https://github.com/trolldbois/ctypeslib/blob/2aeb1942a5a32a5cc798c287cd0d9e684a0181a8/ctypeslib/codegen/handler.py#L55-L60 | train | 203,788 |
trolldbois/ctypeslib | ctypeslib/codegen/handler.py | ClangHandler.set_comment | def set_comment(self, obj, cursor):
""" If a comment is available, add it to the typedesc."""
if isinstance(obj, typedesc.T):
obj.comment = cursor.brief_comment
return | python | def set_comment(self, obj, cursor):
""" If a comment is available, add it to the typedesc."""
if isinstance(obj, typedesc.T):
obj.comment = cursor.brief_comment
return | [
"def",
"set_comment",
"(",
"self",
",",
"obj",
",",
"cursor",
")",
":",
"if",
"isinstance",
"(",
"obj",
",",
"typedesc",
".",
"T",
")",
":",
"obj",
".",
"comment",
"=",
"cursor",
".",
"brief_comment",
"return"
] | If a comment is available, add it to the typedesc. | [
"If",
"a",
"comment",
"is",
"available",
"add",
"it",
"to",
"the",
"typedesc",
"."
] | 2aeb1942a5a32a5cc798c287cd0d9e684a0181a8 | https://github.com/trolldbois/ctypeslib/blob/2aeb1942a5a32a5cc798c287cd0d9e684a0181a8/ctypeslib/codegen/handler.py#L62-L66 | train | 203,789 |
trolldbois/ctypeslib | ctypeslib/codegen/handler.py | ClangHandler.make_python_name | def make_python_name(self, name):
"""Transforms an USR into a valid python name."""
# FIXME see cindex.SpellingCache
for k, v in [('<', '_'), ('>', '_'), ('::', '__'), (',', ''), (' ', ''),
("$", "DOLLAR"), (".", "DOT"), ("@", "_"), (":", "_"),
('-', '_')]:
if k in name: # template
name = name.replace(k, v)
# FIXME: test case ? I want this func to be neutral on C valid
# names.
if name.startswith("__"):
return "_X" + name
if len(name) == 0:
pass
elif name[0] in "01234567879":
return "_" + name
return name | python | def make_python_name(self, name):
"""Transforms an USR into a valid python name."""
# FIXME see cindex.SpellingCache
for k, v in [('<', '_'), ('>', '_'), ('::', '__'), (',', ''), (' ', ''),
("$", "DOLLAR"), (".", "DOT"), ("@", "_"), (":", "_"),
('-', '_')]:
if k in name: # template
name = name.replace(k, v)
# FIXME: test case ? I want this func to be neutral on C valid
# names.
if name.startswith("__"):
return "_X" + name
if len(name) == 0:
pass
elif name[0] in "01234567879":
return "_" + name
return name | [
"def",
"make_python_name",
"(",
"self",
",",
"name",
")",
":",
"# FIXME see cindex.SpellingCache",
"for",
"k",
",",
"v",
"in",
"[",
"(",
"'<'",
",",
"'_'",
")",
",",
"(",
"'>'",
",",
"'_'",
")",
",",
"(",
"'::'",
",",
"'__'",
")",
",",
"(",
"','",
... | Transforms an USR into a valid python name. | [
"Transforms",
"an",
"USR",
"into",
"a",
"valid",
"python",
"name",
"."
] | 2aeb1942a5a32a5cc798c287cd0d9e684a0181a8 | https://github.com/trolldbois/ctypeslib/blob/2aeb1942a5a32a5cc798c287cd0d9e684a0181a8/ctypeslib/codegen/handler.py#L68-L84 | train | 203,790 |
trolldbois/ctypeslib | ctypeslib/codegen/handler.py | ClangHandler._make_unknown_name | def _make_unknown_name(self, cursor):
'''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 the field index from the parent record, as to differenciate
# between unnamed siblings of a same struct
_i = 0
found = False
# Look at the parent fields to find myself
for m in parent.get_children():
# FIXME: make the good indices for fields
log.debug('_make_unknown_name child %d %s %s %s',_i,m.kind, m.type.kind,m.location)
if m.kind not in [CursorKind.STRUCT_DECL,CursorKind.UNION_DECL,
CursorKind.CLASS_DECL]:#,
#CursorKind.FIELD_DECL]:
continue
if m == _cursor_decl:
found = True
break
_i+=1
if not found:
raise NotImplementedError("_make_unknown_name BUG %s"%cursor.location)
# truncate parent name to remove the first part (union or struct)
_premainer = '_'.join(pname.split('_')[1:])
name = '%s_%d'%(_premainer,_i)
return name | python | def _make_unknown_name(self, cursor):
'''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 the field index from the parent record, as to differenciate
# between unnamed siblings of a same struct
_i = 0
found = False
# Look at the parent fields to find myself
for m in parent.get_children():
# FIXME: make the good indices for fields
log.debug('_make_unknown_name child %d %s %s %s',_i,m.kind, m.type.kind,m.location)
if m.kind not in [CursorKind.STRUCT_DECL,CursorKind.UNION_DECL,
CursorKind.CLASS_DECL]:#,
#CursorKind.FIELD_DECL]:
continue
if m == _cursor_decl:
found = True
break
_i+=1
if not found:
raise NotImplementedError("_make_unknown_name BUG %s"%cursor.location)
# truncate parent name to remove the first part (union or struct)
_premainer = '_'.join(pname.split('_')[1:])
name = '%s_%d'%(_premainer,_i)
return name | [
"def",
"_make_unknown_name",
"(",
"self",
",",
"cursor",
")",
":",
"parent",
"=",
"cursor",
".",
"lexical_parent",
"pname",
"=",
"self",
".",
"get_unique_name",
"(",
"parent",
")",
"log",
".",
"debug",
"(",
"'_make_unknown_name: Got parent get_unique_name %s'",
",... | Creates a name for unname type | [
"Creates",
"a",
"name",
"for",
"unname",
"type"
] | 2aeb1942a5a32a5cc798c287cd0d9e684a0181a8 | https://github.com/trolldbois/ctypeslib/blob/2aeb1942a5a32a5cc798c287cd0d9e684a0181a8/ctypeslib/codegen/handler.py#L86-L114 | train | 203,791 |
trolldbois/ctypeslib | ctypeslib/codegen/handler.py | ClangHandler.get_unique_name | def get_unique_name(self, cursor):
"""get the spelling or create a unique name for a cursor"""
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
if (cursor.semantic_parent
and cursor.semantic_parent.kind == CursorKind.TRANSLATION_UNIT):
name = self.make_python_name(cursor.get_usr())
log.debug('get_unique_name: root unnamed type kind %s',cursor.kind)
elif cursor.kind in [CursorKind.STRUCT_DECL,CursorKind.UNION_DECL,
CursorKind.CLASS_DECL,CursorKind.FIELD_DECL]:
name = self._make_unknown_name(cursor)
log.debug('Unnamed cursor type, got name %s',name)
else:
log.debug('Unnamed cursor, No idea what to do')
#import code
#code.interact(local=locals())
return ''
if cursor.kind in [CursorKind.STRUCT_DECL,CursorKind.UNION_DECL,
CursorKind.CLASS_DECL]:
names= {CursorKind.STRUCT_DECL: 'struct',
CursorKind.UNION_DECL: 'union',
CursorKind.CLASS_DECL: 'class',
CursorKind.TYPE_REF: ''}
name = '%s_%s'%(names[cursor.kind],name)
log.debug('get_unique_name: name "%s"',name)
return name | python | def get_unique_name(self, cursor):
"""get the spelling or create a unique name for a cursor"""
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
if (cursor.semantic_parent
and cursor.semantic_parent.kind == CursorKind.TRANSLATION_UNIT):
name = self.make_python_name(cursor.get_usr())
log.debug('get_unique_name: root unnamed type kind %s',cursor.kind)
elif cursor.kind in [CursorKind.STRUCT_DECL,CursorKind.UNION_DECL,
CursorKind.CLASS_DECL,CursorKind.FIELD_DECL]:
name = self._make_unknown_name(cursor)
log.debug('Unnamed cursor type, got name %s',name)
else:
log.debug('Unnamed cursor, No idea what to do')
#import code
#code.interact(local=locals())
return ''
if cursor.kind in [CursorKind.STRUCT_DECL,CursorKind.UNION_DECL,
CursorKind.CLASS_DECL]:
names= {CursorKind.STRUCT_DECL: 'struct',
CursorKind.UNION_DECL: 'union',
CursorKind.CLASS_DECL: 'class',
CursorKind.TYPE_REF: ''}
name = '%s_%s'%(names[cursor.kind],name)
log.debug('get_unique_name: name "%s"',name)
return name | [
"def",
"get_unique_name",
"(",
"self",
",",
"cursor",
")",
":",
"name",
"=",
"''",
"if",
"cursor",
".",
"kind",
"in",
"[",
"CursorKind",
".",
"UNEXPOSED_DECL",
"]",
":",
"return",
"''",
"# covers most cases",
"name",
"=",
"cursor",
".",
"spelling",
"# if i... | get the spelling or create a unique name for a cursor | [
"get",
"the",
"spelling",
"or",
"create",
"a",
"unique",
"name",
"for",
"a",
"cursor"
] | 2aeb1942a5a32a5cc798c287cd0d9e684a0181a8 | https://github.com/trolldbois/ctypeslib/blob/2aeb1942a5a32a5cc798c287cd0d9e684a0181a8/ctypeslib/codegen/handler.py#L116-L147 | train | 203,792 |
trolldbois/ctypeslib | ctypeslib/codegen/handler.py | ClangHandler.get_literal_kind_affinity | def get_literal_kind_affinity(self, literal_kind):
''' 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,
TypeKind.SHORT, TypeKind.INT, TypeKind.LONG,
TypeKind.LONGLONG, TypeKind.INT128, ]
elif literal_kind == CursorKind.STRING_LITERAL:
return [TypeKind.CHAR16, TypeKind.CHAR32, TypeKind.CHAR_S,
TypeKind.SCHAR, TypeKind.WCHAR] # DEBUG
elif literal_kind == CursorKind.CHARACTER_LITERAL:
return [TypeKind.CHAR_U, TypeKind.UCHAR]
elif literal_kind == CursorKind.FLOATING_LITERAL:
return [TypeKind.FLOAT, TypeKind.DOUBLE, TypeKind.LONGDOUBLE]
elif literal_kind == CursorKind.IMAGINARY_LITERAL:
return []
return [] | python | def get_literal_kind_affinity(self, literal_kind):
''' 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,
TypeKind.SHORT, TypeKind.INT, TypeKind.LONG,
TypeKind.LONGLONG, TypeKind.INT128, ]
elif literal_kind == CursorKind.STRING_LITERAL:
return [TypeKind.CHAR16, TypeKind.CHAR32, TypeKind.CHAR_S,
TypeKind.SCHAR, TypeKind.WCHAR] # DEBUG
elif literal_kind == CursorKind.CHARACTER_LITERAL:
return [TypeKind.CHAR_U, TypeKind.UCHAR]
elif literal_kind == CursorKind.FLOATING_LITERAL:
return [TypeKind.FLOAT, TypeKind.DOUBLE, TypeKind.LONGDOUBLE]
elif literal_kind == CursorKind.IMAGINARY_LITERAL:
return []
return [] | [
"def",
"get_literal_kind_affinity",
"(",
"self",
",",
"literal_kind",
")",
":",
"if",
"literal_kind",
"==",
"CursorKind",
".",
"INTEGER_LITERAL",
":",
"return",
"[",
"TypeKind",
".",
"USHORT",
",",
"TypeKind",
".",
"UINT",
",",
"TypeKind",
".",
"ULONG",
",",
... | return the list of fundamental types that are adequate for which
this literal_kind is adequate | [
"return",
"the",
"list",
"of",
"fundamental",
"types",
"that",
"are",
"adequate",
"for",
"which",
"this",
"literal_kind",
"is",
"adequate"
] | 2aeb1942a5a32a5cc798c287cd0d9e684a0181a8 | https://github.com/trolldbois/ctypeslib/blob/2aeb1942a5a32a5cc798c287cd0d9e684a0181a8/ctypeslib/codegen/handler.py#L172-L189 | train | 203,793 |
trolldbois/ctypeslib | ctypeslib/dynamic_module.py | is_newer | 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.
"""
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 | python | 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.
"""
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",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"source",
")",
":",
"raise",
"ValueError",
"(",
"\"file '%s' does not exist\"",
"%",
"source",
")",
"if",
"not",
"os",
".",
"path",
".",
"exi... | 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. | [
"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",
... | 2aeb1942a5a32a5cc798c287cd0d9e684a0181a8 | https://github.com/trolldbois/ctypeslib/blob/2aeb1942a5a32a5cc798c287cd0d9e684a0181a8/ctypeslib/dynamic_module.py#L85-L100 | train | 203,794 |
trolldbois/ctypeslib | ctypeslib/codegen/clangparser.py | Clang_Parser.startElement | def startElement(self, node):
"""Recurses in children of this node"""
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_location:
return
# find and call the handler for this element
log.debug(
'%s:%d: Found a %s|%s|%s',
node.location.file,
node.location.line,
node.kind.name,
node.displayname,
node.spelling)
# build stuff.
try:
stop_recurse = self.parse_cursor(node)
# Signature of parse_cursor is:
# if the fn returns True, do not recurse into children.
# anything else will be ignored.
if stop_recurse is not False: # True:
return
# if fn returns something, if this element has children, treat
# them.
for child in node.get_children():
self.startElement(child)
except InvalidDefinitionError:
# if the definition is invalid
pass
# startElement returns None.
return None | python | def startElement(self, node):
"""Recurses in children of this node"""
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_location:
return
# find and call the handler for this element
log.debug(
'%s:%d: Found a %s|%s|%s',
node.location.file,
node.location.line,
node.kind.name,
node.displayname,
node.spelling)
# build stuff.
try:
stop_recurse = self.parse_cursor(node)
# Signature of parse_cursor is:
# if the fn returns True, do not recurse into children.
# anything else will be ignored.
if stop_recurse is not False: # True:
return
# if fn returns something, if this element has children, treat
# them.
for child in node.get_children():
self.startElement(child)
except InvalidDefinitionError:
# if the definition is invalid
pass
# startElement returns None.
return None | [
"def",
"startElement",
"(",
"self",
",",
"node",
")",
":",
"if",
"node",
"is",
"None",
":",
"return",
"if",
"self",
".",
"__filter_location",
"is",
"not",
"None",
":",
"# dont even parse includes.",
"# FIXME: go back on dependencies ?",
"if",
"node",
".",
"locat... | Recurses in children of this node | [
"Recurses",
"in",
"children",
"of",
"this",
"node"
] | 2aeb1942a5a32a5cc798c287cd0d9e684a0181a8 | https://github.com/trolldbois/ctypeslib/blob/2aeb1942a5a32a5cc798c287cd0d9e684a0181a8/ctypeslib/codegen/clangparser.py#L137-L173 | train | 203,795 |
trolldbois/ctypeslib | ctypeslib/codegen/clangparser.py | Clang_Parser.register | def register(self, name, obj):
"""Registers an unique type description"""
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)
self.all[name] = obj
return obj | python | def register(self, name, obj):
"""Registers an unique type description"""
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)
self.all[name] = obj
return obj | [
"def",
"register",
"(",
"self",
",",
"name",
",",
"obj",
")",
":",
"if",
"name",
"in",
"self",
".",
"all",
":",
"log",
".",
"debug",
"(",
"'register: %s already existed: %s'",
",",
"name",
",",
"obj",
".",
"name",
")",
"# code.interact(local=locals())",
"r... | Registers an unique type description | [
"Registers",
"an",
"unique",
"type",
"description"
] | 2aeb1942a5a32a5cc798c287cd0d9e684a0181a8 | https://github.com/trolldbois/ctypeslib/blob/2aeb1942a5a32a5cc798c287cd0d9e684a0181a8/ctypeslib/codegen/clangparser.py#L175-L184 | train | 203,796 |
trolldbois/ctypeslib | ctypeslib/codegen/util.py | get_tu | 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_warnings is a convenience argument to enable all compiler warnings.
"""
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']
return TranslationUnit.from_source(name, args, unsaved_files=[(name,
source)]) | python | 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_warnings is a convenience argument to enable all compiler warnings.
"""
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']
return TranslationUnit.from_source(name, args, unsaved_files=[(name,
source)]) | [
"def",
"get_tu",
"(",
"source",
",",
"lang",
"=",
"'c'",
",",
"all_warnings",
"=",
"False",
",",
"flags",
"=",
"None",
")",
":",
"args",
"=",
"list",
"(",
"flags",
"or",
"[",
"]",
")",
"name",
"=",
"'t.c'",
"if",
"lang",
"==",
"'cpp'",
":",
"name... | 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_warnings is a convenience argument to enable all compiler warnings. | [
"Obtain",
"a",
"translation",
"unit",
"from",
"source",
"and",
"language",
"."
] | 2aeb1942a5a32a5cc798c287cd0d9e684a0181a8 | https://github.com/trolldbois/ctypeslib/blob/2aeb1942a5a32a5cc798c287cd0d9e684a0181a8/ctypeslib/codegen/util.py#L13-L38 | train | 203,797 |
trolldbois/ctypeslib | ctypeslib/codegen/util.py | get_cursor | 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.
"""
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 = get_cursor(cursor, spelling)
if result is not None:
return result
return None | python | 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.
"""
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 = get_cursor(cursor, spelling)
if result is not None:
return result
return None | [
"def",
"get_cursor",
"(",
"source",
",",
"spelling",
")",
":",
"children",
"=",
"[",
"]",
"if",
"isinstance",
"(",
"source",
",",
"Cursor",
")",
":",
"children",
"=",
"source",
".",
"get_children",
"(",
")",
"else",
":",
"# Assume TU",
"children",
"=",
... | 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. | [
"Obtain",
"a",
"cursor",
"from",
"a",
"source",
"object",
"."
] | 2aeb1942a5a32a5cc798c287cd0d9e684a0181a8 | https://github.com/trolldbois/ctypeslib/blob/2aeb1942a5a32a5cc798c287cd0d9e684a0181a8/ctypeslib/codegen/util.py#L41-L66 | train | 203,798 |
trolldbois/ctypeslib | ctypeslib/codegen/util.py | get_cursors | 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.
"""
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 into children.
cursors.extend(get_cursors(cursor, spelling))
return cursors | python | 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.
"""
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 into children.
cursors.extend(get_cursors(cursor, spelling))
return cursors | [
"def",
"get_cursors",
"(",
"source",
",",
"spelling",
")",
":",
"cursors",
"=",
"[",
"]",
"children",
"=",
"[",
"]",
"if",
"isinstance",
"(",
"source",
",",
"Cursor",
")",
":",
"children",
"=",
"source",
".",
"get_children",
"(",
")",
"else",
":",
"#... | 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. | [
"Obtain",
"all",
"cursors",
"from",
"a",
"source",
"object",
"with",
"a",
"specific",
"spelling",
"."
] | 2aeb1942a5a32a5cc798c287cd0d9e684a0181a8 | https://github.com/trolldbois/ctypeslib/blob/2aeb1942a5a32a5cc798c287cd0d9e684a0181a8/ctypeslib/codegen/util.py#L69-L93 | train | 203,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.