id
int32
0
252k
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
51
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
233,000
awkman/pywifi
pywifi/_wifiutil_win.py
WifiUtil.network_profile_name_list
def network_profile_name_list(self, obj): """Get AP profile names.""" profile_list = pointer(WLAN_PROFILE_INFO_LIST()) self._wlan_get_profile_list(self._handle, byref(obj['guid']), byref(profile_list)) profiles = cast(profile_list.contents.ProfileInfo, POINTER(WLAN_PROFILE_INFO)) profile_name_list = [] for i in range(profile_list.contents.dwNumberOfItems): profile_name = '' for j in range(len(profiles[i].strProfileName)): profile_name += profiles[i].strProfileName[j] profile_name_list.append(profile_name) return profile_name_list
python
def network_profile_name_list(self, obj): profile_list = pointer(WLAN_PROFILE_INFO_LIST()) self._wlan_get_profile_list(self._handle, byref(obj['guid']), byref(profile_list)) profiles = cast(profile_list.contents.ProfileInfo, POINTER(WLAN_PROFILE_INFO)) profile_name_list = [] for i in range(profile_list.contents.dwNumberOfItems): profile_name = '' for j in range(len(profiles[i].strProfileName)): profile_name += profiles[i].strProfileName[j] profile_name_list.append(profile_name) return profile_name_list
[ "def", "network_profile_name_list", "(", "self", ",", "obj", ")", ":", "profile_list", "=", "pointer", "(", "WLAN_PROFILE_INFO_LIST", "(", ")", ")", "self", ".", "_wlan_get_profile_list", "(", "self", ".", "_handle", ",", "byref", "(", "obj", "[", "'guid'", ...
Get AP profile names.
[ "Get", "AP", "profile", "names", "." ]
719baf73d8d32c623dbaf5e9de5d973face152a4
https://github.com/awkman/pywifi/blob/719baf73d8d32c623dbaf5e9de5d973face152a4/pywifi/_wifiutil_win.py#L399-L416
233,001
awkman/pywifi
pywifi/_wifiutil_win.py
WifiUtil.remove_network_profile
def remove_network_profile(self, obj, params): """Remove the specified AP profile.""" self._logger.debug("delete profile: %s", params.ssid) str_buf = create_unicode_buffer(params.ssid) ret = self._wlan_delete_profile(self._handle, obj['guid'], str_buf) self._logger.debug("delete result %d", ret)
python
def remove_network_profile(self, obj, params): self._logger.debug("delete profile: %s", params.ssid) str_buf = create_unicode_buffer(params.ssid) ret = self._wlan_delete_profile(self._handle, obj['guid'], str_buf) self._logger.debug("delete result %d", ret)
[ "def", "remove_network_profile", "(", "self", ",", "obj", ",", "params", ")", ":", "self", ".", "_logger", ".", "debug", "(", "\"delete profile: %s\"", ",", "params", ".", "ssid", ")", "str_buf", "=", "create_unicode_buffer", "(", "params", ".", "ssid", ")",...
Remove the specified AP profile.
[ "Remove", "the", "specified", "AP", "profile", "." ]
719baf73d8d32c623dbaf5e9de5d973face152a4
https://github.com/awkman/pywifi/blob/719baf73d8d32c623dbaf5e9de5d973face152a4/pywifi/_wifiutil_win.py#L452-L458
233,002
awkman/pywifi
pywifi/_wifiutil_win.py
WifiUtil.remove_all_network_profiles
def remove_all_network_profiles(self, obj): """Remove all the AP profiles.""" profile_name_list = self.network_profile_name_list(obj) for profile_name in profile_name_list: self._logger.debug("delete profile: %s", profile_name) str_buf = create_unicode_buffer(profile_name) ret = self._wlan_delete_profile(self._handle, obj['guid'], str_buf) self._logger.debug("delete result %d", ret)
python
def remove_all_network_profiles(self, obj): profile_name_list = self.network_profile_name_list(obj) for profile_name in profile_name_list: self._logger.debug("delete profile: %s", profile_name) str_buf = create_unicode_buffer(profile_name) ret = self._wlan_delete_profile(self._handle, obj['guid'], str_buf) self._logger.debug("delete result %d", ret)
[ "def", "remove_all_network_profiles", "(", "self", ",", "obj", ")", ":", "profile_name_list", "=", "self", ".", "network_profile_name_list", "(", "obj", ")", "for", "profile_name", "in", "profile_name_list", ":", "self", ".", "_logger", ".", "debug", "(", "\"del...
Remove all the AP profiles.
[ "Remove", "all", "the", "AP", "profiles", "." ]
719baf73d8d32c623dbaf5e9de5d973face152a4
https://github.com/awkman/pywifi/blob/719baf73d8d32c623dbaf5e9de5d973face152a4/pywifi/_wifiutil_win.py#L460-L469
233,003
awkman/pywifi
pywifi/_wifiutil_linux.py
WifiUtil.remove_network_profile
def remove_network_profile(self, obj, params): """Remove the specified AP profiles""" network_id = -1 profiles = self.network_profiles(obj) for profile in profiles: if profile == params: network_id = profile.id if network_id != -1: self._send_cmd_to_wpas(obj['name'], 'REMOVE_NETWORK {}'.format(network_id))
python
def remove_network_profile(self, obj, params): network_id = -1 profiles = self.network_profiles(obj) for profile in profiles: if profile == params: network_id = profile.id if network_id != -1: self._send_cmd_to_wpas(obj['name'], 'REMOVE_NETWORK {}'.format(network_id))
[ "def", "remove_network_profile", "(", "self", ",", "obj", ",", "params", ")", ":", "network_id", "=", "-", "1", "profiles", "=", "self", ".", "network_profiles", "(", "obj", ")", "for", "profile", "in", "profiles", ":", "if", "profile", "==", "params", "...
Remove the specified AP profiles
[ "Remove", "the", "specified", "AP", "profiles" ]
719baf73d8d32c623dbaf5e9de5d973face152a4
https://github.com/awkman/pywifi/blob/719baf73d8d32c623dbaf5e9de5d973face152a4/pywifi/_wifiutil_linux.py#L246-L258
233,004
awkman/pywifi
pywifi/iface.py
Interface.scan
def scan(self): """Trigger the wifi interface to scan.""" self._logger.info("iface '%s' scans", self.name()) self._wifi_ctrl.scan(self._raw_obj)
python
def scan(self): self._logger.info("iface '%s' scans", self.name()) self._wifi_ctrl.scan(self._raw_obj)
[ "def", "scan", "(", "self", ")", ":", "self", ".", "_logger", ".", "info", "(", "\"iface '%s' scans\"", ",", "self", ".", "name", "(", ")", ")", "self", ".", "_wifi_ctrl", ".", "scan", "(", "self", ".", "_raw_obj", ")" ]
Trigger the wifi interface to scan.
[ "Trigger", "the", "wifi", "interface", "to", "scan", "." ]
719baf73d8d32c623dbaf5e9de5d973face152a4
https://github.com/awkman/pywifi/blob/719baf73d8d32c623dbaf5e9de5d973face152a4/pywifi/iface.py#L41-L46
233,005
awkman/pywifi
pywifi/iface.py
Interface.scan_results
def scan_results(self): """Return the scan result.""" bsses = self._wifi_ctrl.scan_results(self._raw_obj) if self._logger.isEnabledFor(logging.INFO): for bss in bsses: self._logger.info("Find bss:") self._logger.info("\tbssid: %s", bss.bssid) self._logger.info("\tssid: %s", bss.ssid) self._logger.info("\tfreq: %d", bss.freq) self._logger.info("\tauth: %s", bss.auth) self._logger.info("\takm: %s", bss.akm) self._logger.info("\tsignal: %d", bss.signal) return bsses
python
def scan_results(self): bsses = self._wifi_ctrl.scan_results(self._raw_obj) if self._logger.isEnabledFor(logging.INFO): for bss in bsses: self._logger.info("Find bss:") self._logger.info("\tbssid: %s", bss.bssid) self._logger.info("\tssid: %s", bss.ssid) self._logger.info("\tfreq: %d", bss.freq) self._logger.info("\tauth: %s", bss.auth) self._logger.info("\takm: %s", bss.akm) self._logger.info("\tsignal: %d", bss.signal) return bsses
[ "def", "scan_results", "(", "self", ")", ":", "bsses", "=", "self", ".", "_wifi_ctrl", ".", "scan_results", "(", "self", ".", "_raw_obj", ")", "if", "self", ".", "_logger", ".", "isEnabledFor", "(", "logging", ".", "INFO", ")", ":", "for", "bss", "in",...
Return the scan result.
[ "Return", "the", "scan", "result", "." ]
719baf73d8d32c623dbaf5e9de5d973face152a4
https://github.com/awkman/pywifi/blob/719baf73d8d32c623dbaf5e9de5d973face152a4/pywifi/iface.py#L48-L63
233,006
awkman/pywifi
pywifi/iface.py
Interface.network_profiles
def network_profiles(self): """Get all the AP profiles.""" profiles = self._wifi_ctrl.network_profiles(self._raw_obj) if self._logger.isEnabledFor(logging.INFO): for profile in profiles: self._logger.info("Get profile:") self._logger.info("\tssid: %s", profile.ssid) self._logger.info("\tauth: %s", profile.auth) self._logger.info("\takm: %s", profile.akm) self._logger.info("\tcipher: %s", profile.cipher) return profiles
python
def network_profiles(self): profiles = self._wifi_ctrl.network_profiles(self._raw_obj) if self._logger.isEnabledFor(logging.INFO): for profile in profiles: self._logger.info("Get profile:") self._logger.info("\tssid: %s", profile.ssid) self._logger.info("\tauth: %s", profile.auth) self._logger.info("\takm: %s", profile.akm) self._logger.info("\tcipher: %s", profile.cipher) return profiles
[ "def", "network_profiles", "(", "self", ")", ":", "profiles", "=", "self", ".", "_wifi_ctrl", ".", "network_profiles", "(", "self", ".", "_raw_obj", ")", "if", "self", ".", "_logger", ".", "isEnabledFor", "(", "logging", ".", "INFO", ")", ":", "for", "pr...
Get all the AP profiles.
[ "Get", "all", "the", "AP", "profiles", "." ]
719baf73d8d32c623dbaf5e9de5d973face152a4
https://github.com/awkman/pywifi/blob/719baf73d8d32c623dbaf5e9de5d973face152a4/pywifi/iface.py#L80-L93
233,007
awkman/pywifi
pywifi/iface.py
Interface.disconnect
def disconnect(self): """Disconnect from the specified AP.""" self._logger.info("iface '%s' disconnects", self.name()) self._wifi_ctrl.disconnect(self._raw_obj)
python
def disconnect(self): self._logger.info("iface '%s' disconnects", self.name()) self._wifi_ctrl.disconnect(self._raw_obj)
[ "def", "disconnect", "(", "self", ")", ":", "self", ".", "_logger", ".", "info", "(", "\"iface '%s' disconnects\"", ",", "self", ".", "name", "(", ")", ")", "self", ".", "_wifi_ctrl", ".", "disconnect", "(", "self", ".", "_raw_obj", ")" ]
Disconnect from the specified AP.
[ "Disconnect", "from", "the", "specified", "AP", "." ]
719baf73d8d32c623dbaf5e9de5d973face152a4
https://github.com/awkman/pywifi/blob/719baf73d8d32c623dbaf5e9de5d973face152a4/pywifi/iface.py#L103-L108
233,008
thebjorn/pydeps
pydeps/depgraph.py
Source.label
def label(self): """Convert a module name to a formatted node label. This is a default policy - please override. """ if len(self.name) > 14 and '.' in self.name: return '\\.\\n'.join(self.name.split('.')) # pragma: nocover return self.name
python
def label(self): if len(self.name) > 14 and '.' in self.name: return '\\.\\n'.join(self.name.split('.')) # pragma: nocover return self.name
[ "def", "label", "(", "self", ")", ":", "if", "len", "(", "self", ".", "name", ")", ">", "14", "and", "'.'", "in", "self", ".", "name", ":", "return", "'\\\\.\\\\n'", ".", "join", "(", "self", ".", "name", ".", "split", "(", "'.'", ")", ")", "# ...
Convert a module name to a formatted node label. This is a default policy - please override.
[ "Convert", "a", "module", "name", "to", "a", "formatted", "node", "label", ".", "This", "is", "a", "default", "policy", "-", "please", "override", "." ]
1e6715b7bea47a40e8042821b57937deaaa0fdc3
https://github.com/thebjorn/pydeps/blob/1e6715b7bea47a40e8042821b57937deaaa0fdc3/pydeps/depgraph.py#L131-L137
233,009
thebjorn/pydeps
pydeps/depgraph.py
DepGraph.proximity_metric
def proximity_metric(self, a, b): """Return the weight of the dependency from a to b. Higher weights usually have shorter straighter edges. Return 1 if it has normal weight. A value of 4 is usually good for ensuring that a related pair of modules are drawn next to each other. Returns an int between 1 (unknown, default), and 4 (very related). """ # if self._is_pylib(a) and self._is_pylib(b): # return 1 res = 1 for ap, bp, n in zip(a.path_parts, b.path_parts, list(range(4))): res += ap == bp if n >= 3: break return res
python
def proximity_metric(self, a, b): # if self._is_pylib(a) and self._is_pylib(b): # return 1 res = 1 for ap, bp, n in zip(a.path_parts, b.path_parts, list(range(4))): res += ap == bp if n >= 3: break return res
[ "def", "proximity_metric", "(", "self", ",", "a", ",", "b", ")", ":", "# if self._is_pylib(a) and self._is_pylib(b):", "# return 1", "res", "=", "1", "for", "ap", ",", "bp", ",", "n", "in", "zip", "(", "a", ".", "path_parts", ",", "b", ".", "path_parts...
Return the weight of the dependency from a to b. Higher weights usually have shorter straighter edges. Return 1 if it has normal weight. A value of 4 is usually good for ensuring that a related pair of modules are drawn next to each other. Returns an int between 1 (unknown, default), and 4 (very related).
[ "Return", "the", "weight", "of", "the", "dependency", "from", "a", "to", "b", ".", "Higher", "weights", "usually", "have", "shorter", "straighter", "edges", ".", "Return", "1", "if", "it", "has", "normal", "weight", ".", "A", "value", "of", "4", "is", ...
1e6715b7bea47a40e8042821b57937deaaa0fdc3
https://github.com/thebjorn/pydeps/blob/1e6715b7bea47a40e8042821b57937deaaa0fdc3/pydeps/depgraph.py#L170-L186
233,010
thebjorn/pydeps
pydeps/depgraph.py
DepGraph.dissimilarity_metric
def dissimilarity_metric(self, a, b): """Return non-zero if references to this module are strange, and should be drawn extra-long. The value defines the length, in rank. This is also good for putting some vertical space between seperate subsystems. Returns an int between 1 (default) and 4 (highly unrelated). """ # if self._is_pylib(a) and self._is_pylib(b): # return 1 res = 4 for an, bn, n in zip_longest(a.name_parts, b.name_parts, list(range(4))): res -= an == bn if n >= 3: break return res
python
def dissimilarity_metric(self, a, b): # if self._is_pylib(a) and self._is_pylib(b): # return 1 res = 4 for an, bn, n in zip_longest(a.name_parts, b.name_parts, list(range(4))): res -= an == bn if n >= 3: break return res
[ "def", "dissimilarity_metric", "(", "self", ",", "a", ",", "b", ")", ":", "# if self._is_pylib(a) and self._is_pylib(b):", "# return 1", "res", "=", "4", "for", "an", ",", "bn", ",", "n", "in", "zip_longest", "(", "a", ".", "name_parts", ",", "b", ".", ...
Return non-zero if references to this module are strange, and should be drawn extra-long. The value defines the length, in rank. This is also good for putting some vertical space between seperate subsystems. Returns an int between 1 (default) and 4 (highly unrelated).
[ "Return", "non", "-", "zero", "if", "references", "to", "this", "module", "are", "strange", "and", "should", "be", "drawn", "extra", "-", "long", ".", "The", "value", "defines", "the", "length", "in", "rank", ".", "This", "is", "also", "good", "for", "...
1e6715b7bea47a40e8042821b57937deaaa0fdc3
https://github.com/thebjorn/pydeps/blob/1e6715b7bea47a40e8042821b57937deaaa0fdc3/pydeps/depgraph.py#L188-L204
233,011
thebjorn/pydeps
pydeps/depgraph.py
DepGraph.connect_generations
def connect_generations(self): """Traverse depth-first adding imported_by. """ # for src in list(self.sources.values()): for src in self.sources.values(): for _child in src.imports: if _child in self.sources: child = self.sources[_child] child.imported_by.add(src.name)
python
def connect_generations(self): # for src in list(self.sources.values()): for src in self.sources.values(): for _child in src.imports: if _child in self.sources: child = self.sources[_child] child.imported_by.add(src.name)
[ "def", "connect_generations", "(", "self", ")", ":", "# for src in list(self.sources.values()):", "for", "src", "in", "self", ".", "sources", ".", "values", "(", ")", ":", "for", "_child", "in", "src", ".", "imports", ":", "if", "_child", "in", "self", ".", ...
Traverse depth-first adding imported_by.
[ "Traverse", "depth", "-", "first", "adding", "imported_by", "." ]
1e6715b7bea47a40e8042821b57937deaaa0fdc3
https://github.com/thebjorn/pydeps/blob/1e6715b7bea47a40e8042821b57937deaaa0fdc3/pydeps/depgraph.py#L339-L347
233,012
thebjorn/pydeps
pydeps/depgraph.py
DepGraph.remove_excluded
def remove_excluded(self): """Remove all sources marked as excluded. """ # import yaml # print yaml.dump({k:v.__json__() for k,v in self.sources.items()}, default_flow_style=False) sources = list(self.sources.values()) for src in sources: if src.excluded: del self.sources[src.name] src.imports = [m for m in src.imports if not self._exclude(m)] src.imported_by = [m for m in src.imported_by if not self._exclude(m)]
python
def remove_excluded(self): # import yaml # print yaml.dump({k:v.__json__() for k,v in self.sources.items()}, default_flow_style=False) sources = list(self.sources.values()) for src in sources: if src.excluded: del self.sources[src.name] src.imports = [m for m in src.imports if not self._exclude(m)] src.imported_by = [m for m in src.imported_by if not self._exclude(m)]
[ "def", "remove_excluded", "(", "self", ")", ":", "# import yaml", "# print yaml.dump({k:v.__json__() for k,v in self.sources.items()}, default_flow_style=False)", "sources", "=", "list", "(", "self", ".", "sources", ".", "values", "(", ")", ")", "for", "src", "in", "sou...
Remove all sources marked as excluded.
[ "Remove", "all", "sources", "marked", "as", "excluded", "." ]
1e6715b7bea47a40e8042821b57937deaaa0fdc3
https://github.com/thebjorn/pydeps/blob/1e6715b7bea47a40e8042821b57937deaaa0fdc3/pydeps/depgraph.py#L390-L400
233,013
thebjorn/pydeps
pydeps/dot.py
to_bytes
def to_bytes(s): # pragma: nocover """Convert an item into bytes. """ if isinstance(s, bytes): return s if isinstance(s, str) or is_unicode(s): return s.encode("utf-8") try: return unicode(s).encode("utf-8") except NameError: return str(s).encode("utf-8")
python
def to_bytes(s): # pragma: nocover if isinstance(s, bytes): return s if isinstance(s, str) or is_unicode(s): return s.encode("utf-8") try: return unicode(s).encode("utf-8") except NameError: return str(s).encode("utf-8")
[ "def", "to_bytes", "(", "s", ")", ":", "# pragma: nocover", "if", "isinstance", "(", "s", ",", "bytes", ")", ":", "return", "s", "if", "isinstance", "(", "s", ",", "str", ")", "or", "is_unicode", "(", "s", ")", ":", "return", "s", ".", "encode", "(...
Convert an item into bytes.
[ "Convert", "an", "item", "into", "bytes", "." ]
1e6715b7bea47a40e8042821b57937deaaa0fdc3
https://github.com/thebjorn/pydeps/blob/1e6715b7bea47a40e8042821b57937deaaa0fdc3/pydeps/dot.py#L25-L35
233,014
thebjorn/pydeps
pydeps/dot.py
cmd2args
def cmd2args(cmd): """Prepare a command line for execution by Popen. """ if isinstance(cmd, str): return cmd if win32 else shlex.split(cmd) return cmd
python
def cmd2args(cmd): if isinstance(cmd, str): return cmd if win32 else shlex.split(cmd) return cmd
[ "def", "cmd2args", "(", "cmd", ")", ":", "if", "isinstance", "(", "cmd", ",", "str", ")", ":", "return", "cmd", "if", "win32", "else", "shlex", ".", "split", "(", "cmd", ")", "return", "cmd" ]
Prepare a command line for execution by Popen.
[ "Prepare", "a", "command", "line", "for", "execution", "by", "Popen", "." ]
1e6715b7bea47a40e8042821b57937deaaa0fdc3
https://github.com/thebjorn/pydeps/blob/1e6715b7bea47a40e8042821b57937deaaa0fdc3/pydeps/dot.py#L38-L43
233,015
thebjorn/pydeps
pydeps/dot.py
pipe
def pipe(cmd, txt): """Pipe `txt` into the command `cmd` and return the output. """ return Popen( cmd2args(cmd), stdout=subprocess.PIPE, stdin=subprocess.PIPE, shell=win32 ).communicate(txt)[0]
python
def pipe(cmd, txt): return Popen( cmd2args(cmd), stdout=subprocess.PIPE, stdin=subprocess.PIPE, shell=win32 ).communicate(txt)[0]
[ "def", "pipe", "(", "cmd", ",", "txt", ")", ":", "return", "Popen", "(", "cmd2args", "(", "cmd", ")", ",", "stdout", "=", "subprocess", ".", "PIPE", ",", "stdin", "=", "subprocess", ".", "PIPE", ",", "shell", "=", "win32", ")", ".", "communicate", ...
Pipe `txt` into the command `cmd` and return the output.
[ "Pipe", "txt", "into", "the", "command", "cmd", "and", "return", "the", "output", "." ]
1e6715b7bea47a40e8042821b57937deaaa0fdc3
https://github.com/thebjorn/pydeps/blob/1e6715b7bea47a40e8042821b57937deaaa0fdc3/pydeps/dot.py#L46-L54
233,016
thebjorn/pydeps
pydeps/dot.py
dot
def dot(src, **kw): """Execute the dot command to create an svg output. """ cmd = "dot -T%s" % kw.pop('T', 'svg') for k, v in list(kw.items()): if v is True: cmd += " -%s" % k else: cmd += " -%s%s" % (k, v) return pipe(cmd, to_bytes(src))
python
def dot(src, **kw): cmd = "dot -T%s" % kw.pop('T', 'svg') for k, v in list(kw.items()): if v is True: cmd += " -%s" % k else: cmd += " -%s%s" % (k, v) return pipe(cmd, to_bytes(src))
[ "def", "dot", "(", "src", ",", "*", "*", "kw", ")", ":", "cmd", "=", "\"dot -T%s\"", "%", "kw", ".", "pop", "(", "'T'", ",", "'svg'", ")", "for", "k", ",", "v", "in", "list", "(", "kw", ".", "items", "(", ")", ")", ":", "if", "v", "is", "...
Execute the dot command to create an svg output.
[ "Execute", "the", "dot", "command", "to", "create", "an", "svg", "output", "." ]
1e6715b7bea47a40e8042821b57937deaaa0fdc3
https://github.com/thebjorn/pydeps/blob/1e6715b7bea47a40e8042821b57937deaaa0fdc3/pydeps/dot.py#L57-L67
233,017
thebjorn/pydeps
pydeps/dot.py
call_graphviz_dot
def call_graphviz_dot(src, fmt): """Call dot command, and provide helpful error message if we cannot find it. """ try: svg = dot(src, T=fmt) except OSError as e: # pragma: nocover if e.errno == 2: cli.error(""" cannot find 'dot' pydeps calls dot (from graphviz) to create svg diagrams, please make sure that the dot executable is available on your path. """) raise return svg
python
def call_graphviz_dot(src, fmt): try: svg = dot(src, T=fmt) except OSError as e: # pragma: nocover if e.errno == 2: cli.error(""" cannot find 'dot' pydeps calls dot (from graphviz) to create svg diagrams, please make sure that the dot executable is available on your path. """) raise return svg
[ "def", "call_graphviz_dot", "(", "src", ",", "fmt", ")", ":", "try", ":", "svg", "=", "dot", "(", "src", ",", "T", "=", "fmt", ")", "except", "OSError", "as", "e", ":", "# pragma: nocover", "if", "e", ".", "errno", "==", "2", ":", "cli", ".", "er...
Call dot command, and provide helpful error message if we cannot find it.
[ "Call", "dot", "command", "and", "provide", "helpful", "error", "message", "if", "we", "cannot", "find", "it", "." ]
1e6715b7bea47a40e8042821b57937deaaa0fdc3
https://github.com/thebjorn/pydeps/blob/1e6715b7bea47a40e8042821b57937deaaa0fdc3/pydeps/dot.py#L70-L86
233,018
thebjorn/pydeps
pydeps/dot.py
display_svg
def display_svg(kw, fname): # pragma: nocover """Try to display the svg file on this platform. """ if kw['display'] is None: cli.verbose("Displaying:", fname) if sys.platform == 'win32': os.startfile(fname) else: opener = "open" if sys.platform == "darwin" else "xdg-open" subprocess.call([opener, fname]) else: cli.verbose(kw['display'] + " " + fname) os.system(kw['display'] + " " + fname)
python
def display_svg(kw, fname): # pragma: nocover if kw['display'] is None: cli.verbose("Displaying:", fname) if sys.platform == 'win32': os.startfile(fname) else: opener = "open" if sys.platform == "darwin" else "xdg-open" subprocess.call([opener, fname]) else: cli.verbose(kw['display'] + " " + fname) os.system(kw['display'] + " " + fname)
[ "def", "display_svg", "(", "kw", ",", "fname", ")", ":", "# pragma: nocover", "if", "kw", "[", "'display'", "]", "is", "None", ":", "cli", ".", "verbose", "(", "\"Displaying:\"", ",", "fname", ")", "if", "sys", ".", "platform", "==", "'win32'", ":", "o...
Try to display the svg file on this platform.
[ "Try", "to", "display", "the", "svg", "file", "on", "this", "platform", "." ]
1e6715b7bea47a40e8042821b57937deaaa0fdc3
https://github.com/thebjorn/pydeps/blob/1e6715b7bea47a40e8042821b57937deaaa0fdc3/pydeps/dot.py#L89-L101
233,019
thebjorn/pydeps
pydeps/pystdlib.py
pystdlib
def pystdlib(): """Return a set of all module-names in the Python standard library. """ curver = '.'.join(str(x) for x in sys.version_info[:2]) return (set(stdlib_list.stdlib_list(curver)) | { '_LWPCookieJar', '_MozillaCookieJar', '_abcoll', 'email._parseaddr', 'email.base64mime', 'email.feedparser', 'email.quoprimime', 'encodings', 'genericpath', 'ntpath', 'nturl2path', 'os2emxpath', 'posixpath', 'sre_compile', 'sre_parse', 'unittest.case', 'unittest.loader', 'unittest.main', 'unittest.result', 'unittest.runner', 'unittest.signals', 'unittest.suite', 'unittest.util', '_threading_local', 'sre_constants', 'strop', 'repr', 'opcode', 'nt', 'encodings.aliases', '_bisect', '_codecs', '_collections', '_functools', '_hashlib', '_heapq', '_io', '_locale', '_LWPCookieJar', '_md5', '_MozillaCookieJar', '_random', '_sha', '_sha256', '_sha512', '_socket', '_sre', '_ssl', '_struct', '_subprocess', '_threading_local', '_warnings', '_weakref', '_weakrefset', '_winreg' }) - {'__main__'}
python
def pystdlib(): curver = '.'.join(str(x) for x in sys.version_info[:2]) return (set(stdlib_list.stdlib_list(curver)) | { '_LWPCookieJar', '_MozillaCookieJar', '_abcoll', 'email._parseaddr', 'email.base64mime', 'email.feedparser', 'email.quoprimime', 'encodings', 'genericpath', 'ntpath', 'nturl2path', 'os2emxpath', 'posixpath', 'sre_compile', 'sre_parse', 'unittest.case', 'unittest.loader', 'unittest.main', 'unittest.result', 'unittest.runner', 'unittest.signals', 'unittest.suite', 'unittest.util', '_threading_local', 'sre_constants', 'strop', 'repr', 'opcode', 'nt', 'encodings.aliases', '_bisect', '_codecs', '_collections', '_functools', '_hashlib', '_heapq', '_io', '_locale', '_LWPCookieJar', '_md5', '_MozillaCookieJar', '_random', '_sha', '_sha256', '_sha512', '_socket', '_sre', '_ssl', '_struct', '_subprocess', '_threading_local', '_warnings', '_weakref', '_weakrefset', '_winreg' }) - {'__main__'}
[ "def", "pystdlib", "(", ")", ":", "curver", "=", "'.'", ".", "join", "(", "str", "(", "x", ")", "for", "x", "in", "sys", ".", "version_info", "[", ":", "2", "]", ")", "return", "(", "set", "(", "stdlib_list", ".", "stdlib_list", "(", "curver", ")...
Return a set of all module-names in the Python standard library.
[ "Return", "a", "set", "of", "all", "module", "-", "names", "in", "the", "Python", "standard", "library", "." ]
1e6715b7bea47a40e8042821b57937deaaa0fdc3
https://github.com/thebjorn/pydeps/blob/1e6715b7bea47a40e8042821b57937deaaa0fdc3/pydeps/pystdlib.py#L7-L26
233,020
thebjorn/pydeps
pydeps/mf27.py
ModuleFinder.report
def report(self): # pragma: nocover """Print a report to stdout, listing the found modules with their paths, as well as modules that are missing, or seem to be missing. """ print() print(" %-25s %s" % ("Name", "File")) print(" %-25s %s" % ("----", "----")) # Print modules found keys = list(self.modules.keys()) keys.sort() for key in keys: m = self.modules[key] if m.__path__: print("P", end=' ') else: print("m", end=' ') print("%-25s" % key, m.__file__ or "") # Print missing modules missing, maybe = self.any_missing_maybe() if missing: print() print("Missing modules:") for name in missing: mods = list(self.badmodules[name].keys()) mods.sort() print("?", name, "imported from", ', '.join(mods)) # Print modules that may be missing, but then again, maybe not... if maybe: print() print("Submodules thay appear to be missing, but could also be", end=' ') print("global names in the parent package:") for name in maybe: mods = list(self.badmodules[name].keys()) mods.sort() print("?", name, "imported from", ', '.join(mods))
python
def report(self): # pragma: nocover print() print(" %-25s %s" % ("Name", "File")) print(" %-25s %s" % ("----", "----")) # Print modules found keys = list(self.modules.keys()) keys.sort() for key in keys: m = self.modules[key] if m.__path__: print("P", end=' ') else: print("m", end=' ') print("%-25s" % key, m.__file__ or "") # Print missing modules missing, maybe = self.any_missing_maybe() if missing: print() print("Missing modules:") for name in missing: mods = list(self.badmodules[name].keys()) mods.sort() print("?", name, "imported from", ', '.join(mods)) # Print modules that may be missing, but then again, maybe not... if maybe: print() print("Submodules thay appear to be missing, but could also be", end=' ') print("global names in the parent package:") for name in maybe: mods = list(self.badmodules[name].keys()) mods.sort() print("?", name, "imported from", ', '.join(mods))
[ "def", "report", "(", "self", ")", ":", "# pragma: nocover", "print", "(", ")", "print", "(", "\" %-25s %s\"", "%", "(", "\"Name\"", ",", "\"File\"", ")", ")", "print", "(", "\" %-25s %s\"", "%", "(", "\"----\"", ",", "\"----\"", ")", ")", "# Print modul...
Print a report to stdout, listing the found modules with their paths, as well as modules that are missing, or seem to be missing.
[ "Print", "a", "report", "to", "stdout", "listing", "the", "found", "modules", "with", "their", "paths", "as", "well", "as", "modules", "that", "are", "missing", "or", "seem", "to", "be", "missing", "." ]
1e6715b7bea47a40e8042821b57937deaaa0fdc3
https://github.com/thebjorn/pydeps/blob/1e6715b7bea47a40e8042821b57937deaaa0fdc3/pydeps/mf27.py#L553-L588
233,021
thebjorn/pydeps
pydeps/colors.py
name2rgb
def name2rgb(hue): """Originally used to calculate color based on module name. """ r, g, b = colorsys.hsv_to_rgb(hue / 360.0, .8, .7) return tuple(int(x * 256) for x in [r, g, b])
python
def name2rgb(hue): r, g, b = colorsys.hsv_to_rgb(hue / 360.0, .8, .7) return tuple(int(x * 256) for x in [r, g, b])
[ "def", "name2rgb", "(", "hue", ")", ":", "r", ",", "g", ",", "b", "=", "colorsys", ".", "hsv_to_rgb", "(", "hue", "/", "360.0", ",", ".8", ",", ".7", ")", "return", "tuple", "(", "int", "(", "x", "*", "256", ")", "for", "x", "in", "[", "r", ...
Originally used to calculate color based on module name.
[ "Originally", "used", "to", "calculate", "color", "based", "on", "module", "name", "." ]
1e6715b7bea47a40e8042821b57937deaaa0fdc3
https://github.com/thebjorn/pydeps/blob/1e6715b7bea47a40e8042821b57937deaaa0fdc3/pydeps/colors.py#L70-L74
233,022
thebjorn/pydeps
pydeps/colors.py
foreground
def foreground(background, *options): """Find the best foreground color from `options` based on `background` color. """ def absdiff(a, b): return brightnessdiff(a, b) # return 3 * brightnessdiff(a, b) + colordiff(a, b) diffs = [(absdiff(background, color), color) for color in options] diffs.sort(reverse=True) return diffs[0][1]
python
def foreground(background, *options): def absdiff(a, b): return brightnessdiff(a, b) # return 3 * brightnessdiff(a, b) + colordiff(a, b) diffs = [(absdiff(background, color), color) for color in options] diffs.sort(reverse=True) return diffs[0][1]
[ "def", "foreground", "(", "background", ",", "*", "options", ")", ":", "def", "absdiff", "(", "a", ",", "b", ")", ":", "return", "brightnessdiff", "(", "a", ",", "b", ")", "# return 3 * brightnessdiff(a, b) + colordiff(a, b)", "diffs", "=", "[", "(", "absdif...
Find the best foreground color from `options` based on `background` color.
[ "Find", "the", "best", "foreground", "color", "from", "options", "based", "on", "background", "color", "." ]
1e6715b7bea47a40e8042821b57937deaaa0fdc3
https://github.com/thebjorn/pydeps/blob/1e6715b7bea47a40e8042821b57937deaaa0fdc3/pydeps/colors.py#L102-L111
233,023
thebjorn/pydeps
pydeps/cli.py
base_argparser
def base_argparser(argv=()): """Initial parser that can set values for the rest of the parsing process. """ global verbose verbose = _not_verbose _p = argparse.ArgumentParser(add_help=False) _p.add_argument('--debug', action='store_true', help="turn on all the show and verbose options (mainly for debugging pydeps itself)") _p.add_argument('--config', help="specify config file", metavar="FILE") _p.add_argument('--no-config', help="disable processing of config files", action='store_true') _p.add_argument('--version', action='store_true', help='print pydeps version') _p.add_argument('-L', '--log', help=textwrap.dedent(''' set log-level to one of CRITICAL, ERROR, WARNING, INFO, DEBUG, NOTSET. ''')) _args, argv = _p.parse_known_args(argv) if _args.log: loglevels = "CRITICAL DEBUG ERROR FATAL INFO WARN" if _args.log not in loglevels: # pragma: nocover error('legal values for the -L parameter are:', loglevels) loglevel = getattr(logging, _args.log) else: loglevel = None logging.basicConfig( level=loglevel, format='%(filename)s:%(lineno)d: %(levelname)s: %(message)s' ) if _args.version: # pragma: nocover print("pydeps v" + __version__) sys.exit(0) return _p, _args, argv
python
def base_argparser(argv=()): global verbose verbose = _not_verbose _p = argparse.ArgumentParser(add_help=False) _p.add_argument('--debug', action='store_true', help="turn on all the show and verbose options (mainly for debugging pydeps itself)") _p.add_argument('--config', help="specify config file", metavar="FILE") _p.add_argument('--no-config', help="disable processing of config files", action='store_true') _p.add_argument('--version', action='store_true', help='print pydeps version') _p.add_argument('-L', '--log', help=textwrap.dedent(''' set log-level to one of CRITICAL, ERROR, WARNING, INFO, DEBUG, NOTSET. ''')) _args, argv = _p.parse_known_args(argv) if _args.log: loglevels = "CRITICAL DEBUG ERROR FATAL INFO WARN" if _args.log not in loglevels: # pragma: nocover error('legal values for the -L parameter are:', loglevels) loglevel = getattr(logging, _args.log) else: loglevel = None logging.basicConfig( level=loglevel, format='%(filename)s:%(lineno)d: %(levelname)s: %(message)s' ) if _args.version: # pragma: nocover print("pydeps v" + __version__) sys.exit(0) return _p, _args, argv
[ "def", "base_argparser", "(", "argv", "=", "(", ")", ")", ":", "global", "verbose", "verbose", "=", "_not_verbose", "_p", "=", "argparse", ".", "ArgumentParser", "(", "add_help", "=", "False", ")", "_p", ".", "add_argument", "(", "'--debug'", ",", "action"...
Initial parser that can set values for the rest of the parsing process.
[ "Initial", "parser", "that", "can", "set", "values", "for", "the", "rest", "of", "the", "parsing", "process", "." ]
1e6715b7bea47a40e8042821b57937deaaa0fdc3
https://github.com/thebjorn/pydeps/blob/1e6715b7bea47a40e8042821b57937deaaa0fdc3/pydeps/cli.py#L45-L78
233,024
thebjorn/pydeps
pydeps/tools/pydeps2requirements.py
dep2req
def dep2req(name, imported_by): """Convert dependency to requirement. """ lst = [item for item in sorted(imported_by) if not item.startswith(name)] res = '%-15s # from: ' % name imps = ', '.join(lst) if len(imps) < WIDTH - 24: return res + imps return res + imps[:WIDTH - 24 - 3] + '...'
python
def dep2req(name, imported_by): lst = [item for item in sorted(imported_by) if not item.startswith(name)] res = '%-15s # from: ' % name imps = ', '.join(lst) if len(imps) < WIDTH - 24: return res + imps return res + imps[:WIDTH - 24 - 3] + '...'
[ "def", "dep2req", "(", "name", ",", "imported_by", ")", ":", "lst", "=", "[", "item", "for", "item", "in", "sorted", "(", "imported_by", ")", "if", "not", "item", ".", "startswith", "(", "name", ")", "]", "res", "=", "'%-15s # from: '", "%", "name", ...
Convert dependency to requirement.
[ "Convert", "dependency", "to", "requirement", "." ]
1e6715b7bea47a40e8042821b57937deaaa0fdc3
https://github.com/thebjorn/pydeps/blob/1e6715b7bea47a40e8042821b57937deaaa0fdc3/pydeps/tools/pydeps2requirements.py#L25-L33
233,025
thebjorn/pydeps
pydeps/tools/pydeps2requirements.py
pydeps2reqs
def pydeps2reqs(deps): """Convert a deps instance into requirements. """ reqs = defaultdict(set) for k, v in list(deps.items()): # not a built-in p = v['path'] if p and not p.startswith(sys.real_prefix): if p.startswith(sys.prefix) and 'site-packages' in p: if not p.endswith('.pyd'): if '/win32/' in p.replace('\\', '/'): reqs['win32'] |= set(v['imported_by']) else: name = k.split('.', 1)[0] if name not in skiplist: reqs[name] |= set(v['imported_by']) if '_dummy' in reqs: del reqs['_dummy'] return '\n'.join(dep2req(name, reqs[name]) for name in sorted(reqs))
python
def pydeps2reqs(deps): reqs = defaultdict(set) for k, v in list(deps.items()): # not a built-in p = v['path'] if p and not p.startswith(sys.real_prefix): if p.startswith(sys.prefix) and 'site-packages' in p: if not p.endswith('.pyd'): if '/win32/' in p.replace('\\', '/'): reqs['win32'] |= set(v['imported_by']) else: name = k.split('.', 1)[0] if name not in skiplist: reqs[name] |= set(v['imported_by']) if '_dummy' in reqs: del reqs['_dummy'] return '\n'.join(dep2req(name, reqs[name]) for name in sorted(reqs))
[ "def", "pydeps2reqs", "(", "deps", ")", ":", "reqs", "=", "defaultdict", "(", "set", ")", "for", "k", ",", "v", "in", "list", "(", "deps", ".", "items", "(", ")", ")", ":", "# not a built-in\r", "p", "=", "v", "[", "'path'", "]", "if", "p", "and"...
Convert a deps instance into requirements.
[ "Convert", "a", "deps", "instance", "into", "requirements", "." ]
1e6715b7bea47a40e8042821b57937deaaa0fdc3
https://github.com/thebjorn/pydeps/blob/1e6715b7bea47a40e8042821b57937deaaa0fdc3/pydeps/tools/pydeps2requirements.py#L36-L55
233,026
thebjorn/pydeps
pydeps/tools/pydeps2requirements.py
main
def main(): """Cli entrypoint. """ if len(sys.argv) == 2: fname = sys.argv[1] data = json.load(open(fname, 'rb')) else: data = json.loads(sys.stdin.read()) print(pydeps2reqs(data))
python
def main(): if len(sys.argv) == 2: fname = sys.argv[1] data = json.load(open(fname, 'rb')) else: data = json.loads(sys.stdin.read()) print(pydeps2reqs(data))
[ "def", "main", "(", ")", ":", "if", "len", "(", "sys", ".", "argv", ")", "==", "2", ":", "fname", "=", "sys", ".", "argv", "[", "1", "]", "data", "=", "json", ".", "load", "(", "open", "(", "fname", ",", "'rb'", ")", ")", "else", ":", "data...
Cli entrypoint.
[ "Cli", "entrypoint", "." ]
1e6715b7bea47a40e8042821b57937deaaa0fdc3
https://github.com/thebjorn/pydeps/blob/1e6715b7bea47a40e8042821b57937deaaa0fdc3/pydeps/tools/pydeps2requirements.py#L58-L66
233,027
thebjorn/pydeps
pydeps/pydeps.py
pydeps
def pydeps(**args): """Entry point for the ``pydeps`` command. This function should do all the initial parameter and environment munging before calling ``_pydeps`` (so that function has a clean execution path). """ _args = args if args else cli.parse_args(sys.argv[1:]) inp = target.Target(_args['fname']) log.debug("Target: %r", inp) if _args.get('output'): _args['output'] = os.path.abspath(_args['output']) else: _args['output'] = os.path.join( inp.calling_dir, inp.modpath.replace('.', '_') + '.' + _args.get('format', 'svg') ) with inp.chdir_work(): _args['fname'] = inp.fname _args['isdir'] = inp.is_dir if _args.get('externals'): del _args['fname'] exts = externals(inp, **_args) print(json.dumps(exts, indent=4)) return exts # so the tests can assert else: # this is the call you're looking for :-) return _pydeps(inp, **_args)
python
def pydeps(**args): _args = args if args else cli.parse_args(sys.argv[1:]) inp = target.Target(_args['fname']) log.debug("Target: %r", inp) if _args.get('output'): _args['output'] = os.path.abspath(_args['output']) else: _args['output'] = os.path.join( inp.calling_dir, inp.modpath.replace('.', '_') + '.' + _args.get('format', 'svg') ) with inp.chdir_work(): _args['fname'] = inp.fname _args['isdir'] = inp.is_dir if _args.get('externals'): del _args['fname'] exts = externals(inp, **_args) print(json.dumps(exts, indent=4)) return exts # so the tests can assert else: # this is the call you're looking for :-) return _pydeps(inp, **_args)
[ "def", "pydeps", "(", "*", "*", "args", ")", ":", "_args", "=", "args", "if", "args", "else", "cli", ".", "parse_args", "(", "sys", ".", "argv", "[", "1", ":", "]", ")", "inp", "=", "target", ".", "Target", "(", "_args", "[", "'fname'", "]", ")...
Entry point for the ``pydeps`` command. This function should do all the initial parameter and environment munging before calling ``_pydeps`` (so that function has a clean execution path).
[ "Entry", "point", "for", "the", "pydeps", "command", "." ]
1e6715b7bea47a40e8042821b57937deaaa0fdc3
https://github.com/thebjorn/pydeps/blob/1e6715b7bea47a40e8042821b57937deaaa0fdc3/pydeps/pydeps.py#L101-L131
233,028
thebjorn/pydeps
pydeps/target.py
Target._path_parts
def _path_parts(self, pth): """Return a list of all directories in the path ``pth``. """ res = re.split(r"[\\/]", pth) if res and os.path.splitdrive(res[0]) == (res[0], ''): res[0] += os.path.sep return res
python
def _path_parts(self, pth): res = re.split(r"[\\/]", pth) if res and os.path.splitdrive(res[0]) == (res[0], ''): res[0] += os.path.sep return res
[ "def", "_path_parts", "(", "self", ",", "pth", ")", ":", "res", "=", "re", ".", "split", "(", "r\"[\\\\/]\"", ",", "pth", ")", "if", "res", "and", "os", ".", "path", ".", "splitdrive", "(", "res", "[", "0", "]", ")", "==", "(", "res", "[", "0",...
Return a list of all directories in the path ``pth``.
[ "Return", "a", "list", "of", "all", "directories", "in", "the", "path", "pth", "." ]
1e6715b7bea47a40e8042821b57937deaaa0fdc3
https://github.com/thebjorn/pydeps/blob/1e6715b7bea47a40e8042821b57937deaaa0fdc3/pydeps/target.py#L81-L87
233,029
blue-yonder/turbodbc
python/turbodbc/connection.py
Connection.cursor
def cursor(self): """ Create a new ``Cursor`` instance associated with this ``Connection`` :return: A new ``Cursor`` instance """ self._assert_valid() c = Cursor(self.impl.cursor()) self.cursors.add(c) return c
python
def cursor(self): self._assert_valid() c = Cursor(self.impl.cursor()) self.cursors.add(c) return c
[ "def", "cursor", "(", "self", ")", ":", "self", ".", "_assert_valid", "(", ")", "c", "=", "Cursor", "(", "self", ".", "impl", ".", "cursor", "(", ")", ")", "self", ".", "cursors", ".", "add", "(", "c", ")", "return", "c" ]
Create a new ``Cursor`` instance associated with this ``Connection`` :return: A new ``Cursor`` instance
[ "Create", "a", "new", "Cursor", "instance", "associated", "with", "this", "Connection" ]
5556625e69244d941a708c69eb2c1e7b37c190b1
https://github.com/blue-yonder/turbodbc/blob/5556625e69244d941a708c69eb2c1e7b37c190b1/python/turbodbc/connection.py#L19-L28
233,030
blue-yonder/turbodbc
python/turbodbc/connection.py
Connection.close
def close(self): """ Close the connection and all associated cursors. This will implicitly roll back any uncommitted operations. """ for c in self.cursors: c.close() self.cursors = [] self.impl = None
python
def close(self): for c in self.cursors: c.close() self.cursors = [] self.impl = None
[ "def", "close", "(", "self", ")", ":", "for", "c", "in", "self", ".", "cursors", ":", "c", ".", "close", "(", ")", "self", ".", "cursors", "=", "[", "]", "self", ".", "impl", "=", "None" ]
Close the connection and all associated cursors. This will implicitly roll back any uncommitted operations.
[ "Close", "the", "connection", "and", "all", "associated", "cursors", ".", "This", "will", "implicitly", "roll", "back", "any", "uncommitted", "operations", "." ]
5556625e69244d941a708c69eb2c1e7b37c190b1
https://github.com/blue-yonder/turbodbc/blob/5556625e69244d941a708c69eb2c1e7b37c190b1/python/turbodbc/connection.py#L46-L54
233,031
blue-yonder/turbodbc
python/turbodbc/options.py
make_options
def make_options(read_buffer_size=None, parameter_sets_to_buffer=None, varchar_max_character_limit=None, prefer_unicode=None, use_async_io=None, autocommit=None, large_decimals_as_64_bit_types=None, limit_varchar_results_to_max=None, force_extra_capacity_for_unicode=None, fetch_wchar_as_char=None): """ Create options that control how turbodbc interacts with a database. These options affect performance for the most part, but some options may require adjustment so that all features work correctly with certain databases. If a parameter is set to `None`, this means the default value is used. :param read_buffer_size: Affects performance. Controls the size of batches fetched from the database when reading result sets. Can be either an instance of ``turbodbc.Megabytes`` (recommended) or ``turbodbc.Rows``. :param parameter_sets_to_buffer: Affects performance. Number of parameter sets (rows) which shall be transferred to the server in a single batch when ``executemany()`` is called. Must be an integer. :param varchar_max_character_limit: Affects behavior/performance. If a result set contains fields of type ``VARCHAR(max)`` or ``NVARCHAR(max)`` or the equivalent type of your database, buffers will be allocated to hold the specified number of characters. This may lead to truncation. The default value is ``65535`` characters. Please note that large values reduce the risk of truncation, but may affect the number of rows in a batch of result sets (see ``read_buffer_size``). Please note that this option only relates to retrieving results, not sending parameters to the database. :param use_async_io: Affects performance. Set this option to ``True`` if you want to use asynchronous I/O, i.e., while Python is busy converting database results to Python objects, new result sets are fetched from the database in the background. :param prefer_unicode: May affect functionality and performance. Some databases do not support strings encoded with UTF-8, leading to UTF-8 characters being misinterpreted, misrepresented, or downright rejected. Set this option to ``True`` if you want to transfer character data using the UCS-2/UCS-16 encoding that use (multiple) two-byte instead of (multiple) one-byte characters. :param autocommit: Affects behavior. If set to ``True``, all queries and commands executed with ``cursor.execute()`` or ``cursor.executemany()`` will be succeeded by an implicit ``COMMIT`` operation, persisting any changes made to the database. If not set or set to ``False``, users has to take care of calling ``cursor.commit()`` themselves. :param large_decimals_as_64_bit_types: Affects behavior. If set to ``True``, ``DECIMAL(x, y)`` results with ``x > 18`` will be rendered as 64 bit integers (``y == 0``) or 64 bit floating point numbers (``y > 0``), respectively. Use this option if your decimal data types are larger than the data they actually hold. Using this data type can lead to overflow errors and loss of precision. If not set or set to ``False``, large decimals are rendered as strings. :param limit_varchar_results_to_max: Affects behavior/performance. If set to ``True``, any text-like fields such as ``VARCHAR(n)`` and ``NVARCHAR(n)`` will be limited to a maximum size of ``varchar_max_character_limit`` characters. This may lead to values being truncated, but reduces the amount of memory required to allocate string buffers, leading to larger, more efficient batches. If not set or set to ``False``, strings can exceed ``varchar_max_character_limit`` in size if the database reports them this way. For fields such as ``TEXT``, some databases report a size of 2 billion characters. Please note that this option only relates to retrieving results, not sending parameters to the database. :param force_extra_capacity_for_unicode Affects behavior/performance. Some ODBC drivers report the length of the ``VARCHAR``/``NVARCHAR`` field rather than the number of code points for which space is required to be allocated, resulting in string truncations. Set this option to ``True`` to increase the memory allocated for ``VARCHAR`` and ``NVARCHAR`` fields and prevent string truncations. Please note that this option only relates to retrieving results, not sending parameters to the database. :param fetch_wchar_as_char Affects behavior. Some ODBC drivers retrieve single byte encoded strings into ``NVARCHAR`` fields of result sets, which are decoded incorrectly by turbodbc default settings, resulting in corrupt strings. Set this option to ``True`` to have turbodbc treat ``NVARCHAR`` types as narrow character types when decoding the fields in result sets. Please note that this option only relates to retrieving results, not sending parameters to the database. :return: An option struct that is suitable to pass to the ``turbodbc_options`` parameter of ``turbodbc.connect()`` """ options = Options() if not read_buffer_size is None: options.read_buffer_size = read_buffer_size if not parameter_sets_to_buffer is None: options.parameter_sets_to_buffer = parameter_sets_to_buffer if not varchar_max_character_limit is None: options.varchar_max_character_limit = varchar_max_character_limit if not prefer_unicode is None: options.prefer_unicode = prefer_unicode if not use_async_io is None: options.use_async_io = use_async_io if not autocommit is None: options.autocommit = autocommit if not large_decimals_as_64_bit_types is None: options.large_decimals_as_64_bit_types = large_decimals_as_64_bit_types if not limit_varchar_results_to_max is None: options.limit_varchar_results_to_max = limit_varchar_results_to_max if not force_extra_capacity_for_unicode is None: options.force_extra_capacity_for_unicode = force_extra_capacity_for_unicode if not fetch_wchar_as_char is None: options.fetch_wchar_as_char = fetch_wchar_as_char return options
python
def make_options(read_buffer_size=None, parameter_sets_to_buffer=None, varchar_max_character_limit=None, prefer_unicode=None, use_async_io=None, autocommit=None, large_decimals_as_64_bit_types=None, limit_varchar_results_to_max=None, force_extra_capacity_for_unicode=None, fetch_wchar_as_char=None): options = Options() if not read_buffer_size is None: options.read_buffer_size = read_buffer_size if not parameter_sets_to_buffer is None: options.parameter_sets_to_buffer = parameter_sets_to_buffer if not varchar_max_character_limit is None: options.varchar_max_character_limit = varchar_max_character_limit if not prefer_unicode is None: options.prefer_unicode = prefer_unicode if not use_async_io is None: options.use_async_io = use_async_io if not autocommit is None: options.autocommit = autocommit if not large_decimals_as_64_bit_types is None: options.large_decimals_as_64_bit_types = large_decimals_as_64_bit_types if not limit_varchar_results_to_max is None: options.limit_varchar_results_to_max = limit_varchar_results_to_max if not force_extra_capacity_for_unicode is None: options.force_extra_capacity_for_unicode = force_extra_capacity_for_unicode if not fetch_wchar_as_char is None: options.fetch_wchar_as_char = fetch_wchar_as_char return options
[ "def", "make_options", "(", "read_buffer_size", "=", "None", ",", "parameter_sets_to_buffer", "=", "None", ",", "varchar_max_character_limit", "=", "None", ",", "prefer_unicode", "=", "None", ",", "use_async_io", "=", "None", ",", "autocommit", "=", "None", ",", ...
Create options that control how turbodbc interacts with a database. These options affect performance for the most part, but some options may require adjustment so that all features work correctly with certain databases. If a parameter is set to `None`, this means the default value is used. :param read_buffer_size: Affects performance. Controls the size of batches fetched from the database when reading result sets. Can be either an instance of ``turbodbc.Megabytes`` (recommended) or ``turbodbc.Rows``. :param parameter_sets_to_buffer: Affects performance. Number of parameter sets (rows) which shall be transferred to the server in a single batch when ``executemany()`` is called. Must be an integer. :param varchar_max_character_limit: Affects behavior/performance. If a result set contains fields of type ``VARCHAR(max)`` or ``NVARCHAR(max)`` or the equivalent type of your database, buffers will be allocated to hold the specified number of characters. This may lead to truncation. The default value is ``65535`` characters. Please note that large values reduce the risk of truncation, but may affect the number of rows in a batch of result sets (see ``read_buffer_size``). Please note that this option only relates to retrieving results, not sending parameters to the database. :param use_async_io: Affects performance. Set this option to ``True`` if you want to use asynchronous I/O, i.e., while Python is busy converting database results to Python objects, new result sets are fetched from the database in the background. :param prefer_unicode: May affect functionality and performance. Some databases do not support strings encoded with UTF-8, leading to UTF-8 characters being misinterpreted, misrepresented, or downright rejected. Set this option to ``True`` if you want to transfer character data using the UCS-2/UCS-16 encoding that use (multiple) two-byte instead of (multiple) one-byte characters. :param autocommit: Affects behavior. If set to ``True``, all queries and commands executed with ``cursor.execute()`` or ``cursor.executemany()`` will be succeeded by an implicit ``COMMIT`` operation, persisting any changes made to the database. If not set or set to ``False``, users has to take care of calling ``cursor.commit()`` themselves. :param large_decimals_as_64_bit_types: Affects behavior. If set to ``True``, ``DECIMAL(x, y)`` results with ``x > 18`` will be rendered as 64 bit integers (``y == 0``) or 64 bit floating point numbers (``y > 0``), respectively. Use this option if your decimal data types are larger than the data they actually hold. Using this data type can lead to overflow errors and loss of precision. If not set or set to ``False``, large decimals are rendered as strings. :param limit_varchar_results_to_max: Affects behavior/performance. If set to ``True``, any text-like fields such as ``VARCHAR(n)`` and ``NVARCHAR(n)`` will be limited to a maximum size of ``varchar_max_character_limit`` characters. This may lead to values being truncated, but reduces the amount of memory required to allocate string buffers, leading to larger, more efficient batches. If not set or set to ``False``, strings can exceed ``varchar_max_character_limit`` in size if the database reports them this way. For fields such as ``TEXT``, some databases report a size of 2 billion characters. Please note that this option only relates to retrieving results, not sending parameters to the database. :param force_extra_capacity_for_unicode Affects behavior/performance. Some ODBC drivers report the length of the ``VARCHAR``/``NVARCHAR`` field rather than the number of code points for which space is required to be allocated, resulting in string truncations. Set this option to ``True`` to increase the memory allocated for ``VARCHAR`` and ``NVARCHAR`` fields and prevent string truncations. Please note that this option only relates to retrieving results, not sending parameters to the database. :param fetch_wchar_as_char Affects behavior. Some ODBC drivers retrieve single byte encoded strings into ``NVARCHAR`` fields of result sets, which are decoded incorrectly by turbodbc default settings, resulting in corrupt strings. Set this option to ``True`` to have turbodbc treat ``NVARCHAR`` types as narrow character types when decoding the fields in result sets. Please note that this option only relates to retrieving results, not sending parameters to the database. :return: An option struct that is suitable to pass to the ``turbodbc_options`` parameter of ``turbodbc.connect()``
[ "Create", "options", "that", "control", "how", "turbodbc", "interacts", "with", "a", "database", ".", "These", "options", "affect", "performance", "for", "the", "most", "part", "but", "some", "options", "may", "require", "adjustment", "so", "that", "all", "fea...
5556625e69244d941a708c69eb2c1e7b37c190b1
https://github.com/blue-yonder/turbodbc/blob/5556625e69244d941a708c69eb2c1e7b37c190b1/python/turbodbc/options.py#L3-L104
233,032
blue-yonder/turbodbc
setup.py
_get_distutils_build_directory
def _get_distutils_build_directory(): """ Returns the directory distutils uses to build its files. We need this directory since we build extensions which have to link other ones. """ pattern = "lib.{platform}-{major}.{minor}" return os.path.join('build', pattern.format(platform=sysconfig.get_platform(), major=sys.version_info[0], minor=sys.version_info[1]))
python
def _get_distutils_build_directory(): pattern = "lib.{platform}-{major}.{minor}" return os.path.join('build', pattern.format(platform=sysconfig.get_platform(), major=sys.version_info[0], minor=sys.version_info[1]))
[ "def", "_get_distutils_build_directory", "(", ")", ":", "pattern", "=", "\"lib.{platform}-{major}.{minor}\"", "return", "os", ".", "path", ".", "join", "(", "'build'", ",", "pattern", ".", "format", "(", "platform", "=", "sysconfig", ".", "get_platform", "(", ")...
Returns the directory distutils uses to build its files. We need this directory since we build extensions which have to link other ones.
[ "Returns", "the", "directory", "distutils", "uses", "to", "build", "its", "files", ".", "We", "need", "this", "directory", "since", "we", "build", "extensions", "which", "have", "to", "link", "other", "ones", "." ]
5556625e69244d941a708c69eb2c1e7b37c190b1
https://github.com/blue-yonder/turbodbc/blob/5556625e69244d941a708c69eb2c1e7b37c190b1/setup.py#L22-L31
233,033
blue-yonder/turbodbc
setup.py
get_extension_modules
def get_extension_modules(): extension_modules = [] """ Extension module which is actually a plain C++ library without Python bindings """ turbodbc_sources = _get_source_files('cpp_odbc') + _get_source_files('turbodbc') turbodbc_library = Extension('libturbodbc', sources=turbodbc_sources, include_dirs=include_dirs, extra_compile_args=extra_compile_args, extra_link_args=base_library_link_args, libraries=[odbclib], library_dirs=library_dirs) if sys.platform == "win32": turbodbc_libs = [] else: turbodbc_libs = [_get_turbodbc_libname()] extension_modules.append(turbodbc_library) """ An extension module which contains the main Python bindings for turbodbc """ turbodbc_python_sources = _get_source_files('turbodbc_python') if sys.platform == "win32": turbodbc_python_sources = turbodbc_sources + turbodbc_python_sources turbodbc_python = Extension('turbodbc_intern', sources=turbodbc_python_sources, include_dirs=include_dirs, extra_compile_args=extra_compile_args + hidden_visibility_args, libraries=[odbclib] + turbodbc_libs, extra_link_args=python_module_link_args, library_dirs=library_dirs) extension_modules.append(turbodbc_python) """ An extension module which contains Python bindings which require numpy support to work. Not included in the standard Python bindings so this can stay optional. """ if _has_numpy_headers(): import numpy turbodbc_numpy_sources = _get_source_files('turbodbc_numpy') if sys.platform == "win32": turbodbc_numpy_sources = turbodbc_sources + turbodbc_numpy_sources turbodbc_numpy = Extension('turbodbc_numpy_support', sources=turbodbc_numpy_sources, include_dirs=include_dirs + [numpy.get_include()], extra_compile_args=extra_compile_args + hidden_visibility_args, libraries=[odbclib] + turbodbc_libs, extra_link_args=python_module_link_args, library_dirs=library_dirs) extension_modules.append(turbodbc_numpy) """ An extension module which contains Python bindings which require Apache Arrow support to work. Not included in the standard Python bindings so this can stay optional. """ if _has_arrow_headers(): import pyarrow pyarrow_location = os.path.dirname(pyarrow.__file__) # For now, assume that we build against bundled pyarrow releases. pyarrow_include_dir = os.path.join(pyarrow_location, 'include') turbodbc_arrow_sources = _get_source_files('turbodbc_arrow') pyarrow_module_link_args = list(python_module_link_args) if sys.platform == "win32": turbodbc_arrow_sources = turbodbc_sources + turbodbc_arrow_sources elif sys.platform == "darwin": pyarrow_module_link_args.append('-Wl,-rpath,@loader_path/pyarrow') else: pyarrow_module_link_args.append("-Wl,-rpath,$ORIGIN/pyarrow") turbodbc_arrow = Extension('turbodbc_arrow_support', sources=turbodbc_arrow_sources, include_dirs=include_dirs + [pyarrow_include_dir], extra_compile_args=extra_compile_args + hidden_visibility_args, libraries=[odbclib, 'arrow', 'arrow_python'] + turbodbc_libs, extra_link_args=pyarrow_module_link_args, library_dirs=library_dirs + [pyarrow_location]) extension_modules.append(turbodbc_arrow) return extension_modules
python
def get_extension_modules(): extension_modules = [] turbodbc_sources = _get_source_files('cpp_odbc') + _get_source_files('turbodbc') turbodbc_library = Extension('libturbodbc', sources=turbodbc_sources, include_dirs=include_dirs, extra_compile_args=extra_compile_args, extra_link_args=base_library_link_args, libraries=[odbclib], library_dirs=library_dirs) if sys.platform == "win32": turbodbc_libs = [] else: turbodbc_libs = [_get_turbodbc_libname()] extension_modules.append(turbodbc_library) """ An extension module which contains the main Python bindings for turbodbc """ turbodbc_python_sources = _get_source_files('turbodbc_python') if sys.platform == "win32": turbodbc_python_sources = turbodbc_sources + turbodbc_python_sources turbodbc_python = Extension('turbodbc_intern', sources=turbodbc_python_sources, include_dirs=include_dirs, extra_compile_args=extra_compile_args + hidden_visibility_args, libraries=[odbclib] + turbodbc_libs, extra_link_args=python_module_link_args, library_dirs=library_dirs) extension_modules.append(turbodbc_python) """ An extension module which contains Python bindings which require numpy support to work. Not included in the standard Python bindings so this can stay optional. """ if _has_numpy_headers(): import numpy turbodbc_numpy_sources = _get_source_files('turbodbc_numpy') if sys.platform == "win32": turbodbc_numpy_sources = turbodbc_sources + turbodbc_numpy_sources turbodbc_numpy = Extension('turbodbc_numpy_support', sources=turbodbc_numpy_sources, include_dirs=include_dirs + [numpy.get_include()], extra_compile_args=extra_compile_args + hidden_visibility_args, libraries=[odbclib] + turbodbc_libs, extra_link_args=python_module_link_args, library_dirs=library_dirs) extension_modules.append(turbodbc_numpy) """ An extension module which contains Python bindings which require Apache Arrow support to work. Not included in the standard Python bindings so this can stay optional. """ if _has_arrow_headers(): import pyarrow pyarrow_location = os.path.dirname(pyarrow.__file__) # For now, assume that we build against bundled pyarrow releases. pyarrow_include_dir = os.path.join(pyarrow_location, 'include') turbodbc_arrow_sources = _get_source_files('turbodbc_arrow') pyarrow_module_link_args = list(python_module_link_args) if sys.platform == "win32": turbodbc_arrow_sources = turbodbc_sources + turbodbc_arrow_sources elif sys.platform == "darwin": pyarrow_module_link_args.append('-Wl,-rpath,@loader_path/pyarrow') else: pyarrow_module_link_args.append("-Wl,-rpath,$ORIGIN/pyarrow") turbodbc_arrow = Extension('turbodbc_arrow_support', sources=turbodbc_arrow_sources, include_dirs=include_dirs + [pyarrow_include_dir], extra_compile_args=extra_compile_args + hidden_visibility_args, libraries=[odbclib, 'arrow', 'arrow_python'] + turbodbc_libs, extra_link_args=pyarrow_module_link_args, library_dirs=library_dirs + [pyarrow_location]) extension_modules.append(turbodbc_arrow) return extension_modules
[ "def", "get_extension_modules", "(", ")", ":", "extension_modules", "=", "[", "]", "turbodbc_sources", "=", "_get_source_files", "(", "'cpp_odbc'", ")", "+", "_get_source_files", "(", "'turbodbc'", ")", "turbodbc_library", "=", "Extension", "(", "'libturbodbc'", ","...
Extension module which is actually a plain C++ library without Python bindings
[ "Extension", "module", "which", "is", "actually", "a", "plain", "C", "++", "library", "without", "Python", "bindings" ]
5556625e69244d941a708c69eb2c1e7b37c190b1
https://github.com/blue-yonder/turbodbc/blob/5556625e69244d941a708c69eb2c1e7b37c190b1/setup.py#L119-L199
233,034
blue-yonder/turbodbc
python/turbodbc/connect.py
connect
def connect(dsn=None, turbodbc_options=None, connection_string=None, **kwargs): """ Create a connection with the database identified by the ``dsn`` or the ``connection_string``. :param dsn: Data source name as given in the (unix) odbc.ini file or (Windows) ODBC Data Source Administrator tool. :param turbodbc_options: Options that control how turbodbc interacts with the database. Create such a struct with `turbodbc.make_options()` or leave this blank to take the defaults. :param connection_string: Preformatted ODBC connection string. Specifying this and dsn or kwargs at the same time raises ParameterError. :param \**kwargs: You may specify additional options as you please. These options will go into the connection string that identifies the database. Valid options depend on the specific database you would like to connect with (e.g. `user` and `password`, or `uid` and `pwd`) :return: A connection to your database """ if turbodbc_options is None: turbodbc_options = make_options() if connection_string is not None and (dsn is not None or len(kwargs) > 0): raise ParameterError("Both connection_string and dsn or kwargs specified") if connection_string is None: connection_string = _make_connection_string(dsn, **kwargs) connection = Connection(intern_connect(connection_string, turbodbc_options)) return connection
python
def connect(dsn=None, turbodbc_options=None, connection_string=None, **kwargs): if turbodbc_options is None: turbodbc_options = make_options() if connection_string is not None and (dsn is not None or len(kwargs) > 0): raise ParameterError("Both connection_string and dsn or kwargs specified") if connection_string is None: connection_string = _make_connection_string(dsn, **kwargs) connection = Connection(intern_connect(connection_string, turbodbc_options)) return connection
[ "def", "connect", "(", "dsn", "=", "None", ",", "turbodbc_options", "=", "None", ",", "connection_string", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "turbodbc_options", "is", "None", ":", "turbodbc_options", "=", "make_options", "(", ")", "if",...
Create a connection with the database identified by the ``dsn`` or the ``connection_string``. :param dsn: Data source name as given in the (unix) odbc.ini file or (Windows) ODBC Data Source Administrator tool. :param turbodbc_options: Options that control how turbodbc interacts with the database. Create such a struct with `turbodbc.make_options()` or leave this blank to take the defaults. :param connection_string: Preformatted ODBC connection string. Specifying this and dsn or kwargs at the same time raises ParameterError. :param \**kwargs: You may specify additional options as you please. These options will go into the connection string that identifies the database. Valid options depend on the specific database you would like to connect with (e.g. `user` and `password`, or `uid` and `pwd`) :return: A connection to your database
[ "Create", "a", "connection", "with", "the", "database", "identified", "by", "the", "dsn", "or", "the", "connection_string", "." ]
5556625e69244d941a708c69eb2c1e7b37c190b1
https://github.com/blue-yonder/turbodbc/blob/5556625e69244d941a708c69eb2c1e7b37c190b1/python/turbodbc/connect.py#L19-L46
233,035
blue-yonder/turbodbc
python/turbodbc/cursor.py
Cursor.description
def description(self): """ Retrieve a description of the columns in the current result set :return: A tuple of seven elements. Only some elements are meaningful:\n * Element #0 is the name of the column * Element #1 is the type code of the column * Element #6 is true if the column may contain ``NULL`` values """ if self.result_set: info = self.result_set.get_column_info() return [(c.name, c.type_code(), None, None, None, None, c.supports_null_values) for c in info] else: return None
python
def description(self): if self.result_set: info = self.result_set.get_column_info() return [(c.name, c.type_code(), None, None, None, None, c.supports_null_values) for c in info] else: return None
[ "def", "description", "(", "self", ")", ":", "if", "self", ".", "result_set", ":", "info", "=", "self", ".", "result_set", ".", "get_column_info", "(", ")", "return", "[", "(", "c", ".", "name", ",", "c", ".", "type_code", "(", ")", ",", "None", ",...
Retrieve a description of the columns in the current result set :return: A tuple of seven elements. Only some elements are meaningful:\n * Element #0 is the name of the column * Element #1 is the type code of the column * Element #6 is true if the column may contain ``NULL`` values
[ "Retrieve", "a", "description", "of", "the", "columns", "in", "the", "current", "result", "set" ]
5556625e69244d941a708c69eb2c1e7b37c190b1
https://github.com/blue-yonder/turbodbc/blob/5556625e69244d941a708c69eb2c1e7b37c190b1/python/turbodbc/cursor.py#L96-L109
233,036
blue-yonder/turbodbc
python/turbodbc/cursor.py
Cursor.execute
def execute(self, sql, parameters=None): """ Execute an SQL command or query :param sql: A (unicode) string that contains the SQL command or query. If you would like to use parameters, please use a question mark ``?`` at the location where the parameter shall be inserted. :param parameters: An iterable of parameter values. The number of values must match the number of parameters in the SQL string. :return: The ``Cursor`` object to allow chaining of operations. """ self.rowcount = -1 self._assert_valid() self.impl.prepare(sql) if parameters: buffer = make_parameter_set(self.impl) buffer.add_set(parameters) buffer.flush() return self._execute()
python
def execute(self, sql, parameters=None): self.rowcount = -1 self._assert_valid() self.impl.prepare(sql) if parameters: buffer = make_parameter_set(self.impl) buffer.add_set(parameters) buffer.flush() return self._execute()
[ "def", "execute", "(", "self", ",", "sql", ",", "parameters", "=", "None", ")", ":", "self", ".", "rowcount", "=", "-", "1", "self", ".", "_assert_valid", "(", ")", "self", ".", "impl", ".", "prepare", "(", "sql", ")", "if", "parameters", ":", "buf...
Execute an SQL command or query :param sql: A (unicode) string that contains the SQL command or query. If you would like to use parameters, please use a question mark ``?`` at the location where the parameter shall be inserted. :param parameters: An iterable of parameter values. The number of values must match the number of parameters in the SQL string. :return: The ``Cursor`` object to allow chaining of operations.
[ "Execute", "an", "SQL", "command", "or", "query" ]
5556625e69244d941a708c69eb2c1e7b37c190b1
https://github.com/blue-yonder/turbodbc/blob/5556625e69244d941a708c69eb2c1e7b37c190b1/python/turbodbc/cursor.py#L122-L140
233,037
blue-yonder/turbodbc
python/turbodbc/cursor.py
Cursor.close
def close(self): """ Close the cursor. """ self.result_set = None if self.impl is not None: self.impl._reset() self.impl = None
python
def close(self): self.result_set = None if self.impl is not None: self.impl._reset() self.impl = None
[ "def", "close", "(", "self", ")", ":", "self", ".", "result_set", "=", "None", "if", "self", ".", "impl", "is", "not", "None", ":", "self", ".", "impl", ".", "_reset", "(", ")", "self", ".", "impl", "=", "None" ]
Close the cursor.
[ "Close", "the", "cursor", "." ]
5556625e69244d941a708c69eb2c1e7b37c190b1
https://github.com/blue-yonder/turbodbc/blob/5556625e69244d941a708c69eb2c1e7b37c190b1/python/turbodbc/cursor.py#L370-L377
233,038
prompt-toolkit/pymux
pymux/pipes/win32.py
connect_to_pipe
def connect_to_pipe(pipe_name): """ Connect to a new pipe in message mode. """ pipe_handle = windll.kernel32.CreateFileW( pipe_name, DWORD(GENERIC_READ | GENERIC_WRITE | FILE_WRITE_ATTRIBUTES), DWORD(0), # No sharing. None, # Default security attributes. DWORD(OPEN_EXISTING), # dwCreationDisposition. FILE_FLAG_OVERLAPPED, # dwFlagsAndAttributes. None # hTemplateFile, ) if pipe_handle == INVALID_HANDLE_VALUE: raise Exception('Invalid handle. Connecting to pipe %r failed.' % pipe_name) # Turn pipe into message mode. dwMode = DWORD(PIPE_READMODE_MESSAGE) windll.kernel32.SetNamedPipeHandleState( pipe_handle, byref(dwMode), None, None) return pipe_handle
python
def connect_to_pipe(pipe_name): pipe_handle = windll.kernel32.CreateFileW( pipe_name, DWORD(GENERIC_READ | GENERIC_WRITE | FILE_WRITE_ATTRIBUTES), DWORD(0), # No sharing. None, # Default security attributes. DWORD(OPEN_EXISTING), # dwCreationDisposition. FILE_FLAG_OVERLAPPED, # dwFlagsAndAttributes. None # hTemplateFile, ) if pipe_handle == INVALID_HANDLE_VALUE: raise Exception('Invalid handle. Connecting to pipe %r failed.' % pipe_name) # Turn pipe into message mode. dwMode = DWORD(PIPE_READMODE_MESSAGE) windll.kernel32.SetNamedPipeHandleState( pipe_handle, byref(dwMode), None, None) return pipe_handle
[ "def", "connect_to_pipe", "(", "pipe_name", ")", ":", "pipe_handle", "=", "windll", ".", "kernel32", ".", "CreateFileW", "(", "pipe_name", ",", "DWORD", "(", "GENERIC_READ", "|", "GENERIC_WRITE", "|", "FILE_WRITE_ATTRIBUTES", ")", ",", "DWORD", "(", "0", ")", ...
Connect to a new pipe in message mode.
[ "Connect", "to", "a", "new", "pipe", "in", "message", "mode", "." ]
3f66e62b9de4b2251c7f9afad6c516dc5a30ec67
https://github.com/prompt-toolkit/pymux/blob/3f66e62b9de4b2251c7f9afad6c516dc5a30ec67/pymux/pipes/win32.py#L36-L60
233,039
prompt-toolkit/pymux
pymux/pipes/win32.py
create_event
def create_event(): """ Create Win32 event. """ event = windll.kernel32.CreateEventA( None, # Default security attributes. BOOL(True), # Manual reset event. BOOL(True), # Initial state = signaled. None # Unnamed event object. ) if not event: raise Exception('event creation failed.') return event
python
def create_event(): event = windll.kernel32.CreateEventA( None, # Default security attributes. BOOL(True), # Manual reset event. BOOL(True), # Initial state = signaled. None # Unnamed event object. ) if not event: raise Exception('event creation failed.') return event
[ "def", "create_event", "(", ")", ":", "event", "=", "windll", ".", "kernel32", ".", "CreateEventA", "(", "None", ",", "# Default security attributes.", "BOOL", "(", "True", ")", ",", "# Manual reset event.", "BOOL", "(", "True", ")", ",", "# Initial state = sign...
Create Win32 event.
[ "Create", "Win32", "event", "." ]
3f66e62b9de4b2251c7f9afad6c516dc5a30ec67
https://github.com/prompt-toolkit/pymux/blob/3f66e62b9de4b2251c7f9afad6c516dc5a30ec67/pymux/pipes/win32.py#L63-L75
233,040
prompt-toolkit/pymux
pymux/pipes/win32.py
wait_for_event
def wait_for_event(event): """ Wraps a win32 event into a `Future` and wait for it. """ f = Future() def ready(): get_event_loop().remove_win32_handle(event) f.set_result(None) get_event_loop().add_win32_handle(event, ready) return f
python
def wait_for_event(event): f = Future() def ready(): get_event_loop().remove_win32_handle(event) f.set_result(None) get_event_loop().add_win32_handle(event, ready) return f
[ "def", "wait_for_event", "(", "event", ")", ":", "f", "=", "Future", "(", ")", "def", "ready", "(", ")", ":", "get_event_loop", "(", ")", ".", "remove_win32_handle", "(", "event", ")", "f", ".", "set_result", "(", "None", ")", "get_event_loop", "(", ")...
Wraps a win32 event into a `Future` and wait for it.
[ "Wraps", "a", "win32", "event", "into", "a", "Future", "and", "wait", "for", "it", "." ]
3f66e62b9de4b2251c7f9afad6c516dc5a30ec67
https://github.com/prompt-toolkit/pymux/blob/3f66e62b9de4b2251c7f9afad6c516dc5a30ec67/pymux/pipes/win32.py#L196-L205
233,041
prompt-toolkit/pymux
pymux/client/windows.py
WindowsClient._start_reader
def _start_reader(self): """ Read messages from the Win32 pipe server and handle them. """ while True: message = yield From(self.pipe.read_message()) self._process(message)
python
def _start_reader(self): while True: message = yield From(self.pipe.read_message()) self._process(message)
[ "def", "_start_reader", "(", "self", ")", ":", "while", "True", ":", "message", "=", "yield", "From", "(", "self", ".", "pipe", ".", "read_message", "(", ")", ")", "self", ".", "_process", "(", "message", ")" ]
Read messages from the Win32 pipe server and handle them.
[ "Read", "messages", "from", "the", "Win32", "pipe", "server", "and", "handle", "them", "." ]
3f66e62b9de4b2251c7f9afad6c516dc5a30ec67
https://github.com/prompt-toolkit/pymux/blob/3f66e62b9de4b2251c7f9afad6c516dc5a30ec67/pymux/client/windows.py#L52-L58
233,042
prompt-toolkit/pymux
pymux/layout.py
_draw_number
def _draw_number(screen, x_offset, y_offset, number, style='class:clock', transparent=False): " Write number at position. " fg = Char(' ', 'class:clock') bg = Char(' ', '') for y, row in enumerate(_numbers[number]): screen_row = screen.data_buffer[y + y_offset] for x, n in enumerate(row): if n == '#': screen_row[x + x_offset] = fg elif not transparent: screen_row[x + x_offset] = bg
python
def _draw_number(screen, x_offset, y_offset, number, style='class:clock', transparent=False): " Write number at position. " fg = Char(' ', 'class:clock') bg = Char(' ', '') for y, row in enumerate(_numbers[number]): screen_row = screen.data_buffer[y + y_offset] for x, n in enumerate(row): if n == '#': screen_row[x + x_offset] = fg elif not transparent: screen_row[x + x_offset] = bg
[ "def", "_draw_number", "(", "screen", ",", "x_offset", ",", "y_offset", ",", "number", ",", "style", "=", "'class:clock'", ",", "transparent", "=", "False", ")", ":", "fg", "=", "Char", "(", "' '", ",", "'class:clock'", ")", "bg", "=", "Char", "(", "' ...
Write number at position.
[ "Write", "number", "at", "position", "." ]
3f66e62b9de4b2251c7f9afad6c516dc5a30ec67
https://github.com/prompt-toolkit/pymux/blob/3f66e62b9de4b2251c7f9afad6c516dc5a30ec67/pymux/layout.py#L102-L114
233,043
prompt-toolkit/pymux
pymux/layout.py
_create_split
def _create_split(pymux, window, split): """ Create a prompt_toolkit `Container` instance for the given pymux split. """ assert isinstance(split, (arrangement.HSplit, arrangement.VSplit)) is_vsplit = isinstance(split, arrangement.VSplit) def get_average_weight(): """ Calculate average weight of the children. Return 1 if none of the children has a weight specified yet. """ weights = 0 count = 0 for i in split: if i in split.weights: weights += split.weights[i] count += 1 if weights: return max(1, weights // count) else: return 1 def report_write_position_callback(item, write_position): """ When the layout is rendered, store the actial dimensions as weights in the arrangement.VSplit/HSplit classes. This is required because when a pane is resized with an increase of +1, we want to be sure that this corresponds exactly with one row or column. So, that updating weights corresponds exactly 1/1 to updating the size of the panes. """ if is_vsplit: split.weights[item] = write_position.width else: split.weights[item] = write_position.height def get_size(item): return D(weight=split.weights.get(item) or average_weight) content = [] average_weight = get_average_weight() for i, item in enumerate(split): # Create function for calculating dimensions for child. width = height = None if is_vsplit: width = partial(get_size, item) else: height = partial(get_size, item) # Create child. if isinstance(item, (arrangement.VSplit, arrangement.HSplit)): child = _create_split(pymux, window, item) elif isinstance(item, arrangement.Pane): child = _create_container_for_process(pymux, window, item) else: raise TypeError('Got %r' % (item,)) # Wrap child in `SizedBox` to enforce dimensions and sync back. content.append(SizedBox( child, width=width, height=height, report_write_position_callback=partial(report_write_position_callback, item))) # Create prompt_toolkit Container. if is_vsplit: return_cls = VSplit padding_char = _border_vertical else: return_cls = HSplit padding_char = _border_horizontal return return_cls(content, padding=1, padding_char=padding_char)
python
def _create_split(pymux, window, split): assert isinstance(split, (arrangement.HSplit, arrangement.VSplit)) is_vsplit = isinstance(split, arrangement.VSplit) def get_average_weight(): """ Calculate average weight of the children. Return 1 if none of the children has a weight specified yet. """ weights = 0 count = 0 for i in split: if i in split.weights: weights += split.weights[i] count += 1 if weights: return max(1, weights // count) else: return 1 def report_write_position_callback(item, write_position): """ When the layout is rendered, store the actial dimensions as weights in the arrangement.VSplit/HSplit classes. This is required because when a pane is resized with an increase of +1, we want to be sure that this corresponds exactly with one row or column. So, that updating weights corresponds exactly 1/1 to updating the size of the panes. """ if is_vsplit: split.weights[item] = write_position.width else: split.weights[item] = write_position.height def get_size(item): return D(weight=split.weights.get(item) or average_weight) content = [] average_weight = get_average_weight() for i, item in enumerate(split): # Create function for calculating dimensions for child. width = height = None if is_vsplit: width = partial(get_size, item) else: height = partial(get_size, item) # Create child. if isinstance(item, (arrangement.VSplit, arrangement.HSplit)): child = _create_split(pymux, window, item) elif isinstance(item, arrangement.Pane): child = _create_container_for_process(pymux, window, item) else: raise TypeError('Got %r' % (item,)) # Wrap child in `SizedBox` to enforce dimensions and sync back. content.append(SizedBox( child, width=width, height=height, report_write_position_callback=partial(report_write_position_callback, item))) # Create prompt_toolkit Container. if is_vsplit: return_cls = VSplit padding_char = _border_vertical else: return_cls = HSplit padding_char = _border_horizontal return return_cls(content, padding=1, padding_char=padding_char)
[ "def", "_create_split", "(", "pymux", ",", "window", ",", "split", ")", ":", "assert", "isinstance", "(", "split", ",", "(", "arrangement", ".", "HSplit", ",", "arrangement", ".", "VSplit", ")", ")", "is_vsplit", "=", "isinstance", "(", "split", ",", "ar...
Create a prompt_toolkit `Container` instance for the given pymux split.
[ "Create", "a", "prompt_toolkit", "Container", "instance", "for", "the", "given", "pymux", "split", "." ]
3f66e62b9de4b2251c7f9afad6c516dc5a30ec67
https://github.com/prompt-toolkit/pymux/blob/3f66e62b9de4b2251c7f9afad6c516dc5a30ec67/pymux/layout.py#L604-L679
233,044
prompt-toolkit/pymux
pymux/layout.py
_create_container_for_process
def _create_container_for_process(pymux, window, arrangement_pane, zoom=False): """ Create a `Container` with a titlebar for a process. """ @Condition def clock_is_visible(): return arrangement_pane.clock_mode @Condition def pane_numbers_are_visible(): return pymux.display_pane_numbers terminal_is_focused = has_focus(arrangement_pane.terminal) def get_terminal_style(): if terminal_is_focused(): result = 'class:terminal.focused' else: result = 'class:terminal' return result def get_titlebar_text_fragments(): result = [] if zoom: result.append(('class:titlebar-zoom', ' Z ')) if arrangement_pane.process.is_terminated: result.append(('class:terminated', ' Terminated ')) # Scroll buffer info. if arrangement_pane.display_scroll_buffer: result.append(('class:copymode', ' %s ' % arrangement_pane.scroll_buffer_title)) # Cursor position. document = arrangement_pane.scroll_buffer.document result.append(('class:copymode.position', ' %i,%i ' % ( document.cursor_position_row, document.cursor_position_col))) if arrangement_pane.name: result.append(('class:name', ' %s ' % arrangement_pane.name)) result.append(('', ' ')) return result + [ ('', format_pymux_string(pymux, ' #T ', pane=arrangement_pane)) # XXX: Make configurable. ] def get_pane_index(): try: w = pymux.arrangement.get_active_window() index = w.get_pane_index(arrangement_pane) except ValueError: index = '/' return '%3s ' % index def on_click(): " Click handler for the clock. When clicked, select this pane. " arrangement_pane.clock_mode = False pymux.arrangement.get_active_window().active_pane = arrangement_pane pymux.invalidate() return HighlightBordersIfActive( window, arrangement_pane, get_terminal_style, FloatContainer( HSplit([ # The terminal. TracePaneWritePosition( pymux, arrangement_pane, content=arrangement_pane.terminal), ]), # floats=[ # The title bar. Float(content= ConditionalContainer( content=VSplit([ Window( height=1, content=FormattedTextControl( get_titlebar_text_fragments)), Window( height=1, width=4, content=FormattedTextControl(get_pane_index), style='class:paneindex') ], style='class:titlebar'), filter=Condition(lambda: pymux.enable_pane_status)), left=0, right=0, top=-1, height=1, z_index=Z_INDEX.WINDOW_TITLE_BAR), # The clock. Float( content=ConditionalContainer(BigClock(on_click), filter=clock_is_visible)), # Pane number. Float(content=ConditionalContainer( content=PaneNumber(pymux, arrangement_pane), filter=pane_numbers_are_visible)), ] ) )
python
def _create_container_for_process(pymux, window, arrangement_pane, zoom=False): @Condition def clock_is_visible(): return arrangement_pane.clock_mode @Condition def pane_numbers_are_visible(): return pymux.display_pane_numbers terminal_is_focused = has_focus(arrangement_pane.terminal) def get_terminal_style(): if terminal_is_focused(): result = 'class:terminal.focused' else: result = 'class:terminal' return result def get_titlebar_text_fragments(): result = [] if zoom: result.append(('class:titlebar-zoom', ' Z ')) if arrangement_pane.process.is_terminated: result.append(('class:terminated', ' Terminated ')) # Scroll buffer info. if arrangement_pane.display_scroll_buffer: result.append(('class:copymode', ' %s ' % arrangement_pane.scroll_buffer_title)) # Cursor position. document = arrangement_pane.scroll_buffer.document result.append(('class:copymode.position', ' %i,%i ' % ( document.cursor_position_row, document.cursor_position_col))) if arrangement_pane.name: result.append(('class:name', ' %s ' % arrangement_pane.name)) result.append(('', ' ')) return result + [ ('', format_pymux_string(pymux, ' #T ', pane=arrangement_pane)) # XXX: Make configurable. ] def get_pane_index(): try: w = pymux.arrangement.get_active_window() index = w.get_pane_index(arrangement_pane) except ValueError: index = '/' return '%3s ' % index def on_click(): " Click handler for the clock. When clicked, select this pane. " arrangement_pane.clock_mode = False pymux.arrangement.get_active_window().active_pane = arrangement_pane pymux.invalidate() return HighlightBordersIfActive( window, arrangement_pane, get_terminal_style, FloatContainer( HSplit([ # The terminal. TracePaneWritePosition( pymux, arrangement_pane, content=arrangement_pane.terminal), ]), # floats=[ # The title bar. Float(content= ConditionalContainer( content=VSplit([ Window( height=1, content=FormattedTextControl( get_titlebar_text_fragments)), Window( height=1, width=4, content=FormattedTextControl(get_pane_index), style='class:paneindex') ], style='class:titlebar'), filter=Condition(lambda: pymux.enable_pane_status)), left=0, right=0, top=-1, height=1, z_index=Z_INDEX.WINDOW_TITLE_BAR), # The clock. Float( content=ConditionalContainer(BigClock(on_click), filter=clock_is_visible)), # Pane number. Float(content=ConditionalContainer( content=PaneNumber(pymux, arrangement_pane), filter=pane_numbers_are_visible)), ] ) )
[ "def", "_create_container_for_process", "(", "pymux", ",", "window", ",", "arrangement_pane", ",", "zoom", "=", "False", ")", ":", "@", "Condition", "def", "clock_is_visible", "(", ")", ":", "return", "arrangement_pane", ".", "clock_mode", "@", "Condition", "def...
Create a `Container` with a titlebar for a process.
[ "Create", "a", "Container", "with", "a", "titlebar", "for", "a", "process", "." ]
3f66e62b9de4b2251c7f9afad6c516dc5a30ec67
https://github.com/prompt-toolkit/pymux/blob/3f66e62b9de4b2251c7f9afad6c516dc5a30ec67/pymux/layout.py#L699-L804
233,045
prompt-toolkit/pymux
pymux/layout.py
focus_left
def focus_left(pymux): " Move focus to the left. " _move_focus(pymux, lambda wp: wp.xpos - 2, # 2 in order to skip over the border. lambda wp: wp.ypos)
python
def focus_left(pymux): " Move focus to the left. " _move_focus(pymux, lambda wp: wp.xpos - 2, # 2 in order to skip over the border. lambda wp: wp.ypos)
[ "def", "focus_left", "(", "pymux", ")", ":", "_move_focus", "(", "pymux", ",", "lambda", "wp", ":", "wp", ".", "xpos", "-", "2", ",", "# 2 in order to skip over the border.", "lambda", "wp", ":", "wp", ".", "ypos", ")" ]
Move focus to the left.
[ "Move", "focus", "to", "the", "left", "." ]
3f66e62b9de4b2251c7f9afad6c516dc5a30ec67
https://github.com/prompt-toolkit/pymux/blob/3f66e62b9de4b2251c7f9afad6c516dc5a30ec67/pymux/layout.py#L896-L900
233,046
prompt-toolkit/pymux
pymux/layout.py
focus_right
def focus_right(pymux): " Move focus to the right. " _move_focus(pymux, lambda wp: wp.xpos + wp.width + 1, lambda wp: wp.ypos)
python
def focus_right(pymux): " Move focus to the right. " _move_focus(pymux, lambda wp: wp.xpos + wp.width + 1, lambda wp: wp.ypos)
[ "def", "focus_right", "(", "pymux", ")", ":", "_move_focus", "(", "pymux", ",", "lambda", "wp", ":", "wp", ".", "xpos", "+", "wp", ".", "width", "+", "1", ",", "lambda", "wp", ":", "wp", ".", "ypos", ")" ]
Move focus to the right.
[ "Move", "focus", "to", "the", "right", "." ]
3f66e62b9de4b2251c7f9afad6c516dc5a30ec67
https://github.com/prompt-toolkit/pymux/blob/3f66e62b9de4b2251c7f9afad6c516dc5a30ec67/pymux/layout.py#L903-L907
233,047
prompt-toolkit/pymux
pymux/layout.py
focus_down
def focus_down(pymux): " Move focus down. " _move_focus(pymux, lambda wp: wp.xpos, lambda wp: wp.ypos + wp.height + 2)
python
def focus_down(pymux): " Move focus down. " _move_focus(pymux, lambda wp: wp.xpos, lambda wp: wp.ypos + wp.height + 2)
[ "def", "focus_down", "(", "pymux", ")", ":", "_move_focus", "(", "pymux", ",", "lambda", "wp", ":", "wp", ".", "xpos", ",", "lambda", "wp", ":", "wp", ".", "ypos", "+", "wp", ".", "height", "+", "2", ")" ]
Move focus down.
[ "Move", "focus", "down", "." ]
3f66e62b9de4b2251c7f9afad6c516dc5a30ec67
https://github.com/prompt-toolkit/pymux/blob/3f66e62b9de4b2251c7f9afad6c516dc5a30ec67/pymux/layout.py#L910-L914
233,048
prompt-toolkit/pymux
pymux/layout.py
focus_up
def focus_up(pymux): " Move focus up. " _move_focus(pymux, lambda wp: wp.xpos, lambda wp: wp.ypos - 2)
python
def focus_up(pymux): " Move focus up. " _move_focus(pymux, lambda wp: wp.xpos, lambda wp: wp.ypos - 2)
[ "def", "focus_up", "(", "pymux", ")", ":", "_move_focus", "(", "pymux", ",", "lambda", "wp", ":", "wp", ".", "xpos", ",", "lambda", "wp", ":", "wp", ".", "ypos", "-", "2", ")" ]
Move focus up.
[ "Move", "focus", "up", "." ]
3f66e62b9de4b2251c7f9afad6c516dc5a30ec67
https://github.com/prompt-toolkit/pymux/blob/3f66e62b9de4b2251c7f9afad6c516dc5a30ec67/pymux/layout.py#L919-L923
233,049
prompt-toolkit/pymux
pymux/layout.py
_move_focus
def _move_focus(pymux, get_x, get_y): " Move focus of the active window. " window = pymux.arrangement.get_active_window() try: write_pos = pymux.get_client_state().layout_manager.pane_write_positions[window.active_pane] except KeyError: pass else: x = get_x(write_pos) y = get_y(write_pos) # Look for the pane at this position. for pane, wp in pymux.get_client_state().layout_manager.pane_write_positions.items(): if (wp.xpos <= x < wp.xpos + wp.width and wp.ypos <= y < wp.ypos + wp.height): window.active_pane = pane return
python
def _move_focus(pymux, get_x, get_y): " Move focus of the active window. " window = pymux.arrangement.get_active_window() try: write_pos = pymux.get_client_state().layout_manager.pane_write_positions[window.active_pane] except KeyError: pass else: x = get_x(write_pos) y = get_y(write_pos) # Look for the pane at this position. for pane, wp in pymux.get_client_state().layout_manager.pane_write_positions.items(): if (wp.xpos <= x < wp.xpos + wp.width and wp.ypos <= y < wp.ypos + wp.height): window.active_pane = pane return
[ "def", "_move_focus", "(", "pymux", ",", "get_x", ",", "get_y", ")", ":", "window", "=", "pymux", ".", "arrangement", ".", "get_active_window", "(", ")", "try", ":", "write_pos", "=", "pymux", ".", "get_client_state", "(", ")", ".", "layout_manager", ".", ...
Move focus of the active window.
[ "Move", "focus", "of", "the", "active", "window", "." ]
3f66e62b9de4b2251c7f9afad6c516dc5a30ec67
https://github.com/prompt-toolkit/pymux/blob/3f66e62b9de4b2251c7f9afad6c516dc5a30ec67/pymux/layout.py#L926-L943
233,050
prompt-toolkit/pymux
pymux/layout.py
Background.write_to_screen
def write_to_screen(self, screen, mouse_handlers, write_position, parent_style, erase_bg, z_index): " Fill the whole area of write_position with dots. " default_char = Char(' ', 'class:background') dot = Char('.', 'class:background') ypos = write_position.ypos xpos = write_position.xpos for y in range(ypos, ypos + write_position.height): row = screen.data_buffer[y] for x in range(xpos, xpos + write_position.width): row[x] = dot if (x + y) % 3 == 0 else default_char
python
def write_to_screen(self, screen, mouse_handlers, write_position, parent_style, erase_bg, z_index): " Fill the whole area of write_position with dots. " default_char = Char(' ', 'class:background') dot = Char('.', 'class:background') ypos = write_position.ypos xpos = write_position.xpos for y in range(ypos, ypos + write_position.height): row = screen.data_buffer[y] for x in range(xpos, xpos + write_position.width): row[x] = dot if (x + y) % 3 == 0 else default_char
[ "def", "write_to_screen", "(", "self", ",", "screen", ",", "mouse_handlers", ",", "write_position", ",", "parent_style", ",", "erase_bg", ",", "z_index", ")", ":", "default_char", "=", "Char", "(", "' '", ",", "'class:background'", ")", "dot", "=", "Char", "...
Fill the whole area of write_position with dots.
[ "Fill", "the", "whole", "area", "of", "write_position", "with", "dots", "." ]
3f66e62b9de4b2251c7f9afad6c516dc5a30ec67
https://github.com/prompt-toolkit/pymux/blob/3f66e62b9de4b2251c7f9afad6c516dc5a30ec67/pymux/layout.py#L73-L86
233,051
prompt-toolkit/pymux
pymux/layout.py
BigClock._mouse_handler
def _mouse_handler(self, cli, mouse_event): " Click callback. " if mouse_event.event_type == MouseEventType.MOUSE_UP: self.on_click(cli) else: return NotImplemented
python
def _mouse_handler(self, cli, mouse_event): " Click callback. " if mouse_event.event_type == MouseEventType.MOUSE_UP: self.on_click(cli) else: return NotImplemented
[ "def", "_mouse_handler", "(", "self", ",", "cli", ",", "mouse_event", ")", ":", "if", "mouse_event", ".", "event_type", "==", "MouseEventType", ".", "MOUSE_UP", ":", "self", ".", "on_click", "(", "cli", ")", "else", ":", "return", "NotImplemented" ]
Click callback.
[ "Click", "callback", "." ]
3f66e62b9de4b2251c7f9afad6c516dc5a30ec67
https://github.com/prompt-toolkit/pymux/blob/3f66e62b9de4b2251c7f9afad6c516dc5a30ec67/pymux/layout.py#L168-L173
233,052
prompt-toolkit/pymux
pymux/layout.py
LayoutManager.display_popup
def display_popup(self, title, content): """ Display a pop-up dialog. """ assert isinstance(title, six.text_type) assert isinstance(content, six.text_type) self.popup_dialog.title = title self._popup_textarea.text = content self.client_state.display_popup = True get_app().layout.focus(self._popup_textarea)
python
def display_popup(self, title, content): assert isinstance(title, six.text_type) assert isinstance(content, six.text_type) self.popup_dialog.title = title self._popup_textarea.text = content self.client_state.display_popup = True get_app().layout.focus(self._popup_textarea)
[ "def", "display_popup", "(", "self", ",", "title", ",", "content", ")", ":", "assert", "isinstance", "(", "title", ",", "six", ".", "text_type", ")", "assert", "isinstance", "(", "content", ",", "six", ".", "text_type", ")", "self", ".", "popup_dialog", ...
Display a pop-up dialog.
[ "Display", "a", "pop", "-", "up", "dialog", "." ]
3f66e62b9de4b2251c7f9afad6c516dc5a30ec67
https://github.com/prompt-toolkit/pymux/blob/3f66e62b9de4b2251c7f9afad6c516dc5a30ec67/pymux/layout.py#L295-L305
233,053
prompt-toolkit/pymux
pymux/layout.py
LayoutManager._create_select_window_handler
def _create_select_window_handler(self, window): " Return a mouse handler that selects the given window when clicking. " def handler(mouse_event): if mouse_event.event_type == MouseEventType.MOUSE_DOWN: self.pymux.arrangement.set_active_window(window) self.pymux.invalidate() else: return NotImplemented # Event not handled here. return handler
python
def _create_select_window_handler(self, window): " Return a mouse handler that selects the given window when clicking. " def handler(mouse_event): if mouse_event.event_type == MouseEventType.MOUSE_DOWN: self.pymux.arrangement.set_active_window(window) self.pymux.invalidate() else: return NotImplemented # Event not handled here. return handler
[ "def", "_create_select_window_handler", "(", "self", ",", "window", ")", ":", "def", "handler", "(", "mouse_event", ")", ":", "if", "mouse_event", ".", "event_type", "==", "MouseEventType", ".", "MOUSE_DOWN", ":", "self", ".", "pymux", ".", "arrangement", ".",...
Return a mouse handler that selects the given window when clicking.
[ "Return", "a", "mouse", "handler", "that", "selects", "the", "given", "window", "when", "clicking", "." ]
3f66e62b9de4b2251c7f9afad6c516dc5a30ec67
https://github.com/prompt-toolkit/pymux/blob/3f66e62b9de4b2251c7f9afad6c516dc5a30ec67/pymux/layout.py#L307-L315
233,054
prompt-toolkit/pymux
pymux/layout.py
LayoutManager._get_status_tokens
def _get_status_tokens(self): " The tokens for the status bar. " result = [] # Display panes. for i, w in enumerate(self.pymux.arrangement.windows): if i > 0: result.append(('', ' ')) if w == self.pymux.arrangement.get_active_window(): style = 'class:window.current' format_str = self.pymux.window_status_current_format else: style = 'class:window' format_str = self.pymux.window_status_format result.append(( style, format_pymux_string(self.pymux, format_str, window=w), self._create_select_window_handler(w))) return result
python
def _get_status_tokens(self): " The tokens for the status bar. " result = [] # Display panes. for i, w in enumerate(self.pymux.arrangement.windows): if i > 0: result.append(('', ' ')) if w == self.pymux.arrangement.get_active_window(): style = 'class:window.current' format_str = self.pymux.window_status_current_format else: style = 'class:window' format_str = self.pymux.window_status_format result.append(( style, format_pymux_string(self.pymux, format_str, window=w), self._create_select_window_handler(w))) return result
[ "def", "_get_status_tokens", "(", "self", ")", ":", "result", "=", "[", "]", "# Display panes.", "for", "i", ",", "w", "in", "enumerate", "(", "self", ".", "pymux", ".", "arrangement", ".", "windows", ")", ":", "if", "i", ">", "0", ":", "result", "."...
The tokens for the status bar.
[ "The", "tokens", "for", "the", "status", "bar", "." ]
3f66e62b9de4b2251c7f9afad6c516dc5a30ec67
https://github.com/prompt-toolkit/pymux/blob/3f66e62b9de4b2251c7f9afad6c516dc5a30ec67/pymux/layout.py#L317-L339
233,055
prompt-toolkit/pymux
pymux/layout.py
DynamicBody._get_body
def _get_body(self): " Return the Container object for the current CLI. " new_hash = self.pymux.arrangement.invalidation_hash() # Return existing layout if nothing has changed to the arrangement. app = get_app() if app in self._bodies_for_app: existing_hash, container = self._bodies_for_app[app] if existing_hash == new_hash: return container # The layout changed. Build a new layout when the arrangement changed. new_layout = self._build_layout() self._bodies_for_app[app] = (new_hash, new_layout) return new_layout
python
def _get_body(self): " Return the Container object for the current CLI. " new_hash = self.pymux.arrangement.invalidation_hash() # Return existing layout if nothing has changed to the arrangement. app = get_app() if app in self._bodies_for_app: existing_hash, container = self._bodies_for_app[app] if existing_hash == new_hash: return container # The layout changed. Build a new layout when the arrangement changed. new_layout = self._build_layout() self._bodies_for_app[app] = (new_hash, new_layout) return new_layout
[ "def", "_get_body", "(", "self", ")", ":", "new_hash", "=", "self", ".", "pymux", ".", "arrangement", ".", "invalidation_hash", "(", ")", "# Return existing layout if nothing has changed to the arrangement.", "app", "=", "get_app", "(", ")", "if", "app", "in", "se...
Return the Container object for the current CLI.
[ "Return", "the", "Container", "object", "for", "the", "current", "CLI", "." ]
3f66e62b9de4b2251c7f9afad6c516dc5a30ec67
https://github.com/prompt-toolkit/pymux/blob/3f66e62b9de4b2251c7f9afad6c516dc5a30ec67/pymux/layout.py#L496-L511
233,056
prompt-toolkit/pymux
pymux/layout.py
DynamicBody._build_layout
def _build_layout(self): " Rebuild a new Container object and return that. " logger.info('Rebuilding layout.') if not self.pymux.arrangement.windows: # No Pymux windows in the arrangement. return Window() active_window = self.pymux.arrangement.get_active_window() # When zoomed, only show the current pane, otherwise show all of them. if active_window.zoom: return to_container(_create_container_for_process( self.pymux, active_window, active_window.active_pane, zoom=True)) else: window = self.pymux.arrangement.get_active_window() return HSplit([ # Some spacing for the top status bar. ConditionalContainer( content=Window(height=1), filter=Condition(lambda: self.pymux.enable_pane_status)), # The actual content. _create_split(self.pymux, window, window.root) ])
python
def _build_layout(self): " Rebuild a new Container object and return that. " logger.info('Rebuilding layout.') if not self.pymux.arrangement.windows: # No Pymux windows in the arrangement. return Window() active_window = self.pymux.arrangement.get_active_window() # When zoomed, only show the current pane, otherwise show all of them. if active_window.zoom: return to_container(_create_container_for_process( self.pymux, active_window, active_window.active_pane, zoom=True)) else: window = self.pymux.arrangement.get_active_window() return HSplit([ # Some spacing for the top status bar. ConditionalContainer( content=Window(height=1), filter=Condition(lambda: self.pymux.enable_pane_status)), # The actual content. _create_split(self.pymux, window, window.root) ])
[ "def", "_build_layout", "(", "self", ")", ":", "logger", ".", "info", "(", "'Rebuilding layout.'", ")", "if", "not", "self", ".", "pymux", ".", "arrangement", ".", "windows", ":", "# No Pymux windows in the arrangement.", "return", "Window", "(", ")", "active_wi...
Rebuild a new Container object and return that.
[ "Rebuild", "a", "new", "Container", "object", "and", "return", "that", "." ]
3f66e62b9de4b2251c7f9afad6c516dc5a30ec67
https://github.com/prompt-toolkit/pymux/blob/3f66e62b9de4b2251c7f9afad6c516dc5a30ec67/pymux/layout.py#L513-L536
233,057
prompt-toolkit/pymux
pymux/pipes/__init__.py
bind_and_listen_on_socket
def bind_and_listen_on_socket(socket_name, accept_callback): """ Return socket name. :param accept_callback: Callback is called with a `PipeConnection` as argument. """ if is_windows(): from .win32_server import bind_and_listen_on_win32_socket return bind_and_listen_on_win32_socket(socket_name, accept_callback) else: from .posix import bind_and_listen_on_posix_socket return bind_and_listen_on_posix_socket(socket_name, accept_callback)
python
def bind_and_listen_on_socket(socket_name, accept_callback): if is_windows(): from .win32_server import bind_and_listen_on_win32_socket return bind_and_listen_on_win32_socket(socket_name, accept_callback) else: from .posix import bind_and_listen_on_posix_socket return bind_and_listen_on_posix_socket(socket_name, accept_callback)
[ "def", "bind_and_listen_on_socket", "(", "socket_name", ",", "accept_callback", ")", ":", "if", "is_windows", "(", ")", ":", "from", ".", "win32_server", "import", "bind_and_listen_on_win32_socket", "return", "bind_and_listen_on_win32_socket", "(", "socket_name", ",", "...
Return socket name. :param accept_callback: Callback is called with a `PipeConnection` as argument.
[ "Return", "socket", "name", "." ]
3f66e62b9de4b2251c7f9afad6c516dc5a30ec67
https://github.com/prompt-toolkit/pymux/blob/3f66e62b9de4b2251c7f9afad6c516dc5a30ec67/pymux/pipes/__init__.py#L18-L30
233,058
prompt-toolkit/pymux
pymux/client/posix.py
list_clients
def list_clients(): """ List all the servers that are running. """ p = '%s/pymux.sock.%s.*' % (tempfile.gettempdir(), getpass.getuser()) for path in glob.glob(p): try: yield PosixClient(path) except socket.error: pass
python
def list_clients(): p = '%s/pymux.sock.%s.*' % (tempfile.gettempdir(), getpass.getuser()) for path in glob.glob(p): try: yield PosixClient(path) except socket.error: pass
[ "def", "list_clients", "(", ")", ":", "p", "=", "'%s/pymux.sock.%s.*'", "%", "(", "tempfile", ".", "gettempdir", "(", ")", ",", "getpass", ".", "getuser", "(", ")", ")", "for", "path", "in", "glob", ".", "glob", "(", "p", ")", ":", "try", ":", "yie...
List all the servers that are running.
[ "List", "all", "the", "servers", "that", "are", "running", "." ]
3f66e62b9de4b2251c7f9afad6c516dc5a30ec67
https://github.com/prompt-toolkit/pymux/blob/3f66e62b9de4b2251c7f9afad6c516dc5a30ec67/pymux/client/posix.py#L194-L203
233,059
prompt-toolkit/pymux
pymux/client/posix.py
PosixClient.attach
def attach(self, detach_other_clients=False, color_depth=ColorDepth.DEPTH_8_BIT): """ Attach client user interface. """ assert isinstance(detach_other_clients, bool) self._send_size() self._send_packet({ 'cmd': 'start-gui', 'detach-others': detach_other_clients, 'color-depth': color_depth, 'term': os.environ.get('TERM', ''), 'data': '' }) with raw_mode(sys.stdin.fileno()): data_buffer = b'' stdin_fd = sys.stdin.fileno() socket_fd = self.socket.fileno() current_timeout = INPUT_TIMEOUT # Timeout, used to flush escape sequences. try: def winch_handler(signum, frame): self._send_size() signal.signal(signal.SIGWINCH, winch_handler) while True: r = select_fds([stdin_fd, socket_fd], current_timeout) if socket_fd in r: # Received packet from server. data = self.socket.recv(1024) if data == b'': # End of file. Connection closed. # Reset terminal o = Vt100_Output.from_pty(sys.stdout) o.quit_alternate_screen() o.disable_mouse_support() o.disable_bracketed_paste() o.reset_attributes() o.flush() return else: data_buffer += data while b'\0' in data_buffer: pos = data_buffer.index(b'\0') self._process(data_buffer[:pos]) data_buffer = data_buffer[pos + 1:] elif stdin_fd in r: # Got user input. self._process_stdin() current_timeout = INPUT_TIMEOUT else: # Timeout. (Tell the server to flush the vt100 Escape.) self._send_packet({'cmd': 'flush-input'}) current_timeout = None finally: signal.signal(signal.SIGWINCH, signal.SIG_IGN)
python
def attach(self, detach_other_clients=False, color_depth=ColorDepth.DEPTH_8_BIT): assert isinstance(detach_other_clients, bool) self._send_size() self._send_packet({ 'cmd': 'start-gui', 'detach-others': detach_other_clients, 'color-depth': color_depth, 'term': os.environ.get('TERM', ''), 'data': '' }) with raw_mode(sys.stdin.fileno()): data_buffer = b'' stdin_fd = sys.stdin.fileno() socket_fd = self.socket.fileno() current_timeout = INPUT_TIMEOUT # Timeout, used to flush escape sequences. try: def winch_handler(signum, frame): self._send_size() signal.signal(signal.SIGWINCH, winch_handler) while True: r = select_fds([stdin_fd, socket_fd], current_timeout) if socket_fd in r: # Received packet from server. data = self.socket.recv(1024) if data == b'': # End of file. Connection closed. # Reset terminal o = Vt100_Output.from_pty(sys.stdout) o.quit_alternate_screen() o.disable_mouse_support() o.disable_bracketed_paste() o.reset_attributes() o.flush() return else: data_buffer += data while b'\0' in data_buffer: pos = data_buffer.index(b'\0') self._process(data_buffer[:pos]) data_buffer = data_buffer[pos + 1:] elif stdin_fd in r: # Got user input. self._process_stdin() current_timeout = INPUT_TIMEOUT else: # Timeout. (Tell the server to flush the vt100 Escape.) self._send_packet({'cmd': 'flush-input'}) current_timeout = None finally: signal.signal(signal.SIGWINCH, signal.SIG_IGN)
[ "def", "attach", "(", "self", ",", "detach_other_clients", "=", "False", ",", "color_depth", "=", "ColorDepth", ".", "DEPTH_8_BIT", ")", ":", "assert", "isinstance", "(", "detach_other_clients", ",", "bool", ")", "self", ".", "_send_size", "(", ")", "self", ...
Attach client user interface.
[ "Attach", "client", "user", "interface", "." ]
3f66e62b9de4b2251c7f9afad6c516dc5a30ec67
https://github.com/prompt-toolkit/pymux/blob/3f66e62b9de4b2251c7f9afad6c516dc5a30ec67/pymux/client/posix.py#L63-L125
233,060
prompt-toolkit/pymux
pymux/client/posix.py
PosixClient._process_stdin
def _process_stdin(self): """ Received data on stdin. Read and send to server. """ with nonblocking(sys.stdin.fileno()): data = self._stdin_reader.read() # Send input in chunks of 4k. step = 4056 for i in range(0, len(data), step): self._send_packet({ 'cmd': 'in', 'data': data[i:i + step], })
python
def _process_stdin(self): with nonblocking(sys.stdin.fileno()): data = self._stdin_reader.read() # Send input in chunks of 4k. step = 4056 for i in range(0, len(data), step): self._send_packet({ 'cmd': 'in', 'data': data[i:i + step], })
[ "def", "_process_stdin", "(", "self", ")", ":", "with", "nonblocking", "(", "sys", ".", "stdin", ".", "fileno", "(", ")", ")", ":", "data", "=", "self", ".", "_stdin_reader", ".", "read", "(", ")", "# Send input in chunks of 4k.", "step", "=", "4056", "f...
Received data on stdin. Read and send to server.
[ "Received", "data", "on", "stdin", ".", "Read", "and", "send", "to", "server", "." ]
3f66e62b9de4b2251c7f9afad6c516dc5a30ec67
https://github.com/prompt-toolkit/pymux/blob/3f66e62b9de4b2251c7f9afad6c516dc5a30ec67/pymux/client/posix.py#L160-L173
233,061
prompt-toolkit/pymux
pymux/main.py
ClientState._handle_command
def _handle_command(self, buffer): " When text is accepted in the command line. " text = buffer.text # First leave command mode. We want to make sure that the working # pane is focused again before executing the command handers. self.pymux.leave_command_mode(append_to_history=True) # Execute command. self.pymux.handle_command(text)
python
def _handle_command(self, buffer): " When text is accepted in the command line. " text = buffer.text # First leave command mode. We want to make sure that the working # pane is focused again before executing the command handers. self.pymux.leave_command_mode(append_to_history=True) # Execute command. self.pymux.handle_command(text)
[ "def", "_handle_command", "(", "self", ",", "buffer", ")", ":", "text", "=", "buffer", ".", "text", "# First leave command mode. We want to make sure that the working", "# pane is focused again before executing the command handers.", "self", ".", "pymux", ".", "leave_command_mo...
When text is accepted in the command line.
[ "When", "text", "is", "accepted", "in", "the", "command", "line", "." ]
3f66e62b9de4b2251c7f9afad6c516dc5a30ec67
https://github.com/prompt-toolkit/pymux/blob/3f66e62b9de4b2251c7f9afad6c516dc5a30ec67/pymux/main.py#L109-L118
233,062
prompt-toolkit/pymux
pymux/main.py
ClientState._handle_prompt_command
def _handle_prompt_command(self, buffer): " When a command-prompt command is accepted. " text = buffer.text prompt_command = self.prompt_command # Leave command mode and handle command. self.pymux.leave_command_mode(append_to_history=True) self.pymux.handle_command(prompt_command.replace('%%', text))
python
def _handle_prompt_command(self, buffer): " When a command-prompt command is accepted. " text = buffer.text prompt_command = self.prompt_command # Leave command mode and handle command. self.pymux.leave_command_mode(append_to_history=True) self.pymux.handle_command(prompt_command.replace('%%', text))
[ "def", "_handle_prompt_command", "(", "self", ",", "buffer", ")", ":", "text", "=", "buffer", ".", "text", "prompt_command", "=", "self", ".", "prompt_command", "# Leave command mode and handle command.", "self", ".", "pymux", ".", "leave_command_mode", "(", "append...
When a command-prompt command is accepted.
[ "When", "a", "command", "-", "prompt", "command", "is", "accepted", "." ]
3f66e62b9de4b2251c7f9afad6c516dc5a30ec67
https://github.com/prompt-toolkit/pymux/blob/3f66e62b9de4b2251c7f9afad6c516dc5a30ec67/pymux/main.py#L120-L127
233,063
prompt-toolkit/pymux
pymux/main.py
ClientState._create_app
def _create_app(self): """ Create `Application` instance for this . """ pymux = self.pymux def on_focus_changed(): """ When the focus changes to a read/write buffer, make sure to go to insert mode. This happens when the ViState was set to NAVIGATION in the copy buffer. """ vi_state = app.vi_state if app.current_buffer.read_only(): vi_state.input_mode = InputMode.NAVIGATION else: vi_state.input_mode = InputMode.INSERT app = Application( output=self.output, input=self.input, color_depth=self.color_depth, layout=Layout(container=self.layout_manager.layout), key_bindings=pymux.key_bindings_manager.key_bindings, mouse_support=Condition(lambda: pymux.enable_mouse_support), full_screen=True, style=self.pymux.style, style_transformation=ConditionalStyleTransformation( SwapLightAndDarkStyleTransformation(), Condition(lambda: self.pymux.swap_dark_and_light), ), on_invalidate=(lambda _: pymux.invalidate())) # Synchronize the Vi state with the CLI object. # (This is stored in the current class, but expected to be in the # CommandLineInterface.) def sync_vi_state(_): VI = EditingMode.VI EMACS = EditingMode.EMACS if self.confirm_text or self.prompt_command or self.command_mode: app.editing_mode = VI if pymux.status_keys_vi_mode else EMACS else: app.editing_mode = VI if pymux.mode_keys_vi_mode else EMACS app.key_processor.before_key_press += sync_vi_state app.key_processor.after_key_press += sync_vi_state app.key_processor.after_key_press += self.sync_focus # Set render postpone time. (.1 instead of 0). # This small change ensures that if for a split second a process # outputs a lot of information, we don't give the highest priority to # rendering output. (Nobody reads that fast in real-time.) app.max_render_postpone_time = .1 # Second. # Hide message when a key has been pressed. def key_pressed(_): self.message = None app.key_processor.before_key_press += key_pressed # The following code needs to run with the application active. # Especially, `create_window` needs to know what the current # application is, in order to focus the new pane. with set_app(app): # Redraw all CLIs. (Adding a new client could mean that the others # change size, so everything has to be redrawn.) pymux.invalidate() pymux.startup() return app
python
def _create_app(self): pymux = self.pymux def on_focus_changed(): """ When the focus changes to a read/write buffer, make sure to go to insert mode. This happens when the ViState was set to NAVIGATION in the copy buffer. """ vi_state = app.vi_state if app.current_buffer.read_only(): vi_state.input_mode = InputMode.NAVIGATION else: vi_state.input_mode = InputMode.INSERT app = Application( output=self.output, input=self.input, color_depth=self.color_depth, layout=Layout(container=self.layout_manager.layout), key_bindings=pymux.key_bindings_manager.key_bindings, mouse_support=Condition(lambda: pymux.enable_mouse_support), full_screen=True, style=self.pymux.style, style_transformation=ConditionalStyleTransformation( SwapLightAndDarkStyleTransformation(), Condition(lambda: self.pymux.swap_dark_and_light), ), on_invalidate=(lambda _: pymux.invalidate())) # Synchronize the Vi state with the CLI object. # (This is stored in the current class, but expected to be in the # CommandLineInterface.) def sync_vi_state(_): VI = EditingMode.VI EMACS = EditingMode.EMACS if self.confirm_text or self.prompt_command or self.command_mode: app.editing_mode = VI if pymux.status_keys_vi_mode else EMACS else: app.editing_mode = VI if pymux.mode_keys_vi_mode else EMACS app.key_processor.before_key_press += sync_vi_state app.key_processor.after_key_press += sync_vi_state app.key_processor.after_key_press += self.sync_focus # Set render postpone time. (.1 instead of 0). # This small change ensures that if for a split second a process # outputs a lot of information, we don't give the highest priority to # rendering output. (Nobody reads that fast in real-time.) app.max_render_postpone_time = .1 # Second. # Hide message when a key has been pressed. def key_pressed(_): self.message = None app.key_processor.before_key_press += key_pressed # The following code needs to run with the application active. # Especially, `create_window` needs to know what the current # application is, in order to focus the new pane. with set_app(app): # Redraw all CLIs. (Adding a new client could mean that the others # change size, so everything has to be redrawn.) pymux.invalidate() pymux.startup() return app
[ "def", "_create_app", "(", "self", ")", ":", "pymux", "=", "self", ".", "pymux", "def", "on_focus_changed", "(", ")", ":", "\"\"\" When the focus changes to a read/write buffer, make sure to go\n to insert mode. This happens when the ViState was set to NAVIGATION\n ...
Create `Application` instance for this .
[ "Create", "Application", "instance", "for", "this", "." ]
3f66e62b9de4b2251c7f9afad6c516dc5a30ec67
https://github.com/prompt-toolkit/pymux/blob/3f66e62b9de4b2251c7f9afad6c516dc5a30ec67/pymux/main.py#L129-L199
233,064
prompt-toolkit/pymux
pymux/main.py
ClientState.sync_focus
def sync_focus(self, *_): """ Focus the focused window from the pymux arrangement. """ # Pop-up displayed? if self.display_popup: self.app.layout.focus(self.layout_manager.popup_dialog) return # Confirm. if self.confirm_text: return # Custom prompt. if self.prompt_command: return # Focus prompt # Command mode. if self.command_mode: return # Focus command # No windows left, return. We will quit soon. if not self.pymux.arrangement.windows: return pane = self.pymux.arrangement.get_active_pane() self.app.layout.focus(pane.terminal)
python
def sync_focus(self, *_): # Pop-up displayed? if self.display_popup: self.app.layout.focus(self.layout_manager.popup_dialog) return # Confirm. if self.confirm_text: return # Custom prompt. if self.prompt_command: return # Focus prompt # Command mode. if self.command_mode: return # Focus command # No windows left, return. We will quit soon. if not self.pymux.arrangement.windows: return pane = self.pymux.arrangement.get_active_pane() self.app.layout.focus(pane.terminal)
[ "def", "sync_focus", "(", "self", ",", "*", "_", ")", ":", "# Pop-up displayed?", "if", "self", ".", "display_popup", ":", "self", ".", "app", ".", "layout", ".", "focus", "(", "self", ".", "layout_manager", ".", "popup_dialog", ")", "return", "# Confirm."...
Focus the focused window from the pymux arrangement.
[ "Focus", "the", "focused", "window", "from", "the", "pymux", "arrangement", "." ]
3f66e62b9de4b2251c7f9afad6c516dc5a30ec67
https://github.com/prompt-toolkit/pymux/blob/3f66e62b9de4b2251c7f9afad6c516dc5a30ec67/pymux/main.py#L201-L227
233,065
prompt-toolkit/pymux
pymux/main.py
Pymux._start_auto_refresh_thread
def _start_auto_refresh_thread(self): """ Start the background thread that auto refreshes all clients according to `self.status_interval`. """ def run(): while True: time.sleep(self.status_interval) self.invalidate() t = threading.Thread(target=run) t.daemon = True t.start()
python
def _start_auto_refresh_thread(self): def run(): while True: time.sleep(self.status_interval) self.invalidate() t = threading.Thread(target=run) t.daemon = True t.start()
[ "def", "_start_auto_refresh_thread", "(", "self", ")", ":", "def", "run", "(", ")", ":", "while", "True", ":", "time", ".", "sleep", "(", "self", ".", "status_interval", ")", "self", ".", "invalidate", "(", ")", "t", "=", "threading", ".", "Thread", "(...
Start the background thread that auto refreshes all clients according to `self.status_interval`.
[ "Start", "the", "background", "thread", "that", "auto", "refreshes", "all", "clients", "according", "to", "self", ".", "status_interval", "." ]
3f66e62b9de4b2251c7f9afad6c516dc5a30ec67
https://github.com/prompt-toolkit/pymux/blob/3f66e62b9de4b2251c7f9afad6c516dc5a30ec67/pymux/main.py#L301-L313
233,066
prompt-toolkit/pymux
pymux/main.py
Pymux.get_client_state
def get_client_state(self): " Return the active ClientState instance. " app = get_app() for client_state in self._client_states.values(): if client_state.app == app: return client_state raise ValueError('Client state for app %r not found' % (app, ))
python
def get_client_state(self): " Return the active ClientState instance. " app = get_app() for client_state in self._client_states.values(): if client_state.app == app: return client_state raise ValueError('Client state for app %r not found' % (app, ))
[ "def", "get_client_state", "(", "self", ")", ":", "app", "=", "get_app", "(", ")", "for", "client_state", "in", "self", ".", "_client_states", ".", "values", "(", ")", ":", "if", "client_state", ".", "app", "==", "app", ":", "return", "client_state", "ra...
Return the active ClientState instance.
[ "Return", "the", "active", "ClientState", "instance", "." ]
3f66e62b9de4b2251c7f9afad6c516dc5a30ec67
https://github.com/prompt-toolkit/pymux/blob/3f66e62b9de4b2251c7f9afad6c516dc5a30ec67/pymux/main.py#L319-L326
233,067
prompt-toolkit/pymux
pymux/main.py
Pymux.get_connection
def get_connection(self): " Return the active Connection instance. " app = get_app() for connection, client_state in self._client_states.items(): if client_state.app == app: return connection raise ValueError('Connection for app %r not found' % (app, ))
python
def get_connection(self): " Return the active Connection instance. " app = get_app() for connection, client_state in self._client_states.items(): if client_state.app == app: return connection raise ValueError('Connection for app %r not found' % (app, ))
[ "def", "get_connection", "(", "self", ")", ":", "app", "=", "get_app", "(", ")", "for", "connection", ",", "client_state", "in", "self", ".", "_client_states", ".", "items", "(", ")", ":", "if", "client_state", ".", "app", "==", "app", ":", "return", "...
Return the active Connection instance.
[ "Return", "the", "active", "Connection", "instance", "." ]
3f66e62b9de4b2251c7f9afad6c516dc5a30ec67
https://github.com/prompt-toolkit/pymux/blob/3f66e62b9de4b2251c7f9afad6c516dc5a30ec67/pymux/main.py#L328-L335
233,068
prompt-toolkit/pymux
pymux/main.py
Pymux.get_title
def get_title(self): """ The title to be displayed in the titlebar of the terminal. """ w = self.arrangement.get_active_window() if w and w.active_process: title = w.active_process.screen.title else: title = '' if title: return '%s - Pymux' % (title, ) else: return 'Pymux'
python
def get_title(self): w = self.arrangement.get_active_window() if w and w.active_process: title = w.active_process.screen.title else: title = '' if title: return '%s - Pymux' % (title, ) else: return 'Pymux'
[ "def", "get_title", "(", "self", ")", ":", "w", "=", "self", ".", "arrangement", ".", "get_active_window", "(", ")", "if", "w", "and", "w", ".", "active_process", ":", "title", "=", "w", ".", "active_process", ".", "screen", ".", "title", "else", ":", ...
The title to be displayed in the titlebar of the terminal.
[ "The", "title", "to", "be", "displayed", "in", "the", "titlebar", "of", "the", "terminal", "." ]
3f66e62b9de4b2251c7f9afad6c516dc5a30ec67
https://github.com/prompt-toolkit/pymux/blob/3f66e62b9de4b2251c7f9afad6c516dc5a30ec67/pymux/main.py#L354-L368
233,069
prompt-toolkit/pymux
pymux/main.py
Pymux.get_window_size
def get_window_size(self): """ Get the size to be used for the DynamicBody. This will be the smallest size of all clients. """ def active_window_for_app(app): with set_app(app): return self.arrangement.get_active_window() active_window = self.arrangement.get_active_window() # Get sizes for connections watching the same window. apps = [client_state.app for client_state in self._client_states.values() if active_window_for_app(client_state.app) == active_window] sizes = [app.output.get_size() for app in apps] rows = [s.rows for s in sizes] columns = [s.columns for s in sizes] if rows and columns: return Size(rows=min(rows) - (1 if self.enable_status else 0), columns=min(columns)) else: return Size(rows=20, columns=80)
python
def get_window_size(self): def active_window_for_app(app): with set_app(app): return self.arrangement.get_active_window() active_window = self.arrangement.get_active_window() # Get sizes for connections watching the same window. apps = [client_state.app for client_state in self._client_states.values() if active_window_for_app(client_state.app) == active_window] sizes = [app.output.get_size() for app in apps] rows = [s.rows for s in sizes] columns = [s.columns for s in sizes] if rows and columns: return Size(rows=min(rows) - (1 if self.enable_status else 0), columns=min(columns)) else: return Size(rows=20, columns=80)
[ "def", "get_window_size", "(", "self", ")", ":", "def", "active_window_for_app", "(", "app", ")", ":", "with", "set_app", "(", "app", ")", ":", "return", "self", ".", "arrangement", ".", "get_active_window", "(", ")", "active_window", "=", "self", ".", "ar...
Get the size to be used for the DynamicBody. This will be the smallest size of all clients.
[ "Get", "the", "size", "to", "be", "used", "for", "the", "DynamicBody", ".", "This", "will", "be", "the", "smallest", "size", "of", "all", "clients", "." ]
3f66e62b9de4b2251c7f9afad6c516dc5a30ec67
https://github.com/prompt-toolkit/pymux/blob/3f66e62b9de4b2251c7f9afad6c516dc5a30ec67/pymux/main.py#L370-L393
233,070
prompt-toolkit/pymux
pymux/main.py
Pymux.invalidate
def invalidate(self): " Invalidate the UI for all clients. " logger.info('Invalidating %s applications', len(self.apps)) for app in self.apps: app.invalidate()
python
def invalidate(self): " Invalidate the UI for all clients. " logger.info('Invalidating %s applications', len(self.apps)) for app in self.apps: app.invalidate()
[ "def", "invalidate", "(", "self", ")", ":", "logger", ".", "info", "(", "'Invalidating %s applications'", ",", "len", "(", "self", ".", "apps", ")", ")", "for", "app", "in", "self", ".", "apps", ":", "app", ".", "invalidate", "(", ")" ]
Invalidate the UI for all clients.
[ "Invalidate", "the", "UI", "for", "all", "clients", "." ]
3f66e62b9de4b2251c7f9afad6c516dc5a30ec67
https://github.com/prompt-toolkit/pymux/blob/3f66e62b9de4b2251c7f9afad6c516dc5a30ec67/pymux/main.py#L475-L480
233,071
prompt-toolkit/pymux
pymux/main.py
Pymux.kill_pane
def kill_pane(self, pane): """ Kill the given pane, and remove it from the arrangement. """ assert isinstance(pane, Pane) # Send kill signal. if not pane.process.is_terminated: pane.process.kill() # Remove from layout. self.arrangement.remove_pane(pane)
python
def kill_pane(self, pane): assert isinstance(pane, Pane) # Send kill signal. if not pane.process.is_terminated: pane.process.kill() # Remove from layout. self.arrangement.remove_pane(pane)
[ "def", "kill_pane", "(", "self", ",", "pane", ")", ":", "assert", "isinstance", "(", "pane", ",", "Pane", ")", "# Send kill signal.", "if", "not", "pane", ".", "process", ".", "is_terminated", ":", "pane", ".", "process", ".", "kill", "(", ")", "# Remove...
Kill the given pane, and remove it from the arrangement.
[ "Kill", "the", "given", "pane", "and", "remove", "it", "from", "the", "arrangement", "." ]
3f66e62b9de4b2251c7f9afad6c516dc5a30ec67
https://github.com/prompt-toolkit/pymux/blob/3f66e62b9de4b2251c7f9afad6c516dc5a30ec67/pymux/main.py#L514-L525
233,072
prompt-toolkit/pymux
pymux/main.py
Pymux.detach_client
def detach_client(self, app): """ Detach the client that belongs to this CLI. """ connection = self.get_connection() if connection: connection.detach_and_close() # Redraw all clients -> Maybe their size has to change. self.invalidate()
python
def detach_client(self, app): connection = self.get_connection() if connection: connection.detach_and_close() # Redraw all clients -> Maybe their size has to change. self.invalidate()
[ "def", "detach_client", "(", "self", ",", "app", ")", ":", "connection", "=", "self", ".", "get_connection", "(", ")", "if", "connection", ":", "connection", ".", "detach_and_close", "(", ")", "# Redraw all clients -> Maybe their size has to change.", "self", ".", ...
Detach the client that belongs to this CLI.
[ "Detach", "the", "client", "that", "belongs", "to", "this", "CLI", "." ]
3f66e62b9de4b2251c7f9afad6c516dc5a30ec67
https://github.com/prompt-toolkit/pymux/blob/3f66e62b9de4b2251c7f9afad6c516dc5a30ec67/pymux/main.py#L556-L565
233,073
prompt-toolkit/pymux
pymux/main.py
Pymux.listen_on_socket
def listen_on_socket(self, socket_name=None): """ Listen for clients on a Unix socket. Returns the socket name. """ def connection_cb(pipe_connection): # We have to create a new `context`, because this will be the scope for # a new prompt_toolkit.Application to become active. with context(): connection = ServerConnection(self, pipe_connection) self.connections.append(connection) self.socket_name = bind_and_listen_on_socket(socket_name, connection_cb) # Set session_name according to socket name. # if '.' in self.socket_name: # self.session_name = self.socket_name.rpartition('.')[-1] logger.info('Listening on %r.' % self.socket_name) return self.socket_name
python
def listen_on_socket(self, socket_name=None): def connection_cb(pipe_connection): # We have to create a new `context`, because this will be the scope for # a new prompt_toolkit.Application to become active. with context(): connection = ServerConnection(self, pipe_connection) self.connections.append(connection) self.socket_name = bind_and_listen_on_socket(socket_name, connection_cb) # Set session_name according to socket name. # if '.' in self.socket_name: # self.session_name = self.socket_name.rpartition('.')[-1] logger.info('Listening on %r.' % self.socket_name) return self.socket_name
[ "def", "listen_on_socket", "(", "self", ",", "socket_name", "=", "None", ")", ":", "def", "connection_cb", "(", "pipe_connection", ")", ":", "# We have to create a new `context`, because this will be the scope for", "# a new prompt_toolkit.Application to become active.", "with", ...
Listen for clients on a Unix socket. Returns the socket name.
[ "Listen", "for", "clients", "on", "a", "Unix", "socket", ".", "Returns", "the", "socket", "name", "." ]
3f66e62b9de4b2251c7f9afad6c516dc5a30ec67
https://github.com/prompt-toolkit/pymux/blob/3f66e62b9de4b2251c7f9afad6c516dc5a30ec67/pymux/main.py#L567-L587
233,074
prompt-toolkit/pymux
pymux/pipes/posix.py
_bind_posix_socket
def _bind_posix_socket(socket_name=None): """ Find a socket to listen on and return it. Returns (socket_name, sock_obj) """ assert socket_name is None or isinstance(socket_name, six.text_type) s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) if socket_name: s.bind(socket_name) return socket_name, s else: i = 0 while True: try: socket_name = '%s/pymux.sock.%s.%i' % ( tempfile.gettempdir(), getpass.getuser(), i) s.bind(socket_name) return socket_name, s except (OSError, socket.error): i += 1 # When 100 times failed, cancel server if i == 100: logger.warning('100 times failed to listen on posix socket. ' 'Please clean up old sockets.') raise
python
def _bind_posix_socket(socket_name=None): assert socket_name is None or isinstance(socket_name, six.text_type) s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) if socket_name: s.bind(socket_name) return socket_name, s else: i = 0 while True: try: socket_name = '%s/pymux.sock.%s.%i' % ( tempfile.gettempdir(), getpass.getuser(), i) s.bind(socket_name) return socket_name, s except (OSError, socket.error): i += 1 # When 100 times failed, cancel server if i == 100: logger.warning('100 times failed to listen on posix socket. ' 'Please clean up old sockets.') raise
[ "def", "_bind_posix_socket", "(", "socket_name", "=", "None", ")", ":", "assert", "socket_name", "is", "None", "or", "isinstance", "(", "socket_name", ",", "six", ".", "text_type", ")", "s", "=", "socket", ".", "socket", "(", "socket", ".", "AF_UNIX", ",",...
Find a socket to listen on and return it. Returns (socket_name, sock_obj)
[ "Find", "a", "socket", "to", "listen", "on", "and", "return", "it", "." ]
3f66e62b9de4b2251c7f9afad6c516dc5a30ec67
https://github.com/prompt-toolkit/pymux/blob/3f66e62b9de4b2251c7f9afad6c516dc5a30ec67/pymux/pipes/posix.py#L54-L82
233,075
prompt-toolkit/pymux
pymux/pipes/posix.py
PosixSocketConnection.write
def write(self, message): """ Coroutine that writes the next packet. """ try: self.socket.send(message.encode('utf-8') + b'\0') except socket.error: if not self._closed: raise BrokenPipeError return Future.succeed(None)
python
def write(self, message): try: self.socket.send(message.encode('utf-8') + b'\0') except socket.error: if not self._closed: raise BrokenPipeError return Future.succeed(None)
[ "def", "write", "(", "self", ",", "message", ")", ":", "try", ":", "self", ".", "socket", ".", "send", "(", "message", ".", "encode", "(", "'utf-8'", ")", "+", "b'\\0'", ")", "except", "socket", ".", "error", ":", "if", "not", "self", ".", "_closed...
Coroutine that writes the next packet.
[ "Coroutine", "that", "writes", "the", "next", "packet", "." ]
3f66e62b9de4b2251c7f9afad6c516dc5a30ec67
https://github.com/prompt-toolkit/pymux/blob/3f66e62b9de4b2251c7f9afad6c516dc5a30ec67/pymux/pipes/posix.py#L112-L122
233,076
prompt-toolkit/pymux
pymux/key_bindings.py
PymuxKeyBindings._load_prefix_binding
def _load_prefix_binding(self): """ Load the prefix key binding. """ pymux = self.pymux # Remove previous binding. if self._prefix_binding: self.custom_key_bindings.remove_binding(self._prefix_binding) # Create new Python binding. @self.custom_key_bindings.add(*self._prefix, filter= ~(HasPrefix(pymux) | has_focus(COMMAND) | has_focus(PROMPT) | WaitsForConfirmation(pymux))) def enter_prefix_handler(event): " Enter prefix mode. " pymux.get_client_state().has_prefix = True self._prefix_binding = enter_prefix_handler
python
def _load_prefix_binding(self): pymux = self.pymux # Remove previous binding. if self._prefix_binding: self.custom_key_bindings.remove_binding(self._prefix_binding) # Create new Python binding. @self.custom_key_bindings.add(*self._prefix, filter= ~(HasPrefix(pymux) | has_focus(COMMAND) | has_focus(PROMPT) | WaitsForConfirmation(pymux))) def enter_prefix_handler(event): " Enter prefix mode. " pymux.get_client_state().has_prefix = True self._prefix_binding = enter_prefix_handler
[ "def", "_load_prefix_binding", "(", "self", ")", ":", "pymux", "=", "self", ".", "pymux", "# Remove previous binding.", "if", "self", ".", "_prefix_binding", ":", "self", ".", "custom_key_bindings", ".", "remove_binding", "(", "self", ".", "_prefix_binding", ")", ...
Load the prefix key binding.
[ "Load", "the", "prefix", "key", "binding", "." ]
3f66e62b9de4b2251c7f9afad6c516dc5a30ec67
https://github.com/prompt-toolkit/pymux/blob/3f66e62b9de4b2251c7f9afad6c516dc5a30ec67/pymux/key_bindings.py#L50-L68
233,077
prompt-toolkit/pymux
pymux/key_bindings.py
PymuxKeyBindings.prefix
def prefix(self, keys): """ Set a new prefix key. """ assert isinstance(keys, tuple) self._prefix = keys self._load_prefix_binding()
python
def prefix(self, keys): assert isinstance(keys, tuple) self._prefix = keys self._load_prefix_binding()
[ "def", "prefix", "(", "self", ",", "keys", ")", ":", "assert", "isinstance", "(", "keys", ",", "tuple", ")", "self", ".", "_prefix", "=", "keys", "self", ".", "_load_prefix_binding", "(", ")" ]
Set a new prefix key.
[ "Set", "a", "new", "prefix", "key", "." ]
3f66e62b9de4b2251c7f9afad6c516dc5a30ec67
https://github.com/prompt-toolkit/pymux/blob/3f66e62b9de4b2251c7f9afad6c516dc5a30ec67/pymux/key_bindings.py#L76-L83
233,078
prompt-toolkit/pymux
pymux/key_bindings.py
PymuxKeyBindings.remove_custom_binding
def remove_custom_binding(self, key_name, needs_prefix=False): """ Remove custom key binding for a key. :param key_name: Pymux key name, for instance "C-A". """ k = (needs_prefix, key_name) if k in self.custom_bindings: self.custom_key_bindings.remove(self.custom_bindings[k].handler) del self.custom_bindings[k]
python
def remove_custom_binding(self, key_name, needs_prefix=False): k = (needs_prefix, key_name) if k in self.custom_bindings: self.custom_key_bindings.remove(self.custom_bindings[k].handler) del self.custom_bindings[k]
[ "def", "remove_custom_binding", "(", "self", ",", "key_name", ",", "needs_prefix", "=", "False", ")", ":", "k", "=", "(", "needs_prefix", ",", "key_name", ")", "if", "k", "in", "self", ".", "custom_bindings", ":", "self", ".", "custom_key_bindings", ".", "...
Remove custom key binding for a key. :param key_name: Pymux key name, for instance "C-A".
[ "Remove", "custom", "key", "binding", "for", "a", "key", "." ]
3f66e62b9de4b2251c7f9afad6c516dc5a30ec67
https://github.com/prompt-toolkit/pymux/blob/3f66e62b9de4b2251c7f9afad6c516dc5a30ec67/pymux/key_bindings.py#L236-L246
233,079
prompt-toolkit/pymux
pymux/pipes/win32_server.py
PipeInstance._handle_client
def _handle_client(self): """ Coroutine that connects to a single client and handles that. """ while True: try: # Wait for connection. logger.info('Waiting for connection in pipe instance.') yield From(self._connect_client()) logger.info('Connected in pipe instance') conn = Win32PipeConnection(self) self.pipe_connection_cb(conn) yield From(conn.done_f) logger.info('Pipe instance done.') finally: # Disconnect and reconnect. logger.info('Disconnecting pipe instance.') windll.kernel32.DisconnectNamedPipe(self.pipe_handle)
python
def _handle_client(self): while True: try: # Wait for connection. logger.info('Waiting for connection in pipe instance.') yield From(self._connect_client()) logger.info('Connected in pipe instance') conn = Win32PipeConnection(self) self.pipe_connection_cb(conn) yield From(conn.done_f) logger.info('Pipe instance done.') finally: # Disconnect and reconnect. logger.info('Disconnecting pipe instance.') windll.kernel32.DisconnectNamedPipe(self.pipe_handle)
[ "def", "_handle_client", "(", "self", ")", ":", "while", "True", ":", "try", ":", "# Wait for connection.", "logger", ".", "info", "(", "'Waiting for connection in pipe instance.'", ")", "yield", "From", "(", "self", ".", "_connect_client", "(", ")", ")", "logge...
Coroutine that connects to a single client and handles that.
[ "Coroutine", "that", "connects", "to", "a", "single", "client", "and", "handles", "that", "." ]
3f66e62b9de4b2251c7f9afad6c516dc5a30ec67
https://github.com/prompt-toolkit/pymux/blob/3f66e62b9de4b2251c7f9afad6c516dc5a30ec67/pymux/pipes/win32_server.py#L125-L145
233,080
prompt-toolkit/pymux
pymux/pipes/win32_server.py
PipeInstance._connect_client
def _connect_client(self): """ Wait for a client to connect to this pipe. """ overlapped = OVERLAPPED() overlapped.hEvent = create_event() while True: success = windll.kernel32.ConnectNamedPipe( self.pipe_handle, byref(overlapped)) if success: return last_error = windll.kernel32.GetLastError() if last_error == ERROR_IO_PENDING: yield From(wait_for_event(overlapped.hEvent)) # XXX: Call GetOverlappedResult. return # Connection succeeded. else: raise Exception('connect failed with error code' + str(last_error))
python
def _connect_client(self): overlapped = OVERLAPPED() overlapped.hEvent = create_event() while True: success = windll.kernel32.ConnectNamedPipe( self.pipe_handle, byref(overlapped)) if success: return last_error = windll.kernel32.GetLastError() if last_error == ERROR_IO_PENDING: yield From(wait_for_event(overlapped.hEvent)) # XXX: Call GetOverlappedResult. return # Connection succeeded. else: raise Exception('connect failed with error code' + str(last_error))
[ "def", "_connect_client", "(", "self", ")", ":", "overlapped", "=", "OVERLAPPED", "(", ")", "overlapped", ".", "hEvent", "=", "create_event", "(", ")", "while", "True", ":", "success", "=", "windll", ".", "kernel32", ".", "ConnectNamedPipe", "(", "self", "...
Wait for a client to connect to this pipe.
[ "Wait", "for", "a", "client", "to", "connect", "to", "this", "pipe", "." ]
3f66e62b9de4b2251c7f9afad6c516dc5a30ec67
https://github.com/prompt-toolkit/pymux/blob/3f66e62b9de4b2251c7f9afad6c516dc5a30ec67/pymux/pipes/win32_server.py#L147-L170
233,081
prompt-toolkit/pymux
pymux/key_mappings.py
pymux_key_to_prompt_toolkit_key_sequence
def pymux_key_to_prompt_toolkit_key_sequence(key): """ Turn a pymux description of a key. E.g. "C-a" or "M-x" into a prompt-toolkit key sequence. Raises `ValueError` if the key is not known. """ # Make the c- and m- prefixes case insensitive. if key.lower().startswith('m-c-'): key = 'M-C-' + key[4:] elif key.lower().startswith('c-'): key = 'C-' + key[2:] elif key.lower().startswith('m-'): key = 'M-' + key[2:] # Lookup key. try: return PYMUX_TO_PROMPT_TOOLKIT_KEYS[key] except KeyError: if len(key) == 1: return (key, ) else: raise ValueError('Unknown key: %r' % (key, ))
python
def pymux_key_to_prompt_toolkit_key_sequence(key): # Make the c- and m- prefixes case insensitive. if key.lower().startswith('m-c-'): key = 'M-C-' + key[4:] elif key.lower().startswith('c-'): key = 'C-' + key[2:] elif key.lower().startswith('m-'): key = 'M-' + key[2:] # Lookup key. try: return PYMUX_TO_PROMPT_TOOLKIT_KEYS[key] except KeyError: if len(key) == 1: return (key, ) else: raise ValueError('Unknown key: %r' % (key, ))
[ "def", "pymux_key_to_prompt_toolkit_key_sequence", "(", "key", ")", ":", "# Make the c- and m- prefixes case insensitive.", "if", "key", ".", "lower", "(", ")", ".", "startswith", "(", "'m-c-'", ")", ":", "key", "=", "'M-C-'", "+", "key", "[", "4", ":", "]", "...
Turn a pymux description of a key. E.g. "C-a" or "M-x" into a prompt-toolkit key sequence. Raises `ValueError` if the key is not known.
[ "Turn", "a", "pymux", "description", "of", "a", "key", ".", "E", ".", "g", ".", "C", "-", "a", "or", "M", "-", "x", "into", "a", "prompt", "-", "toolkit", "key", "sequence", "." ]
3f66e62b9de4b2251c7f9afad6c516dc5a30ec67
https://github.com/prompt-toolkit/pymux/blob/3f66e62b9de4b2251c7f9afad6c516dc5a30ec67/pymux/key_mappings.py#L16-L38
233,082
prompt-toolkit/pymux
pymux/options.py
PositiveIntOption.set_value
def set_value(self, pymux, value): """ Take a string, and return an integer. Raise SetOptionError when the given text does not parse to a positive integer. """ try: value = int(value) if value < 0: raise ValueError except ValueError: raise SetOptionError('Expecting an integer.') else: setattr(pymux, self.attribute_name, value)
python
def set_value(self, pymux, value): try: value = int(value) if value < 0: raise ValueError except ValueError: raise SetOptionError('Expecting an integer.') else: setattr(pymux, self.attribute_name, value)
[ "def", "set_value", "(", "self", ",", "pymux", ",", "value", ")", ":", "try", ":", "value", "=", "int", "(", "value", ")", "if", "value", "<", "0", ":", "raise", "ValueError", "except", "ValueError", ":", "raise", "SetOptionError", "(", "'Expecting an in...
Take a string, and return an integer. Raise SetOptionError when the given text does not parse to a positive integer.
[ "Take", "a", "string", "and", "return", "an", "integer", ".", "Raise", "SetOptionError", "when", "the", "given", "text", "does", "not", "parse", "to", "a", "positive", "integer", "." ]
3f66e62b9de4b2251c7f9afad6c516dc5a30ec67
https://github.com/prompt-toolkit/pymux/blob/3f66e62b9de4b2251c7f9afad6c516dc5a30ec67/pymux/options.py#L100-L112
233,083
prompt-toolkit/pymux
pymux/commands/commands.py
handle_command
def handle_command(pymux, input_string): """ Handle command. """ assert isinstance(input_string, six.text_type) input_string = input_string.strip() logger.info('handle command: %s %s.', input_string, type(input_string)) if input_string and not input_string.startswith('#'): # Ignore comments. try: if six.PY2: # In Python2.6, shlex doesn't work with unicode input at all. # In Python2.7, shlex tries to encode using ASCII. parts = shlex.split(input_string.encode('utf-8')) parts = [p.decode('utf-8') for p in parts] else: parts = shlex.split(input_string) except ValueError as e: # E.g. missing closing quote. pymux.show_message('Invalid command %s: %s' % (input_string, e)) else: call_command_handler(parts[0], pymux, parts[1:])
python
def handle_command(pymux, input_string): assert isinstance(input_string, six.text_type) input_string = input_string.strip() logger.info('handle command: %s %s.', input_string, type(input_string)) if input_string and not input_string.startswith('#'): # Ignore comments. try: if six.PY2: # In Python2.6, shlex doesn't work with unicode input at all. # In Python2.7, shlex tries to encode using ASCII. parts = shlex.split(input_string.encode('utf-8')) parts = [p.decode('utf-8') for p in parts] else: parts = shlex.split(input_string) except ValueError as e: # E.g. missing closing quote. pymux.show_message('Invalid command %s: %s' % (input_string, e)) else: call_command_handler(parts[0], pymux, parts[1:])
[ "def", "handle_command", "(", "pymux", ",", "input_string", ")", ":", "assert", "isinstance", "(", "input_string", ",", "six", ".", "text_type", ")", "input_string", "=", "input_string", ".", "strip", "(", ")", "logger", ".", "info", "(", "'handle command: %s ...
Handle command.
[ "Handle", "command", "." ]
3f66e62b9de4b2251c7f9afad6c516dc5a30ec67
https://github.com/prompt-toolkit/pymux/blob/3f66e62b9de4b2251c7f9afad6c516dc5a30ec67/pymux/commands/commands.py#L50-L72
233,084
prompt-toolkit/pymux
pymux/commands/commands.py
cmd
def cmd(name, options=''): """ Decorator for all commands. Commands will receive (pymux, variables) as input. Commands can raise CommandException. """ # Validate options. if options: try: docopt.docopt('Usage:\n %s %s' % (name, options, ), []) except SystemExit: pass def decorator(func): def command_wrapper(pymux, arguments): # Hack to make the 'bind-key' option work. # (bind-key expects a variable number of arguments.) if name == 'bind-key' and '--' not in arguments: # Insert a double dash after the first non-option. for i, p in enumerate(arguments): if not p.startswith('-'): arguments.insert(i + 1, '--') break # Parse options. try: # Python 2 workaround: pass bytes to docopt. # From the following, only the bytes version returns the right # output in Python 2: # docopt.docopt('Usage:\n app <params>...', [b'a', b'b']) # docopt.docopt('Usage:\n app <params>...', [u'a', u'b']) # https://github.com/docopt/docopt/issues/30 # (Not sure how reliable this is...) if six.PY2: arguments = [a.encode('utf-8') for a in arguments] received_options = docopt.docopt( 'Usage:\n %s %s' % (name, options), arguments, help=False) # Don't interpret the '-h' option as help. # Make sure that all the received options from docopt are # unicode objects. (Docopt returns 'str' for Python2.) for k, v in received_options.items(): if isinstance(v, six.binary_type): received_options[k] = v.decode('utf-8') except SystemExit: raise CommandException('Usage: %s %s' % (name, options)) # Call handler. func(pymux, received_options) # Invalidate all clients, not just the current CLI. pymux.invalidate() COMMANDS_TO_HANDLERS[name] = command_wrapper COMMANDS_TO_HELP[name] = options # Get list of option flags. flags = re.findall(r'-[a-zA-Z0-9]\b', options) COMMANDS_TO_OPTION_FLAGS[name] = flags return func return decorator
python
def cmd(name, options=''): # Validate options. if options: try: docopt.docopt('Usage:\n %s %s' % (name, options, ), []) except SystemExit: pass def decorator(func): def command_wrapper(pymux, arguments): # Hack to make the 'bind-key' option work. # (bind-key expects a variable number of arguments.) if name == 'bind-key' and '--' not in arguments: # Insert a double dash after the first non-option. for i, p in enumerate(arguments): if not p.startswith('-'): arguments.insert(i + 1, '--') break # Parse options. try: # Python 2 workaround: pass bytes to docopt. # From the following, only the bytes version returns the right # output in Python 2: # docopt.docopt('Usage:\n app <params>...', [b'a', b'b']) # docopt.docopt('Usage:\n app <params>...', [u'a', u'b']) # https://github.com/docopt/docopt/issues/30 # (Not sure how reliable this is...) if six.PY2: arguments = [a.encode('utf-8') for a in arguments] received_options = docopt.docopt( 'Usage:\n %s %s' % (name, options), arguments, help=False) # Don't interpret the '-h' option as help. # Make sure that all the received options from docopt are # unicode objects. (Docopt returns 'str' for Python2.) for k, v in received_options.items(): if isinstance(v, six.binary_type): received_options[k] = v.decode('utf-8') except SystemExit: raise CommandException('Usage: %s %s' % (name, options)) # Call handler. func(pymux, received_options) # Invalidate all clients, not just the current CLI. pymux.invalidate() COMMANDS_TO_HANDLERS[name] = command_wrapper COMMANDS_TO_HELP[name] = options # Get list of option flags. flags = re.findall(r'-[a-zA-Z0-9]\b', options) COMMANDS_TO_OPTION_FLAGS[name] = flags return func return decorator
[ "def", "cmd", "(", "name", ",", "options", "=", "''", ")", ":", "# Validate options.", "if", "options", ":", "try", ":", "docopt", ".", "docopt", "(", "'Usage:\\n %s %s'", "%", "(", "name", ",", "options", ",", ")", ",", "[", "]", ")", "except", "...
Decorator for all commands. Commands will receive (pymux, variables) as input. Commands can raise CommandException.
[ "Decorator", "for", "all", "commands", "." ]
3f66e62b9de4b2251c7f9afad6c516dc5a30ec67
https://github.com/prompt-toolkit/pymux/blob/3f66e62b9de4b2251c7f9afad6c516dc5a30ec67/pymux/commands/commands.py#L97-L161
233,085
prompt-toolkit/pymux
pymux/commands/commands.py
kill_window
def kill_window(pymux, variables): " Kill all panes in the current window. " for pane in pymux.arrangement.get_active_window().panes: pymux.kill_pane(pane)
python
def kill_window(pymux, variables): " Kill all panes in the current window. " for pane in pymux.arrangement.get_active_window().panes: pymux.kill_pane(pane)
[ "def", "kill_window", "(", "pymux", ",", "variables", ")", ":", "for", "pane", "in", "pymux", ".", "arrangement", ".", "get_active_window", "(", ")", ".", "panes", ":", "pymux", ".", "kill_pane", "(", "pane", ")" ]
Kill all panes in the current window.
[ "Kill", "all", "panes", "in", "the", "current", "window", "." ]
3f66e62b9de4b2251c7f9afad6c516dc5a30ec67
https://github.com/prompt-toolkit/pymux/blob/3f66e62b9de4b2251c7f9afad6c516dc5a30ec67/pymux/commands/commands.py#L275-L278
233,086
prompt-toolkit/pymux
pymux/commands/commands.py
next_layout
def next_layout(pymux, variables): " Select next layout. " pane = pymux.arrangement.get_active_window() if pane: pane.select_next_layout()
python
def next_layout(pymux, variables): " Select next layout. " pane = pymux.arrangement.get_active_window() if pane: pane.select_next_layout()
[ "def", "next_layout", "(", "pymux", ",", "variables", ")", ":", "pane", "=", "pymux", ".", "arrangement", ".", "get_active_window", "(", ")", "if", "pane", ":", "pane", ".", "select_next_layout", "(", ")" ]
Select next layout.
[ "Select", "next", "layout", "." ]
3f66e62b9de4b2251c7f9afad6c516dc5a30ec67
https://github.com/prompt-toolkit/pymux/blob/3f66e62b9de4b2251c7f9afad6c516dc5a30ec67/pymux/commands/commands.py#L306-L310
233,087
prompt-toolkit/pymux
pymux/commands/commands.py
previous_layout
def previous_layout(pymux, variables): " Select previous layout. " pane = pymux.arrangement.get_active_window() if pane: pane.select_previous_layout()
python
def previous_layout(pymux, variables): " Select previous layout. " pane = pymux.arrangement.get_active_window() if pane: pane.select_previous_layout()
[ "def", "previous_layout", "(", "pymux", ",", "variables", ")", ":", "pane", "=", "pymux", ".", "arrangement", ".", "get_active_window", "(", ")", "if", "pane", ":", "pane", ".", "select_previous_layout", "(", ")" ]
Select previous layout.
[ "Select", "previous", "layout", "." ]
3f66e62b9de4b2251c7f9afad6c516dc5a30ec67
https://github.com/prompt-toolkit/pymux/blob/3f66e62b9de4b2251c7f9afad6c516dc5a30ec67/pymux/commands/commands.py#L314-L318
233,088
prompt-toolkit/pymux
pymux/commands/commands.py
_
def _(pymux, variables): " Go to previous active window. " w = pymux.arrangement.get_previous_active_window() if w: pymux.arrangement.set_active_window(w)
python
def _(pymux, variables): " Go to previous active window. " w = pymux.arrangement.get_previous_active_window() if w: pymux.arrangement.set_active_window(w)
[ "def", "_", "(", "pymux", ",", "variables", ")", ":", "w", "=", "pymux", ".", "arrangement", ".", "get_previous_active_window", "(", ")", "if", "w", ":", "pymux", ".", "arrangement", ".", "set_active_window", "(", "w", ")" ]
Go to previous active window.
[ "Go", "to", "previous", "active", "window", "." ]
3f66e62b9de4b2251c7f9afad6c516dc5a30ec67
https://github.com/prompt-toolkit/pymux/blob/3f66e62b9de4b2251c7f9afad6c516dc5a30ec67/pymux/commands/commands.py#L337-L342
233,089
prompt-toolkit/pymux
pymux/commands/commands.py
split_window
def split_window(pymux, variables): """ Split horizontally or vertically. """ executable = variables['<executable>'] start_directory = variables['<start-directory>'] # The tmux definition of horizontal is the opposite of prompt_toolkit. pymux.add_process(executable, vsplit=variables['-h'], start_directory=start_directory)
python
def split_window(pymux, variables): executable = variables['<executable>'] start_directory = variables['<start-directory>'] # The tmux definition of horizontal is the opposite of prompt_toolkit. pymux.add_process(executable, vsplit=variables['-h'], start_directory=start_directory)
[ "def", "split_window", "(", "pymux", ",", "variables", ")", ":", "executable", "=", "variables", "[", "'<executable>'", "]", "start_directory", "=", "variables", "[", "'<start-directory>'", "]", "# The tmux definition of horizontal is the opposite of prompt_toolkit.", "pymu...
Split horizontally or vertically.
[ "Split", "horizontally", "or", "vertically", "." ]
3f66e62b9de4b2251c7f9afad6c516dc5a30ec67
https://github.com/prompt-toolkit/pymux/blob/3f66e62b9de4b2251c7f9afad6c516dc5a30ec67/pymux/commands/commands.py#L386-L395
233,090
prompt-toolkit/pymux
pymux/commands/commands.py
command_prompt
def command_prompt(pymux, variables): """ Enter command prompt. """ client_state = pymux.get_client_state() if variables['<command>']: # When a 'command' has been given. client_state.prompt_text = variables['<message>'] or '(%s)' % variables['<command>'].split()[0] client_state.prompt_command = variables['<command>'] client_state.prompt_mode = True client_state.prompt_buffer.reset(Document( format_pymux_string(pymux, variables['<default>'] or ''))) get_app().layout.focus(client_state.prompt_buffer) else: # Show the ':' prompt. client_state.prompt_text = '' client_state.prompt_command = '' get_app().layout.focus(client_state.command_buffer) # Go to insert mode. get_app().vi_state.input_mode = InputMode.INSERT
python
def command_prompt(pymux, variables): client_state = pymux.get_client_state() if variables['<command>']: # When a 'command' has been given. client_state.prompt_text = variables['<message>'] or '(%s)' % variables['<command>'].split()[0] client_state.prompt_command = variables['<command>'] client_state.prompt_mode = True client_state.prompt_buffer.reset(Document( format_pymux_string(pymux, variables['<default>'] or ''))) get_app().layout.focus(client_state.prompt_buffer) else: # Show the ':' prompt. client_state.prompt_text = '' client_state.prompt_command = '' get_app().layout.focus(client_state.command_buffer) # Go to insert mode. get_app().vi_state.input_mode = InputMode.INSERT
[ "def", "command_prompt", "(", "pymux", ",", "variables", ")", ":", "client_state", "=", "pymux", ".", "get_client_state", "(", ")", "if", "variables", "[", "'<command>'", "]", ":", "# When a 'command' has been given.", "client_state", ".", "prompt_text", "=", "var...
Enter command prompt.
[ "Enter", "command", "prompt", "." ]
3f66e62b9de4b2251c7f9afad6c516dc5a30ec67
https://github.com/prompt-toolkit/pymux/blob/3f66e62b9de4b2251c7f9afad6c516dc5a30ec67/pymux/commands/commands.py#L438-L462
233,091
prompt-toolkit/pymux
pymux/commands/commands.py
send_prefix
def send_prefix(pymux, variables): """ Send prefix to active pane. """ process = pymux.arrangement.get_active_pane().process for k in pymux.key_bindings_manager.prefix: vt100_data = prompt_toolkit_key_to_vt100_key(k) process.write_input(vt100_data)
python
def send_prefix(pymux, variables): process = pymux.arrangement.get_active_pane().process for k in pymux.key_bindings_manager.prefix: vt100_data = prompt_toolkit_key_to_vt100_key(k) process.write_input(vt100_data)
[ "def", "send_prefix", "(", "pymux", ",", "variables", ")", ":", "process", "=", "pymux", ".", "arrangement", ".", "get_active_pane", "(", ")", ".", "process", "for", "k", "in", "pymux", ".", "key_bindings_manager", ".", "prefix", ":", "vt100_data", "=", "p...
Send prefix to active pane.
[ "Send", "prefix", "to", "active", "pane", "." ]
3f66e62b9de4b2251c7f9afad6c516dc5a30ec67
https://github.com/prompt-toolkit/pymux/blob/3f66e62b9de4b2251c7f9afad6c516dc5a30ec67/pymux/commands/commands.py#L466-L474
233,092
prompt-toolkit/pymux
pymux/commands/commands.py
unbind_key
def unbind_key(pymux, variables): """ Remove key binding. """ key = variables['<key>'] needs_prefix = not variables['-n'] pymux.key_bindings_manager.remove_custom_binding( key, needs_prefix=needs_prefix)
python
def unbind_key(pymux, variables): key = variables['<key>'] needs_prefix = not variables['-n'] pymux.key_bindings_manager.remove_custom_binding( key, needs_prefix=needs_prefix)
[ "def", "unbind_key", "(", "pymux", ",", "variables", ")", ":", "key", "=", "variables", "[", "'<key>'", "]", "needs_prefix", "=", "not", "variables", "[", "'-n'", "]", "pymux", ".", "key_bindings_manager", ".", "remove_custom_binding", "(", "key", ",", "need...
Remove key binding.
[ "Remove", "key", "binding", "." ]
3f66e62b9de4b2251c7f9afad6c516dc5a30ec67
https://github.com/prompt-toolkit/pymux/blob/3f66e62b9de4b2251c7f9afad6c516dc5a30ec67/pymux/commands/commands.py#L496-L504
233,093
prompt-toolkit/pymux
pymux/commands/commands.py
send_keys
def send_keys(pymux, variables): """ Send key strokes to the active process. """ pane = pymux.arrangement.get_active_pane() if pane.display_scroll_buffer: raise CommandException('Cannot send keys. Pane is in copy mode.') for key in variables['<keys>']: # Translate key from pymux key to prompt_toolkit key. try: keys_sequence = pymux_key_to_prompt_toolkit_key_sequence(key) except ValueError: raise CommandException('Invalid key: %r' % (key, )) # Translate prompt_toolkit key to VT100 key. for k in keys_sequence: pane.process.write_key(k)
python
def send_keys(pymux, variables): pane = pymux.arrangement.get_active_pane() if pane.display_scroll_buffer: raise CommandException('Cannot send keys. Pane is in copy mode.') for key in variables['<keys>']: # Translate key from pymux key to prompt_toolkit key. try: keys_sequence = pymux_key_to_prompt_toolkit_key_sequence(key) except ValueError: raise CommandException('Invalid key: %r' % (key, )) # Translate prompt_toolkit key to VT100 key. for k in keys_sequence: pane.process.write_key(k)
[ "def", "send_keys", "(", "pymux", ",", "variables", ")", ":", "pane", "=", "pymux", ".", "arrangement", ".", "get_active_pane", "(", ")", "if", "pane", ".", "display_scroll_buffer", ":", "raise", "CommandException", "(", "'Cannot send keys. Pane is in copy mode.'", ...
Send key strokes to the active process.
[ "Send", "key", "strokes", "to", "the", "active", "process", "." ]
3f66e62b9de4b2251c7f9afad6c516dc5a30ec67
https://github.com/prompt-toolkit/pymux/blob/3f66e62b9de4b2251c7f9afad6c516dc5a30ec67/pymux/commands/commands.py#L508-L526
233,094
prompt-toolkit/pymux
pymux/commands/commands.py
copy_mode
def copy_mode(pymux, variables): """ Enter copy mode. """ go_up = variables['-u'] # Go in copy mode and page-up directly. # TODO: handle '-u' pane = pymux.arrangement.get_active_pane() pane.enter_copy_mode()
python
def copy_mode(pymux, variables): go_up = variables['-u'] # Go in copy mode and page-up directly. # TODO: handle '-u' pane = pymux.arrangement.get_active_pane() pane.enter_copy_mode()
[ "def", "copy_mode", "(", "pymux", ",", "variables", ")", ":", "go_up", "=", "variables", "[", "'-u'", "]", "# Go in copy mode and page-up directly.", "# TODO: handle '-u'", "pane", "=", "pymux", ".", "arrangement", ".", "get_active_pane", "(", ")", "pane", ".", ...
Enter copy mode.
[ "Enter", "copy", "mode", "." ]
3f66e62b9de4b2251c7f9afad6c516dc5a30ec67
https://github.com/prompt-toolkit/pymux/blob/3f66e62b9de4b2251c7f9afad6c516dc5a30ec67/pymux/commands/commands.py#L530-L538
233,095
prompt-toolkit/pymux
pymux/commands/commands.py
paste_buffer
def paste_buffer(pymux, variables): """ Paste clipboard content into buffer. """ pane = pymux.arrangement.get_active_pane() pane.process.write_input(get_app().clipboard.get_data().text, paste=True)
python
def paste_buffer(pymux, variables): pane = pymux.arrangement.get_active_pane() pane.process.write_input(get_app().clipboard.get_data().text, paste=True)
[ "def", "paste_buffer", "(", "pymux", ",", "variables", ")", ":", "pane", "=", "pymux", ".", "arrangement", ".", "get_active_pane", "(", ")", "pane", ".", "process", ".", "write_input", "(", "get_app", "(", ")", ".", "clipboard", ".", "get_data", "(", ")"...
Paste clipboard content into buffer.
[ "Paste", "clipboard", "content", "into", "buffer", "." ]
3f66e62b9de4b2251c7f9afad6c516dc5a30ec67
https://github.com/prompt-toolkit/pymux/blob/3f66e62b9de4b2251c7f9afad6c516dc5a30ec67/pymux/commands/commands.py#L542-L547
233,096
prompt-toolkit/pymux
pymux/commands/commands.py
source_file
def source_file(pymux, variables): """ Source configuration file. """ filename = os.path.expanduser(variables['<filename>']) try: with open(filename, 'rb') as f: for line in f: line = line.decode('utf-8') handle_command(pymux, line) except IOError as e: raise CommandException('IOError: %s' % (e, ))
python
def source_file(pymux, variables): filename = os.path.expanduser(variables['<filename>']) try: with open(filename, 'rb') as f: for line in f: line = line.decode('utf-8') handle_command(pymux, line) except IOError as e: raise CommandException('IOError: %s' % (e, ))
[ "def", "source_file", "(", "pymux", ",", "variables", ")", ":", "filename", "=", "os", ".", "path", ".", "expanduser", "(", "variables", "[", "'<filename>'", "]", ")", "try", ":", "with", "open", "(", "filename", ",", "'rb'", ")", "as", "f", ":", "fo...
Source configuration file.
[ "Source", "configuration", "file", "." ]
3f66e62b9de4b2251c7f9afad6c516dc5a30ec67
https://github.com/prompt-toolkit/pymux/blob/3f66e62b9de4b2251c7f9afad6c516dc5a30ec67/pymux/commands/commands.py#L551-L562
233,097
prompt-toolkit/pymux
pymux/commands/commands.py
display_message
def display_message(pymux, variables): " Display a message. " message = variables['<message>'] client_state = pymux.get_client_state() client_state.message = message
python
def display_message(pymux, variables): " Display a message. " message = variables['<message>'] client_state = pymux.get_client_state() client_state.message = message
[ "def", "display_message", "(", "pymux", ",", "variables", ")", ":", "message", "=", "variables", "[", "'<message>'", "]", "client_state", "=", "pymux", ".", "get_client_state", "(", ")", "client_state", ".", "message", "=", "message" ]
Display a message.
[ "Display", "a", "message", "." ]
3f66e62b9de4b2251c7f9afad6c516dc5a30ec67
https://github.com/prompt-toolkit/pymux/blob/3f66e62b9de4b2251c7f9afad6c516dc5a30ec67/pymux/commands/commands.py#L595-L599
233,098
prompt-toolkit/pymux
pymux/commands/commands.py
clear_history
def clear_history(pymux, variables): " Clear scrollback buffer. " pane = pymux.arrangement.get_active_pane() if pane.display_scroll_buffer: raise CommandException('Not available in copy mode') else: pane.process.screen.clear_history()
python
def clear_history(pymux, variables): " Clear scrollback buffer. " pane = pymux.arrangement.get_active_pane() if pane.display_scroll_buffer: raise CommandException('Not available in copy mode') else: pane.process.screen.clear_history()
[ "def", "clear_history", "(", "pymux", ",", "variables", ")", ":", "pane", "=", "pymux", ".", "arrangement", ".", "get_active_pane", "(", ")", "if", "pane", ".", "display_scroll_buffer", ":", "raise", "CommandException", "(", "'Not available in copy mode'", ")", ...
Clear scrollback buffer.
[ "Clear", "scrollback", "buffer", "." ]
3f66e62b9de4b2251c7f9afad6c516dc5a30ec67
https://github.com/prompt-toolkit/pymux/blob/3f66e62b9de4b2251c7f9afad6c516dc5a30ec67/pymux/commands/commands.py#L603-L610
233,099
prompt-toolkit/pymux
pymux/commands/commands.py
list_keys
def list_keys(pymux, variables): """ Display all configured key bindings. """ # Create help string. result = [] for k, custom_binding in pymux.key_bindings_manager.custom_bindings.items(): needs_prefix, key = k result.append('bind-key %3s %-10s %s %s' % ( ('-n' if needs_prefix else ''), key, custom_binding.command, ' '.join(map(wrap_argument, custom_binding.arguments)))) # Display help in pane. result = '\n'.join(sorted(result)) pymux.get_client_state().layout_manager.display_popup('list-keys', result)
python
def list_keys(pymux, variables): # Create help string. result = [] for k, custom_binding in pymux.key_bindings_manager.custom_bindings.items(): needs_prefix, key = k result.append('bind-key %3s %-10s %s %s' % ( ('-n' if needs_prefix else ''), key, custom_binding.command, ' '.join(map(wrap_argument, custom_binding.arguments)))) # Display help in pane. result = '\n'.join(sorted(result)) pymux.get_client_state().layout_manager.display_popup('list-keys', result)
[ "def", "list_keys", "(", "pymux", ",", "variables", ")", ":", "# Create help string.", "result", "=", "[", "]", "for", "k", ",", "custom_binding", "in", "pymux", ".", "key_bindings_manager", ".", "custom_bindings", ".", "items", "(", ")", ":", "needs_prefix", ...
Display all configured key bindings.
[ "Display", "all", "configured", "key", "bindings", "." ]
3f66e62b9de4b2251c7f9afad6c516dc5a30ec67
https://github.com/prompt-toolkit/pymux/blob/3f66e62b9de4b2251c7f9afad6c516dc5a30ec67/pymux/commands/commands.py#L614-L630