repository_name
stringlengths
5
67
func_path_in_repository
stringlengths
4
234
func_name
stringlengths
0
314
whole_func_string
stringlengths
52
3.87M
language
stringclasses
6 values
func_code_string
stringlengths
52
3.87M
func_code_tokens
listlengths
15
672k
func_documentation_string
stringlengths
1
47.2k
func_documentation_tokens
listlengths
1
3.92k
split_name
stringclasses
1 value
func_code_url
stringlengths
85
339
jborean93/smbprotocol
smbprotocol/open.py
Open.query_directory
def query_directory(self, pattern, file_information_class, flags=None, file_index=0, max_output=65536, send=True): """ Run a Query/Find on an opened directory based on the params passed in. Supports out of band send function, call this function with send=False to...
python
def query_directory(self, pattern, file_information_class, flags=None, file_index=0, max_output=65536, send=True): """ Run a Query/Find on an opened directory based on the params passed in. Supports out of band send function, call this function with send=False to...
[ "def", "query_directory", "(", "self", ",", "pattern", ",", "file_information_class", ",", "flags", "=", "None", ",", "file_index", "=", "0", ",", "max_output", "=", "65536", ",", "send", "=", "True", ")", ":", "query", "=", "SMB2QueryDirectoryRequest", "(",...
Run a Query/Find on an opened directory based on the params passed in. Supports out of band send function, call this function with send=False to return a tuple of (SMB2QueryDirectoryRequest, receive_func) instead of sending the the request and waiting for the response. The receive_func ...
[ "Run", "a", "Query", "/", "Find", "on", "an", "opened", "directory", "based", "on", "the", "params", "passed", "in", "." ]
train
https://github.com/jborean93/smbprotocol/blob/d8eb00fbc824f97d0f4946e3f768c5e6c723499a/smbprotocol/open.py#L1230-L1276
jborean93/smbprotocol
smbprotocol/open.py
Open.close
def close(self, get_attributes=False, send=True): """ Closes an opened file. Supports out of band send function, call this function with send=False to return a tuple of (SMB2CloseRequest, receive_func) instead of sending the the request and waiting for the response. The receive_...
python
def close(self, get_attributes=False, send=True): """ Closes an opened file. Supports out of band send function, call this function with send=False to return a tuple of (SMB2CloseRequest, receive_func) instead of sending the the request and waiting for the response. The receive_...
[ "def", "close", "(", "self", ",", "get_attributes", "=", "False", ",", "send", "=", "True", ")", ":", "# it is already closed and this isn't for an out of band request", "if", "not", "self", ".", "_connected", "and", "send", ":", "return", "close", "=", "SMB2Close...
Closes an opened file. Supports out of band send function, call this function with send=False to return a tuple of (SMB2CloseRequest, receive_func) instead of sending the the request and waiting for the response. The receive_func can be used to get the response from the server by passin...
[ "Closes", "an", "opened", "file", "." ]
train
https://github.com/jborean93/smbprotocol/blob/d8eb00fbc824f97d0f4946e3f768c5e6c723499a/smbprotocol/open.py#L1294-L1331
jborean93/smbprotocol
smbprotocol/security_descriptor.py
SIDPacket.from_string
def from_string(self, sid_string): """ Used to set the structure parameters based on the input string :param sid_string: String of the sid in S-x-x-x-x form """ if not sid_string.startswith("S-"): raise ValueError("A SID string must start with S-") sid_entri...
python
def from_string(self, sid_string): """ Used to set the structure parameters based on the input string :param sid_string: String of the sid in S-x-x-x-x form """ if not sid_string.startswith("S-"): raise ValueError("A SID string must start with S-") sid_entri...
[ "def", "from_string", "(", "self", ",", "sid_string", ")", ":", "if", "not", "sid_string", ".", "startswith", "(", "\"S-\"", ")", ":", "raise", "ValueError", "(", "\"A SID string must start with S-\"", ")", "sid_entries", "=", "sid_string", ".", "split", "(", ...
Used to set the structure parameters based on the input string :param sid_string: String of the sid in S-x-x-x-x form
[ "Used", "to", "set", "the", "structure", "parameters", "based", "on", "the", "input", "string" ]
train
https://github.com/jborean93/smbprotocol/blob/d8eb00fbc824f97d0f4946e3f768c5e6c723499a/smbprotocol/security_descriptor.py#L160-L180
Thibauth/python-pushover
pushover.py
MessageRequest.poll
def poll(self): """If the message request has a priority of 2, Pushover keeps sending the same notification until the client acknowledges it. Calling the :func:`poll` function fetches the status of the :class:`MessageRequest` object until the notifications either expires, is acknowledged...
python
def poll(self): """If the message request has a priority of 2, Pushover keeps sending the same notification until the client acknowledges it. Calling the :func:`poll` function fetches the status of the :class:`MessageRequest` object until the notifications either expires, is acknowledged...
[ "def", "poll", "(", "self", ")", ":", "if", "not", "self", ".", "status", "[", "\"done\"", "]", ":", "r", "=", "Request", "(", "\"get\"", ",", "self", ".", "url", "+", "\".json\"", ",", "{", "\"token\"", ":", "self", ".", "payload", "[", "\"token\"...
If the message request has a priority of 2, Pushover keeps sending the same notification until the client acknowledges it. Calling the :func:`poll` function fetches the status of the :class:`MessageRequest` object until the notifications either expires, is acknowledged by the client, or ...
[ "If", "the", "message", "request", "has", "a", "priority", "of", "2", "Pushover", "keeps", "sending", "the", "same", "notification", "until", "the", "client", "acknowledges", "it", ".", "Calling", "the", ":", "func", ":", "poll", "function", "fetches", "the"...
train
https://github.com/Thibauth/python-pushover/blob/420bde9a2bd7981b5ea8f0c1cb8875d5f676f368/pushover.py#L90-L119
Thibauth/python-pushover
pushover.py
Pushover.sounds
def sounds(self): """Return a dictionary of sounds recognized by Pushover and that can be used in a notification message. """ if not Pushover._SOUNDS: request = Request("get", SOUND_URL, {"token": self.token}) Pushover._SOUNDS = request.answer["sounds"] re...
python
def sounds(self): """Return a dictionary of sounds recognized by Pushover and that can be used in a notification message. """ if not Pushover._SOUNDS: request = Request("get", SOUND_URL, {"token": self.token}) Pushover._SOUNDS = request.answer["sounds"] re...
[ "def", "sounds", "(", "self", ")", ":", "if", "not", "Pushover", ".", "_SOUNDS", ":", "request", "=", "Request", "(", "\"get\"", ",", "SOUND_URL", ",", "{", "\"token\"", ":", "self", ".", "token", "}", ")", "Pushover", ".", "_SOUNDS", "=", "request", ...
Return a dictionary of sounds recognized by Pushover and that can be used in a notification message.
[ "Return", "a", "dictionary", "of", "sounds", "recognized", "by", "Pushover", "and", "that", "can", "be", "used", "in", "a", "notification", "message", "." ]
train
https://github.com/Thibauth/python-pushover/blob/420bde9a2bd7981b5ea8f0c1cb8875d5f676f368/pushover.py#L163-L170
Thibauth/python-pushover
pushover.py
Pushover.verify
def verify(self, user, device=None): """Verify that the `user` and optional `device` exist. Returns `None` when the user/device does not exist or a list of the user's devices otherwise. """ payload = {"user": user, "token": self.token} if device: payload["devi...
python
def verify(self, user, device=None): """Verify that the `user` and optional `device` exist. Returns `None` when the user/device does not exist or a list of the user's devices otherwise. """ payload = {"user": user, "token": self.token} if device: payload["devi...
[ "def", "verify", "(", "self", ",", "user", ",", "device", "=", "None", ")", ":", "payload", "=", "{", "\"user\"", ":", "user", ",", "\"token\"", ":", "self", ".", "token", "}", "if", "device", ":", "payload", "[", "\"device\"", "]", "=", "device", ...
Verify that the `user` and optional `device` exist. Returns `None` when the user/device does not exist or a list of the user's devices otherwise.
[ "Verify", "that", "the", "user", "and", "optional", "device", "exist", ".", "Returns", "None", "when", "the", "user", "/", "device", "does", "not", "exist", "or", "a", "list", "of", "the", "user", "s", "devices", "otherwise", "." ]
train
https://github.com/Thibauth/python-pushover/blob/420bde9a2bd7981b5ea8f0c1cb8875d5f676f368/pushover.py#L172-L185
Thibauth/python-pushover
pushover.py
Pushover.message
def message(self, user, message, **kwargs): """Send `message` to the user specified by `user`. It is possible to specify additional properties of the message by passing keyword arguments. The list of valid keywords is ``title, priority, sound, callback, timestamp, url, url_title, device,...
python
def message(self, user, message, **kwargs): """Send `message` to the user specified by `user`. It is possible to specify additional properties of the message by passing keyword arguments. The list of valid keywords is ``title, priority, sound, callback, timestamp, url, url_title, device,...
[ "def", "message", "(", "self", ",", "user", ",", "message", ",", "*", "*", "kwargs", ")", ":", "payload", "=", "{", "\"message\"", ":", "message", ",", "\"user\"", ":", "user", ",", "\"token\"", ":", "self", ".", "token", "}", "for", "key", ",", "v...
Send `message` to the user specified by `user`. It is possible to specify additional properties of the message by passing keyword arguments. The list of valid keywords is ``title, priority, sound, callback, timestamp, url, url_title, device, retry, expire and html`` which are described i...
[ "Send", "message", "to", "the", "user", "specified", "by", "user", ".", "It", "is", "possible", "to", "specify", "additional", "properties", "of", "the", "message", "by", "passing", "keyword", "arguments", ".", "The", "list", "of", "valid", "keywords", "is",...
train
https://github.com/Thibauth/python-pushover/blob/420bde9a2bd7981b5ea8f0c1cb8875d5f676f368/pushover.py#L187-L214
Thibauth/python-pushover
pushover.py
Pushover.glance
def glance(self, user, **kwargs): """Send a glance to the user. The default property is ``text``, as this is used on most glances, however a valid glance does not need to require text and can be constructed using any combination of valid keyword properties. The list of valid keywords is ...
python
def glance(self, user, **kwargs): """Send a glance to the user. The default property is ``text``, as this is used on most glances, however a valid glance does not need to require text and can be constructed using any combination of valid keyword properties. The list of valid keywords is ...
[ "def", "glance", "(", "self", ",", "user", ",", "*", "*", "kwargs", ")", ":", "payload", "=", "{", "\"user\"", ":", "user", ",", "\"token\"", ":", "self", ".", "token", "}", "for", "key", ",", "value", "in", "kwargs", ".", "iteritems", "(", ")", ...
Send a glance to the user. The default property is ``text``, as this is used on most glances, however a valid glance does not need to require text and can be constructed using any combination of valid keyword properties. The list of valid keywords is ``title, text, subtext, count, percen...
[ "Send", "a", "glance", "to", "the", "user", ".", "The", "default", "property", "is", "text", "as", "this", "is", "used", "on", "most", "glances", "however", "a", "valid", "glance", "does", "not", "need", "to", "require", "text", "and", "can", "be", "co...
train
https://github.com/Thibauth/python-pushover/blob/420bde9a2bd7981b5ea8f0c1cb8875d5f676f368/pushover.py#L216-L234
Wramberg/adaptfilt
adaptfilt/misc.py
mswe
def mswe(w, v): """ Calculate mean squared weight error between estimated and true filter coefficients, in respect to iterations. Parameters ---------- v : array-like True coefficients used to generate desired signal, must be a one-dimensional array. w : array-like E...
python
def mswe(w, v): """ Calculate mean squared weight error between estimated and true filter coefficients, in respect to iterations. Parameters ---------- v : array-like True coefficients used to generate desired signal, must be a one-dimensional array. w : array-like E...
[ "def", "mswe", "(", "w", ",", "v", ")", ":", "# Ensure inputs are numpy arrays", "w", "=", "np", ".", "array", "(", "w", ")", "v", "=", "np", ".", "array", "(", "v", ")", "# Check dimensions", "if", "(", "len", "(", "w", ".", "shape", ")", "!=", ...
Calculate mean squared weight error between estimated and true filter coefficients, in respect to iterations. Parameters ---------- v : array-like True coefficients used to generate desired signal, must be a one-dimensional array. w : array-like Estimated coefficients from a...
[ "Calculate", "mean", "squared", "weight", "error", "between", "estimated", "and", "true", "filter", "coefficients", "in", "respect", "to", "iterations", "." ]
train
https://github.com/Wramberg/adaptfilt/blob/9bb943bb5e4162e10a8aaabfc68339b8fc06c11a/adaptfilt/misc.py#L7-L57
Wramberg/adaptfilt
adaptfilt/nlms.py
nlms
def nlms(u, d, M, step, eps=0.001, leak=0, initCoeffs=None, N=None, returnCoeffs=False): """ Perform normalized least-mean-squares (NLMS) adaptive filtering on u to minimize error given by e=d-y, where y is the output of the adaptive filter. Parameters ---------- u : array-like ...
python
def nlms(u, d, M, step, eps=0.001, leak=0, initCoeffs=None, N=None, returnCoeffs=False): """ Perform normalized least-mean-squares (NLMS) adaptive filtering on u to minimize error given by e=d-y, where y is the output of the adaptive filter. Parameters ---------- u : array-like ...
[ "def", "nlms", "(", "u", ",", "d", ",", "M", ",", "step", ",", "eps", "=", "0.001", ",", "leak", "=", "0", ",", "initCoeffs", "=", "None", ",", "N", "=", "None", ",", "returnCoeffs", "=", "False", ")", ":", "# Check epsilon", "_pchk", ".", "check...
Perform normalized least-mean-squares (NLMS) adaptive filtering on u to minimize error given by e=d-y, where y is the output of the adaptive filter. Parameters ---------- u : array-like One-dimensional filter input. d : array-like One-dimensional desired signal, i.e., the output...
[ "Perform", "normalized", "least", "-", "mean", "-", "squares", "(", "NLMS", ")", "adaptive", "filtering", "on", "u", "to", "minimize", "error", "given", "by", "e", "=", "d", "-", "y", "where", "y", "is", "the", "output", "of", "the", "adaptive", "filte...
train
https://github.com/Wramberg/adaptfilt/blob/9bb943bb5e4162e10a8aaabfc68339b8fc06c11a/adaptfilt/nlms.py#L5-L154
Wramberg/adaptfilt
adaptfilt/ap.py
ap
def ap(u, d, M, step, K, eps=0.001, leak=0, initCoeffs=None, N=None, returnCoeffs=False): """ Perform affine projection (AP) adaptive filtering on u to minimize error given by e=d-y, where y is the output of the adaptive filter. Parameters ---------- u : array-like One-dimensiona...
python
def ap(u, d, M, step, K, eps=0.001, leak=0, initCoeffs=None, N=None, returnCoeffs=False): """ Perform affine projection (AP) adaptive filtering on u to minimize error given by e=d-y, where y is the output of the adaptive filter. Parameters ---------- u : array-like One-dimensiona...
[ "def", "ap", "(", "u", ",", "d", ",", "M", ",", "step", ",", "K", ",", "eps", "=", "0.001", ",", "leak", "=", "0", ",", "initCoeffs", "=", "None", ",", "N", "=", "None", ",", "returnCoeffs", "=", "False", ")", ":", "# Check epsilon", "_pchk", "...
Perform affine projection (AP) adaptive filtering on u to minimize error given by e=d-y, where y is the output of the adaptive filter. Parameters ---------- u : array-like One-dimensional filter input. d : array-like One-dimensional desired signal, i.e., the output of the unknown FI...
[ "Perform", "affine", "projection", "(", "AP", ")", "adaptive", "filtering", "on", "u", "to", "minimize", "error", "given", "by", "e", "=", "d", "-", "y", "where", "y", "is", "the", "output", "of", "the", "adaptive", "filter", "." ]
train
https://github.com/Wramberg/adaptfilt/blob/9bb943bb5e4162e10a8aaabfc68339b8fc06c11a/adaptfilt/ap.py#L5-L176
vmalyi/adb_android
adb_android/adb_android.py
bugreport
def bugreport(dest_file="default.log"): """ Prints dumpsys, dumpstate, and logcat data to the screen, for the purposes of bug reporting :return: result of _exec_command() execution """ adb_full_cmd = [v.ADB_COMMAND_PREFIX, v.ADB_COMMAND_BUGREPORT] try: dest_file_handler = open(dest_file,...
python
def bugreport(dest_file="default.log"): """ Prints dumpsys, dumpstate, and logcat data to the screen, for the purposes of bug reporting :return: result of _exec_command() execution """ adb_full_cmd = [v.ADB_COMMAND_PREFIX, v.ADB_COMMAND_BUGREPORT] try: dest_file_handler = open(dest_file,...
[ "def", "bugreport", "(", "dest_file", "=", "\"default.log\"", ")", ":", "adb_full_cmd", "=", "[", "v", ".", "ADB_COMMAND_PREFIX", ",", "v", ".", "ADB_COMMAND_BUGREPORT", "]", "try", ":", "dest_file_handler", "=", "open", "(", "dest_file", ",", "\"w\"", ")", ...
Prints dumpsys, dumpstate, and logcat data to the screen, for the purposes of bug reporting :return: result of _exec_command() execution
[ "Prints", "dumpsys", "dumpstate", "and", "logcat", "data", "to", "the", "screen", "for", "the", "purposes", "of", "bug", "reporting", ":", "return", ":", "result", "of", "_exec_command", "()", "execution" ]
train
https://github.com/vmalyi/adb_android/blob/de53dc54f27b14dc8c2ae64b136a60a59e1a1cb1/adb_android/adb_android.py#L28-L47
vmalyi/adb_android
adb_android/adb_android.py
push
def push(src, dest): """ Push object from host to target :param src: string path to source object on host :param dest: string destination path on target :return: result of _exec_command() execution """ adb_full_cmd = [v.ADB_COMMAND_PREFIX, v.ADB_COMMAND_PUSH, src, dest] return _exec_comm...
python
def push(src, dest): """ Push object from host to target :param src: string path to source object on host :param dest: string destination path on target :return: result of _exec_command() execution """ adb_full_cmd = [v.ADB_COMMAND_PREFIX, v.ADB_COMMAND_PUSH, src, dest] return _exec_comm...
[ "def", "push", "(", "src", ",", "dest", ")", ":", "adb_full_cmd", "=", "[", "v", ".", "ADB_COMMAND_PREFIX", ",", "v", ".", "ADB_COMMAND_PUSH", ",", "src", ",", "dest", "]", "return", "_exec_command", "(", "adb_full_cmd", ")" ]
Push object from host to target :param src: string path to source object on host :param dest: string destination path on target :return: result of _exec_command() execution
[ "Push", "object", "from", "host", "to", "target", ":", "param", "src", ":", "string", "path", "to", "source", "object", "on", "host", ":", "param", "dest", ":", "string", "destination", "path", "on", "target", ":", "return", ":", "result", "of", "_exec_c...
train
https://github.com/vmalyi/adb_android/blob/de53dc54f27b14dc8c2ae64b136a60a59e1a1cb1/adb_android/adb_android.py#L50-L58
vmalyi/adb_android
adb_android/adb_android.py
pull
def pull(src, dest): """ Pull object from target to host :param src: string path of object on target :param dest: string destination path on host :return: result of _exec_command() execution """ adb_full_cmd = [v.ADB_COMMAND_PREFIX, v.ADB_COMMAND_PULL, src, dest] return _exec_command(adb...
python
def pull(src, dest): """ Pull object from target to host :param src: string path of object on target :param dest: string destination path on host :return: result of _exec_command() execution """ adb_full_cmd = [v.ADB_COMMAND_PREFIX, v.ADB_COMMAND_PULL, src, dest] return _exec_command(adb...
[ "def", "pull", "(", "src", ",", "dest", ")", ":", "adb_full_cmd", "=", "[", "v", ".", "ADB_COMMAND_PREFIX", ",", "v", ".", "ADB_COMMAND_PULL", ",", "src", ",", "dest", "]", "return", "_exec_command", "(", "adb_full_cmd", ")" ]
Pull object from target to host :param src: string path of object on target :param dest: string destination path on host :return: result of _exec_command() execution
[ "Pull", "object", "from", "target", "to", "host", ":", "param", "src", ":", "string", "path", "of", "object", "on", "target", ":", "param", "dest", ":", "string", "destination", "path", "on", "host", ":", "return", ":", "result", "of", "_exec_command", "...
train
https://github.com/vmalyi/adb_android/blob/de53dc54f27b14dc8c2ae64b136a60a59e1a1cb1/adb_android/adb_android.py#L61-L69
vmalyi/adb_android
adb_android/adb_android.py
devices
def devices(opts=[]): """ Get list of all available devices including emulators :param opts: list command options (e.g. ["-r", "-a"]) :return: result of _exec_command() execution """ adb_full_cmd = [v.ADB_COMMAND_PREFIX, v.ADB_COMMAND_DEVICES, _convert_opts(opts)] return _exec_command(adb_fu...
python
def devices(opts=[]): """ Get list of all available devices including emulators :param opts: list command options (e.g. ["-r", "-a"]) :return: result of _exec_command() execution """ adb_full_cmd = [v.ADB_COMMAND_PREFIX, v.ADB_COMMAND_DEVICES, _convert_opts(opts)] return _exec_command(adb_fu...
[ "def", "devices", "(", "opts", "=", "[", "]", ")", ":", "adb_full_cmd", "=", "[", "v", ".", "ADB_COMMAND_PREFIX", ",", "v", ".", "ADB_COMMAND_DEVICES", ",", "_convert_opts", "(", "opts", ")", "]", "return", "_exec_command", "(", "adb_full_cmd", ")" ]
Get list of all available devices including emulators :param opts: list command options (e.g. ["-r", "-a"]) :return: result of _exec_command() execution
[ "Get", "list", "of", "all", "available", "devices", "including", "emulators", ":", "param", "opts", ":", "list", "command", "options", "(", "e", ".", "g", ".", "[", "-", "r", "-", "a", "]", ")", ":", "return", ":", "result", "of", "_exec_command", "(...
train
https://github.com/vmalyi/adb_android/blob/de53dc54f27b14dc8c2ae64b136a60a59e1a1cb1/adb_android/adb_android.py#L72-L79
vmalyi/adb_android
adb_android/adb_android.py
shell
def shell(cmd): """ Execute shell command on target :param cmd: string shell command to execute :return: result of _exec_command() execution """ adb_full_cmd = [v.ADB_COMMAND_PREFIX, v.ADB_COMMAND_SHELL, cmd] return _exec_command(adb_full_cmd)
python
def shell(cmd): """ Execute shell command on target :param cmd: string shell command to execute :return: result of _exec_command() execution """ adb_full_cmd = [v.ADB_COMMAND_PREFIX, v.ADB_COMMAND_SHELL, cmd] return _exec_command(adb_full_cmd)
[ "def", "shell", "(", "cmd", ")", ":", "adb_full_cmd", "=", "[", "v", ".", "ADB_COMMAND_PREFIX", ",", "v", ".", "ADB_COMMAND_SHELL", ",", "cmd", "]", "return", "_exec_command", "(", "adb_full_cmd", ")" ]
Execute shell command on target :param cmd: string shell command to execute :return: result of _exec_command() execution
[ "Execute", "shell", "command", "on", "target", ":", "param", "cmd", ":", "string", "shell", "command", "to", "execute", ":", "return", ":", "result", "of", "_exec_command", "()", "execution" ]
train
https://github.com/vmalyi/adb_android/blob/de53dc54f27b14dc8c2ae64b136a60a59e1a1cb1/adb_android/adb_android.py#L82-L89
vmalyi/adb_android
adb_android/adb_android.py
install
def install(apk, opts=[]): """ Install *.apk on target :param apk: string path to apk on host to install :param opts: list command options (e.g. ["-r", "-a"]) :return: result of _exec_command() execution """ adb_full_cmd = [v.ADB_COMMAND_PREFIX, v.ADB_COMMAND_INSTALL, _convert_opts(opts), ap...
python
def install(apk, opts=[]): """ Install *.apk on target :param apk: string path to apk on host to install :param opts: list command options (e.g. ["-r", "-a"]) :return: result of _exec_command() execution """ adb_full_cmd = [v.ADB_COMMAND_PREFIX, v.ADB_COMMAND_INSTALL, _convert_opts(opts), ap...
[ "def", "install", "(", "apk", ",", "opts", "=", "[", "]", ")", ":", "adb_full_cmd", "=", "[", "v", ".", "ADB_COMMAND_PREFIX", ",", "v", ".", "ADB_COMMAND_INSTALL", ",", "_convert_opts", "(", "opts", ")", ",", "apk", "]", "return", "_exec_command", "(", ...
Install *.apk on target :param apk: string path to apk on host to install :param opts: list command options (e.g. ["-r", "-a"]) :return: result of _exec_command() execution
[ "Install", "*", ".", "apk", "on", "target", ":", "param", "apk", ":", "string", "path", "to", "apk", "on", "host", "to", "install", ":", "param", "opts", ":", "list", "command", "options", "(", "e", ".", "g", ".", "[", "-", "r", "-", "a", "]", ...
train
https://github.com/vmalyi/adb_android/blob/de53dc54f27b14dc8c2ae64b136a60a59e1a1cb1/adb_android/adb_android.py#L92-L100
vmalyi/adb_android
adb_android/adb_android.py
uninstall
def uninstall(app, opts=[]): """ Uninstall app from target :param app: app name to uninstall from target (e.g. "com.example.android.valid") :param opts: list command options (e.g. ["-r", "-a"]) :return: result of _exec_command() execution """ adb_full_cmd = [v.ADB_COMMAND_PREFIX, v.ADB_COMMA...
python
def uninstall(app, opts=[]): """ Uninstall app from target :param app: app name to uninstall from target (e.g. "com.example.android.valid") :param opts: list command options (e.g. ["-r", "-a"]) :return: result of _exec_command() execution """ adb_full_cmd = [v.ADB_COMMAND_PREFIX, v.ADB_COMMA...
[ "def", "uninstall", "(", "app", ",", "opts", "=", "[", "]", ")", ":", "adb_full_cmd", "=", "[", "v", ".", "ADB_COMMAND_PREFIX", ",", "v", ".", "ADB_COMMAND_UNINSTALL", ",", "_convert_opts", "(", "opts", ")", ",", "app", "]", "return", "_exec_command", "(...
Uninstall app from target :param app: app name to uninstall from target (e.g. "com.example.android.valid") :param opts: list command options (e.g. ["-r", "-a"]) :return: result of _exec_command() execution
[ "Uninstall", "app", "from", "target", ":", "param", "app", ":", "app", "name", "to", "uninstall", "from", "target", "(", "e", ".", "g", ".", "com", ".", "example", ".", "android", ".", "valid", ")", ":", "param", "opts", ":", "list", "command", "opti...
train
https://github.com/vmalyi/adb_android/blob/de53dc54f27b14dc8c2ae64b136a60a59e1a1cb1/adb_android/adb_android.py#L103-L111
vmalyi/adb_android
adb_android/adb_android.py
sync
def sync(): """ Copy host->device only if changed :return: result of _exec_command() execution """ adb_full_cmd = [v.ADB_COMMAND_PREFIX, v.ADB_COMMAND_SHELL ,v.ADB_COMMAND_SYNC] return _exec_command(adb_full_cmd)
python
def sync(): """ Copy host->device only if changed :return: result of _exec_command() execution """ adb_full_cmd = [v.ADB_COMMAND_PREFIX, v.ADB_COMMAND_SHELL ,v.ADB_COMMAND_SYNC] return _exec_command(adb_full_cmd)
[ "def", "sync", "(", ")", ":", "adb_full_cmd", "=", "[", "v", ".", "ADB_COMMAND_PREFIX", ",", "v", ".", "ADB_COMMAND_SHELL", ",", "v", ".", "ADB_COMMAND_SYNC", "]", "return", "_exec_command", "(", "adb_full_cmd", ")" ]
Copy host->device only if changed :return: result of _exec_command() execution
[ "Copy", "host", "-", ">", "device", "only", "if", "changed", ":", "return", ":", "result", "of", "_exec_command", "()", "execution" ]
train
https://github.com/vmalyi/adb_android/blob/de53dc54f27b14dc8c2ae64b136a60a59e1a1cb1/adb_android/adb_android.py#L132-L138
vmalyi/adb_android
adb_android/adb_android.py
_exec_command
def _exec_command(adb_cmd): """ Format adb command and execute it in shell :param adb_cmd: list adb command to execute :return: string '0' and shell command output if successful, otherwise raise CalledProcessError exception and return error code """ t = tempfile.TemporaryFile() final_adb...
python
def _exec_command(adb_cmd): """ Format adb command and execute it in shell :param adb_cmd: list adb command to execute :return: string '0' and shell command output if successful, otherwise raise CalledProcessError exception and return error code """ t = tempfile.TemporaryFile() final_adb...
[ "def", "_exec_command", "(", "adb_cmd", ")", ":", "t", "=", "tempfile", ".", "TemporaryFile", "(", ")", "final_adb_cmd", "=", "[", "]", "for", "e", "in", "adb_cmd", ":", "if", "e", "!=", "''", ":", "# avoid items with empty string...", "final_adb_cmd", ".", ...
Format adb command and execute it in shell :param adb_cmd: list adb command to execute :return: string '0' and shell command output if successful, otherwise raise CalledProcessError exception and return error code
[ "Format", "adb", "command", "and", "execute", "it", "in", "shell", ":", "param", "adb_cmd", ":", "list", "adb", "command", "to", "execute", ":", "return", ":", "string", "0", "and", "shell", "command", "output", "if", "successful", "otherwise", "raise", "C...
train
https://github.com/vmalyi/adb_android/blob/de53dc54f27b14dc8c2ae64b136a60a59e1a1cb1/adb_android/adb_android.py#L178-L202
vmalyi/adb_android
adb_android/adb_android.py
_exec_command_to_file
def _exec_command_to_file(adb_cmd, dest_file_handler): """ Format adb command and execute it in shell and redirects to a file :param adb_cmd: list adb command to execute :param dest_file_handler: file handler to which output will be redirected :return: string '0' and writes shell command output to f...
python
def _exec_command_to_file(adb_cmd, dest_file_handler): """ Format adb command and execute it in shell and redirects to a file :param adb_cmd: list adb command to execute :param dest_file_handler: file handler to which output will be redirected :return: string '0' and writes shell command output to f...
[ "def", "_exec_command_to_file", "(", "adb_cmd", ",", "dest_file_handler", ")", ":", "t", "=", "tempfile", ".", "TemporaryFile", "(", ")", "final_adb_cmd", "=", "[", "]", "for", "e", "in", "adb_cmd", ":", "if", "e", "!=", "''", ":", "# avoid items with empty ...
Format adb command and execute it in shell and redirects to a file :param adb_cmd: list adb command to execute :param dest_file_handler: file handler to which output will be redirected :return: string '0' and writes shell command output to file if successful, otherwise raise CalledProcessError exception...
[ "Format", "adb", "command", "and", "execute", "it", "in", "shell", "and", "redirects", "to", "a", "file", ":", "param", "adb_cmd", ":", "list", "adb", "command", "to", "execute", ":", "param", "dest_file_handler", ":", "file", "handler", "to", "which", "ou...
train
https://github.com/vmalyi/adb_android/blob/de53dc54f27b14dc8c2ae64b136a60a59e1a1cb1/adb_android/adb_android.py#L205-L230
mlavin/django-selectable
selectable/forms/fields.py
BaseAutoCompleteField.has_changed
def has_changed(self, initial, data): "Detects if the data was changed. This is added in 1.6." if initial is None and data is None: return False if data and not hasattr(data, '__iter__'): data = self.widget.decompress(data) initial = self.to_python(initial) ...
python
def has_changed(self, initial, data): "Detects if the data was changed. This is added in 1.6." if initial is None and data is None: return False if data and not hasattr(data, '__iter__'): data = self.widget.decompress(data) initial = self.to_python(initial) ...
[ "def", "has_changed", "(", "self", ",", "initial", ",", "data", ")", ":", "if", "initial", "is", "None", "and", "data", "is", "None", ":", "return", "False", "if", "data", "and", "not", "hasattr", "(", "data", ",", "'__iter__'", ")", ":", "data", "="...
Detects if the data was changed. This is added in 1.6.
[ "Detects", "if", "the", "data", "was", "changed", ".", "This", "is", "added", "in", "1", ".", "6", "." ]
train
https://github.com/mlavin/django-selectable/blob/3d7b8db0526dd924a774c599f0c665eff98fb375/selectable/forms/fields.py#L29-L42
mlavin/django-selectable
selectable/decorators.py
results_decorator
def results_decorator(func): """ Helper for constructing simple decorators around Lookup.results. func is a function which takes a request as the first parameter. If func returns an HttpReponse it is returned otherwise the original Lookup.results is returned. """ # Wrap function to maintian...
python
def results_decorator(func): """ Helper for constructing simple decorators around Lookup.results. func is a function which takes a request as the first parameter. If func returns an HttpReponse it is returned otherwise the original Lookup.results is returned. """ # Wrap function to maintian...
[ "def", "results_decorator", "(", "func", ")", ":", "# Wrap function to maintian the original doc string, etc", "@", "wraps", "(", "func", ")", "def", "decorator", "(", "lookup_cls", ")", ":", "# Construct a class decorator from the original function", "original", "=", "look...
Helper for constructing simple decorators around Lookup.results. func is a function which takes a request as the first parameter. If func returns an HttpReponse it is returned otherwise the original Lookup.results is returned.
[ "Helper", "for", "constructing", "simple", "decorators", "around", "Lookup", ".", "results", "." ]
train
https://github.com/mlavin/django-selectable/blob/3d7b8db0526dd924a774c599f0c665eff98fb375/selectable/decorators.py#L16-L39
mlavin/django-selectable
selectable/decorators.py
login_required
def login_required(request): "Lookup decorator to require the user to be authenticated." user = getattr(request, 'user', None) if user is None or not user.is_authenticated: return HttpResponse(status=401)
python
def login_required(request): "Lookup decorator to require the user to be authenticated." user = getattr(request, 'user', None) if user is None or not user.is_authenticated: return HttpResponse(status=401)
[ "def", "login_required", "(", "request", ")", ":", "user", "=", "getattr", "(", "request", ",", "'user'", ",", "None", ")", "if", "user", "is", "None", "or", "not", "user", ".", "is_authenticated", ":", "return", "HttpResponse", "(", "status", "=", "401"...
Lookup decorator to require the user to be authenticated.
[ "Lookup", "decorator", "to", "require", "the", "user", "to", "be", "authenticated", "." ]
train
https://github.com/mlavin/django-selectable/blob/3d7b8db0526dd924a774c599f0c665eff98fb375/selectable/decorators.py#L50-L54
mlavin/django-selectable
selectable/decorators.py
staff_member_required
def staff_member_required(request): "Lookup decorator to require the user is a staff member." user = getattr(request, 'user', None) if user is None or not user.is_authenticated: return HttpResponse(status=401) # Unauthorized elif not user.is_staff: return HttpResponseForbidden()
python
def staff_member_required(request): "Lookup decorator to require the user is a staff member." user = getattr(request, 'user', None) if user is None or not user.is_authenticated: return HttpResponse(status=401) # Unauthorized elif not user.is_staff: return HttpResponseForbidden()
[ "def", "staff_member_required", "(", "request", ")", ":", "user", "=", "getattr", "(", "request", ",", "'user'", ",", "None", ")", "if", "user", "is", "None", "or", "not", "user", ".", "is_authenticated", ":", "return", "HttpResponse", "(", "status", "=", ...
Lookup decorator to require the user is a staff member.
[ "Lookup", "decorator", "to", "require", "the", "user", "is", "a", "staff", "member", "." ]
train
https://github.com/mlavin/django-selectable/blob/3d7b8db0526dd924a774c599f0c665eff98fb375/selectable/decorators.py#L58-L64
mlavin/django-selectable
selectable/base.py
LookupBase.format_item
def format_item(self, item): "Construct result dictionary for the match item." result = { 'id': self.get_item_id(item), 'value': self.get_item_value(item), 'label': self.get_item_label(item), } for key in settings.SELECTABLE_ESCAPED_KEYS: i...
python
def format_item(self, item): "Construct result dictionary for the match item." result = { 'id': self.get_item_id(item), 'value': self.get_item_value(item), 'label': self.get_item_label(item), } for key in settings.SELECTABLE_ESCAPED_KEYS: i...
[ "def", "format_item", "(", "self", ",", "item", ")", ":", "result", "=", "{", "'id'", ":", "self", ".", "get_item_id", "(", "item", ")", ",", "'value'", ":", "self", ".", "get_item_value", "(", "item", ")", ",", "'label'", ":", "self", ".", "get_item...
Construct result dictionary for the match item.
[ "Construct", "result", "dictionary", "for", "the", "match", "item", "." ]
train
https://github.com/mlavin/django-selectable/blob/3d7b8db0526dd924a774c599f0c665eff98fb375/selectable/base.py#L67-L77
mlavin/django-selectable
selectable/base.py
LookupBase.paginate_results
def paginate_results(self, results, options): "Return a django.core.paginator.Page of results." limit = options.get('limit', settings.SELECTABLE_MAX_LIMIT) paginator = Paginator(results, limit) page = options.get('page', 1) try: results = paginator.page(page) ...
python
def paginate_results(self, results, options): "Return a django.core.paginator.Page of results." limit = options.get('limit', settings.SELECTABLE_MAX_LIMIT) paginator = Paginator(results, limit) page = options.get('page', 1) try: results = paginator.page(page) ...
[ "def", "paginate_results", "(", "self", ",", "results", ",", "options", ")", ":", "limit", "=", "options", ".", "get", "(", "'limit'", ",", "settings", ".", "SELECTABLE_MAX_LIMIT", ")", "paginator", "=", "Paginator", "(", "results", ",", "limit", ")", "pag...
Return a django.core.paginator.Page of results.
[ "Return", "a", "django", ".", "core", ".", "paginator", ".", "Page", "of", "results", "." ]
train
https://github.com/mlavin/django-selectable/blob/3d7b8db0526dd924a774c599f0c665eff98fb375/selectable/base.py#L79-L88
mlavin/django-selectable
selectable/base.py
LookupBase.results
def results(self, request): "Match results to given term and return the serialized HttpResponse." results = {} form = self.form(request.GET) if form.is_valid(): options = form.cleaned_data term = options.get('term', '') raw_data = self.get_query(reques...
python
def results(self, request): "Match results to given term and return the serialized HttpResponse." results = {} form = self.form(request.GET) if form.is_valid(): options = form.cleaned_data term = options.get('term', '') raw_data = self.get_query(reques...
[ "def", "results", "(", "self", ",", "request", ")", ":", "results", "=", "{", "}", "form", "=", "self", ".", "form", "(", "request", ".", "GET", ")", "if", "form", ".", "is_valid", "(", ")", ":", "options", "=", "form", ".", "cleaned_data", "term",...
Match results to given term and return the serialized HttpResponse.
[ "Match", "results", "to", "given", "term", "and", "return", "the", "serialized", "HttpResponse", "." ]
train
https://github.com/mlavin/django-selectable/blob/3d7b8db0526dd924a774c599f0c665eff98fb375/selectable/base.py#L90-L99
mlavin/django-selectable
selectable/base.py
LookupBase.format_results
def format_results(self, raw_data, options): ''' Returns a python structure that later gets serialized. raw_data full list of objects matching the search term options a dictionary of the given options ''' page_data = self.paginate_results(raw_data,...
python
def format_results(self, raw_data, options): ''' Returns a python structure that later gets serialized. raw_data full list of objects matching the search term options a dictionary of the given options ''' page_data = self.paginate_results(raw_data,...
[ "def", "format_results", "(", "self", ",", "raw_data", ",", "options", ")", ":", "page_data", "=", "self", ".", "paginate_results", "(", "raw_data", ",", "options", ")", "results", "=", "{", "}", "meta", "=", "options", ".", "copy", "(", ")", "meta", "...
Returns a python structure that later gets serialized. raw_data full list of objects matching the search term options a dictionary of the given options
[ "Returns", "a", "python", "structure", "that", "later", "gets", "serialized", ".", "raw_data", "full", "list", "of", "objects", "matching", "the", "search", "term", "options", "a", "dictionary", "of", "the", "given", "options" ]
train
https://github.com/mlavin/django-selectable/blob/3d7b8db0526dd924a774c599f0c665eff98fb375/selectable/base.py#L101-L119
mlavin/django-selectable
selectable/forms/base.py
import_lookup_class
def import_lookup_class(lookup_class): """ Import lookup_class as a dotted base and ensure it extends LookupBase """ from selectable.base import LookupBase if isinstance(lookup_class, string_types): mod_str, cls_str = lookup_class.rsplit('.', 1) mod = import_module(mod_str) l...
python
def import_lookup_class(lookup_class): """ Import lookup_class as a dotted base and ensure it extends LookupBase """ from selectable.base import LookupBase if isinstance(lookup_class, string_types): mod_str, cls_str = lookup_class.rsplit('.', 1) mod = import_module(mod_str) l...
[ "def", "import_lookup_class", "(", "lookup_class", ")", ":", "from", "selectable", ".", "base", "import", "LookupBase", "if", "isinstance", "(", "lookup_class", ",", "string_types", ")", ":", "mod_str", ",", "cls_str", "=", "lookup_class", ".", "rsplit", "(", ...
Import lookup_class as a dotted base and ensure it extends LookupBase
[ "Import", "lookup_class", "as", "a", "dotted", "base", "and", "ensure", "it", "extends", "LookupBase" ]
train
https://github.com/mlavin/django-selectable/blob/3d7b8db0526dd924a774c599f0c665eff98fb375/selectable/forms/base.py#L34-L45
mlavin/django-selectable
selectable/forms/base.py
BaseLookupForm.clean_limit
def clean_limit(self): "Ensure given limit is less than default if defined" limit = self.cleaned_data.get('limit', None) if (settings.SELECTABLE_MAX_LIMIT is not None and (not limit or limit > settings.SELECTABLE_MAX_LIMIT)): limit = settings.SELECTABLE_MAX_LIMIT ...
python
def clean_limit(self): "Ensure given limit is less than default if defined" limit = self.cleaned_data.get('limit', None) if (settings.SELECTABLE_MAX_LIMIT is not None and (not limit or limit > settings.SELECTABLE_MAX_LIMIT)): limit = settings.SELECTABLE_MAX_LIMIT ...
[ "def", "clean_limit", "(", "self", ")", ":", "limit", "=", "self", ".", "cleaned_data", ".", "get", "(", "'limit'", ",", "None", ")", "if", "(", "settings", ".", "SELECTABLE_MAX_LIMIT", "is", "not", "None", "and", "(", "not", "limit", "or", "limit", ">...
Ensure given limit is less than default if defined
[ "Ensure", "given", "limit", "is", "less", "than", "default", "if", "defined" ]
train
https://github.com/mlavin/django-selectable/blob/3d7b8db0526dd924a774c599f0c665eff98fb375/selectable/forms/base.py#L21-L27
desbma/sacad
sacad/sources/google_images.py
GoogleImagesWebScrapeCoverSource.getSearchUrl
def getSearchUrl(self, album, artist): """ See CoverSource.getSearchUrl. """ # build request url params = collections.OrderedDict() params["gbv"] = "2" params["q"] = "\"%s\" \"%s\" front cover" % (artist, album) if abs(self.target_size - 500) < 300: params["tbs"] = "isz:m" elif self.ta...
python
def getSearchUrl(self, album, artist): """ See CoverSource.getSearchUrl. """ # build request url params = collections.OrderedDict() params["gbv"] = "2" params["q"] = "\"%s\" \"%s\" front cover" % (artist, album) if abs(self.target_size - 500) < 300: params["tbs"] = "isz:m" elif self.ta...
[ "def", "getSearchUrl", "(", "self", ",", "album", ",", "artist", ")", ":", "# build request url", "params", "=", "collections", ".", "OrderedDict", "(", ")", "params", "[", "\"gbv\"", "]", "=", "\"2\"", "params", "[", "\"q\"", "]", "=", "\"\\\"%s\\\" \\\"%s\...
See CoverSource.getSearchUrl.
[ "See", "CoverSource", ".", "getSearchUrl", "." ]
train
https://github.com/desbma/sacad/blob/a7a010c4d9618a0c90927f1acb530101ca05fac4/sacad/sources/google_images.py#L33-L44
desbma/sacad
sacad/sources/google_images.py
GoogleImagesWebScrapeCoverSource.parseResults
async def parseResults(self, api_data): """ See CoverSource.parseResults. """ results = [] # parse HTML and get results parser = lxml.etree.HTMLParser() html = lxml.etree.XML(api_data.decode("latin-1"), parser) for rank, result in enumerate(__class__.RESULTS_SELECTOR(html), 1): # extract...
python
async def parseResults(self, api_data): """ See CoverSource.parseResults. """ results = [] # parse HTML and get results parser = lxml.etree.HTMLParser() html = lxml.etree.XML(api_data.decode("latin-1"), parser) for rank, result in enumerate(__class__.RESULTS_SELECTOR(html), 1): # extract...
[ "async", "def", "parseResults", "(", "self", ",", "api_data", ")", ":", "results", "=", "[", "]", "# parse HTML and get results", "parser", "=", "lxml", ".", "etree", ".", "HTMLParser", "(", ")", "html", "=", "lxml", ".", "etree", ".", "XML", "(", "api_d...
See CoverSource.parseResults.
[ "See", "CoverSource", ".", "parseResults", "." ]
train
https://github.com/desbma/sacad/blob/a7a010c4d9618a0c90927f1acb530101ca05fac4/sacad/sources/google_images.py#L50-L98
desbma/sacad
sacad/rate_watcher.py
AccessRateWatcher.waitAccessAsync
async def waitAccessAsync(self): """ Wait the needed time before sending a request to honor rate limit. """ async with self.lock: while True: last_access_ts = self.__getLastAccess() if last_access_ts is not None: now = time.time() last_access_ts = last_access_ts[0] ...
python
async def waitAccessAsync(self): """ Wait the needed time before sending a request to honor rate limit. """ async with self.lock: while True: last_access_ts = self.__getLastAccess() if last_access_ts is not None: now = time.time() last_access_ts = last_access_ts[0] ...
[ "async", "def", "waitAccessAsync", "(", "self", ")", ":", "async", "with", "self", ".", "lock", ":", "while", "True", ":", "last_access_ts", "=", "self", ".", "__getLastAccess", "(", ")", "if", "last_access_ts", "is", "not", "None", ":", "now", "=", "tim...
Wait the needed time before sending a request to honor rate limit.
[ "Wait", "the", "needed", "time", "before", "sending", "a", "request", "to", "honor", "rate", "limit", "." ]
train
https://github.com/desbma/sacad/blob/a7a010c4d9618a0c90927f1acb530101ca05fac4/sacad/rate_watcher.py#L28-L53
desbma/sacad
sacad/rate_watcher.py
AccessRateWatcher.__access
def __access(self, ts): """ Record an API access. """ with self.connection: self.connection.execute("INSERT OR REPLACE INTO access_timestamp (timestamp, domain) VALUES (?, ?)", (ts, self.domain))
python
def __access(self, ts): """ Record an API access. """ with self.connection: self.connection.execute("INSERT OR REPLACE INTO access_timestamp (timestamp, domain) VALUES (?, ?)", (ts, self.domain))
[ "def", "__access", "(", "self", ",", "ts", ")", ":", "with", "self", ".", "connection", ":", "self", ".", "connection", ".", "execute", "(", "\"INSERT OR REPLACE INTO access_timestamp (timestamp, domain) VALUES (?, ?)\"", ",", "(", "ts", ",", "self", ".", "domain"...
Record an API access.
[ "Record", "an", "API", "access", "." ]
train
https://github.com/desbma/sacad/blob/a7a010c4d9618a0c90927f1acb530101ca05fac4/sacad/rate_watcher.py#L62-L66
desbma/sacad
sacad/http_helpers.py
aiohttp_socket_timeout
def aiohttp_socket_timeout(socket_timeout_s): """ Return a aiohttp.ClientTimeout object with only socket timeouts set. """ return aiohttp.ClientTimeout(total=None, connect=None, sock_connect=socket_timeout_s, sock_read=sock...
python
def aiohttp_socket_timeout(socket_timeout_s): """ Return a aiohttp.ClientTimeout object with only socket timeouts set. """ return aiohttp.ClientTimeout(total=None, connect=None, sock_connect=socket_timeout_s, sock_read=sock...
[ "def", "aiohttp_socket_timeout", "(", "socket_timeout_s", ")", ":", "return", "aiohttp", ".", "ClientTimeout", "(", "total", "=", "None", ",", "connect", "=", "None", ",", "sock_connect", "=", "socket_timeout_s", ",", "sock_read", "=", "socket_timeout_s", ")" ]
Return a aiohttp.ClientTimeout object with only socket timeouts set.
[ "Return", "a", "aiohttp", ".", "ClientTimeout", "object", "with", "only", "socket", "timeouts", "set", "." ]
train
https://github.com/desbma/sacad/blob/a7a010c4d9618a0c90927f1acb530101ca05fac4/sacad/http_helpers.py#L15-L20
desbma/sacad
sacad/http_helpers.py
Http.query
async def query(self, url, *, post_data=None, headers=None, verify=True, cache=None, pre_cache_callback=None): """ Send a GET/POST request or get data from cache, retry if it fails, and return a tuple of store in cache callback, response content. """ async def store_in_cache_callback(): pass if cache ...
python
async def query(self, url, *, post_data=None, headers=None, verify=True, cache=None, pre_cache_callback=None): """ Send a GET/POST request or get data from cache, retry if it fails, and return a tuple of store in cache callback, response content. """ async def store_in_cache_callback(): pass if cache ...
[ "async", "def", "query", "(", "self", ",", "url", ",", "*", ",", "post_data", "=", "None", ",", "headers", "=", "None", ",", "verify", "=", "True", ",", "cache", "=", "None", ",", "pre_cache_callback", "=", "None", ")", ":", "async", "def", "store_in...
Send a GET/POST request or get data from cache, retry if it fails, and return a tuple of store in cache callback, response content.
[ "Send", "a", "GET", "/", "POST", "request", "or", "get", "data", "from", "cache", "retry", "if", "it", "fails", "and", "return", "a", "tuple", "of", "store", "in", "cache", "callback", "response", "content", "." ]
train
https://github.com/desbma/sacad/blob/a7a010c4d9618a0c90927f1acb530101ca05fac4/sacad/http_helpers.py#L52-L128
desbma/sacad
sacad/http_helpers.py
Http.isReachable
async def isReachable(self, url, *, headers=None, verify=True, response_headers=None, cache=None): """ Send a HEAD request with short timeout or get data from cache, return True if ressource has 2xx status code, False instead. """ if (cache is not None) and (url in cache): # try from cache first sel...
python
async def isReachable(self, url, *, headers=None, verify=True, response_headers=None, cache=None): """ Send a HEAD request with short timeout or get data from cache, return True if ressource has 2xx status code, False instead. """ if (cache is not None) and (url in cache): # try from cache first sel...
[ "async", "def", "isReachable", "(", "self", ",", "url", ",", "*", ",", "headers", "=", "None", ",", "verify", "=", "True", ",", "response_headers", "=", "None", ",", "cache", "=", "None", ")", ":", "if", "(", "cache", "is", "not", "None", ")", "and...
Send a HEAD request with short timeout or get data from cache, return True if ressource has 2xx status code, False instead.
[ "Send", "a", "HEAD", "request", "with", "short", "timeout", "or", "get", "data", "from", "cache", "return", "True", "if", "ressource", "has", "2xx", "status", "code", "False", "instead", "." ]
train
https://github.com/desbma/sacad/blob/a7a010c4d9618a0c90927f1acb530101ca05fac4/sacad/http_helpers.py#L130-L187
desbma/sacad
sacad/http_helpers.py
Http.fastStreamedQuery
async def fastStreamedQuery(self, url, *, headers=None, verify=True): """ Send a GET request with short timeout, do not retry, and return streamed response. """ response = await self.session.get(url, headers=self._buildHeaders(headers), ...
python
async def fastStreamedQuery(self, url, *, headers=None, verify=True): """ Send a GET request with short timeout, do not retry, and return streamed response. """ response = await self.session.get(url, headers=self._buildHeaders(headers), ...
[ "async", "def", "fastStreamedQuery", "(", "self", ",", "url", ",", "*", ",", "headers", "=", "None", ",", "verify", "=", "True", ")", ":", "response", "=", "await", "self", ".", "session", ".", "get", "(", "url", ",", "headers", "=", "self", ".", "...
Send a GET request with short timeout, do not retry, and return streamed response.
[ "Send", "a", "GET", "request", "with", "short", "timeout", "do", "not", "retry", "and", "return", "streamed", "response", "." ]
train
https://github.com/desbma/sacad/blob/a7a010c4d9618a0c90927f1acb530101ca05fac4/sacad/http_helpers.py#L189-L198
desbma/sacad
sacad/sources/lastfm.py
LastFmCoverSource.getSearchUrl
def getSearchUrl(self, album, artist): """ See CoverSource.getSearchUrl. """ # build request url params = collections.OrderedDict() params["method"] = "album.getinfo" params["api_key"] = __class__.API_KEY params["album"] = album params["artist"] = artist return __class__.assembleUrl(__c...
python
def getSearchUrl(self, album, artist): """ See CoverSource.getSearchUrl. """ # build request url params = collections.OrderedDict() params["method"] = "album.getinfo" params["api_key"] = __class__.API_KEY params["album"] = album params["artist"] = artist return __class__.assembleUrl(__c...
[ "def", "getSearchUrl", "(", "self", ",", "album", ",", "artist", ")", ":", "# build request url", "params", "=", "collections", ".", "OrderedDict", "(", ")", "params", "[", "\"method\"", "]", "=", "\"album.getinfo\"", "params", "[", "\"api_key\"", "]", "=", ...
See CoverSource.getSearchUrl.
[ "See", "CoverSource", ".", "getSearchUrl", "." ]
train
https://github.com/desbma/sacad/blob/a7a010c4d9618a0c90927f1acb530101ca05fac4/sacad/sources/lastfm.py#L36-L45
desbma/sacad
sacad/sources/lastfm.py
LastFmCoverSource.processQueryString
def processQueryString(self, s): """ See CoverSource.processQueryString. """ char_blacklist = set(string.punctuation) char_blacklist.remove("'") char_blacklist.remove("&") char_blacklist = frozenset(char_blacklist) return __class__.unpunctuate(s.lower(), char_blacklist=char_blacklist)
python
def processQueryString(self, s): """ See CoverSource.processQueryString. """ char_blacklist = set(string.punctuation) char_blacklist.remove("'") char_blacklist.remove("&") char_blacklist = frozenset(char_blacklist) return __class__.unpunctuate(s.lower(), char_blacklist=char_blacklist)
[ "def", "processQueryString", "(", "self", ",", "s", ")", ":", "char_blacklist", "=", "set", "(", "string", ".", "punctuation", ")", "char_blacklist", ".", "remove", "(", "\"'\"", ")", "char_blacklist", ".", "remove", "(", "\"&\"", ")", "char_blacklist", "=",...
See CoverSource.processQueryString.
[ "See", "CoverSource", ".", "processQueryString", "." ]
train
https://github.com/desbma/sacad/blob/a7a010c4d9618a0c90927f1acb530101ca05fac4/sacad/sources/lastfm.py#L47-L53
desbma/sacad
sacad/sources/lastfm.py
LastFmCoverSource.parseResults
async def parseResults(self, api_data): """ See CoverSource.parseResults. """ results = [] # get xml results list xml_text = api_data.decode("utf-8") xml_root = xml.etree.ElementTree.fromstring(xml_text) status = xml_root.get("status") if status != "ok": raise Exception("Unexpected La...
python
async def parseResults(self, api_data): """ See CoverSource.parseResults. """ results = [] # get xml results list xml_text = api_data.decode("utf-8") xml_root = xml.etree.ElementTree.fromstring(xml_text) status = xml_root.get("status") if status != "ok": raise Exception("Unexpected La...
[ "async", "def", "parseResults", "(", "self", ",", "api_data", ")", ":", "results", "=", "[", "]", "# get xml results list", "xml_text", "=", "api_data", ".", "decode", "(", "\"utf-8\"", ")", "xml_root", "=", "xml", ".", "etree", ".", "ElementTree", ".", "f...
See CoverSource.parseResults.
[ "See", "CoverSource", ".", "parseResults", "." ]
train
https://github.com/desbma/sacad/blob/a7a010c4d9618a0c90927f1acb530101ca05fac4/sacad/sources/lastfm.py#L55-L96
desbma/sacad
sacad/__init__.py
search_and_download
async def search_and_download(album, artist, format, size, out_filepath, *, size_tolerance_prct, amazon_tlds, no_lq_sources, async_loop): """ Search and download a cover, return True if success, False instead. """ # register sources source_args = (size, size_tolerance_prct) cover_s...
python
async def search_and_download(album, artist, format, size, out_filepath, *, size_tolerance_prct, amazon_tlds, no_lq_sources, async_loop): """ Search and download a cover, return True if success, False instead. """ # register sources source_args = (size, size_tolerance_prct) cover_s...
[ "async", "def", "search_and_download", "(", "album", ",", "artist", ",", "format", ",", "size", ",", "out_filepath", ",", "*", ",", "size_tolerance_prct", ",", "amazon_tlds", ",", "no_lq_sources", ",", "async_loop", ")", ":", "# register sources", "source_args", ...
Search and download a cover, return True if success, False instead.
[ "Search", "and", "download", "a", "cover", "return", "True", "if", "success", "False", "instead", "." ]
train
https://github.com/desbma/sacad/blob/a7a010c4d9618a0c90927f1acb530101ca05fac4/sacad/__init__.py#L20-L70
desbma/sacad
sacad/sources/amazondigital.py
AmazonDigitalCoverSource.getSearchUrl
def getSearchUrl(self, album, artist): """ See CoverSource.getSearchUrl. """ url = "%s/search" % (__class__.BASE_URL) params = collections.OrderedDict() params["search-alias"] = "digital-music" params["field-keywords"] = " ".join((artist, album)) params["sort"] = "relevancerank" return __cla...
python
def getSearchUrl(self, album, artist): """ See CoverSource.getSearchUrl. """ url = "%s/search" % (__class__.BASE_URL) params = collections.OrderedDict() params["search-alias"] = "digital-music" params["field-keywords"] = " ".join((artist, album)) params["sort"] = "relevancerank" return __cla...
[ "def", "getSearchUrl", "(", "self", ",", "album", ",", "artist", ")", ":", "url", "=", "\"%s/search\"", "%", "(", "__class__", ".", "BASE_URL", ")", "params", "=", "collections", ".", "OrderedDict", "(", ")", "params", "[", "\"search-alias\"", "]", "=", ...
See CoverSource.getSearchUrl.
[ "See", "CoverSource", ".", "getSearchUrl", "." ]
train
https://github.com/desbma/sacad/blob/a7a010c4d9618a0c90927f1acb530101ca05fac4/sacad/sources/amazondigital.py#L58-L65
desbma/sacad
sacad/sources/amazondigital.py
AmazonDigitalCoverSource.parseResults
async def parseResults(self, api_data): """ See CoverSource.parseResults. """ results = [] # parse page parser = lxml.etree.HTMLParser() html = lxml.etree.XML(api_data.decode("utf-8"), parser) for page_struct_version, result_selector in enumerate(__class__.RESULTS_SELECTORS): result_node...
python
async def parseResults(self, api_data): """ See CoverSource.parseResults. """ results = [] # parse page parser = lxml.etree.HTMLParser() html = lxml.etree.XML(api_data.decode("utf-8"), parser) for page_struct_version, result_selector in enumerate(__class__.RESULTS_SELECTORS): result_node...
[ "async", "def", "parseResults", "(", "self", ",", "api_data", ")", ":", "results", "=", "[", "]", "# parse page", "parser", "=", "lxml", ".", "etree", ".", "HTMLParser", "(", ")", "html", "=", "lxml", ".", "etree", ".", "XML", "(", "api_data", ".", "...
See CoverSource.parseResults.
[ "See", "CoverSource", ".", "parseResults", "." ]
train
https://github.com/desbma/sacad/blob/a7a010c4d9618a0c90927f1acb530101ca05fac4/sacad/sources/amazondigital.py#L71-L132
desbma/sacad
sacad/sources/amazondigital.py
AmazonDigitalCoverSource.generateImgUrls
def generateImgUrls(self, product_id, dynapi_key, format_id, slice_count): """ Generate URLs for slice_count^2 subimages of a product. """ for x in range(slice_count): for y in range(slice_count): yield ("http://z2-ec2.images-amazon.com/R/1/a=" + product_id + "+c=" + dynapi_key + ...
python
def generateImgUrls(self, product_id, dynapi_key, format_id, slice_count): """ Generate URLs for slice_count^2 subimages of a product. """ for x in range(slice_count): for y in range(slice_count): yield ("http://z2-ec2.images-amazon.com/R/1/a=" + product_id + "+c=" + dynapi_key + ...
[ "def", "generateImgUrls", "(", "self", ",", "product_id", ",", "dynapi_key", ",", "format_id", ",", "slice_count", ")", ":", "for", "x", "in", "range", "(", "slice_count", ")", ":", "for", "y", "in", "range", "(", "slice_count", ")", ":", "yield", "(", ...
Generate URLs for slice_count^2 subimages of a product.
[ "Generate", "URLs", "for", "slice_count^2", "subimages", "of", "a", "product", "." ]
train
https://github.com/desbma/sacad/blob/a7a010c4d9618a0c90927f1acb530101ca05fac4/sacad/sources/amazondigital.py#L134-L140
desbma/sacad
sacad/redo.py
retrier
def retrier(*, max_attempts, sleeptime, max_sleeptime, sleepscale=1.5, jitter=0.2): """ Generator yielding time to wait for, after the attempt, if it failed. """ assert(max_attempts > 1) assert(sleeptime >= 0) assert(0 <= jitter <= sleeptime) assert(sleepscale >= 1) cur_sleeptime = min(max_sleeptime, sleep...
python
def retrier(*, max_attempts, sleeptime, max_sleeptime, sleepscale=1.5, jitter=0.2): """ Generator yielding time to wait for, after the attempt, if it failed. """ assert(max_attempts > 1) assert(sleeptime >= 0) assert(0 <= jitter <= sleeptime) assert(sleepscale >= 1) cur_sleeptime = min(max_sleeptime, sleep...
[ "def", "retrier", "(", "*", ",", "max_attempts", ",", "sleeptime", ",", "max_sleeptime", ",", "sleepscale", "=", "1.5", ",", "jitter", "=", "0.2", ")", ":", "assert", "(", "max_attempts", ">", "1", ")", "assert", "(", "sleeptime", ">=", "0", ")", "asse...
Generator yielding time to wait for, after the attempt, if it failed.
[ "Generator", "yielding", "time", "to", "wait", "for", "after", "the", "attempt", "if", "it", "failed", "." ]
train
https://github.com/desbma/sacad/blob/a7a010c4d9618a0c90927f1acb530101ca05fac4/sacad/redo.py#L6-L18
desbma/sacad
sacad/cover.py
CoverSourceResult.get
async def get(self, target_format, target_size, size_tolerance_prct, out_filepath): """ Download cover and process it. """ if self.source_quality.value <= CoverSourceQuality.LOW.value: logging.getLogger("Cover").warning("Cover is from a potentially unreliable source and may be unrelated to the search") ...
python
async def get(self, target_format, target_size, size_tolerance_prct, out_filepath): """ Download cover and process it. """ if self.source_quality.value <= CoverSourceQuality.LOW.value: logging.getLogger("Cover").warning("Cover is from a potentially unreliable source and may be unrelated to the search") ...
[ "async", "def", "get", "(", "self", ",", "target_format", ",", "target_size", ",", "size_tolerance_prct", ",", "out_filepath", ")", ":", "if", "self", ".", "source_quality", ".", "value", "<=", "CoverSourceQuality", ".", "LOW", ".", "value", ":", "logging", ...
Download cover and process it.
[ "Download", "cover", "and", "process", "it", "." ]
train
https://github.com/desbma/sacad/blob/a7a010c4d9618a0c90927f1acb530101ca05fac4/sacad/cover.py#L114-L157
desbma/sacad
sacad/cover.py
CoverSourceResult.postProcess
def postProcess(self, images_data, new_format, new_size): """ Convert image binary data to a target format and/or size (None if no conversion needed), and return the processed data. """ if len(images_data) == 1: in_bytes = io.BytesIO(images_data[0]) img = PIL.Image.open(in_bytes) if img.mode !...
python
def postProcess(self, images_data, new_format, new_size): """ Convert image binary data to a target format and/or size (None if no conversion needed), and return the processed data. """ if len(images_data) == 1: in_bytes = io.BytesIO(images_data[0]) img = PIL.Image.open(in_bytes) if img.mode !...
[ "def", "postProcess", "(", "self", ",", "images_data", ",", "new_format", ",", "new_size", ")", ":", "if", "len", "(", "images_data", ")", "==", "1", ":", "in_bytes", "=", "io", ".", "BytesIO", "(", "images_data", "[", "0", "]", ")", "img", "=", "PIL...
Convert image binary data to a target format and/or size (None if no conversion needed), and return the processed data.
[ "Convert", "image", "binary", "data", "to", "a", "target", "format", "and", "/", "or", "size", "(", "None", "if", "no", "conversion", "needed", ")", "and", "return", "the", "processed", "data", "." ]
train
https://github.com/desbma/sacad/blob/a7a010c4d9618a0c90927f1acb530101ca05fac4/sacad/cover.py#L159-L212
desbma/sacad
sacad/cover.py
CoverSourceResult.updateImageMetadata
async def updateImageMetadata(self): """ Partially download image file(s) to get its real metadata, or get it from cache. """ assert(self.needMetadataUpdate()) width_sum, height_sum = 0, 0 # only download metadata for the needed images to get full size idxs = [] assert(is_square(len(self.urls)...
python
async def updateImageMetadata(self): """ Partially download image file(s) to get its real metadata, or get it from cache. """ assert(self.needMetadataUpdate()) width_sum, height_sum = 0, 0 # only download metadata for the needed images to get full size idxs = [] assert(is_square(len(self.urls)...
[ "async", "def", "updateImageMetadata", "(", "self", ")", ":", "assert", "(", "self", ".", "needMetadataUpdate", "(", ")", ")", "width_sum", ",", "height_sum", "=", "0", ",", "0", "# only download metadata for the needed images to get full size", "idxs", "=", "[", ...
Partially download image file(s) to get its real metadata, or get it from cache.
[ "Partially", "download", "image", "file", "(", "s", ")", "to", "get", "its", "real", "metadata", "or", "get", "it", "from", "cache", "." ]
train
https://github.com/desbma/sacad/blob/a7a010c4d9618a0c90927f1acb530101ca05fac4/sacad/cover.py#L214-L307
desbma/sacad
sacad/cover.py
CoverSourceResult.setFormatMetadata
def setFormatMetadata(self, format): """ Set format image metadata to what has been reliably identified. """ assert((self.needMetadataUpdate(CoverImageMetadata.FORMAT)) or (self.format is format)) self.format = format self.check_metadata &= ~CoverImageMetadata.FORMAT
python
def setFormatMetadata(self, format): """ Set format image metadata to what has been reliably identified. """ assert((self.needMetadataUpdate(CoverImageMetadata.FORMAT)) or (self.format is format)) self.format = format self.check_metadata &= ~CoverImageMetadata.FORMAT
[ "def", "setFormatMetadata", "(", "self", ",", "format", ")", ":", "assert", "(", "(", "self", ".", "needMetadataUpdate", "(", "CoverImageMetadata", ".", "FORMAT", ")", ")", "or", "(", "self", ".", "format", "is", "format", ")", ")", "self", ".", "format"...
Set format image metadata to what has been reliably identified.
[ "Set", "format", "image", "metadata", "to", "what", "has", "been", "reliably", "identified", "." ]
train
https://github.com/desbma/sacad/blob/a7a010c4d9618a0c90927f1acb530101ca05fac4/sacad/cover.py#L313-L318
desbma/sacad
sacad/cover.py
CoverSourceResult.setSizeMetadata
def setSizeMetadata(self, size): """ Set size image metadata to what has been reliably identified. """ assert((self.needMetadataUpdate(CoverImageMetadata.SIZE)) or (self.size == size)) self.size = size self.check_metadata &= ~CoverImageMetadata.SIZE
python
def setSizeMetadata(self, size): """ Set size image metadata to what has been reliably identified. """ assert((self.needMetadataUpdate(CoverImageMetadata.SIZE)) or (self.size == size)) self.size = size self.check_metadata &= ~CoverImageMetadata.SIZE
[ "def", "setSizeMetadata", "(", "self", ",", "size", ")", ":", "assert", "(", "(", "self", ".", "needMetadataUpdate", "(", "CoverImageMetadata", ".", "SIZE", ")", ")", "or", "(", "self", ".", "size", "==", "size", ")", ")", "self", ".", "size", "=", "...
Set size image metadata to what has been reliably identified.
[ "Set", "size", "image", "metadata", "to", "what", "has", "been", "reliably", "identified", "." ]
train
https://github.com/desbma/sacad/blob/a7a010c4d9618a0c90927f1acb530101ca05fac4/sacad/cover.py#L320-L325
desbma/sacad
sacad/cover.py
CoverSourceResult.updateSignature
async def updateSignature(self): """ Calculate a cover's "signature" using its thumbnail url. """ assert(self.thumbnail_sig is None) if self.thumbnail_url is None: logging.getLogger("Cover").warning("No thumbnail available for %s" % (self)) return # download logging.getLogger("Cover")....
python
async def updateSignature(self): """ Calculate a cover's "signature" using its thumbnail url. """ assert(self.thumbnail_sig is None) if self.thumbnail_url is None: logging.getLogger("Cover").warning("No thumbnail available for %s" % (self)) return # download logging.getLogger("Cover")....
[ "async", "def", "updateSignature", "(", "self", ")", ":", "assert", "(", "self", ".", "thumbnail_sig", "is", "None", ")", "if", "self", ".", "thumbnail_url", "is", "None", ":", "logging", ".", "getLogger", "(", "\"Cover\"", ")", ".", "warning", "(", "\"N...
Calculate a cover's "signature" using its thumbnail url.
[ "Calculate", "a", "cover", "s", "signature", "using", "its", "thumbnail", "url", "." ]
train
https://github.com/desbma/sacad/blob/a7a010c4d9618a0c90927f1acb530101ca05fac4/sacad/cover.py#L327-L363
desbma/sacad
sacad/cover.py
CoverSourceResult.compare
def compare(first, second, *, target_size, size_tolerance_prct): """ Compare cover relevance/quality. Return -1 if first is a worst match than second, 1 otherwise, or 0 if cover can't be discriminated. This code is responsible for comparing two cover results to identify the best one, and is used to so...
python
def compare(first, second, *, target_size, size_tolerance_prct): """ Compare cover relevance/quality. Return -1 if first is a worst match than second, 1 otherwise, or 0 if cover can't be discriminated. This code is responsible for comparing two cover results to identify the best one, and is used to so...
[ "def", "compare", "(", "first", ",", "second", ",", "*", ",", "target_size", ",", "size_tolerance_prct", ")", ":", "for", "c", "in", "(", "first", ",", "second", ")", ":", "assert", "(", "c", ".", "format", "is", "not", "None", ")", "assert", "(", ...
Compare cover relevance/quality. Return -1 if first is a worst match than second, 1 otherwise, or 0 if cover can't be discriminated. This code is responsible for comparing two cover results to identify the best one, and is used to sort all results. It is probably the most important piece of code of this t...
[ "Compare", "cover", "relevance", "/", "quality", "." ]
train
https://github.com/desbma/sacad/blob/a7a010c4d9618a0c90927f1acb530101ca05fac4/sacad/cover.py#L366-L457
desbma/sacad
sacad/cover.py
CoverSourceResult.crunch
async def crunch(image_data, format, silent=False): """ Crunch image data, and return the processed data, or orignal data if operation failed. """ if (((format is CoverImageFormat.PNG) and (not HAS_OPTIPNG)) or ((format is CoverImageFormat.JPEG) and (not HAS_JPEGOPTIM))): return image_data ...
python
async def crunch(image_data, format, silent=False): """ Crunch image data, and return the processed data, or orignal data if operation failed. """ if (((format is CoverImageFormat.PNG) and (not HAS_OPTIPNG)) or ((format is CoverImageFormat.JPEG) and (not HAS_JPEGOPTIM))): return image_data ...
[ "async", "def", "crunch", "(", "image_data", ",", "format", ",", "silent", "=", "False", ")", ":", "if", "(", "(", "(", "format", "is", "CoverImageFormat", ".", "PNG", ")", "and", "(", "not", "HAS_OPTIPNG", ")", ")", "or", "(", "(", "format", "is", ...
Crunch image data, and return the processed data, or orignal data if operation failed.
[ "Crunch", "image", "data", "and", "return", "the", "processed", "data", "or", "orignal", "data", "if", "operation", "failed", "." ]
train
https://github.com/desbma/sacad/blob/a7a010c4d9618a0c90927f1acb530101ca05fac4/sacad/cover.py#L460-L491
desbma/sacad
sacad/cover.py
CoverSourceResult.guessImageMetadataFromData
def guessImageMetadataFromData(img_data): """ Identify an image format and size from its first bytes. """ format, width, height = None, None, None img_stream = io.BytesIO(img_data) try: img = PIL.Image.open(img_stream) except IOError: format = imghdr.what(None, h=img_data) format =...
python
def guessImageMetadataFromData(img_data): """ Identify an image format and size from its first bytes. """ format, width, height = None, None, None img_stream = io.BytesIO(img_data) try: img = PIL.Image.open(img_stream) except IOError: format = imghdr.what(None, h=img_data) format =...
[ "def", "guessImageMetadataFromData", "(", "img_data", ")", ":", "format", ",", "width", ",", "height", "=", "None", ",", "None", ",", "None", "img_stream", "=", "io", ".", "BytesIO", "(", "img_data", ")", "try", ":", "img", "=", "PIL", ".", "Image", "....
Identify an image format and size from its first bytes.
[ "Identify", "an", "image", "format", "and", "size", "from", "its", "first", "bytes", "." ]
train
https://github.com/desbma/sacad/blob/a7a010c4d9618a0c90927f1acb530101ca05fac4/sacad/cover.py#L494-L507
desbma/sacad
sacad/cover.py
CoverSourceResult.guessImageMetadataFromHttpData
async def guessImageMetadataFromHttpData(response): """ Identify an image format and size from the beginning of its HTTP data. """ metadata = None img_data = bytearray() while len(img_data) < CoverSourceResult.MAX_FILE_METADATA_PEEK_SIZE: new_img_data = await response.content.read(__class__.METAD...
python
async def guessImageMetadataFromHttpData(response): """ Identify an image format and size from the beginning of its HTTP data. """ metadata = None img_data = bytearray() while len(img_data) < CoverSourceResult.MAX_FILE_METADATA_PEEK_SIZE: new_img_data = await response.content.read(__class__.METAD...
[ "async", "def", "guessImageMetadataFromHttpData", "(", "response", ")", ":", "metadata", "=", "None", "img_data", "=", "bytearray", "(", ")", "while", "len", "(", "img_data", ")", "<", "CoverSourceResult", ".", "MAX_FILE_METADATA_PEEK_SIZE", ":", "new_img_data", "...
Identify an image format and size from the beginning of its HTTP data.
[ "Identify", "an", "image", "format", "and", "size", "from", "the", "beginning", "of", "its", "HTTP", "data", "." ]
train
https://github.com/desbma/sacad/blob/a7a010c4d9618a0c90927f1acb530101ca05fac4/sacad/cover.py#L510-L525
desbma/sacad
sacad/cover.py
CoverSourceResult.guessImageFormatFromHttpResponse
def guessImageFormatFromHttpResponse(response): """ Guess file format from HTTP response, return format or None. """ extensions = [] # try to guess extension from response content-type header try: content_type = response.headers["Content-Type"] except KeyError: pass else: ext ...
python
def guessImageFormatFromHttpResponse(response): """ Guess file format from HTTP response, return format or None. """ extensions = [] # try to guess extension from response content-type header try: content_type = response.headers["Content-Type"] except KeyError: pass else: ext ...
[ "def", "guessImageFormatFromHttpResponse", "(", "response", ")", ":", "extensions", "=", "[", "]", "# try to guess extension from response content-type header", "try", ":", "content_type", "=", "response", ".", "headers", "[", "\"Content-Type\"", "]", "except", "KeyError"...
Guess file format from HTTP response, return format or None.
[ "Guess", "file", "format", "from", "HTTP", "response", "return", "format", "or", "None", "." ]
train
https://github.com/desbma/sacad/blob/a7a010c4d9618a0c90927f1acb530101ca05fac4/sacad/cover.py#L528-L554
desbma/sacad
sacad/cover.py
CoverSourceResult.preProcessForComparison
async def preProcessForComparison(results, target_size, size_tolerance_prct): """ Process results to prepare them for future comparison and sorting. """ # find reference (=image most likely to match target cover ignoring factors like size and format) reference = None for result in results: if resu...
python
async def preProcessForComparison(results, target_size, size_tolerance_prct): """ Process results to prepare them for future comparison and sorting. """ # find reference (=image most likely to match target cover ignoring factors like size and format) reference = None for result in results: if resu...
[ "async", "def", "preProcessForComparison", "(", "results", ",", "target_size", ",", "size_tolerance_prct", ")", ":", "# find reference (=image most likely to match target cover ignoring factors like size and format)", "reference", "=", "None", "for", "result", "in", "results", ...
Process results to prepare them for future comparison and sorting.
[ "Process", "results", "to", "prepare", "them", "for", "future", "comparison", "and", "sorting", "." ]
train
https://github.com/desbma/sacad/blob/a7a010c4d9618a0c90927f1acb530101ca05fac4/sacad/cover.py#L557-L627
desbma/sacad
sacad/cover.py
CoverSourceResult.computeImgSignature
def computeImgSignature(image_data): """ Calculate an image signature. This is similar to ahash but uses 3 colors components See: https://github.com/JohannesBuchner/imagehash/blob/4.0/imagehash/__init__.py#L125 """ parser = PIL.ImageFile.Parser() parser.feed(image_data) img = parser.cl...
python
def computeImgSignature(image_data): """ Calculate an image signature. This is similar to ahash but uses 3 colors components See: https://github.com/JohannesBuchner/imagehash/blob/4.0/imagehash/__init__.py#L125 """ parser = PIL.ImageFile.Parser() parser.feed(image_data) img = parser.cl...
[ "def", "computeImgSignature", "(", "image_data", ")", ":", "parser", "=", "PIL", ".", "ImageFile", ".", "Parser", "(", ")", "parser", ".", "feed", "(", "image_data", ")", "img", "=", "parser", ".", "close", "(", ")", "target_size", "=", "(", "__class__",...
Calculate an image signature. This is similar to ahash but uses 3 colors components See: https://github.com/JohannesBuchner/imagehash/blob/4.0/imagehash/__init__.py#L125
[ "Calculate", "an", "image", "signature", "." ]
train
https://github.com/desbma/sacad/blob/a7a010c4d9618a0c90927f1acb530101ca05fac4/sacad/cover.py#L630-L657
desbma/sacad
sacad/recurse.py
analyze_lib
def analyze_lib(lib_dir, cover_filename, *, ignore_existing=False): """ Recursively analyze library, and return a dict of path -> (artist, album). """ work = {} stats = collections.OrderedDict(((k, 0) for k in("files", "albums", "missing covers", "errors"))) with tqdm.tqdm(desc="Analyzing library", ...
python
def analyze_lib(lib_dir, cover_filename, *, ignore_existing=False): """ Recursively analyze library, and return a dict of path -> (artist, album). """ work = {} stats = collections.OrderedDict(((k, 0) for k in("files", "albums", "missing covers", "errors"))) with tqdm.tqdm(desc="Analyzing library", ...
[ "def", "analyze_lib", "(", "lib_dir", ",", "cover_filename", ",", "*", ",", "ignore_existing", "=", "False", ")", ":", "work", "=", "{", "}", "stats", "=", "collections", ".", "OrderedDict", "(", "(", "(", "k", ",", "0", ")", "for", "k", "in", "(", ...
Recursively analyze library, and return a dict of path -> (artist, album).
[ "Recursively", "analyze", "library", "and", "return", "a", "dict", "of", "path", "-", ">", "(", "artist", "album", ")", "." ]
train
https://github.com/desbma/sacad/blob/a7a010c4d9618a0c90927f1acb530101ca05fac4/sacad/recurse.py#L38-L56
desbma/sacad
sacad/recurse.py
get_metadata
def get_metadata(audio_filepaths): """ Return a tuple of album, artist, has_embedded_album_art from a list of audio files. """ artist, album, has_embedded_album_art = None, None, None for audio_filepath in audio_filepaths: try: mf = mutagen.File(audio_filepath) except Exception: continue i...
python
def get_metadata(audio_filepaths): """ Return a tuple of album, artist, has_embedded_album_art from a list of audio files. """ artist, album, has_embedded_album_art = None, None, None for audio_filepath in audio_filepaths: try: mf = mutagen.File(audio_filepath) except Exception: continue i...
[ "def", "get_metadata", "(", "audio_filepaths", ")", ":", "artist", ",", "album", ",", "has_embedded_album_art", "=", "None", ",", "None", ",", "None", "for", "audio_filepath", "in", "audio_filepaths", ":", "try", ":", "mf", "=", "mutagen", ".", "File", "(", ...
Return a tuple of album, artist, has_embedded_album_art from a list of audio files.
[ "Return", "a", "tuple", "of", "album", "artist", "has_embedded_album_art", "from", "a", "list", "of", "audio", "files", "." ]
train
https://github.com/desbma/sacad/blob/a7a010c4d9618a0c90927f1acb530101ca05fac4/sacad/recurse.py#L59-L106
desbma/sacad
sacad/recurse.py
analyze_dir
def analyze_dir(stats, parent_dir, rel_filepaths, cover_filename, *, ignore_existing=False): """ Analyze a directory (non recursively) to get its album metadata if it is one. """ no_metadata = None, None, None metadata = no_metadata audio_filepaths = [] for rel_filepath in rel_filepaths: stats["files"] +=...
python
def analyze_dir(stats, parent_dir, rel_filepaths, cover_filename, *, ignore_existing=False): """ Analyze a directory (non recursively) to get its album metadata if it is one. """ no_metadata = None, None, None metadata = no_metadata audio_filepaths = [] for rel_filepath in rel_filepaths: stats["files"] +=...
[ "def", "analyze_dir", "(", "stats", ",", "parent_dir", ",", "rel_filepaths", ",", "cover_filename", ",", "*", ",", "ignore_existing", "=", "False", ")", ":", "no_metadata", "=", "None", ",", "None", ",", "None", "metadata", "=", "no_metadata", "audio_filepaths...
Analyze a directory (non recursively) to get its album metadata if it is one.
[ "Analyze", "a", "directory", "(", "non", "recursively", ")", "to", "get", "its", "album", "metadata", "if", "it", "is", "one", "." ]
train
https://github.com/desbma/sacad/blob/a7a010c4d9618a0c90927f1acb530101ca05fac4/sacad/recurse.py#L109-L139
desbma/sacad
sacad/recurse.py
embed_album_art
def embed_album_art(cover_filepath, path): """ Embed album art into audio files. """ with open(cover_filepath, "rb") as f: cover_data = f.read() for filename in os.listdir(path): try: ext = os.path.splitext(filename)[1][1:].lower() except IndexError: continue if ext in AUDIO_EXTENSIO...
python
def embed_album_art(cover_filepath, path): """ Embed album art into audio files. """ with open(cover_filepath, "rb") as f: cover_data = f.read() for filename in os.listdir(path): try: ext = os.path.splitext(filename)[1][1:].lower() except IndexError: continue if ext in AUDIO_EXTENSIO...
[ "def", "embed_album_art", "(", "cover_filepath", ",", "path", ")", ":", "with", "open", "(", "cover_filepath", ",", "\"rb\"", ")", "as", "f", ":", "cover_data", "=", "f", ".", "read", "(", ")", "for", "filename", "in", "os", ".", "listdir", "(", "path"...
Embed album art into audio files.
[ "Embed", "album", "art", "into", "audio", "files", "." ]
train
https://github.com/desbma/sacad/blob/a7a010c4d9618a0c90927f1acb530101ca05fac4/sacad/recurse.py#L142-L173
desbma/sacad
sacad/recurse.py
ichunk
def ichunk(iterable, n): """ Split an iterable into n-sized chunks. """ it = iter(iterable) while True: chunk = tuple(itertools.islice(it, n)) if not chunk: return yield chunk
python
def ichunk(iterable, n): """ Split an iterable into n-sized chunks. """ it = iter(iterable) while True: chunk = tuple(itertools.islice(it, n)) if not chunk: return yield chunk
[ "def", "ichunk", "(", "iterable", ",", "n", ")", ":", "it", "=", "iter", "(", "iterable", ")", "while", "True", ":", "chunk", "=", "tuple", "(", "itertools", ".", "islice", "(", "it", ",", "n", ")", ")", "if", "not", "chunk", ":", "return", "yiel...
Split an iterable into n-sized chunks.
[ "Split", "an", "iterable", "into", "n", "-", "sized", "chunks", "." ]
train
https://github.com/desbma/sacad/blob/a7a010c4d9618a0c90927f1acb530101ca05fac4/sacad/recurse.py#L176-L183
desbma/sacad
sacad/recurse.py
get_covers
def get_covers(work, args): """ Get missing covers. """ with contextlib.ExitStack() as cm: if args.filename == EMBEDDED_ALBUM_ART_SYMBOL: tmp_prefix = "%s_" % (os.path.splitext(os.path.basename(inspect.getfile(inspect.currentframe())))[0]) tmp_dir = cm.enter_context(tempfile.TemporaryDirectory(pref...
python
def get_covers(work, args): """ Get missing covers. """ with contextlib.ExitStack() as cm: if args.filename == EMBEDDED_ALBUM_ART_SYMBOL: tmp_prefix = "%s_" % (os.path.splitext(os.path.basename(inspect.getfile(inspect.currentframe())))[0]) tmp_dir = cm.enter_context(tempfile.TemporaryDirectory(pref...
[ "def", "get_covers", "(", "work", ",", "args", ")", ":", "with", "contextlib", ".", "ExitStack", "(", ")", "as", "cm", ":", "if", "args", ".", "filename", "==", "EMBEDDED_ALBUM_ART_SYMBOL", ":", "tmp_prefix", "=", "\"%s_\"", "%", "(", "os", ".", "path", ...
Get missing covers.
[ "Get", "missing", "covers", "." ]
train
https://github.com/desbma/sacad/blob/a7a010c4d9618a0c90927f1acb530101ca05fac4/sacad/recurse.py#L186-L273
desbma/sacad
sacad/mkstemp_ctx.py
mkstemp
def mkstemp(*args, **kwargs): """ Context manager similar to tempfile.NamedTemporaryFile except the file is not deleted on close, and only the filepath is returned .. warnings:: Unlike tempfile.mkstemp, this is not secure """ fd, filename = tempfile.mkstemp(*args, **kwargs) os.close(fd) try: yield f...
python
def mkstemp(*args, **kwargs): """ Context manager similar to tempfile.NamedTemporaryFile except the file is not deleted on close, and only the filepath is returned .. warnings:: Unlike tempfile.mkstemp, this is not secure """ fd, filename = tempfile.mkstemp(*args, **kwargs) os.close(fd) try: yield f...
[ "def", "mkstemp", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "fd", ",", "filename", "=", "tempfile", ".", "mkstemp", "(", "*", "args", ",", "*", "*", "kwargs", ")", "os", ".", "close", "(", "fd", ")", "try", ":", "yield", "filename", ...
Context manager similar to tempfile.NamedTemporaryFile except the file is not deleted on close, and only the filepath is returned .. warnings:: Unlike tempfile.mkstemp, this is not secure
[ "Context", "manager", "similar", "to", "tempfile", ".", "NamedTemporaryFile", "except", "the", "file", "is", "not", "deleted", "on", "close", "and", "only", "the", "filepath", "is", "returned", "..", "warnings", "::", "Unlike", "tempfile", ".", "mkstemp", "thi...
train
https://github.com/desbma/sacad/blob/a7a010c4d9618a0c90927f1acb530101ca05fac4/sacad/mkstemp_ctx.py#L7-L18
desbma/sacad
sacad/tqdm_logging.py
redirect_logging
def redirect_logging(tqdm_obj, logger=logging.getLogger()): """ Context manager to redirect logging to a TqdmLoggingHandler object and then restore the original. """ # remove current handler assert(len(logger.handlers) == 1) prev_handler = logger.handlers[0] logger.removeHandler(prev_handler) # add tqdm ha...
python
def redirect_logging(tqdm_obj, logger=logging.getLogger()): """ Context manager to redirect logging to a TqdmLoggingHandler object and then restore the original. """ # remove current handler assert(len(logger.handlers) == 1) prev_handler = logger.handlers[0] logger.removeHandler(prev_handler) # add tqdm ha...
[ "def", "redirect_logging", "(", "tqdm_obj", ",", "logger", "=", "logging", ".", "getLogger", "(", ")", ")", ":", "# remove current handler", "assert", "(", "len", "(", "logger", ".", "handlers", ")", "==", "1", ")", "prev_handler", "=", "logger", ".", "han...
Context manager to redirect logging to a TqdmLoggingHandler object and then restore the original.
[ "Context", "manager", "to", "redirect", "logging", "to", "a", "TqdmLoggingHandler", "object", "and", "then", "restore", "the", "original", "." ]
train
https://github.com/desbma/sacad/blob/a7a010c4d9618a0c90927f1acb530101ca05fac4/sacad/tqdm_logging.py#L21-L39
desbma/sacad
sacad/sources/base.py
CoverSource.search
async def search(self, album, artist): """ Search for a given album/artist and return an iterable of CoverSourceResult. """ self.logger.debug("Searching with source '%s'..." % (self.__class__.__name__)) album = self.processAlbumString(album) artist = self.processArtistString(artist) url_data = self....
python
async def search(self, album, artist): """ Search for a given album/artist and return an iterable of CoverSourceResult. """ self.logger.debug("Searching with source '%s'..." % (self.__class__.__name__)) album = self.processAlbumString(album) artist = self.processArtistString(artist) url_data = self....
[ "async", "def", "search", "(", "self", ",", "album", ",", "artist", ")", ":", "self", ".", "logger", ".", "debug", "(", "\"Searching with source '%s'...\"", "%", "(", "self", ".", "__class__", ".", "__name__", ")", ")", "album", "=", "self", ".", "proces...
Search for a given album/artist and return an iterable of CoverSourceResult.
[ "Search", "for", "a", "given", "album", "/", "artist", "and", "return", "an", "iterable", "of", "CoverSourceResult", "." ]
train
https://github.com/desbma/sacad/blob/a7a010c4d9618a0c90927f1acb530101ca05fac4/sacad/sources/base.py#L60-L128
desbma/sacad
sacad/sources/base.py
CoverSource.fetchResults
async def fetchResults(self, url, post_data=None): """ Get a (store in cache callback, search results) tuple from an URL. """ if post_data is not None: self.logger.debug("Querying URL '%s' %s..." % (url, dict(post_data))) else: self.logger.debug("Querying URL '%s'..." % (url)) headers = {} ...
python
async def fetchResults(self, url, post_data=None): """ Get a (store in cache callback, search results) tuple from an URL. """ if post_data is not None: self.logger.debug("Querying URL '%s' %s..." % (url, dict(post_data))) else: self.logger.debug("Querying URL '%s'..." % (url)) headers = {} ...
[ "async", "def", "fetchResults", "(", "self", ",", "url", ",", "post_data", "=", "None", ")", ":", "if", "post_data", "is", "not", "None", ":", "self", ".", "logger", ".", "debug", "(", "\"Querying URL '%s' %s...\"", "%", "(", "url", ",", "dict", "(", "...
Get a (store in cache callback, search results) tuple from an URL.
[ "Get", "a", "(", "store", "in", "cache", "callback", "search", "results", ")", "tuple", "from", "an", "URL", "." ]
train
https://github.com/desbma/sacad/blob/a7a010c4d9618a0c90927f1acb530101ca05fac4/sacad/sources/base.py#L130-L141
desbma/sacad
sacad/sources/base.py
CoverSource.probeUrl
async def probeUrl(self, url, response_headers=None): """ Probe URL reachability from cache or HEAD request. """ self.logger.debug("Probing URL '%s'..." % (url)) headers = {} self.updateHttpHeaders(headers) resp_headers = {} resp_ok = await self.http.isReachable(url, ...
python
async def probeUrl(self, url, response_headers=None): """ Probe URL reachability from cache or HEAD request. """ self.logger.debug("Probing URL '%s'..." % (url)) headers = {} self.updateHttpHeaders(headers) resp_headers = {} resp_ok = await self.http.isReachable(url, ...
[ "async", "def", "probeUrl", "(", "self", ",", "url", ",", "response_headers", "=", "None", ")", ":", "self", ".", "logger", ".", "debug", "(", "\"Probing URL '%s'...\"", "%", "(", "url", ")", ")", "headers", "=", "{", "}", "self", ".", "updateHttpHeaders...
Probe URL reachability from cache or HEAD request.
[ "Probe", "URL", "reachability", "from", "cache", "or", "HEAD", "request", "." ]
train
https://github.com/desbma/sacad/blob/a7a010c4d9618a0c90927f1acb530101ca05fac4/sacad/sources/base.py#L143-L157
desbma/sacad
sacad/sources/base.py
CoverSource.unaccentuate
def unaccentuate(s): """ Replace accentuated chars in string by their non accentuated equivalent. """ return "".join(c for c in unicodedata.normalize("NFKD", s) if not unicodedata.combining(c))
python
def unaccentuate(s): """ Replace accentuated chars in string by their non accentuated equivalent. """ return "".join(c for c in unicodedata.normalize("NFKD", s) if not unicodedata.combining(c))
[ "def", "unaccentuate", "(", "s", ")", ":", "return", "\"\"", ".", "join", "(", "c", "for", "c", "in", "unicodedata", ".", "normalize", "(", "\"NFKD\"", ",", "s", ")", "if", "not", "unicodedata", ".", "combining", "(", "c", ")", ")" ]
Replace accentuated chars in string by their non accentuated equivalent.
[ "Replace", "accentuated", "chars", "in", "string", "by", "their", "non", "accentuated", "equivalent", "." ]
train
https://github.com/desbma/sacad/blob/a7a010c4d9618a0c90927f1acb530101ca05fac4/sacad/sources/base.py#L165-L167
desbma/sacad
sacad/sources/base.py
CoverSource.unpunctuate
def unpunctuate(s, *, char_blacklist=string.punctuation): """ Remove punctuation from string s. """ # remove punctuation s = "".join(c for c in s if c not in char_blacklist) # remove consecutive spaces return " ".join(filter(None, s.split(" ")))
python
def unpunctuate(s, *, char_blacklist=string.punctuation): """ Remove punctuation from string s. """ # remove punctuation s = "".join(c for c in s if c not in char_blacklist) # remove consecutive spaces return " ".join(filter(None, s.split(" ")))
[ "def", "unpunctuate", "(", "s", ",", "*", ",", "char_blacklist", "=", "string", ".", "punctuation", ")", ":", "# remove punctuation", "s", "=", "\"\"", ".", "join", "(", "c", "for", "c", "in", "s", "if", "c", "not", "in", "char_blacklist", ")", "# remo...
Remove punctuation from string s.
[ "Remove", "punctuation", "from", "string", "s", "." ]
train
https://github.com/desbma/sacad/blob/a7a010c4d9618a0c90927f1acb530101ca05fac4/sacad/sources/base.py#L170-L175
desbma/sacad
sacad/sources/amazoncd.py
AmazonCdCoverSource.getSearchUrl
def getSearchUrl(self, album, artist): """ See CoverSource.getSearchUrl. """ params = collections.OrderedDict() params["search-alias"] = "popular" params["field-artist"] = artist params["field-title"] = album params["sort"] = "relevancerank" return __class__.assembleUrl(self.base_url, params...
python
def getSearchUrl(self, album, artist): """ See CoverSource.getSearchUrl. """ params = collections.OrderedDict() params["search-alias"] = "popular" params["field-artist"] = artist params["field-title"] = album params["sort"] = "relevancerank" return __class__.assembleUrl(self.base_url, params...
[ "def", "getSearchUrl", "(", "self", ",", "album", ",", "artist", ")", ":", "params", "=", "collections", ".", "OrderedDict", "(", ")", "params", "[", "\"search-alias\"", "]", "=", "\"popular\"", "params", "[", "\"field-artist\"", "]", "=", "artist", "params"...
See CoverSource.getSearchUrl.
[ "See", "CoverSource", ".", "getSearchUrl", "." ]
train
https://github.com/desbma/sacad/blob/a7a010c4d9618a0c90927f1acb530101ca05fac4/sacad/sources/amazoncd.py#L46-L53
desbma/sacad
sacad/sources/amazoncd.py
AmazonCdCoverSource.parseResults
async def parseResults(self, api_data): """ See CoverSource.parseResults. """ results = [] # parse page parser = lxml.etree.HTMLParser() html = lxml.etree.XML(api_data.decode("utf-8", "ignore"), parser) for page_struct_version, result_selector in enumerate(__class__.RESULTS_SELECTORS): r...
python
async def parseResults(self, api_data): """ See CoverSource.parseResults. """ results = [] # parse page parser = lxml.etree.HTMLParser() html = lxml.etree.XML(api_data.decode("utf-8", "ignore"), parser) for page_struct_version, result_selector in enumerate(__class__.RESULTS_SELECTORS): r...
[ "async", "def", "parseResults", "(", "self", ",", "api_data", ")", ":", "results", "=", "[", "]", "# parse page", "parser", "=", "lxml", ".", "etree", ".", "HTMLParser", "(", ")", "html", "=", "lxml", ".", "etree", ".", "XML", "(", "api_data", ".", "...
See CoverSource.parseResults.
[ "See", "CoverSource", ".", "parseResults", "." ]
train
https://github.com/desbma/sacad/blob/a7a010c4d9618a0c90927f1acb530101ca05fac4/sacad/sources/amazoncd.py#L59-L142
fogleman/pg
pg/core.py
delete_all
def delete_all(obj): '''Calls `delete()` on all members of `obj` that are recognized as instances of `pg` objects.''' types = tuple([ Shader, Mesh, VertexBuffer, IndexBuffer, Texture, Program, Context, ]) for name in dir(obj): child = g...
python
def delete_all(obj): '''Calls `delete()` on all members of `obj` that are recognized as instances of `pg` objects.''' types = tuple([ Shader, Mesh, VertexBuffer, IndexBuffer, Texture, Program, Context, ]) for name in dir(obj): child = g...
[ "def", "delete_all", "(", "obj", ")", ":", "types", "=", "tuple", "(", "[", "Shader", ",", "Mesh", ",", "VertexBuffer", ",", "IndexBuffer", ",", "Texture", ",", "Program", ",", "Context", ",", "]", ")", "for", "name", "in", "dir", "(", "obj", ")", ...
Calls `delete()` on all members of `obj` that are recognized as instances of `pg` objects.
[ "Calls", "delete", "()", "on", "all", "members", "of", "obj", "that", "are", "recognized", "as", "instances", "of", "pg", "objects", "." ]
train
https://github.com/fogleman/pg/blob/124ea3803c788b2c98c4f3a428e5d26842a67b58/pg/core.py#L14-L29
fogleman/pg
pg/glfw.py
_glfw_get_version
def _glfw_get_version(filename): ''' Queries and returns the library version tuple or None by using a subprocess. ''' version_checker_source = """ import sys import ctypes def get_version(library_handle): ''' Queries and returns the library version tu...
python
def _glfw_get_version(filename): ''' Queries and returns the library version tuple or None by using a subprocess. ''' version_checker_source = """ import sys import ctypes def get_version(library_handle): ''' Queries and returns the library version tu...
[ "def", "_glfw_get_version", "(", "filename", ")", ":", "version_checker_source", "=", "\"\"\"\n import sys\n import ctypes\n\n def get_version(library_handle):\n '''\n Queries and returns the library version tuple or None.\n '''\n majo...
Queries and returns the library version tuple or None by using a subprocess.
[ "Queries", "and", "returns", "the", "library", "version", "tuple", "or", "None", "by", "using", "a", "subprocess", "." ]
train
https://github.com/fogleman/pg/blob/124ea3803c788b2c98c4f3a428e5d26842a67b58/pg/glfw.py#L84-L135
fogleman/pg
pg/glfw.py
set_error_callback
def set_error_callback(cbfun): ''' Sets the error callback. Wrapper for: GLFWerrorfun glfwSetErrorCallback(GLFWerrorfun cbfun); ''' global _error_callback previous_callback = _error_callback if cbfun is None: cbfun = 0 c_cbfun = _GLFWerrorfun(cbfun) _error_callback =...
python
def set_error_callback(cbfun): ''' Sets the error callback. Wrapper for: GLFWerrorfun glfwSetErrorCallback(GLFWerrorfun cbfun); ''' global _error_callback previous_callback = _error_callback if cbfun is None: cbfun = 0 c_cbfun = _GLFWerrorfun(cbfun) _error_callback =...
[ "def", "set_error_callback", "(", "cbfun", ")", ":", "global", "_error_callback", "previous_callback", "=", "_error_callback", "if", "cbfun", "is", "None", ":", "cbfun", "=", "0", "c_cbfun", "=", "_GLFWerrorfun", "(", "cbfun", ")", "_error_callback", "=", "(", ...
Sets the error callback. Wrapper for: GLFWerrorfun glfwSetErrorCallback(GLFWerrorfun cbfun);
[ "Sets", "the", "error", "callback", "." ]
train
https://github.com/fogleman/pg/blob/124ea3803c788b2c98c4f3a428e5d26842a67b58/pg/glfw.py#L579-L595
fogleman/pg
pg/glfw.py
destroy_window
def destroy_window(window): ''' Destroys the specified window and its context. Wrapper for: void glfwDestroyWindow(GLFWwindow* window); ''' _glfw.glfwDestroyWindow(window) window_addr = ctypes.cast(ctypes.pointer(window), ctypes.POINTER(ctypes.c_ulong)).con...
python
def destroy_window(window): ''' Destroys the specified window and its context. Wrapper for: void glfwDestroyWindow(GLFWwindow* window); ''' _glfw.glfwDestroyWindow(window) window_addr = ctypes.cast(ctypes.pointer(window), ctypes.POINTER(ctypes.c_ulong)).con...
[ "def", "destroy_window", "(", "window", ")", ":", "_glfw", ".", "glfwDestroyWindow", "(", "window", ")", "window_addr", "=", "ctypes", ".", "cast", "(", "ctypes", ".", "pointer", "(", "window", ")", ",", "ctypes", ".", "POINTER", "(", "ctypes", ".", "c_u...
Destroys the specified window and its context. Wrapper for: void glfwDestroyWindow(GLFWwindow* window);
[ "Destroys", "the", "specified", "window", "and", "its", "context", "." ]
train
https://github.com/fogleman/pg/blob/124ea3803c788b2c98c4f3a428e5d26842a67b58/pg/glfw.py#L798-L810
fogleman/pg
pg/glfw.py
_GLFWvidmode.unwrap
def unwrap(self): ''' Returns a nested python sequence. ''' size = self.width, self.height bits = self.red_bits, self.green_bits, self.blue_bits return size, bits, self.refresh_rate
python
def unwrap(self): ''' Returns a nested python sequence. ''' size = self.width, self.height bits = self.red_bits, self.green_bits, self.blue_bits return size, bits, self.refresh_rate
[ "def", "unwrap", "(", "self", ")", ":", "size", "=", "self", ".", "width", ",", "self", ".", "height", "bits", "=", "self", ".", "red_bits", ",", "self", ".", "green_bits", ",", "self", ".", "blue_bits", "return", "size", ",", "bits", ",", "self", ...
Returns a nested python sequence.
[ "Returns", "a", "nested", "python", "sequence", "." ]
train
https://github.com/fogleman/pg/blob/124ea3803c788b2c98c4f3a428e5d26842a67b58/pg/glfw.py#L190-L196
fogleman/pg
pg/glfw.py
_GLFWgammaramp.wrap
def wrap(self, gammaramp): ''' Wraps a nested python sequence. ''' red, green, blue = gammaramp size = min(len(red), len(green), len(blue)) array_type = ctypes.c_ushort*size self.size = ctypes.c_uint(size) self.red_array = array_type() self.green_a...
python
def wrap(self, gammaramp): ''' Wraps a nested python sequence. ''' red, green, blue = gammaramp size = min(len(red), len(green), len(blue)) array_type = ctypes.c_ushort*size self.size = ctypes.c_uint(size) self.red_array = array_type() self.green_a...
[ "def", "wrap", "(", "self", ",", "gammaramp", ")", ":", "red", ",", "green", ",", "blue", "=", "gammaramp", "size", "=", "min", "(", "len", "(", "red", ")", ",", "len", "(", "green", ")", ",", "len", "(", "blue", ")", ")", "array_type", "=", "c...
Wraps a nested python sequence.
[ "Wraps", "a", "nested", "python", "sequence", "." ]
train
https://github.com/fogleman/pg/blob/124ea3803c788b2c98c4f3a428e5d26842a67b58/pg/glfw.py#L219-L237
fogleman/pg
pg/glfw.py
_GLFWgammaramp.unwrap
def unwrap(self): ''' Returns a nested python sequence. ''' red = [self.red[i]/65535.0 for i in range(self.size)] green = [self.green[i]/65535.0 for i in range(self.size)] blue = [self.blue[i]/65535.0 for i in range(self.size)] return red, green, blue
python
def unwrap(self): ''' Returns a nested python sequence. ''' red = [self.red[i]/65535.0 for i in range(self.size)] green = [self.green[i]/65535.0 for i in range(self.size)] blue = [self.blue[i]/65535.0 for i in range(self.size)] return red, green, blue
[ "def", "unwrap", "(", "self", ")", ":", "red", "=", "[", "self", ".", "red", "[", "i", "]", "/", "65535.0", "for", "i", "in", "range", "(", "self", ".", "size", ")", "]", "green", "=", "[", "self", ".", "green", "[", "i", "]", "/", "65535.0",...
Returns a nested python sequence.
[ "Returns", "a", "nested", "python", "sequence", "." ]
train
https://github.com/fogleman/pg/blob/124ea3803c788b2c98c4f3a428e5d26842a67b58/pg/glfw.py#L239-L246
fogleman/pg
pg/util.py
hex_color
def hex_color(value): '''Accepts a hexadecimal color `value` in the format ``0xrrggbb`` and returns an (r, g, b) tuple where 0.0 <= r, g, b <= 1.0. ''' r = ((value >> (8 * 2)) & 255) / 255.0 g = ((value >> (8 * 1)) & 255) / 255.0 b = ((value >> (8 * 0)) & 255) / 255.0 return (r, g, b)
python
def hex_color(value): '''Accepts a hexadecimal color `value` in the format ``0xrrggbb`` and returns an (r, g, b) tuple where 0.0 <= r, g, b <= 1.0. ''' r = ((value >> (8 * 2)) & 255) / 255.0 g = ((value >> (8 * 1)) & 255) / 255.0 b = ((value >> (8 * 0)) & 255) / 255.0 return (r, g, b)
[ "def", "hex_color", "(", "value", ")", ":", "r", "=", "(", "(", "value", ">>", "(", "8", "*", "2", ")", ")", "&", "255", ")", "/", "255.0", "g", "=", "(", "(", "value", ">>", "(", "8", "*", "1", ")", ")", "&", "255", ")", "/", "255.0", ...
Accepts a hexadecimal color `value` in the format ``0xrrggbb`` and returns an (r, g, b) tuple where 0.0 <= r, g, b <= 1.0.
[ "Accepts", "a", "hexadecimal", "color", "value", "in", "the", "format", "0xrrggbb", "and", "returns", "an", "(", "r", "g", "b", ")", "tuple", "where", "0", ".", "0", "<", "=", "r", "g", "b", "<", "=", "1", ".", "0", "." ]
train
https://github.com/fogleman/pg/blob/124ea3803c788b2c98c4f3a428e5d26842a67b58/pg/util.py#L5-L12
fogleman/pg
pg/util.py
normalize
def normalize(vector): '''Normalizes the `vector` so that its length is 1. `vector` can have any number of components. ''' d = sum(x * x for x in vector) ** 0.5 return tuple(x / d for x in vector)
python
def normalize(vector): '''Normalizes the `vector` so that its length is 1. `vector` can have any number of components. ''' d = sum(x * x for x in vector) ** 0.5 return tuple(x / d for x in vector)
[ "def", "normalize", "(", "vector", ")", ":", "d", "=", "sum", "(", "x", "*", "x", "for", "x", "in", "vector", ")", "**", "0.5", "return", "tuple", "(", "x", "/", "d", "for", "x", "in", "vector", ")" ]
Normalizes the `vector` so that its length is 1. `vector` can have any number of components.
[ "Normalizes", "the", "vector", "so", "that", "its", "length", "is", "1", ".", "vector", "can", "have", "any", "number", "of", "components", "." ]
train
https://github.com/fogleman/pg/blob/124ea3803c788b2c98c4f3a428e5d26842a67b58/pg/util.py#L14-L19
fogleman/pg
pg/util.py
distance
def distance(p1, p2): '''Computes and returns the distance between two points, `p1` and `p2`. The points can have any number of components. ''' return sum((a - b) ** 2 for a, b in zip(p1, p2)) ** 0.5
python
def distance(p1, p2): '''Computes and returns the distance between two points, `p1` and `p2`. The points can have any number of components. ''' return sum((a - b) ** 2 for a, b in zip(p1, p2)) ** 0.5
[ "def", "distance", "(", "p1", ",", "p2", ")", ":", "return", "sum", "(", "(", "a", "-", "b", ")", "**", "2", "for", "a", ",", "b", "in", "zip", "(", "p1", ",", "p2", ")", ")", "**", "0.5" ]
Computes and returns the distance between two points, `p1` and `p2`. The points can have any number of components.
[ "Computes", "and", "returns", "the", "distance", "between", "two", "points", "p1", "and", "p2", ".", "The", "points", "can", "have", "any", "number", "of", "components", "." ]
train
https://github.com/fogleman/pg/blob/124ea3803c788b2c98c4f3a428e5d26842a67b58/pg/util.py#L21-L25
fogleman/pg
pg/util.py
cross
def cross(v1, v2): '''Computes the cross product of two vectors. ''' return ( v1[1] * v2[2] - v1[2] * v2[1], v1[2] * v2[0] - v1[0] * v2[2], v1[0] * v2[1] - v1[1] * v2[0], )
python
def cross(v1, v2): '''Computes the cross product of two vectors. ''' return ( v1[1] * v2[2] - v1[2] * v2[1], v1[2] * v2[0] - v1[0] * v2[2], v1[0] * v2[1] - v1[1] * v2[0], )
[ "def", "cross", "(", "v1", ",", "v2", ")", ":", "return", "(", "v1", "[", "1", "]", "*", "v2", "[", "2", "]", "-", "v1", "[", "2", "]", "*", "v2", "[", "1", "]", ",", "v1", "[", "2", "]", "*", "v2", "[", "0", "]", "-", "v1", "[", "0...
Computes the cross product of two vectors.
[ "Computes", "the", "cross", "product", "of", "two", "vectors", "." ]
train
https://github.com/fogleman/pg/blob/124ea3803c788b2c98c4f3a428e5d26842a67b58/pg/util.py#L27-L34
fogleman/pg
pg/util.py
dot
def dot(v1, v2): '''Computes the dot product of two vectors. ''' x1, y1, z1 = v1 x2, y2, z2 = v2 return x1 * x2 + y1 * y2 + z1 * z2
python
def dot(v1, v2): '''Computes the dot product of two vectors. ''' x1, y1, z1 = v1 x2, y2, z2 = v2 return x1 * x2 + y1 * y2 + z1 * z2
[ "def", "dot", "(", "v1", ",", "v2", ")", ":", "x1", ",", "y1", ",", "z1", "=", "v1", "x2", ",", "y2", ",", "z2", "=", "v2", "return", "x1", "*", "x2", "+", "y1", "*", "y2", "+", "z1", "*", "z2" ]
Computes the dot product of two vectors.
[ "Computes", "the", "dot", "product", "of", "two", "vectors", "." ]
train
https://github.com/fogleman/pg/blob/124ea3803c788b2c98c4f3a428e5d26842a67b58/pg/util.py#L36-L41
fogleman/pg
pg/util.py
add
def add(v1, v2): '''Adds two vectors. ''' return tuple(a + b for a, b in zip(v1, v2))
python
def add(v1, v2): '''Adds two vectors. ''' return tuple(a + b for a, b in zip(v1, v2))
[ "def", "add", "(", "v1", ",", "v2", ")", ":", "return", "tuple", "(", "a", "+", "b", "for", "a", ",", "b", "in", "zip", "(", "v1", ",", "v2", ")", ")" ]
Adds two vectors.
[ "Adds", "two", "vectors", "." ]
train
https://github.com/fogleman/pg/blob/124ea3803c788b2c98c4f3a428e5d26842a67b58/pg/util.py#L43-L46
fogleman/pg
pg/util.py
sub
def sub(v1, v2): '''Subtracts two vectors. ''' return tuple(a - b for a, b in zip(v1, v2))
python
def sub(v1, v2): '''Subtracts two vectors. ''' return tuple(a - b for a, b in zip(v1, v2))
[ "def", "sub", "(", "v1", ",", "v2", ")", ":", "return", "tuple", "(", "a", "-", "b", "for", "a", ",", "b", "in", "zip", "(", "v1", ",", "v2", ")", ")" ]
Subtracts two vectors.
[ "Subtracts", "two", "vectors", "." ]
train
https://github.com/fogleman/pg/blob/124ea3803c788b2c98c4f3a428e5d26842a67b58/pg/util.py#L48-L51
fogleman/pg
pg/util.py
interpolate
def interpolate(v1, v2, t): '''Interpolate from one vector to another. ''' return add(v1, mul(sub(v2, v1), t))
python
def interpolate(v1, v2, t): '''Interpolate from one vector to another. ''' return add(v1, mul(sub(v2, v1), t))
[ "def", "interpolate", "(", "v1", ",", "v2", ",", "t", ")", ":", "return", "add", "(", "v1", ",", "mul", "(", "sub", "(", "v2", ",", "v1", ")", ",", "t", ")", ")" ]
Interpolate from one vector to another.
[ "Interpolate", "from", "one", "vector", "to", "another", "." ]
train
https://github.com/fogleman/pg/blob/124ea3803c788b2c98c4f3a428e5d26842a67b58/pg/util.py#L63-L66
fogleman/pg
pg/util.py
normal_from_points
def normal_from_points(a, b, c): '''Computes a normal vector given three points. ''' x1, y1, z1 = a x2, y2, z2 = b x3, y3, z3 = c ab = (x2 - x1, y2 - y1, z2 - z1) ac = (x3 - x1, y3 - y1, z3 - z1) x, y, z = cross(ab, ac) d = (x * x + y * y + z * z) ** 0.5 return (x / d, y / d, z /...
python
def normal_from_points(a, b, c): '''Computes a normal vector given three points. ''' x1, y1, z1 = a x2, y2, z2 = b x3, y3, z3 = c ab = (x2 - x1, y2 - y1, z2 - z1) ac = (x3 - x1, y3 - y1, z3 - z1) x, y, z = cross(ab, ac) d = (x * x + y * y + z * z) ** 0.5 return (x / d, y / d, z /...
[ "def", "normal_from_points", "(", "a", ",", "b", ",", "c", ")", ":", "x1", ",", "y1", ",", "z1", "=", "a", "x2", ",", "y2", ",", "z2", "=", "b", "x3", ",", "y3", ",", "z3", "=", "c", "ab", "=", "(", "x2", "-", "x1", ",", "y2", "-", "y1"...
Computes a normal vector given three points.
[ "Computes", "a", "normal", "vector", "given", "three", "points", "." ]
train
https://github.com/fogleman/pg/blob/124ea3803c788b2c98c4f3a428e5d26842a67b58/pg/util.py#L68-L78
fogleman/pg
pg/util.py
smooth_normals
def smooth_normals(positions, normals): '''Assigns an averaged normal to each position based on all of the normals originally used for the position. ''' lookup = defaultdict(list) for position, normal in zip(positions, normals): lookup[position].append(normal) result = [] for positio...
python
def smooth_normals(positions, normals): '''Assigns an averaged normal to each position based on all of the normals originally used for the position. ''' lookup = defaultdict(list) for position, normal in zip(positions, normals): lookup[position].append(normal) result = [] for positio...
[ "def", "smooth_normals", "(", "positions", ",", "normals", ")", ":", "lookup", "=", "defaultdict", "(", "list", ")", "for", "position", ",", "normal", "in", "zip", "(", "positions", ",", "normals", ")", ":", "lookup", "[", "position", "]", ".", "append",...
Assigns an averaged normal to each position based on all of the normals originally used for the position.
[ "Assigns", "an", "averaged", "normal", "to", "each", "position", "based", "on", "all", "of", "the", "normals", "originally", "used", "for", "the", "position", "." ]
train
https://github.com/fogleman/pg/blob/124ea3803c788b2c98c4f3a428e5d26842a67b58/pg/util.py#L80-L96
fogleman/pg
pg/util.py
bounding_box
def bounding_box(positions): '''Computes the bounding box for a list of 3-dimensional points. ''' (x0, y0, z0) = (x1, y1, z1) = positions[0] for x, y, z in positions: x0 = min(x0, x) y0 = min(y0, y) z0 = min(z0, z) x1 = max(x1, x) y1 = max(y1, y) z1 = max(...
python
def bounding_box(positions): '''Computes the bounding box for a list of 3-dimensional points. ''' (x0, y0, z0) = (x1, y1, z1) = positions[0] for x, y, z in positions: x0 = min(x0, x) y0 = min(y0, y) z0 = min(z0, z) x1 = max(x1, x) y1 = max(y1, y) z1 = max(...
[ "def", "bounding_box", "(", "positions", ")", ":", "(", "x0", ",", "y0", ",", "z0", ")", "=", "(", "x1", ",", "y1", ",", "z1", ")", "=", "positions", "[", "0", "]", "for", "x", ",", "y", ",", "z", "in", "positions", ":", "x0", "=", "min", "...
Computes the bounding box for a list of 3-dimensional points.
[ "Computes", "the", "bounding", "box", "for", "a", "list", "of", "3", "-", "dimensional", "points", "." ]
train
https://github.com/fogleman/pg/blob/124ea3803c788b2c98c4f3a428e5d26842a67b58/pg/util.py#L98-L109
fogleman/pg
pg/util.py
recenter
def recenter(positions): '''Returns a list of new positions centered around the origin. ''' (x0, y0, z0), (x1, y1, z1) = bounding_box(positions) dx = x1 - (x1 - x0) / 2.0 dy = y1 - (y1 - y0) / 2.0 dz = z1 - (z1 - z0) / 2.0 result = [] for x, y, z in positions: result.append((x - ...
python
def recenter(positions): '''Returns a list of new positions centered around the origin. ''' (x0, y0, z0), (x1, y1, z1) = bounding_box(positions) dx = x1 - (x1 - x0) / 2.0 dy = y1 - (y1 - y0) / 2.0 dz = z1 - (z1 - z0) / 2.0 result = [] for x, y, z in positions: result.append((x - ...
[ "def", "recenter", "(", "positions", ")", ":", "(", "x0", ",", "y0", ",", "z0", ")", ",", "(", "x1", ",", "y1", ",", "z1", ")", "=", "bounding_box", "(", "positions", ")", "dx", "=", "x1", "-", "(", "x1", "-", "x0", ")", "/", "2.0", "dy", "...
Returns a list of new positions centered around the origin.
[ "Returns", "a", "list", "of", "new", "positions", "centered", "around", "the", "origin", "." ]
train
https://github.com/fogleman/pg/blob/124ea3803c788b2c98c4f3a428e5d26842a67b58/pg/util.py#L111-L121
fogleman/pg
pg/util.py
interleave
def interleave(*args): '''Interleaves the elements of the provided arrays. >>> a = [(0, 0), (1, 0), (2, 0), (3, 0)] >>> b = [(0, 0), (0, 1), (0, 2), (0, 3)] >>> interleave(a, b) [(0, 0, 0, 0), (1, 0, 0, 1), (2, 0, 0, 2), (3, 0, 0, 3)] This is useful for combining multiple verte...
python
def interleave(*args): '''Interleaves the elements of the provided arrays. >>> a = [(0, 0), (1, 0), (2, 0), (3, 0)] >>> b = [(0, 0), (0, 1), (0, 2), (0, 3)] >>> interleave(a, b) [(0, 0, 0, 0), (1, 0, 0, 1), (2, 0, 0, 2), (3, 0, 0, 3)] This is useful for combining multiple verte...
[ "def", "interleave", "(", "*", "args", ")", ":", "result", "=", "[", "]", "for", "array", "in", "zip", "(", "*", "args", ")", ":", "result", ".", "append", "(", "tuple", "(", "flatten", "(", "array", ")", ")", ")", "return", "result" ]
Interleaves the elements of the provided arrays. >>> a = [(0, 0), (1, 0), (2, 0), (3, 0)] >>> b = [(0, 0), (0, 1), (0, 2), (0, 3)] >>> interleave(a, b) [(0, 0, 0, 0), (1, 0, 0, 1), (2, 0, 0, 2), (3, 0, 0, 3)] This is useful for combining multiple vertex attributes into a single ...
[ "Interleaves", "the", "elements", "of", "the", "provided", "arrays", "." ]
train
https://github.com/fogleman/pg/blob/124ea3803c788b2c98c4f3a428e5d26842a67b58/pg/util.py#L123-L138
fogleman/pg
pg/util.py
distinct
def distinct(iterable, keyfunc=None): '''Yields distinct items from `iterable` in the order that they appear. ''' seen = set() for item in iterable: key = item if keyfunc is None else keyfunc(item) if key not in seen: seen.add(key) yield item
python
def distinct(iterable, keyfunc=None): '''Yields distinct items from `iterable` in the order that they appear. ''' seen = set() for item in iterable: key = item if keyfunc is None else keyfunc(item) if key not in seen: seen.add(key) yield item
[ "def", "distinct", "(", "iterable", ",", "keyfunc", "=", "None", ")", ":", "seen", "=", "set", "(", ")", "for", "item", "in", "iterable", ":", "key", "=", "item", "if", "keyfunc", "is", "None", "else", "keyfunc", "(", "item", ")", "if", "key", "not...
Yields distinct items from `iterable` in the order that they appear.
[ "Yields", "distinct", "items", "from", "iterable", "in", "the", "order", "that", "they", "appear", "." ]
train
https://github.com/fogleman/pg/blob/124ea3803c788b2c98c4f3a428e5d26842a67b58/pg/util.py#L154-L162
fogleman/pg
pg/util.py
ray_triangle_intersection
def ray_triangle_intersection(v1, v2, v3, o, d): '''Computes the distance from a point to a triangle given a ray. ''' eps = 1e-6 e1 = sub(v2, v1) e2 = sub(v3, v1) p = cross(d, e2) det = dot(e1, p) if abs(det) < eps: return None inv = 1.0 / det t = sub(o, v1) u = dot(t...
python
def ray_triangle_intersection(v1, v2, v3, o, d): '''Computes the distance from a point to a triangle given a ray. ''' eps = 1e-6 e1 = sub(v2, v1) e2 = sub(v3, v1) p = cross(d, e2) det = dot(e1, p) if abs(det) < eps: return None inv = 1.0 / det t = sub(o, v1) u = dot(t...
[ "def", "ray_triangle_intersection", "(", "v1", ",", "v2", ",", "v3", ",", "o", ",", "d", ")", ":", "eps", "=", "1e-6", "e1", "=", "sub", "(", "v2", ",", "v1", ")", "e2", "=", "sub", "(", "v3", ",", "v1", ")", "p", "=", "cross", "(", "d", ",...
Computes the distance from a point to a triangle given a ray.
[ "Computes", "the", "distance", "from", "a", "point", "to", "a", "triangle", "given", "a", "ray", "." ]
train
https://github.com/fogleman/pg/blob/124ea3803c788b2c98c4f3a428e5d26842a67b58/pg/util.py#L164-L186
fogleman/pg
pg/util.py
pack_list
def pack_list(fmt, data): '''Convert a Python list into a ctypes buffer. This appears to be faster than the typical method of creating a ctypes array, e.g. (c_float * len(data))(*data) ''' func = struct.Struct(fmt).pack return create_string_buffer(''.join([func(x) for x in data]))
python
def pack_list(fmt, data): '''Convert a Python list into a ctypes buffer. This appears to be faster than the typical method of creating a ctypes array, e.g. (c_float * len(data))(*data) ''' func = struct.Struct(fmt).pack return create_string_buffer(''.join([func(x) for x in data]))
[ "def", "pack_list", "(", "fmt", ",", "data", ")", ":", "func", "=", "struct", ".", "Struct", "(", "fmt", ")", ".", "pack", "return", "create_string_buffer", "(", "''", ".", "join", "(", "[", "func", "(", "x", ")", "for", "x", "in", "data", "]", "...
Convert a Python list into a ctypes buffer. This appears to be faster than the typical method of creating a ctypes array, e.g. (c_float * len(data))(*data)
[ "Convert", "a", "Python", "list", "into", "a", "ctypes", "buffer", "." ]
train
https://github.com/fogleman/pg/blob/124ea3803c788b2c98c4f3a428e5d26842a67b58/pg/util.py#L188-L195
wgnet/webium
webium/controls/click.py
Clickable.click
def click(self, jquery=False): """ Click by WebElement, if not, JQuery click """ if jquery: e = JQuery(self) e.click() else: super(Clickable, self).click()
python
def click(self, jquery=False): """ Click by WebElement, if not, JQuery click """ if jquery: e = JQuery(self) e.click() else: super(Clickable, self).click()
[ "def", "click", "(", "self", ",", "jquery", "=", "False", ")", ":", "if", "jquery", ":", "e", "=", "JQuery", "(", "self", ")", "e", ".", "click", "(", ")", "else", ":", "super", "(", "Clickable", ",", "self", ")", ".", "click", "(", ")" ]
Click by WebElement, if not, JQuery click
[ "Click", "by", "WebElement", "if", "not", "JQuery", "click" ]
train
https://github.com/wgnet/webium/blob/ccb09876a201e75f5c5810392d4db7a8708b90cb/webium/controls/click.py#L8-L16
wgnet/webium
webium/cookie.py
convert_cookie_to_dict
def convert_cookie_to_dict(cookie, keys_map=WEB_DRIVER_COOKIE_KEYS_MAP): """ Converts an instance of Cookie class from cookielib to a dict. The names of attributes can be changed according to keys_map:. For example, this method can be used to create a cookie which compatible with WebDriver format. ...
python
def convert_cookie_to_dict(cookie, keys_map=WEB_DRIVER_COOKIE_KEYS_MAP): """ Converts an instance of Cookie class from cookielib to a dict. The names of attributes can be changed according to keys_map:. For example, this method can be used to create a cookie which compatible with WebDriver format. ...
[ "def", "convert_cookie_to_dict", "(", "cookie", ",", "keys_map", "=", "WEB_DRIVER_COOKIE_KEYS_MAP", ")", ":", "cookie_dict", "=", "dict", "(", ")", "for", "k", "in", "keys_map", ".", "keys", "(", ")", ":", "key", "=", "_to_unicode_if_str", "(", "keys_map", "...
Converts an instance of Cookie class from cookielib to a dict. The names of attributes can be changed according to keys_map:. For example, this method can be used to create a cookie which compatible with WebDriver format. :param cookie: Cookie instance received from requests/sessions using url2lib or reque...
[ "Converts", "an", "instance", "of", "Cookie", "class", "from", "cookielib", "to", "a", "dict", ".", "The", "names", "of", "attributes", "can", "be", "changed", "according", "to", "keys_map", ":", ".", "For", "example", "this", "method", "can", "be", "used"...
train
https://github.com/wgnet/webium/blob/ccb09876a201e75f5c5810392d4db7a8708b90cb/webium/cookie.py#L20-L38