repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1 value | code stringlengths 75 19.8k | code_tokens listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1 value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
jd/tenacity | tenacity/compat.py | wait_func_accept_retry_state | def wait_func_accept_retry_state(wait_func):
"""Wrap wait function to accept "retry_state" parameter."""
if not six.callable(wait_func):
return wait_func
if func_takes_retry_state(wait_func):
return wait_func
if func_takes_last_result(wait_func):
@_utils.wraps(wait_func)
def wrapped_wait_func(retry_state):
warn_about_non_retry_state_deprecation(
'wait', wait_func, stacklevel=4)
return wait_func(
retry_state.attempt_number,
retry_state.seconds_since_start,
last_result=retry_state.outcome,
)
else:
@_utils.wraps(wait_func)
def wrapped_wait_func(retry_state):
warn_about_non_retry_state_deprecation(
'wait', wait_func, stacklevel=4)
return wait_func(
retry_state.attempt_number,
retry_state.seconds_since_start,
)
return wrapped_wait_func | python | def wait_func_accept_retry_state(wait_func):
"""Wrap wait function to accept "retry_state" parameter."""
if not six.callable(wait_func):
return wait_func
if func_takes_retry_state(wait_func):
return wait_func
if func_takes_last_result(wait_func):
@_utils.wraps(wait_func)
def wrapped_wait_func(retry_state):
warn_about_non_retry_state_deprecation(
'wait', wait_func, stacklevel=4)
return wait_func(
retry_state.attempt_number,
retry_state.seconds_since_start,
last_result=retry_state.outcome,
)
else:
@_utils.wraps(wait_func)
def wrapped_wait_func(retry_state):
warn_about_non_retry_state_deprecation(
'wait', wait_func, stacklevel=4)
return wait_func(
retry_state.attempt_number,
retry_state.seconds_since_start,
)
return wrapped_wait_func | [
"def",
"wait_func_accept_retry_state",
"(",
"wait_func",
")",
":",
"if",
"not",
"six",
".",
"callable",
"(",
"wait_func",
")",
":",
"return",
"wait_func",
"if",
"func_takes_retry_state",
"(",
"wait_func",
")",
":",
"return",
"wait_func",
"if",
"func_takes_last_res... | Wrap wait function to accept "retry_state" parameter. | [
"Wrap",
"wait",
"function",
"to",
"accept",
"retry_state",
"parameter",
"."
] | 354c40b7dc8e728c438668100dd020b65c84dfc6 | https://github.com/jd/tenacity/blob/354c40b7dc8e728c438668100dd020b65c84dfc6/tenacity/compat.py#L164-L191 | train | 222,500 |
jd/tenacity | tenacity/compat.py | retry_func_accept_retry_state | def retry_func_accept_retry_state(retry_func):
"""Wrap "retry" function to accept "retry_state" parameter."""
if not six.callable(retry_func):
return retry_func
if func_takes_retry_state(retry_func):
return retry_func
@_utils.wraps(retry_func)
def wrapped_retry_func(retry_state):
warn_about_non_retry_state_deprecation(
'retry', retry_func, stacklevel=4)
return retry_func(retry_state.outcome)
return wrapped_retry_func | python | def retry_func_accept_retry_state(retry_func):
"""Wrap "retry" function to accept "retry_state" parameter."""
if not six.callable(retry_func):
return retry_func
if func_takes_retry_state(retry_func):
return retry_func
@_utils.wraps(retry_func)
def wrapped_retry_func(retry_state):
warn_about_non_retry_state_deprecation(
'retry', retry_func, stacklevel=4)
return retry_func(retry_state.outcome)
return wrapped_retry_func | [
"def",
"retry_func_accept_retry_state",
"(",
"retry_func",
")",
":",
"if",
"not",
"six",
".",
"callable",
"(",
"retry_func",
")",
":",
"return",
"retry_func",
"if",
"func_takes_retry_state",
"(",
"retry_func",
")",
":",
"return",
"retry_func",
"@",
"_utils",
"."... | Wrap "retry" function to accept "retry_state" parameter. | [
"Wrap",
"retry",
"function",
"to",
"accept",
"retry_state",
"parameter",
"."
] | 354c40b7dc8e728c438668100dd020b65c84dfc6 | https://github.com/jd/tenacity/blob/354c40b7dc8e728c438668100dd020b65c84dfc6/tenacity/compat.py#L215-L228 | train | 222,501 |
jd/tenacity | tenacity/compat.py | before_func_accept_retry_state | def before_func_accept_retry_state(fn):
"""Wrap "before" function to accept "retry_state"."""
if not six.callable(fn):
return fn
if func_takes_retry_state(fn):
return fn
@_utils.wraps(fn)
def wrapped_before_func(retry_state):
# func, trial_number, trial_time_taken
warn_about_non_retry_state_deprecation('before', fn, stacklevel=4)
return fn(
retry_state.fn,
retry_state.attempt_number,
)
return wrapped_before_func | python | def before_func_accept_retry_state(fn):
"""Wrap "before" function to accept "retry_state"."""
if not six.callable(fn):
return fn
if func_takes_retry_state(fn):
return fn
@_utils.wraps(fn)
def wrapped_before_func(retry_state):
# func, trial_number, trial_time_taken
warn_about_non_retry_state_deprecation('before', fn, stacklevel=4)
return fn(
retry_state.fn,
retry_state.attempt_number,
)
return wrapped_before_func | [
"def",
"before_func_accept_retry_state",
"(",
"fn",
")",
":",
"if",
"not",
"six",
".",
"callable",
"(",
"fn",
")",
":",
"return",
"fn",
"if",
"func_takes_retry_state",
"(",
"fn",
")",
":",
"return",
"fn",
"@",
"_utils",
".",
"wraps",
"(",
"fn",
")",
"d... | Wrap "before" function to accept "retry_state". | [
"Wrap",
"before",
"function",
"to",
"accept",
"retry_state",
"."
] | 354c40b7dc8e728c438668100dd020b65c84dfc6 | https://github.com/jd/tenacity/blob/354c40b7dc8e728c438668100dd020b65c84dfc6/tenacity/compat.py#L231-L247 | train | 222,502 |
jd/tenacity | tenacity/compat.py | after_func_accept_retry_state | def after_func_accept_retry_state(fn):
"""Wrap "after" function to accept "retry_state"."""
if not six.callable(fn):
return fn
if func_takes_retry_state(fn):
return fn
@_utils.wraps(fn)
def wrapped_after_sleep_func(retry_state):
# func, trial_number, trial_time_taken
warn_about_non_retry_state_deprecation('after', fn, stacklevel=4)
return fn(
retry_state.fn,
retry_state.attempt_number,
retry_state.seconds_since_start)
return wrapped_after_sleep_func | python | def after_func_accept_retry_state(fn):
"""Wrap "after" function to accept "retry_state"."""
if not six.callable(fn):
return fn
if func_takes_retry_state(fn):
return fn
@_utils.wraps(fn)
def wrapped_after_sleep_func(retry_state):
# func, trial_number, trial_time_taken
warn_about_non_retry_state_deprecation('after', fn, stacklevel=4)
return fn(
retry_state.fn,
retry_state.attempt_number,
retry_state.seconds_since_start)
return wrapped_after_sleep_func | [
"def",
"after_func_accept_retry_state",
"(",
"fn",
")",
":",
"if",
"not",
"six",
".",
"callable",
"(",
"fn",
")",
":",
"return",
"fn",
"if",
"func_takes_retry_state",
"(",
"fn",
")",
":",
"return",
"fn",
"@",
"_utils",
".",
"wraps",
"(",
"fn",
")",
"de... | Wrap "after" function to accept "retry_state". | [
"Wrap",
"after",
"function",
"to",
"accept",
"retry_state",
"."
] | 354c40b7dc8e728c438668100dd020b65c84dfc6 | https://github.com/jd/tenacity/blob/354c40b7dc8e728c438668100dd020b65c84dfc6/tenacity/compat.py#L250-L266 | train | 222,503 |
jd/tenacity | tenacity/compat.py | before_sleep_func_accept_retry_state | def before_sleep_func_accept_retry_state(fn):
"""Wrap "before_sleep" function to accept "retry_state"."""
if not six.callable(fn):
return fn
if func_takes_retry_state(fn):
return fn
@_utils.wraps(fn)
def wrapped_before_sleep_func(retry_state):
# retry_object, sleep, last_result
warn_about_non_retry_state_deprecation(
'before_sleep', fn, stacklevel=4)
return fn(
retry_state.retry_object,
sleep=getattr(retry_state.next_action, 'sleep'),
last_result=retry_state.outcome)
return wrapped_before_sleep_func | python | def before_sleep_func_accept_retry_state(fn):
"""Wrap "before_sleep" function to accept "retry_state"."""
if not six.callable(fn):
return fn
if func_takes_retry_state(fn):
return fn
@_utils.wraps(fn)
def wrapped_before_sleep_func(retry_state):
# retry_object, sleep, last_result
warn_about_non_retry_state_deprecation(
'before_sleep', fn, stacklevel=4)
return fn(
retry_state.retry_object,
sleep=getattr(retry_state.next_action, 'sleep'),
last_result=retry_state.outcome)
return wrapped_before_sleep_func | [
"def",
"before_sleep_func_accept_retry_state",
"(",
"fn",
")",
":",
"if",
"not",
"six",
".",
"callable",
"(",
"fn",
")",
":",
"return",
"fn",
"if",
"func_takes_retry_state",
"(",
"fn",
")",
":",
"return",
"fn",
"@",
"_utils",
".",
"wraps",
"(",
"fn",
")"... | Wrap "before_sleep" function to accept "retry_state". | [
"Wrap",
"before_sleep",
"function",
"to",
"accept",
"retry_state",
"."
] | 354c40b7dc8e728c438668100dd020b65c84dfc6 | https://github.com/jd/tenacity/blob/354c40b7dc8e728c438668100dd020b65c84dfc6/tenacity/compat.py#L269-L286 | train | 222,504 |
divio/django-filer | filer/admin/patched/admin_utils.py | NestedObjects.nested | def nested(self, format_callback=None):
"""
Return the graph as a nested list.
"""
seen = set()
roots = []
for root in self.edges.get(None, ()):
roots.extend(self._nested(root, seen, format_callback))
return roots | python | def nested(self, format_callback=None):
"""
Return the graph as a nested list.
"""
seen = set()
roots = []
for root in self.edges.get(None, ()):
roots.extend(self._nested(root, seen, format_callback))
return roots | [
"def",
"nested",
"(",
"self",
",",
"format_callback",
"=",
"None",
")",
":",
"seen",
"=",
"set",
"(",
")",
"roots",
"=",
"[",
"]",
"for",
"root",
"in",
"self",
".",
"edges",
".",
"get",
"(",
"None",
",",
"(",
")",
")",
":",
"roots",
".",
"exten... | Return the graph as a nested list. | [
"Return",
"the",
"graph",
"as",
"a",
"nested",
"list",
"."
] | 946629087943d41eff290f07bfdf240b8853dd88 | https://github.com/divio/django-filer/blob/946629087943d41eff290f07bfdf240b8853dd88/filer/admin/patched/admin_utils.py#L132-L140 | train | 222,505 |
divio/django-filer | filer/utils/files.py | get_valid_filename | def get_valid_filename(s):
"""
like the regular get_valid_filename, but also slugifies away
umlauts and stuff.
"""
s = get_valid_filename_django(s)
filename, ext = os.path.splitext(s)
filename = slugify(filename)
ext = slugify(ext)
if ext:
return "%s.%s" % (filename, ext)
else:
return "%s" % (filename,) | python | def get_valid_filename(s):
"""
like the regular get_valid_filename, but also slugifies away
umlauts and stuff.
"""
s = get_valid_filename_django(s)
filename, ext = os.path.splitext(s)
filename = slugify(filename)
ext = slugify(ext)
if ext:
return "%s.%s" % (filename, ext)
else:
return "%s" % (filename,) | [
"def",
"get_valid_filename",
"(",
"s",
")",
":",
"s",
"=",
"get_valid_filename_django",
"(",
"s",
")",
"filename",
",",
"ext",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"s",
")",
"filename",
"=",
"slugify",
"(",
"filename",
")",
"ext",
"=",
"slugif... | like the regular get_valid_filename, but also slugifies away
umlauts and stuff. | [
"like",
"the",
"regular",
"get_valid_filename",
"but",
"also",
"slugifies",
"away",
"umlauts",
"and",
"stuff",
"."
] | 946629087943d41eff290f07bfdf240b8853dd88 | https://github.com/divio/django-filer/blob/946629087943d41eff290f07bfdf240b8853dd88/filer/utils/files.py#L122-L134 | train | 222,506 |
divio/django-filer | filer/management/commands/import_files.py | FileImporter.walker | def walker(self, path=None, base_folder=None):
"""
This method walk a directory structure and create the
Folders and Files as they appear.
"""
path = path or self.path or ''
base_folder = base_folder or self.base_folder
# prevent trailing slashes and other inconsistencies on path.
path = os.path.normpath(upath(path))
if base_folder:
base_folder = os.path.normpath(upath(base_folder))
print("The directory structure will be imported in %s" % (base_folder,))
if self.verbosity >= 1:
print("Import the folders and files in %s" % (path,))
root_folder_name = os.path.basename(path)
for root, dirs, files in os.walk(path):
rel_folders = root.partition(path)[2].strip(os.path.sep).split(os.path.sep)
while '' in rel_folders:
rel_folders.remove('')
if base_folder:
folder_names = base_folder.split('/') + [root_folder_name] + rel_folders
else:
folder_names = [root_folder_name] + rel_folders
folder = self.get_or_create_folder(folder_names)
for file_obj in files:
dj_file = DjangoFile(open(os.path.join(root, file_obj), mode='rb'),
name=file_obj)
self.import_file(file_obj=dj_file, folder=folder)
if self.verbosity >= 1:
print(('folder_created #%s / file_created #%s / ' + 'image_created #%s') % (self.folder_created, self.file_created, self.image_created)) | python | def walker(self, path=None, base_folder=None):
"""
This method walk a directory structure and create the
Folders and Files as they appear.
"""
path = path or self.path or ''
base_folder = base_folder or self.base_folder
# prevent trailing slashes and other inconsistencies on path.
path = os.path.normpath(upath(path))
if base_folder:
base_folder = os.path.normpath(upath(base_folder))
print("The directory structure will be imported in %s" % (base_folder,))
if self.verbosity >= 1:
print("Import the folders and files in %s" % (path,))
root_folder_name = os.path.basename(path)
for root, dirs, files in os.walk(path):
rel_folders = root.partition(path)[2].strip(os.path.sep).split(os.path.sep)
while '' in rel_folders:
rel_folders.remove('')
if base_folder:
folder_names = base_folder.split('/') + [root_folder_name] + rel_folders
else:
folder_names = [root_folder_name] + rel_folders
folder = self.get_or_create_folder(folder_names)
for file_obj in files:
dj_file = DjangoFile(open(os.path.join(root, file_obj), mode='rb'),
name=file_obj)
self.import_file(file_obj=dj_file, folder=folder)
if self.verbosity >= 1:
print(('folder_created #%s / file_created #%s / ' + 'image_created #%s') % (self.folder_created, self.file_created, self.image_created)) | [
"def",
"walker",
"(",
"self",
",",
"path",
"=",
"None",
",",
"base_folder",
"=",
"None",
")",
":",
"path",
"=",
"path",
"or",
"self",
".",
"path",
"or",
"''",
"base_folder",
"=",
"base_folder",
"or",
"self",
".",
"base_folder",
"# prevent trailing slashes ... | This method walk a directory structure and create the
Folders and Files as they appear. | [
"This",
"method",
"walk",
"a",
"directory",
"structure",
"and",
"create",
"the",
"Folders",
"and",
"Files",
"as",
"they",
"appear",
"."
] | 946629087943d41eff290f07bfdf240b8853dd88 | https://github.com/divio/django-filer/blob/946629087943d41eff290f07bfdf240b8853dd88/filer/management/commands/import_files.py#L79-L108 | train | 222,507 |
divio/django-filer | filer/utils/zip.py | unzip | def unzip(file_obj):
"""
Take a path to a zipfile and checks if it is a valid zip file
and returns...
"""
files = []
# TODO: implement try-except here
zip = ZipFile(file_obj)
bad_file = zip.testzip()
if bad_file:
raise Exception('"%s" in the .zip archive is corrupt.' % bad_file)
infolist = zip.infolist()
for zipinfo in infolist:
if zipinfo.filename.startswith('__'): # do not process meta files
continue
file_obj = SimpleUploadedFile(name=zipinfo.filename, content=zip.read(zipinfo))
files.append((file_obj, zipinfo.filename))
zip.close()
return files | python | def unzip(file_obj):
"""
Take a path to a zipfile and checks if it is a valid zip file
and returns...
"""
files = []
# TODO: implement try-except here
zip = ZipFile(file_obj)
bad_file = zip.testzip()
if bad_file:
raise Exception('"%s" in the .zip archive is corrupt.' % bad_file)
infolist = zip.infolist()
for zipinfo in infolist:
if zipinfo.filename.startswith('__'): # do not process meta files
continue
file_obj = SimpleUploadedFile(name=zipinfo.filename, content=zip.read(zipinfo))
files.append((file_obj, zipinfo.filename))
zip.close()
return files | [
"def",
"unzip",
"(",
"file_obj",
")",
":",
"files",
"=",
"[",
"]",
"# TODO: implement try-except here",
"zip",
"=",
"ZipFile",
"(",
"file_obj",
")",
"bad_file",
"=",
"zip",
".",
"testzip",
"(",
")",
"if",
"bad_file",
":",
"raise",
"Exception",
"(",
"'\"%s\... | Take a path to a zipfile and checks if it is a valid zip file
and returns... | [
"Take",
"a",
"path",
"to",
"a",
"zipfile",
"and",
"checks",
"if",
"it",
"is",
"a",
"valid",
"zip",
"file",
"and",
"returns",
"..."
] | 946629087943d41eff290f07bfdf240b8853dd88 | https://github.com/divio/django-filer/blob/946629087943d41eff290f07bfdf240b8853dd88/filer/utils/zip.py#L9-L27 | train | 222,508 |
divio/django-filer | filer/utils/filer_easy_thumbnails.py | ThumbnailerNameMixin.get_thumbnail_name | def get_thumbnail_name(self, thumbnail_options, transparent=False,
high_resolution=False):
"""
A version of ``Thumbnailer.get_thumbnail_name`` that produces a
reproducible thumbnail name that can be converted back to the original
filename.
"""
path, source_filename = os.path.split(self.name)
source_extension = os.path.splitext(source_filename)[1][1:]
if self.thumbnail_preserve_extensions is True or \
(self.thumbnail_preserve_extensions and source_extension.lower()
in self.thumbnail_preserve_extensions):
extension = source_extension
elif transparent:
extension = self.thumbnail_transparency_extension
else:
extension = self.thumbnail_extension
extension = extension or 'jpg'
thumbnail_options = thumbnail_options.copy()
size = tuple(thumbnail_options.pop('size'))
quality = thumbnail_options.pop('quality', self.thumbnail_quality)
initial_opts = ['%sx%s' % size, 'q%s' % quality]
opts = list(thumbnail_options.items())
opts.sort() # Sort the options so the file name is consistent.
opts = ['%s' % (v is not True and '%s-%s' % (k, v) or k)
for k, v in opts if v]
all_opts = '_'.join(initial_opts + opts)
basedir = self.thumbnail_basedir
subdir = self.thumbnail_subdir
# make sure our magic delimiter is not used in all_opts
all_opts = all_opts.replace('__', '_')
if high_resolution:
try:
all_opts += self.thumbnail_highres_infix
except AttributeError:
all_opts += '@2x'
filename = '%s__%s.%s' % (source_filename, all_opts, extension)
return os.path.join(basedir, path, subdir, filename) | python | def get_thumbnail_name(self, thumbnail_options, transparent=False,
high_resolution=False):
"""
A version of ``Thumbnailer.get_thumbnail_name`` that produces a
reproducible thumbnail name that can be converted back to the original
filename.
"""
path, source_filename = os.path.split(self.name)
source_extension = os.path.splitext(source_filename)[1][1:]
if self.thumbnail_preserve_extensions is True or \
(self.thumbnail_preserve_extensions and source_extension.lower()
in self.thumbnail_preserve_extensions):
extension = source_extension
elif transparent:
extension = self.thumbnail_transparency_extension
else:
extension = self.thumbnail_extension
extension = extension or 'jpg'
thumbnail_options = thumbnail_options.copy()
size = tuple(thumbnail_options.pop('size'))
quality = thumbnail_options.pop('quality', self.thumbnail_quality)
initial_opts = ['%sx%s' % size, 'q%s' % quality]
opts = list(thumbnail_options.items())
opts.sort() # Sort the options so the file name is consistent.
opts = ['%s' % (v is not True and '%s-%s' % (k, v) or k)
for k, v in opts if v]
all_opts = '_'.join(initial_opts + opts)
basedir = self.thumbnail_basedir
subdir = self.thumbnail_subdir
# make sure our magic delimiter is not used in all_opts
all_opts = all_opts.replace('__', '_')
if high_resolution:
try:
all_opts += self.thumbnail_highres_infix
except AttributeError:
all_opts += '@2x'
filename = '%s__%s.%s' % (source_filename, all_opts, extension)
return os.path.join(basedir, path, subdir, filename) | [
"def",
"get_thumbnail_name",
"(",
"self",
",",
"thumbnail_options",
",",
"transparent",
"=",
"False",
",",
"high_resolution",
"=",
"False",
")",
":",
"path",
",",
"source_filename",
"=",
"os",
".",
"path",
".",
"split",
"(",
"self",
".",
"name",
")",
"sour... | A version of ``Thumbnailer.get_thumbnail_name`` that produces a
reproducible thumbnail name that can be converted back to the original
filename. | [
"A",
"version",
"of",
"Thumbnailer",
".",
"get_thumbnail_name",
"that",
"produces",
"a",
"reproducible",
"thumbnail",
"name",
"that",
"can",
"be",
"converted",
"back",
"to",
"the",
"original",
"filename",
"."
] | 946629087943d41eff290f07bfdf240b8853dd88 | https://github.com/divio/django-filer/blob/946629087943d41eff290f07bfdf240b8853dd88/filer/utils/filer_easy_thumbnails.py#L29-L72 | train | 222,509 |
divio/django-filer | filer/utils/filer_easy_thumbnails.py | ActionThumbnailerMixin.get_thumbnail_name | def get_thumbnail_name(self, thumbnail_options, transparent=False,
high_resolution=False):
"""
A version of ``Thumbnailer.get_thumbnail_name`` that returns the original
filename to resize.
"""
path, filename = os.path.split(self.name)
basedir = self.thumbnail_basedir
subdir = self.thumbnail_subdir
return os.path.join(basedir, path, subdir, filename) | python | def get_thumbnail_name(self, thumbnail_options, transparent=False,
high_resolution=False):
"""
A version of ``Thumbnailer.get_thumbnail_name`` that returns the original
filename to resize.
"""
path, filename = os.path.split(self.name)
basedir = self.thumbnail_basedir
subdir = self.thumbnail_subdir
return os.path.join(basedir, path, subdir, filename) | [
"def",
"get_thumbnail_name",
"(",
"self",
",",
"thumbnail_options",
",",
"transparent",
"=",
"False",
",",
"high_resolution",
"=",
"False",
")",
":",
"path",
",",
"filename",
"=",
"os",
".",
"path",
".",
"split",
"(",
"self",
".",
"name",
")",
"basedir",
... | A version of ``Thumbnailer.get_thumbnail_name`` that returns the original
filename to resize. | [
"A",
"version",
"of",
"Thumbnailer",
".",
"get_thumbnail_name",
"that",
"returns",
"the",
"original",
"filename",
"to",
"resize",
"."
] | 946629087943d41eff290f07bfdf240b8853dd88 | https://github.com/divio/django-filer/blob/946629087943d41eff290f07bfdf240b8853dd88/filer/utils/filer_easy_thumbnails.py#L80-L91 | train | 222,510 |
divio/django-filer | filer/admin/folderadmin.py | FolderAdmin.owner_search_fields | def owner_search_fields(self):
"""
Returns all the fields that are CharFields except for password from the
User model. For the built-in User model, that means username,
first_name, last_name, and email.
"""
try:
from django.contrib.auth import get_user_model
except ImportError: # Django < 1.5
from django.contrib.auth.models import User
else:
User = get_user_model()
return [
field.name for field in User._meta.fields
if isinstance(field, models.CharField) and field.name != 'password'
] | python | def owner_search_fields(self):
"""
Returns all the fields that are CharFields except for password from the
User model. For the built-in User model, that means username,
first_name, last_name, and email.
"""
try:
from django.contrib.auth import get_user_model
except ImportError: # Django < 1.5
from django.contrib.auth.models import User
else:
User = get_user_model()
return [
field.name for field in User._meta.fields
if isinstance(field, models.CharField) and field.name != 'password'
] | [
"def",
"owner_search_fields",
"(",
"self",
")",
":",
"try",
":",
"from",
"django",
".",
"contrib",
".",
"auth",
"import",
"get_user_model",
"except",
"ImportError",
":",
"# Django < 1.5",
"from",
"django",
".",
"contrib",
".",
"auth",
".",
"models",
"import",
... | Returns all the fields that are CharFields except for password from the
User model. For the built-in User model, that means username,
first_name, last_name, and email. | [
"Returns",
"all",
"the",
"fields",
"that",
"are",
"CharFields",
"except",
"for",
"password",
"from",
"the",
"User",
"model",
".",
"For",
"the",
"built",
"-",
"in",
"User",
"model",
"that",
"means",
"username",
"first_name",
"last_name",
"and",
"email",
"."
] | 946629087943d41eff290f07bfdf240b8853dd88 | https://github.com/divio/django-filer/blob/946629087943d41eff290f07bfdf240b8853dd88/filer/admin/folderadmin.py#L481-L496 | train | 222,511 |
divio/django-filer | filer/admin/folderadmin.py | FolderAdmin.move_to_clipboard | def move_to_clipboard(self, request, files_queryset, folders_queryset):
"""
Action which moves the selected files and files in selected folders
to clipboard.
"""
if not self.has_change_permission(request):
raise PermissionDenied
if request.method != 'POST':
return None
clipboard = tools.get_user_clipboard(request.user)
check_files_edit_permissions(request, files_queryset)
check_folder_edit_permissions(request, folders_queryset)
# TODO: Display a confirmation page if moving more than X files to
# clipboard?
# We define it like that so that we can modify it inside the
# move_files function
files_count = [0]
def move_files(files):
files_count[0] += tools.move_file_to_clipboard(files, clipboard)
def move_folders(folders):
for f in folders:
move_files(f.files)
move_folders(f.children.all())
move_files(files_queryset)
move_folders(folders_queryset)
self.message_user(request, _("Successfully moved %(count)d files to "
"clipboard.") % {"count": files_count[0]})
return None | python | def move_to_clipboard(self, request, files_queryset, folders_queryset):
"""
Action which moves the selected files and files in selected folders
to clipboard.
"""
if not self.has_change_permission(request):
raise PermissionDenied
if request.method != 'POST':
return None
clipboard = tools.get_user_clipboard(request.user)
check_files_edit_permissions(request, files_queryset)
check_folder_edit_permissions(request, folders_queryset)
# TODO: Display a confirmation page if moving more than X files to
# clipboard?
# We define it like that so that we can modify it inside the
# move_files function
files_count = [0]
def move_files(files):
files_count[0] += tools.move_file_to_clipboard(files, clipboard)
def move_folders(folders):
for f in folders:
move_files(f.files)
move_folders(f.children.all())
move_files(files_queryset)
move_folders(folders_queryset)
self.message_user(request, _("Successfully moved %(count)d files to "
"clipboard.") % {"count": files_count[0]})
return None | [
"def",
"move_to_clipboard",
"(",
"self",
",",
"request",
",",
"files_queryset",
",",
"folders_queryset",
")",
":",
"if",
"not",
"self",
".",
"has_change_permission",
"(",
"request",
")",
":",
"raise",
"PermissionDenied",
"if",
"request",
".",
"method",
"!=",
"... | Action which moves the selected files and files in selected folders
to clipboard. | [
"Action",
"which",
"moves",
"the",
"selected",
"files",
"and",
"files",
"in",
"selected",
"folders",
"to",
"clipboard",
"."
] | 946629087943d41eff290f07bfdf240b8853dd88 | https://github.com/divio/django-filer/blob/946629087943d41eff290f07bfdf240b8853dd88/filer/admin/folderadmin.py#L596-L634 | train | 222,512 |
divio/django-filer | filer/admin/tools.py | admin_url_params | def admin_url_params(request, params=None):
"""
given a request, looks at GET and POST values to determine which params
should be added. Is used to keep the context of popup and picker mode.
"""
params = params or {}
if popup_status(request):
params[IS_POPUP_VAR] = '1'
pick_type = popup_pick_type(request)
if pick_type:
params['_pick'] = pick_type
return params | python | def admin_url_params(request, params=None):
"""
given a request, looks at GET and POST values to determine which params
should be added. Is used to keep the context of popup and picker mode.
"""
params = params or {}
if popup_status(request):
params[IS_POPUP_VAR] = '1'
pick_type = popup_pick_type(request)
if pick_type:
params['_pick'] = pick_type
return params | [
"def",
"admin_url_params",
"(",
"request",
",",
"params",
"=",
"None",
")",
":",
"params",
"=",
"params",
"or",
"{",
"}",
"if",
"popup_status",
"(",
"request",
")",
":",
"params",
"[",
"IS_POPUP_VAR",
"]",
"=",
"'1'",
"pick_type",
"=",
"popup_pick_type",
... | given a request, looks at GET and POST values to determine which params
should be added. Is used to keep the context of popup and picker mode. | [
"given",
"a",
"request",
"looks",
"at",
"GET",
"and",
"POST",
"values",
"to",
"determine",
"which",
"params",
"should",
"be",
"added",
".",
"Is",
"used",
"to",
"keep",
"the",
"context",
"of",
"popup",
"and",
"picker",
"mode",
"."
] | 946629087943d41eff290f07bfdf240b8853dd88 | https://github.com/divio/django-filer/blob/946629087943d41eff290f07bfdf240b8853dd88/filer/admin/tools.py#L70-L81 | train | 222,513 |
divio/django-filer | filer/admin/imageadmin.py | ImageAdminForm.clean_subject_location | def clean_subject_location(self):
"""
Validate subject_location preserving last saved value.
Last valid value of the subject_location field is shown to the user
for subject location widget to receive valid coordinates on field
validation errors.
"""
cleaned_data = super(ImageAdminForm, self).clean()
subject_location = cleaned_data['subject_location']
if not subject_location:
# if supplied subject location is empty, do not check it
return subject_location
# use thumbnail's helper function to check the format
coordinates = normalize_subject_location(subject_location)
if not coordinates:
err_msg = ugettext_lazy('Invalid subject location format. ')
err_code = 'invalid_subject_format'
elif (
coordinates[0] > self.instance.width
or coordinates[1] > self.instance.height
):
err_msg = ugettext_lazy(
'Subject location is outside of the image. ')
err_code = 'subject_out_of_bounds'
else:
return subject_location
self._set_previous_subject_location(cleaned_data)
raise forms.ValidationError(
string_concat(
err_msg,
ugettext_lazy('Your input: "{subject_location}". '.format(
subject_location=subject_location)),
'Previous value is restored.'),
code=err_code) | python | def clean_subject_location(self):
"""
Validate subject_location preserving last saved value.
Last valid value of the subject_location field is shown to the user
for subject location widget to receive valid coordinates on field
validation errors.
"""
cleaned_data = super(ImageAdminForm, self).clean()
subject_location = cleaned_data['subject_location']
if not subject_location:
# if supplied subject location is empty, do not check it
return subject_location
# use thumbnail's helper function to check the format
coordinates = normalize_subject_location(subject_location)
if not coordinates:
err_msg = ugettext_lazy('Invalid subject location format. ')
err_code = 'invalid_subject_format'
elif (
coordinates[0] > self.instance.width
or coordinates[1] > self.instance.height
):
err_msg = ugettext_lazy(
'Subject location is outside of the image. ')
err_code = 'subject_out_of_bounds'
else:
return subject_location
self._set_previous_subject_location(cleaned_data)
raise forms.ValidationError(
string_concat(
err_msg,
ugettext_lazy('Your input: "{subject_location}". '.format(
subject_location=subject_location)),
'Previous value is restored.'),
code=err_code) | [
"def",
"clean_subject_location",
"(",
"self",
")",
":",
"cleaned_data",
"=",
"super",
"(",
"ImageAdminForm",
",",
"self",
")",
".",
"clean",
"(",
")",
"subject_location",
"=",
"cleaned_data",
"[",
"'subject_location'",
"]",
"if",
"not",
"subject_location",
":",
... | Validate subject_location preserving last saved value.
Last valid value of the subject_location field is shown to the user
for subject location widget to receive valid coordinates on field
validation errors. | [
"Validate",
"subject_location",
"preserving",
"last",
"saved",
"value",
"."
] | 946629087943d41eff290f07bfdf240b8853dd88 | https://github.com/divio/django-filer/blob/946629087943d41eff290f07bfdf240b8853dd88/filer/admin/imageadmin.py#L42-L80 | train | 222,514 |
divio/django-filer | filer/utils/loader.py | load_object | def load_object(import_path):
"""
Loads an object from an 'import_path', like in MIDDLEWARE_CLASSES and the
likes.
Import paths should be: "mypackage.mymodule.MyObject". It then imports the
module up until the last dot and tries to get the attribute after that dot
from the imported module.
If the import path does not contain any dots, a TypeError is raised.
If the module cannot be imported, an ImportError is raised.
If the attribute does not exist in the module, a AttributeError is raised.
"""
if not isinstance(import_path, six.string_types):
return import_path
if '.' not in import_path:
raise TypeError(
"'import_path' argument to 'django_load.core.load_object' must "
"contain at least one dot.")
module_name, object_name = import_path.rsplit('.', 1)
module = import_module(module_name)
return getattr(module, object_name) | python | def load_object(import_path):
"""
Loads an object from an 'import_path', like in MIDDLEWARE_CLASSES and the
likes.
Import paths should be: "mypackage.mymodule.MyObject". It then imports the
module up until the last dot and tries to get the attribute after that dot
from the imported module.
If the import path does not contain any dots, a TypeError is raised.
If the module cannot be imported, an ImportError is raised.
If the attribute does not exist in the module, a AttributeError is raised.
"""
if not isinstance(import_path, six.string_types):
return import_path
if '.' not in import_path:
raise TypeError(
"'import_path' argument to 'django_load.core.load_object' must "
"contain at least one dot.")
module_name, object_name = import_path.rsplit('.', 1)
module = import_module(module_name)
return getattr(module, object_name) | [
"def",
"load_object",
"(",
"import_path",
")",
":",
"if",
"not",
"isinstance",
"(",
"import_path",
",",
"six",
".",
"string_types",
")",
":",
"return",
"import_path",
"if",
"'.'",
"not",
"in",
"import_path",
":",
"raise",
"TypeError",
"(",
"\"'import_path' arg... | Loads an object from an 'import_path', like in MIDDLEWARE_CLASSES and the
likes.
Import paths should be: "mypackage.mymodule.MyObject". It then imports the
module up until the last dot and tries to get the attribute after that dot
from the imported module.
If the import path does not contain any dots, a TypeError is raised.
If the module cannot be imported, an ImportError is raised.
If the attribute does not exist in the module, a AttributeError is raised. | [
"Loads",
"an",
"object",
"from",
"an",
"import_path",
"like",
"in",
"MIDDLEWARE_CLASSES",
"and",
"the",
"likes",
"."
] | 946629087943d41eff290f07bfdf240b8853dd88 | https://github.com/divio/django-filer/blob/946629087943d41eff290f07bfdf240b8853dd88/filer/utils/loader.py#L18-L41 | train | 222,515 |
divio/django-filer | filer/management/commands/generate_thumbnails.py | Command.handle | def handle(self, *args, **options):
"""
Generates image thumbnails
NOTE: To keep memory consumption stable avoid iteration over the Image queryset
"""
pks = Image.objects.all().values_list('id', flat=True)
total = len(pks)
for idx, pk in enumerate(pks):
image = None
try:
image = Image.objects.get(pk=pk)
self.stdout.write(u'Processing image {0} / {1} {2}'.format(idx + 1, total, image))
self.stdout.flush()
image.thumbnails
image.icons
except IOError as e:
self.stderr.write('Failed to generate thumbnails: {0}'.format(str(e)))
self.stderr.flush()
finally:
del image | python | def handle(self, *args, **options):
"""
Generates image thumbnails
NOTE: To keep memory consumption stable avoid iteration over the Image queryset
"""
pks = Image.objects.all().values_list('id', flat=True)
total = len(pks)
for idx, pk in enumerate(pks):
image = None
try:
image = Image.objects.get(pk=pk)
self.stdout.write(u'Processing image {0} / {1} {2}'.format(idx + 1, total, image))
self.stdout.flush()
image.thumbnails
image.icons
except IOError as e:
self.stderr.write('Failed to generate thumbnails: {0}'.format(str(e)))
self.stderr.flush()
finally:
del image | [
"def",
"handle",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"options",
")",
":",
"pks",
"=",
"Image",
".",
"objects",
".",
"all",
"(",
")",
".",
"values_list",
"(",
"'id'",
",",
"flat",
"=",
"True",
")",
"total",
"=",
"len",
"(",
"pks",
")",... | Generates image thumbnails
NOTE: To keep memory consumption stable avoid iteration over the Image queryset | [
"Generates",
"image",
"thumbnails"
] | 946629087943d41eff290f07bfdf240b8853dd88 | https://github.com/divio/django-filer/blob/946629087943d41eff290f07bfdf240b8853dd88/filer/management/commands/generate_thumbnails.py#L9-L29 | train | 222,516 |
divio/django-filer | filer/utils/compatibility.py | upath | def upath(path):
"""
Always return a unicode path.
"""
if six.PY2 and not isinstance(path, six.text_type):
return path.decode(fs_encoding)
return path | python | def upath(path):
"""
Always return a unicode path.
"""
if six.PY2 and not isinstance(path, six.text_type):
return path.decode(fs_encoding)
return path | [
"def",
"upath",
"(",
"path",
")",
":",
"if",
"six",
".",
"PY2",
"and",
"not",
"isinstance",
"(",
"path",
",",
"six",
".",
"text_type",
")",
":",
"return",
"path",
".",
"decode",
"(",
"fs_encoding",
")",
"return",
"path"
] | Always return a unicode path. | [
"Always",
"return",
"a",
"unicode",
"path",
"."
] | 946629087943d41eff290f07bfdf240b8853dd88 | https://github.com/divio/django-filer/blob/946629087943d41eff290f07bfdf240b8853dd88/filer/utils/compatibility.py#L60-L66 | train | 222,517 |
divio/django-filer | filer/utils/model_label.py | get_model_label | def get_model_label(model):
"""
Take a model class or model label and return its model label.
>>> get_model_label(MyModel)
"myapp.MyModel"
>>> get_model_label("myapp.MyModel")
"myapp.MyModel"
"""
if isinstance(model, six.string_types):
return model
else:
return "%s.%s" % (
model._meta.app_label,
model.__name__
) | python | def get_model_label(model):
"""
Take a model class or model label and return its model label.
>>> get_model_label(MyModel)
"myapp.MyModel"
>>> get_model_label("myapp.MyModel")
"myapp.MyModel"
"""
if isinstance(model, six.string_types):
return model
else:
return "%s.%s" % (
model._meta.app_label,
model.__name__
) | [
"def",
"get_model_label",
"(",
"model",
")",
":",
"if",
"isinstance",
"(",
"model",
",",
"six",
".",
"string_types",
")",
":",
"return",
"model",
"else",
":",
"return",
"\"%s.%s\"",
"%",
"(",
"model",
".",
"_meta",
".",
"app_label",
",",
"model",
".",
... | Take a model class or model label and return its model label.
>>> get_model_label(MyModel)
"myapp.MyModel"
>>> get_model_label("myapp.MyModel")
"myapp.MyModel" | [
"Take",
"a",
"model",
"class",
"or",
"model",
"label",
"and",
"return",
"its",
"model",
"label",
"."
] | 946629087943d41eff290f07bfdf240b8853dd88 | https://github.com/divio/django-filer/blob/946629087943d41eff290f07bfdf240b8853dd88/filer/utils/model_label.py#L8-L24 | train | 222,518 |
divio/django-filer | filer/admin/clipboardadmin.py | ajax_upload | def ajax_upload(request, folder_id=None):
"""
Receives an upload from the uploader. Receives only one file at a time.
"""
folder = None
if folder_id:
try:
# Get folder
folder = Folder.objects.get(pk=folder_id)
except Folder.DoesNotExist:
return JsonResponse({'error': NO_FOLDER_ERROR})
# check permissions
if folder and not folder.has_add_children_permission(request):
return JsonResponse({'error': NO_PERMISSIONS_FOR_FOLDER})
try:
if len(request.FILES) == 1:
# dont check if request is ajax or not, just grab the file
upload, filename, is_raw = handle_request_files_upload(request)
else:
# else process the request as usual
upload, filename, is_raw = handle_upload(request)
# TODO: Deprecated/refactor
# Get clipboad
# clipboard = Clipboard.objects.get_or_create(user=request.user)[0]
# find the file type
for filer_class in filer_settings.FILER_FILE_MODELS:
FileSubClass = load_model(filer_class)
# TODO: What if there are more than one that qualify?
if FileSubClass.matches_file_type(filename, upload, request):
FileForm = modelform_factory(
model=FileSubClass,
fields=('original_filename', 'owner', 'file')
)
break
uploadform = FileForm({'original_filename': filename,
'owner': request.user.pk},
{'file': upload})
if uploadform.is_valid():
file_obj = uploadform.save(commit=False)
# Enforce the FILER_IS_PUBLIC_DEFAULT
file_obj.is_public = filer_settings.FILER_IS_PUBLIC_DEFAULT
file_obj.folder = folder
file_obj.save()
# TODO: Deprecated/refactor
# clipboard_item = ClipboardItem(
# clipboard=clipboard, file=file_obj)
# clipboard_item.save()
# Try to generate thumbnails.
if not file_obj.icons:
# There is no point to continue, as we can't generate
# thumbnails for this file. Usual reasons: bad format or
# filename.
file_obj.delete()
# This would be logged in BaseImage._generate_thumbnails()
# if FILER_ENABLE_LOGGING is on.
return JsonResponse(
{'error': 'failed to generate icons for file'},
status=500,
)
thumbnail = None
# Backwards compatibility: try to get specific icon size (32px)
# first. Then try medium icon size (they are already sorted),
# fallback to the first (smallest) configured icon.
for size in (['32']
+ filer_settings.FILER_ADMIN_ICON_SIZES[1::-1]):
try:
thumbnail = file_obj.icons[size]
break
except KeyError:
continue
data = {
'thumbnail': thumbnail,
'alt_text': '',
'label': str(file_obj),
'file_id': file_obj.pk,
}
# prepare preview thumbnail
if type(file_obj) == Image:
thumbnail_180_options = {
'size': (180, 180),
'crop': True,
'upscale': True,
}
thumbnail_180 = file_obj.file.get_thumbnail(
thumbnail_180_options)
data['thumbnail_180'] = thumbnail_180.url
data['original_image'] = file_obj.url
return JsonResponse(data)
else:
form_errors = '; '.join(['%s: %s' % (
field,
', '.join(errors)) for field, errors in list(
uploadform.errors.items())
])
raise UploadException(
"AJAX request not valid: form invalid '%s'" % (
form_errors,))
except UploadException as e:
return JsonResponse({'error': str(e)}, status=500) | python | def ajax_upload(request, folder_id=None):
"""
Receives an upload from the uploader. Receives only one file at a time.
"""
folder = None
if folder_id:
try:
# Get folder
folder = Folder.objects.get(pk=folder_id)
except Folder.DoesNotExist:
return JsonResponse({'error': NO_FOLDER_ERROR})
# check permissions
if folder and not folder.has_add_children_permission(request):
return JsonResponse({'error': NO_PERMISSIONS_FOR_FOLDER})
try:
if len(request.FILES) == 1:
# dont check if request is ajax or not, just grab the file
upload, filename, is_raw = handle_request_files_upload(request)
else:
# else process the request as usual
upload, filename, is_raw = handle_upload(request)
# TODO: Deprecated/refactor
# Get clipboad
# clipboard = Clipboard.objects.get_or_create(user=request.user)[0]
# find the file type
for filer_class in filer_settings.FILER_FILE_MODELS:
FileSubClass = load_model(filer_class)
# TODO: What if there are more than one that qualify?
if FileSubClass.matches_file_type(filename, upload, request):
FileForm = modelform_factory(
model=FileSubClass,
fields=('original_filename', 'owner', 'file')
)
break
uploadform = FileForm({'original_filename': filename,
'owner': request.user.pk},
{'file': upload})
if uploadform.is_valid():
file_obj = uploadform.save(commit=False)
# Enforce the FILER_IS_PUBLIC_DEFAULT
file_obj.is_public = filer_settings.FILER_IS_PUBLIC_DEFAULT
file_obj.folder = folder
file_obj.save()
# TODO: Deprecated/refactor
# clipboard_item = ClipboardItem(
# clipboard=clipboard, file=file_obj)
# clipboard_item.save()
# Try to generate thumbnails.
if not file_obj.icons:
# There is no point to continue, as we can't generate
# thumbnails for this file. Usual reasons: bad format or
# filename.
file_obj.delete()
# This would be logged in BaseImage._generate_thumbnails()
# if FILER_ENABLE_LOGGING is on.
return JsonResponse(
{'error': 'failed to generate icons for file'},
status=500,
)
thumbnail = None
# Backwards compatibility: try to get specific icon size (32px)
# first. Then try medium icon size (they are already sorted),
# fallback to the first (smallest) configured icon.
for size in (['32']
+ filer_settings.FILER_ADMIN_ICON_SIZES[1::-1]):
try:
thumbnail = file_obj.icons[size]
break
except KeyError:
continue
data = {
'thumbnail': thumbnail,
'alt_text': '',
'label': str(file_obj),
'file_id': file_obj.pk,
}
# prepare preview thumbnail
if type(file_obj) == Image:
thumbnail_180_options = {
'size': (180, 180),
'crop': True,
'upscale': True,
}
thumbnail_180 = file_obj.file.get_thumbnail(
thumbnail_180_options)
data['thumbnail_180'] = thumbnail_180.url
data['original_image'] = file_obj.url
return JsonResponse(data)
else:
form_errors = '; '.join(['%s: %s' % (
field,
', '.join(errors)) for field, errors in list(
uploadform.errors.items())
])
raise UploadException(
"AJAX request not valid: form invalid '%s'" % (
form_errors,))
except UploadException as e:
return JsonResponse({'error': str(e)}, status=500) | [
"def",
"ajax_upload",
"(",
"request",
",",
"folder_id",
"=",
"None",
")",
":",
"folder",
"=",
"None",
"if",
"folder_id",
":",
"try",
":",
"# Get folder",
"folder",
"=",
"Folder",
".",
"objects",
".",
"get",
"(",
"pk",
"=",
"folder_id",
")",
"except",
"... | Receives an upload from the uploader. Receives only one file at a time. | [
"Receives",
"an",
"upload",
"from",
"the",
"uploader",
".",
"Receives",
"only",
"one",
"file",
"at",
"a",
"time",
"."
] | 946629087943d41eff290f07bfdf240b8853dd88 | https://github.com/divio/django-filer/blob/946629087943d41eff290f07bfdf240b8853dd88/filer/admin/clipboardadmin.py#L72-L174 | train | 222,519 |
pyeve/cerberus | cerberus/validator.py | BareValidator.__store_config | def __store_config(self, args, kwargs):
""" Assign args to kwargs and store configuration. """
signature = (
'schema',
'ignore_none_values',
'allow_unknown',
'require_all',
'purge_unknown',
'purge_readonly',
)
for i, p in enumerate(signature[: len(args)]):
if p in kwargs:
raise TypeError("__init__ got multiple values for argument " "'%s'" % p)
else:
kwargs[p] = args[i]
self._config = kwargs
""" This dictionary holds the configuration arguments that were used to
initialize the :class:`Validator` instance except the
``error_handler``. """ | python | def __store_config(self, args, kwargs):
""" Assign args to kwargs and store configuration. """
signature = (
'schema',
'ignore_none_values',
'allow_unknown',
'require_all',
'purge_unknown',
'purge_readonly',
)
for i, p in enumerate(signature[: len(args)]):
if p in kwargs:
raise TypeError("__init__ got multiple values for argument " "'%s'" % p)
else:
kwargs[p] = args[i]
self._config = kwargs
""" This dictionary holds the configuration arguments that were used to
initialize the :class:`Validator` instance except the
``error_handler``. """ | [
"def",
"__store_config",
"(",
"self",
",",
"args",
",",
"kwargs",
")",
":",
"signature",
"=",
"(",
"'schema'",
",",
"'ignore_none_values'",
",",
"'allow_unknown'",
",",
"'require_all'",
",",
"'purge_unknown'",
",",
"'purge_readonly'",
",",
")",
"for",
"i",
","... | Assign args to kwargs and store configuration. | [
"Assign",
"args",
"to",
"kwargs",
"and",
"store",
"configuration",
"."
] | 688a67a4069e88042ed424bda7be0f4fa5fc3910 | https://github.com/pyeve/cerberus/blob/688a67a4069e88042ed424bda7be0f4fa5fc3910/cerberus/validator.py#L207-L225 | train | 222,520 |
pyeve/cerberus | cerberus/validator.py | BareValidator._error | def _error(self, *args):
""" Creates and adds one or multiple errors.
:param args: Accepts different argument's signatures.
*1. Bulk addition of errors:*
- :term:`iterable` of
:class:`~cerberus.errors.ValidationError`-instances
The errors will be added to
:attr:`~cerberus.Validator._errors`.
*2. Custom error:*
- the invalid field's name
- the error message
A custom error containing the message will be created and
added to :attr:`~cerberus.Validator._errors`.
There will however be fewer information contained in the
error (no reference to the violated rule and its
constraint).
*3. Defined error:*
- the invalid field's name
- the error-reference, see :mod:`cerberus.errors`
- arbitrary, supplemental information about the error
A :class:`~cerberus.errors.ValidationError` instance will
be created and added to
:attr:`~cerberus.Validator._errors`.
"""
if len(args) == 1:
self._errors.extend(args[0])
self._errors.sort()
for error in args[0]:
self.document_error_tree.add(error)
self.schema_error_tree.add(error)
self.error_handler.emit(error)
elif len(args) == 2 and isinstance(args[1], _str_type):
self._error(args[0], errors.CUSTOM, args[1])
elif len(args) >= 2:
field = args[0]
code = args[1].code
rule = args[1].rule
info = args[2:]
document_path = self.document_path + (field,)
schema_path = self.schema_path
if code != errors.UNKNOWN_FIELD.code and rule is not None:
schema_path += (field, rule)
if not rule:
constraint = None
else:
field_definitions = self._resolve_rules_set(self.schema[field])
if rule == 'nullable':
constraint = field_definitions.get(rule, False)
elif rule == 'required':
constraint = field_definitions.get(rule, self.require_all)
if rule not in field_definitions:
schema_path = "__require_all__"
else:
constraint = field_definitions[rule]
value = self.document.get(field)
self.recent_error = errors.ValidationError(
document_path, schema_path, code, rule, constraint, value, info
)
self._error([self.recent_error]) | python | def _error(self, *args):
""" Creates and adds one or multiple errors.
:param args: Accepts different argument's signatures.
*1. Bulk addition of errors:*
- :term:`iterable` of
:class:`~cerberus.errors.ValidationError`-instances
The errors will be added to
:attr:`~cerberus.Validator._errors`.
*2. Custom error:*
- the invalid field's name
- the error message
A custom error containing the message will be created and
added to :attr:`~cerberus.Validator._errors`.
There will however be fewer information contained in the
error (no reference to the violated rule and its
constraint).
*3. Defined error:*
- the invalid field's name
- the error-reference, see :mod:`cerberus.errors`
- arbitrary, supplemental information about the error
A :class:`~cerberus.errors.ValidationError` instance will
be created and added to
:attr:`~cerberus.Validator._errors`.
"""
if len(args) == 1:
self._errors.extend(args[0])
self._errors.sort()
for error in args[0]:
self.document_error_tree.add(error)
self.schema_error_tree.add(error)
self.error_handler.emit(error)
elif len(args) == 2 and isinstance(args[1], _str_type):
self._error(args[0], errors.CUSTOM, args[1])
elif len(args) >= 2:
field = args[0]
code = args[1].code
rule = args[1].rule
info = args[2:]
document_path = self.document_path + (field,)
schema_path = self.schema_path
if code != errors.UNKNOWN_FIELD.code and rule is not None:
schema_path += (field, rule)
if not rule:
constraint = None
else:
field_definitions = self._resolve_rules_set(self.schema[field])
if rule == 'nullable':
constraint = field_definitions.get(rule, False)
elif rule == 'required':
constraint = field_definitions.get(rule, self.require_all)
if rule not in field_definitions:
schema_path = "__require_all__"
else:
constraint = field_definitions[rule]
value = self.document.get(field)
self.recent_error = errors.ValidationError(
document_path, schema_path, code, rule, constraint, value, info
)
self._error([self.recent_error]) | [
"def",
"_error",
"(",
"self",
",",
"*",
"args",
")",
":",
"if",
"len",
"(",
"args",
")",
"==",
"1",
":",
"self",
".",
"_errors",
".",
"extend",
"(",
"args",
"[",
"0",
"]",
")",
"self",
".",
"_errors",
".",
"sort",
"(",
")",
"for",
"error",
"i... | Creates and adds one or multiple errors.
:param args: Accepts different argument's signatures.
*1. Bulk addition of errors:*
- :term:`iterable` of
:class:`~cerberus.errors.ValidationError`-instances
The errors will be added to
:attr:`~cerberus.Validator._errors`.
*2. Custom error:*
- the invalid field's name
- the error message
A custom error containing the message will be created and
added to :attr:`~cerberus.Validator._errors`.
There will however be fewer information contained in the
error (no reference to the violated rule and its
constraint).
*3. Defined error:*
- the invalid field's name
- the error-reference, see :mod:`cerberus.errors`
- arbitrary, supplemental information about the error
A :class:`~cerberus.errors.ValidationError` instance will
be created and added to
:attr:`~cerberus.Validator._errors`. | [
"Creates",
"and",
"adds",
"one",
"or",
"multiple",
"errors",
"."
] | 688a67a4069e88042ed424bda7be0f4fa5fc3910 | https://github.com/pyeve/cerberus/blob/688a67a4069e88042ed424bda7be0f4fa5fc3910/cerberus/validator.py#L232-L308 | train | 222,521 |
pyeve/cerberus | cerberus/validator.py | BareValidator.__validate_definitions | def __validate_definitions(self, definitions, field):
""" Validate a field's value against its defined rules. """
def validate_rule(rule):
validator = self.__get_rule_handler('validate', rule)
return validator(definitions.get(rule, None), field, value)
definitions = self._resolve_rules_set(definitions)
value = self.document[field]
rules_queue = [
x
for x in self.priority_validations
if x in definitions or x in self.mandatory_validations
]
rules_queue.extend(
x for x in self.mandatory_validations if x not in rules_queue
)
rules_queue.extend(
x
for x in definitions
if x not in rules_queue
and x not in self.normalization_rules
and x not in ('allow_unknown', 'require_all', 'meta', 'required')
)
self._remaining_rules = rules_queue
while self._remaining_rules:
rule = self._remaining_rules.pop(0)
try:
result = validate_rule(rule)
# TODO remove on next breaking release
if result:
break
except _SchemaRuleTypeError:
break
self._drop_remaining_rules() | python | def __validate_definitions(self, definitions, field):
""" Validate a field's value against its defined rules. """
def validate_rule(rule):
validator = self.__get_rule_handler('validate', rule)
return validator(definitions.get(rule, None), field, value)
definitions = self._resolve_rules_set(definitions)
value = self.document[field]
rules_queue = [
x
for x in self.priority_validations
if x in definitions or x in self.mandatory_validations
]
rules_queue.extend(
x for x in self.mandatory_validations if x not in rules_queue
)
rules_queue.extend(
x
for x in definitions
if x not in rules_queue
and x not in self.normalization_rules
and x not in ('allow_unknown', 'require_all', 'meta', 'required')
)
self._remaining_rules = rules_queue
while self._remaining_rules:
rule = self._remaining_rules.pop(0)
try:
result = validate_rule(rule)
# TODO remove on next breaking release
if result:
break
except _SchemaRuleTypeError:
break
self._drop_remaining_rules() | [
"def",
"__validate_definitions",
"(",
"self",
",",
"definitions",
",",
"field",
")",
":",
"def",
"validate_rule",
"(",
"rule",
")",
":",
"validator",
"=",
"self",
".",
"__get_rule_handler",
"(",
"'validate'",
",",
"rule",
")",
"return",
"validator",
"(",
"de... | Validate a field's value against its defined rules. | [
"Validate",
"a",
"field",
"s",
"value",
"against",
"its",
"defined",
"rules",
"."
] | 688a67a4069e88042ed424bda7be0f4fa5fc3910 | https://github.com/pyeve/cerberus/blob/688a67a4069e88042ed424bda7be0f4fa5fc3910/cerberus/validator.py#L1036-L1073 | train | 222,522 |
mobolic/facebook-sdk | facebook/__init__.py | get_user_from_cookie | def get_user_from_cookie(cookies, app_id, app_secret):
"""Parses the cookie set by the official Facebook JavaScript SDK.
cookies should be a dictionary-like object mapping cookie names to
cookie values.
If the user is logged in via Facebook, we return a dictionary with
the keys "uid" and "access_token". The former is the user's
Facebook ID, and the latter can be used to make authenticated
requests to the Graph API. If the user is not logged in, we
return None.
Read more about Facebook authentication at
https://developers.facebook.com/docs/facebook-login.
"""
cookie = cookies.get("fbsr_" + app_id, "")
if not cookie:
return None
parsed_request = parse_signed_request(cookie, app_secret)
if not parsed_request:
return None
try:
result = GraphAPI().get_access_token_from_code(
parsed_request["code"], "", app_id, app_secret
)
except GraphAPIError:
return None
result["uid"] = parsed_request["user_id"]
return result | python | def get_user_from_cookie(cookies, app_id, app_secret):
"""Parses the cookie set by the official Facebook JavaScript SDK.
cookies should be a dictionary-like object mapping cookie names to
cookie values.
If the user is logged in via Facebook, we return a dictionary with
the keys "uid" and "access_token". The former is the user's
Facebook ID, and the latter can be used to make authenticated
requests to the Graph API. If the user is not logged in, we
return None.
Read more about Facebook authentication at
https://developers.facebook.com/docs/facebook-login.
"""
cookie = cookies.get("fbsr_" + app_id, "")
if not cookie:
return None
parsed_request = parse_signed_request(cookie, app_secret)
if not parsed_request:
return None
try:
result = GraphAPI().get_access_token_from_code(
parsed_request["code"], "", app_id, app_secret
)
except GraphAPIError:
return None
result["uid"] = parsed_request["user_id"]
return result | [
"def",
"get_user_from_cookie",
"(",
"cookies",
",",
"app_id",
",",
"app_secret",
")",
":",
"cookie",
"=",
"cookies",
".",
"get",
"(",
"\"fbsr_\"",
"+",
"app_id",
",",
"\"\"",
")",
"if",
"not",
"cookie",
":",
"return",
"None",
"parsed_request",
"=",
"parse_... | Parses the cookie set by the official Facebook JavaScript SDK.
cookies should be a dictionary-like object mapping cookie names to
cookie values.
If the user is logged in via Facebook, we return a dictionary with
the keys "uid" and "access_token". The former is the user's
Facebook ID, and the latter can be used to make authenticated
requests to the Graph API. If the user is not logged in, we
return None.
Read more about Facebook authentication at
https://developers.facebook.com/docs/facebook-login. | [
"Parses",
"the",
"cookie",
"set",
"by",
"the",
"official",
"Facebook",
"JavaScript",
"SDK",
"."
] | 65ff582e77f7ed68b6e9643a7490e5dee2a1031b | https://github.com/mobolic/facebook-sdk/blob/65ff582e77f7ed68b6e9643a7490e5dee2a1031b/facebook/__init__.py#L443-L472 | train | 222,523 |
mobolic/facebook-sdk | facebook/__init__.py | parse_signed_request | def parse_signed_request(signed_request, app_secret):
""" Return dictionary with signed request data.
We return a dictionary containing the information in the
signed_request. This includes a user_id if the user has authorised
your application, as well as any information requested.
If the signed_request is malformed or corrupted, False is returned.
"""
try:
encoded_sig, payload = map(str, signed_request.split(".", 1))
sig = base64.urlsafe_b64decode(
encoded_sig + "=" * ((4 - len(encoded_sig) % 4) % 4)
)
data = base64.urlsafe_b64decode(
payload + "=" * ((4 - len(payload) % 4) % 4)
)
except IndexError:
# Signed request was malformed.
return False
except TypeError:
# Signed request had a corrupted payload.
return False
except binascii.Error:
# Signed request had a corrupted payload.
return False
data = json.loads(data.decode("ascii"))
if data.get("algorithm", "").upper() != "HMAC-SHA256":
return False
# HMAC can only handle ascii (byte) strings
# https://bugs.python.org/issue5285
app_secret = app_secret.encode("ascii")
payload = payload.encode("ascii")
expected_sig = hmac.new(
app_secret, msg=payload, digestmod=hashlib.sha256
).digest()
if sig != expected_sig:
return False
return data | python | def parse_signed_request(signed_request, app_secret):
""" Return dictionary with signed request data.
We return a dictionary containing the information in the
signed_request. This includes a user_id if the user has authorised
your application, as well as any information requested.
If the signed_request is malformed or corrupted, False is returned.
"""
try:
encoded_sig, payload = map(str, signed_request.split(".", 1))
sig = base64.urlsafe_b64decode(
encoded_sig + "=" * ((4 - len(encoded_sig) % 4) % 4)
)
data = base64.urlsafe_b64decode(
payload + "=" * ((4 - len(payload) % 4) % 4)
)
except IndexError:
# Signed request was malformed.
return False
except TypeError:
# Signed request had a corrupted payload.
return False
except binascii.Error:
# Signed request had a corrupted payload.
return False
data = json.loads(data.decode("ascii"))
if data.get("algorithm", "").upper() != "HMAC-SHA256":
return False
# HMAC can only handle ascii (byte) strings
# https://bugs.python.org/issue5285
app_secret = app_secret.encode("ascii")
payload = payload.encode("ascii")
expected_sig = hmac.new(
app_secret, msg=payload, digestmod=hashlib.sha256
).digest()
if sig != expected_sig:
return False
return data | [
"def",
"parse_signed_request",
"(",
"signed_request",
",",
"app_secret",
")",
":",
"try",
":",
"encoded_sig",
",",
"payload",
"=",
"map",
"(",
"str",
",",
"signed_request",
".",
"split",
"(",
"\".\"",
",",
"1",
")",
")",
"sig",
"=",
"base64",
".",
"urlsa... | Return dictionary with signed request data.
We return a dictionary containing the information in the
signed_request. This includes a user_id if the user has authorised
your application, as well as any information requested.
If the signed_request is malformed or corrupted, False is returned. | [
"Return",
"dictionary",
"with",
"signed",
"request",
"data",
"."
] | 65ff582e77f7ed68b6e9643a7490e5dee2a1031b | https://github.com/mobolic/facebook-sdk/blob/65ff582e77f7ed68b6e9643a7490e5dee2a1031b/facebook/__init__.py#L475-L519 | train | 222,524 |
mobolic/facebook-sdk | facebook/__init__.py | GraphAPI.get_permissions | def get_permissions(self, user_id):
"""Fetches the permissions object from the graph."""
response = self.request(
"{0}/{1}/permissions".format(self.version, user_id), {}
)["data"]
return {x["permission"] for x in response if x["status"] == "granted"} | python | def get_permissions(self, user_id):
"""Fetches the permissions object from the graph."""
response = self.request(
"{0}/{1}/permissions".format(self.version, user_id), {}
)["data"]
return {x["permission"] for x in response if x["status"] == "granted"} | [
"def",
"get_permissions",
"(",
"self",
",",
"user_id",
")",
":",
"response",
"=",
"self",
".",
"request",
"(",
"\"{0}/{1}/permissions\"",
".",
"format",
"(",
"self",
".",
"version",
",",
"user_id",
")",
",",
"{",
"}",
")",
"[",
"\"data\"",
"]",
"return",... | Fetches the permissions object from the graph. | [
"Fetches",
"the",
"permissions",
"object",
"from",
"the",
"graph",
"."
] | 65ff582e77f7ed68b6e9643a7490e5dee2a1031b | https://github.com/mobolic/facebook-sdk/blob/65ff582e77f7ed68b6e9643a7490e5dee2a1031b/facebook/__init__.py#L126-L131 | train | 222,525 |
mobolic/facebook-sdk | facebook/__init__.py | GraphAPI.get_object | def get_object(self, id, **args):
"""Fetches the given object from the graph."""
return self.request("{0}/{1}".format(self.version, id), args) | python | def get_object(self, id, **args):
"""Fetches the given object from the graph."""
return self.request("{0}/{1}".format(self.version, id), args) | [
"def",
"get_object",
"(",
"self",
",",
"id",
",",
"*",
"*",
"args",
")",
":",
"return",
"self",
".",
"request",
"(",
"\"{0}/{1}\"",
".",
"format",
"(",
"self",
".",
"version",
",",
"id",
")",
",",
"args",
")"
] | Fetches the given object from the graph. | [
"Fetches",
"the",
"given",
"object",
"from",
"the",
"graph",
"."
] | 65ff582e77f7ed68b6e9643a7490e5dee2a1031b | https://github.com/mobolic/facebook-sdk/blob/65ff582e77f7ed68b6e9643a7490e5dee2a1031b/facebook/__init__.py#L133-L135 | train | 222,526 |
mobolic/facebook-sdk | facebook/__init__.py | GraphAPI.get_objects | def get_objects(self, ids, **args):
"""Fetches all of the given object from the graph.
We return a map from ID to object. If any of the IDs are
invalid, we raise an exception.
"""
args["ids"] = ",".join(ids)
return self.request(self.version + "/", args) | python | def get_objects(self, ids, **args):
"""Fetches all of the given object from the graph.
We return a map from ID to object. If any of the IDs are
invalid, we raise an exception.
"""
args["ids"] = ",".join(ids)
return self.request(self.version + "/", args) | [
"def",
"get_objects",
"(",
"self",
",",
"ids",
",",
"*",
"*",
"args",
")",
":",
"args",
"[",
"\"ids\"",
"]",
"=",
"\",\"",
".",
"join",
"(",
"ids",
")",
"return",
"self",
".",
"request",
"(",
"self",
".",
"version",
"+",
"\"/\"",
",",
"args",
")"... | Fetches all of the given object from the graph.
We return a map from ID to object. If any of the IDs are
invalid, we raise an exception. | [
"Fetches",
"all",
"of",
"the",
"given",
"object",
"from",
"the",
"graph",
"."
] | 65ff582e77f7ed68b6e9643a7490e5dee2a1031b | https://github.com/mobolic/facebook-sdk/blob/65ff582e77f7ed68b6e9643a7490e5dee2a1031b/facebook/__init__.py#L137-L144 | train | 222,527 |
mobolic/facebook-sdk | facebook/__init__.py | GraphAPI.get_connections | def get_connections(self, id, connection_name, **args):
"""Fetches the connections for given object."""
return self.request(
"{0}/{1}/{2}".format(self.version, id, connection_name), args
) | python | def get_connections(self, id, connection_name, **args):
"""Fetches the connections for given object."""
return self.request(
"{0}/{1}/{2}".format(self.version, id, connection_name), args
) | [
"def",
"get_connections",
"(",
"self",
",",
"id",
",",
"connection_name",
",",
"*",
"*",
"args",
")",
":",
"return",
"self",
".",
"request",
"(",
"\"{0}/{1}/{2}\"",
".",
"format",
"(",
"self",
".",
"version",
",",
"id",
",",
"connection_name",
")",
",",
... | Fetches the connections for given object. | [
"Fetches",
"the",
"connections",
"for",
"given",
"object",
"."
] | 65ff582e77f7ed68b6e9643a7490e5dee2a1031b | https://github.com/mobolic/facebook-sdk/blob/65ff582e77f7ed68b6e9643a7490e5dee2a1031b/facebook/__init__.py#L156-L160 | train | 222,528 |
mobolic/facebook-sdk | facebook/__init__.py | GraphAPI.get_all_connections | def get_all_connections(self, id, connection_name, **args):
"""Get all pages from a get_connections call
This will iterate over all pages returned by a get_connections call
and yield the individual items.
"""
while True:
page = self.get_connections(id, connection_name, **args)
for post in page["data"]:
yield post
next = page.get("paging", {}).get("next")
if not next:
return
args = parse_qs(urlparse(next).query)
del args["access_token"] | python | def get_all_connections(self, id, connection_name, **args):
"""Get all pages from a get_connections call
This will iterate over all pages returned by a get_connections call
and yield the individual items.
"""
while True:
page = self.get_connections(id, connection_name, **args)
for post in page["data"]:
yield post
next = page.get("paging", {}).get("next")
if not next:
return
args = parse_qs(urlparse(next).query)
del args["access_token"] | [
"def",
"get_all_connections",
"(",
"self",
",",
"id",
",",
"connection_name",
",",
"*",
"*",
"args",
")",
":",
"while",
"True",
":",
"page",
"=",
"self",
".",
"get_connections",
"(",
"id",
",",
"connection_name",
",",
"*",
"*",
"args",
")",
"for",
"pos... | Get all pages from a get_connections call
This will iterate over all pages returned by a get_connections call
and yield the individual items. | [
"Get",
"all",
"pages",
"from",
"a",
"get_connections",
"call"
] | 65ff582e77f7ed68b6e9643a7490e5dee2a1031b | https://github.com/mobolic/facebook-sdk/blob/65ff582e77f7ed68b6e9643a7490e5dee2a1031b/facebook/__init__.py#L162-L176 | train | 222,529 |
mobolic/facebook-sdk | facebook/__init__.py | GraphAPI.put_object | def put_object(self, parent_object, connection_name, **data):
"""Writes the given object to the graph, connected to the given parent.
For example,
graph.put_object("me", "feed", message="Hello, world")
writes "Hello, world" to the active user's wall. Likewise, this
will comment on the first post of the active user's feed:
feed = graph.get_connections("me", "feed")
post = feed["data"][0]
graph.put_object(post["id"], "comments", message="First!")
Certain operations require extended permissions. See
https://developers.facebook.com/docs/facebook-login/permissions
for details about permissions.
"""
assert self.access_token, "Write operations require an access token"
return self.request(
"{0}/{1}/{2}".format(self.version, parent_object, connection_name),
post_args=data,
method="POST",
) | python | def put_object(self, parent_object, connection_name, **data):
"""Writes the given object to the graph, connected to the given parent.
For example,
graph.put_object("me", "feed", message="Hello, world")
writes "Hello, world" to the active user's wall. Likewise, this
will comment on the first post of the active user's feed:
feed = graph.get_connections("me", "feed")
post = feed["data"][0]
graph.put_object(post["id"], "comments", message="First!")
Certain operations require extended permissions. See
https://developers.facebook.com/docs/facebook-login/permissions
for details about permissions.
"""
assert self.access_token, "Write operations require an access token"
return self.request(
"{0}/{1}/{2}".format(self.version, parent_object, connection_name),
post_args=data,
method="POST",
) | [
"def",
"put_object",
"(",
"self",
",",
"parent_object",
",",
"connection_name",
",",
"*",
"*",
"data",
")",
":",
"assert",
"self",
".",
"access_token",
",",
"\"Write operations require an access token\"",
"return",
"self",
".",
"request",
"(",
"\"{0}/{1}/{2}\"",
"... | Writes the given object to the graph, connected to the given parent.
For example,
graph.put_object("me", "feed", message="Hello, world")
writes "Hello, world" to the active user's wall. Likewise, this
will comment on the first post of the active user's feed:
feed = graph.get_connections("me", "feed")
post = feed["data"][0]
graph.put_object(post["id"], "comments", message="First!")
Certain operations require extended permissions. See
https://developers.facebook.com/docs/facebook-login/permissions
for details about permissions. | [
"Writes",
"the",
"given",
"object",
"to",
"the",
"graph",
"connected",
"to",
"the",
"given",
"parent",
"."
] | 65ff582e77f7ed68b6e9643a7490e5dee2a1031b | https://github.com/mobolic/facebook-sdk/blob/65ff582e77f7ed68b6e9643a7490e5dee2a1031b/facebook/__init__.py#L178-L202 | train | 222,530 |
mobolic/facebook-sdk | facebook/__init__.py | GraphAPI.delete_request | def delete_request(self, user_id, request_id):
"""Deletes the Request with the given ID for the given user."""
return self.request(
"{0}_{1}".format(request_id, user_id), method="DELETE"
) | python | def delete_request(self, user_id, request_id):
"""Deletes the Request with the given ID for the given user."""
return self.request(
"{0}_{1}".format(request_id, user_id), method="DELETE"
) | [
"def",
"delete_request",
"(",
"self",
",",
"user_id",
",",
"request_id",
")",
":",
"return",
"self",
".",
"request",
"(",
"\"{0}_{1}\"",
".",
"format",
"(",
"request_id",
",",
"user_id",
")",
",",
"method",
"=",
"\"DELETE\"",
")"
] | Deletes the Request with the given ID for the given user. | [
"Deletes",
"the",
"Request",
"with",
"the",
"given",
"ID",
"for",
"the",
"given",
"user",
"."
] | 65ff582e77f7ed68b6e9643a7490e5dee2a1031b | https://github.com/mobolic/facebook-sdk/blob/65ff582e77f7ed68b6e9643a7490e5dee2a1031b/facebook/__init__.py#L218-L222 | train | 222,531 |
mobolic/facebook-sdk | facebook/__init__.py | GraphAPI.get_version | def get_version(self):
"""Fetches the current version number of the Graph API being used."""
args = {"access_token": self.access_token}
try:
response = self.session.request(
"GET",
FACEBOOK_GRAPH_URL + self.version + "/me",
params=args,
timeout=self.timeout,
proxies=self.proxies,
)
except requests.HTTPError as e:
response = json.loads(e.read())
raise GraphAPIError(response)
try:
headers = response.headers
version = headers["facebook-api-version"].replace("v", "")
return str(version)
except Exception:
raise GraphAPIError("API version number not available") | python | def get_version(self):
"""Fetches the current version number of the Graph API being used."""
args = {"access_token": self.access_token}
try:
response = self.session.request(
"GET",
FACEBOOK_GRAPH_URL + self.version + "/me",
params=args,
timeout=self.timeout,
proxies=self.proxies,
)
except requests.HTTPError as e:
response = json.loads(e.read())
raise GraphAPIError(response)
try:
headers = response.headers
version = headers["facebook-api-version"].replace("v", "")
return str(version)
except Exception:
raise GraphAPIError("API version number not available") | [
"def",
"get_version",
"(",
"self",
")",
":",
"args",
"=",
"{",
"\"access_token\"",
":",
"self",
".",
"access_token",
"}",
"try",
":",
"response",
"=",
"self",
".",
"session",
".",
"request",
"(",
"\"GET\"",
",",
"FACEBOOK_GRAPH_URL",
"+",
"self",
".",
"v... | Fetches the current version number of the Graph API being used. | [
"Fetches",
"the",
"current",
"version",
"number",
"of",
"the",
"Graph",
"API",
"being",
"used",
"."
] | 65ff582e77f7ed68b6e9643a7490e5dee2a1031b | https://github.com/mobolic/facebook-sdk/blob/65ff582e77f7ed68b6e9643a7490e5dee2a1031b/facebook/__init__.py#L239-L259 | train | 222,532 |
mobolic/facebook-sdk | facebook/__init__.py | GraphAPI.request | def request(
self, path, args=None, post_args=None, files=None, method=None
):
"""Fetches the given path in the Graph API.
We translate args to a valid query string. If post_args is
given, we send a POST request to the given path with the given
arguments.
"""
if args is None:
args = dict()
if post_args is not None:
method = "POST"
# Add `access_token` to post_args or args if it has not already been
# included.
if self.access_token:
# If post_args exists, we assume that args either does not exists
# or it does not need `access_token`.
if post_args and "access_token" not in post_args:
post_args["access_token"] = self.access_token
elif "access_token" not in args:
args["access_token"] = self.access_token
try:
response = self.session.request(
method or "GET",
FACEBOOK_GRAPH_URL + path,
timeout=self.timeout,
params=args,
data=post_args,
proxies=self.proxies,
files=files,
)
except requests.HTTPError as e:
response = json.loads(e.read())
raise GraphAPIError(response)
headers = response.headers
if "json" in headers["content-type"]:
result = response.json()
elif "image/" in headers["content-type"]:
mimetype = headers["content-type"]
result = {
"data": response.content,
"mime-type": mimetype,
"url": response.url,
}
elif "access_token" in parse_qs(response.text):
query_str = parse_qs(response.text)
if "access_token" in query_str:
result = {"access_token": query_str["access_token"][0]}
if "expires" in query_str:
result["expires"] = query_str["expires"][0]
else:
raise GraphAPIError(response.json())
else:
raise GraphAPIError("Maintype was not text, image, or querystring")
if result and isinstance(result, dict) and result.get("error"):
raise GraphAPIError(result)
return result | python | def request(
self, path, args=None, post_args=None, files=None, method=None
):
"""Fetches the given path in the Graph API.
We translate args to a valid query string. If post_args is
given, we send a POST request to the given path with the given
arguments.
"""
if args is None:
args = dict()
if post_args is not None:
method = "POST"
# Add `access_token` to post_args or args if it has not already been
# included.
if self.access_token:
# If post_args exists, we assume that args either does not exists
# or it does not need `access_token`.
if post_args and "access_token" not in post_args:
post_args["access_token"] = self.access_token
elif "access_token" not in args:
args["access_token"] = self.access_token
try:
response = self.session.request(
method or "GET",
FACEBOOK_GRAPH_URL + path,
timeout=self.timeout,
params=args,
data=post_args,
proxies=self.proxies,
files=files,
)
except requests.HTTPError as e:
response = json.loads(e.read())
raise GraphAPIError(response)
headers = response.headers
if "json" in headers["content-type"]:
result = response.json()
elif "image/" in headers["content-type"]:
mimetype = headers["content-type"]
result = {
"data": response.content,
"mime-type": mimetype,
"url": response.url,
}
elif "access_token" in parse_qs(response.text):
query_str = parse_qs(response.text)
if "access_token" in query_str:
result = {"access_token": query_str["access_token"][0]}
if "expires" in query_str:
result["expires"] = query_str["expires"][0]
else:
raise GraphAPIError(response.json())
else:
raise GraphAPIError("Maintype was not text, image, or querystring")
if result and isinstance(result, dict) and result.get("error"):
raise GraphAPIError(result)
return result | [
"def",
"request",
"(",
"self",
",",
"path",
",",
"args",
"=",
"None",
",",
"post_args",
"=",
"None",
",",
"files",
"=",
"None",
",",
"method",
"=",
"None",
")",
":",
"if",
"args",
"is",
"None",
":",
"args",
"=",
"dict",
"(",
")",
"if",
"post_args... | Fetches the given path in the Graph API.
We translate args to a valid query string. If post_args is
given, we send a POST request to the given path with the given
arguments. | [
"Fetches",
"the",
"given",
"path",
"in",
"the",
"Graph",
"API",
"."
] | 65ff582e77f7ed68b6e9643a7490e5dee2a1031b | https://github.com/mobolic/facebook-sdk/blob/65ff582e77f7ed68b6e9643a7490e5dee2a1031b/facebook/__init__.py#L261-L323 | train | 222,533 |
mobolic/facebook-sdk | facebook/__init__.py | GraphAPI.get_access_token_from_code | def get_access_token_from_code(
self, code, redirect_uri, app_id, app_secret
):
"""Get an access token from the "code" returned from an OAuth dialog.
Returns a dict containing the user-specific access token and its
expiration date (if applicable).
"""
args = {
"code": code,
"redirect_uri": redirect_uri,
"client_id": app_id,
"client_secret": app_secret,
}
return self.request(
"{0}/oauth/access_token".format(self.version), args
) | python | def get_access_token_from_code(
self, code, redirect_uri, app_id, app_secret
):
"""Get an access token from the "code" returned from an OAuth dialog.
Returns a dict containing the user-specific access token and its
expiration date (if applicable).
"""
args = {
"code": code,
"redirect_uri": redirect_uri,
"client_id": app_id,
"client_secret": app_secret,
}
return self.request(
"{0}/oauth/access_token".format(self.version), args
) | [
"def",
"get_access_token_from_code",
"(",
"self",
",",
"code",
",",
"redirect_uri",
",",
"app_id",
",",
"app_secret",
")",
":",
"args",
"=",
"{",
"\"code\"",
":",
"code",
",",
"\"redirect_uri\"",
":",
"redirect_uri",
",",
"\"client_id\"",
":",
"app_id",
",",
... | Get an access token from the "code" returned from an OAuth dialog.
Returns a dict containing the user-specific access token and its
expiration date (if applicable). | [
"Get",
"an",
"access",
"token",
"from",
"the",
"code",
"returned",
"from",
"an",
"OAuth",
"dialog",
"."
] | 65ff582e77f7ed68b6e9643a7490e5dee2a1031b | https://github.com/mobolic/facebook-sdk/blob/65ff582e77f7ed68b6e9643a7490e5dee2a1031b/facebook/__init__.py#L346-L364 | train | 222,534 |
mobolic/facebook-sdk | facebook/__init__.py | GraphAPI.get_auth_url | def get_auth_url(self, app_id, canvas_url, perms=None, **kwargs):
"""Build a URL to create an OAuth dialog."""
url = "{0}{1}/{2}".format(
FACEBOOK_WWW_URL, self.version, FACEBOOK_OAUTH_DIALOG_PATH
)
args = {"client_id": app_id, "redirect_uri": canvas_url}
if perms:
args["scope"] = ",".join(perms)
args.update(kwargs)
return url + urlencode(args) | python | def get_auth_url(self, app_id, canvas_url, perms=None, **kwargs):
"""Build a URL to create an OAuth dialog."""
url = "{0}{1}/{2}".format(
FACEBOOK_WWW_URL, self.version, FACEBOOK_OAUTH_DIALOG_PATH
)
args = {"client_id": app_id, "redirect_uri": canvas_url}
if perms:
args["scope"] = ",".join(perms)
args.update(kwargs)
return url + urlencode(args) | [
"def",
"get_auth_url",
"(",
"self",
",",
"app_id",
",",
"canvas_url",
",",
"perms",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"url",
"=",
"\"{0}{1}/{2}\"",
".",
"format",
"(",
"FACEBOOK_WWW_URL",
",",
"self",
".",
"version",
",",
"FACEBOOK_OAUTH_DIAL... | Build a URL to create an OAuth dialog. | [
"Build",
"a",
"URL",
"to",
"create",
"an",
"OAuth",
"dialog",
"."
] | 65ff582e77f7ed68b6e9643a7490e5dee2a1031b | https://github.com/mobolic/facebook-sdk/blob/65ff582e77f7ed68b6e9643a7490e5dee2a1031b/facebook/__init__.py#L401-L411 | train | 222,535 |
mobolic/facebook-sdk | examples/flask/app/views.py | get_current_user | def get_current_user():
"""Set g.user to the currently logged in user.
Called before each request, get_current_user sets the global g.user
variable to the currently logged in user. A currently logged in user is
determined by seeing if it exists in Flask's session dictionary.
If it is the first time the user is logging into this application it will
create the user and insert it into the database. If the user is not logged
in, None will be set to g.user.
"""
# Set the user in the session dictionary as a global g.user and bail out
# of this function early.
if session.get("user"):
g.user = session.get("user")
return
# Attempt to get the short term access token for the current user.
result = get_user_from_cookie(
cookies=request.cookies, app_id=FB_APP_ID, app_secret=FB_APP_SECRET
)
# If there is no result, we assume the user is not logged in.
if result:
# Check to see if this user is already in our database.
user = User.query.filter(User.id == result["uid"]).first()
if not user:
# Not an existing user so get info
graph = GraphAPI(result["access_token"])
profile = graph.get_object("me")
if "link" not in profile:
profile["link"] = ""
# Create the user and insert it into the database
user = User(
id=str(profile["id"]),
name=profile["name"],
profile_url=profile["link"],
access_token=result["access_token"],
)
db.session.add(user)
elif user.access_token != result["access_token"]:
# If an existing user, update the access token
user.access_token = result["access_token"]
# Add the user to the current session
session["user"] = dict(
name=user.name,
profile_url=user.profile_url,
id=user.id,
access_token=user.access_token,
)
# Commit changes to the database and set the user as a global g.user
db.session.commit()
g.user = session.get("user", None) | python | def get_current_user():
"""Set g.user to the currently logged in user.
Called before each request, get_current_user sets the global g.user
variable to the currently logged in user. A currently logged in user is
determined by seeing if it exists in Flask's session dictionary.
If it is the first time the user is logging into this application it will
create the user and insert it into the database. If the user is not logged
in, None will be set to g.user.
"""
# Set the user in the session dictionary as a global g.user and bail out
# of this function early.
if session.get("user"):
g.user = session.get("user")
return
# Attempt to get the short term access token for the current user.
result = get_user_from_cookie(
cookies=request.cookies, app_id=FB_APP_ID, app_secret=FB_APP_SECRET
)
# If there is no result, we assume the user is not logged in.
if result:
# Check to see if this user is already in our database.
user = User.query.filter(User.id == result["uid"]).first()
if not user:
# Not an existing user so get info
graph = GraphAPI(result["access_token"])
profile = graph.get_object("me")
if "link" not in profile:
profile["link"] = ""
# Create the user and insert it into the database
user = User(
id=str(profile["id"]),
name=profile["name"],
profile_url=profile["link"],
access_token=result["access_token"],
)
db.session.add(user)
elif user.access_token != result["access_token"]:
# If an existing user, update the access token
user.access_token = result["access_token"]
# Add the user to the current session
session["user"] = dict(
name=user.name,
profile_url=user.profile_url,
id=user.id,
access_token=user.access_token,
)
# Commit changes to the database and set the user as a global g.user
db.session.commit()
g.user = session.get("user", None) | [
"def",
"get_current_user",
"(",
")",
":",
"# Set the user in the session dictionary as a global g.user and bail out",
"# of this function early.",
"if",
"session",
".",
"get",
"(",
"\"user\"",
")",
":",
"g",
".",
"user",
"=",
"session",
".",
"get",
"(",
"\"user\"",
")... | Set g.user to the currently logged in user.
Called before each request, get_current_user sets the global g.user
variable to the currently logged in user. A currently logged in user is
determined by seeing if it exists in Flask's session dictionary.
If it is the first time the user is logging into this application it will
create the user and insert it into the database. If the user is not logged
in, None will be set to g.user. | [
"Set",
"g",
".",
"user",
"to",
"the",
"currently",
"logged",
"in",
"user",
"."
] | 65ff582e77f7ed68b6e9643a7490e5dee2a1031b | https://github.com/mobolic/facebook-sdk/blob/65ff582e77f7ed68b6e9643a7490e5dee2a1031b/examples/flask/app/views.py#L38-L95 | train | 222,536 |
NetEaseGame/ATX | atx/record/scene_detector.py | SceneDetector.build_tree | def build_tree(self, directory):
'''build scene tree from images'''
confile = os.path.join(directory, 'config.yml')
conf = {}
if os.path.exists(confile):
conf = yaml.load(open(confile).read())
class node(defaultdict):
name = ''
parent = None
tmpl = None
rect = None
mask = None
def __str__(self):
obj = self
names = []
while obj.parent is not None:
names.append(obj.name)
obj = obj.parent
return '-'.join(names[::-1])
def tree():
return node(tree)
root = tree()
for s in os.listdir(directory):
if not s.endswith('.png') or s.endswith('_mask.png'):
continue
obj = root
for i in s[:-4].split('-'):
obj[i].name = i
obj[i].parent = obj
obj = obj[i]
obj.tmpl = cv2.imread(os.path.join(directory, s))
obj.rect = conf.get(s[:-4], {}).get('rect')
maskimg = conf.get(s[:-4], {}).get('mask')
if maskimg is not None:
maskimg = os.path.join(directory, maskimg)
if os.path.exists(maskimg):
obj.mask = cv2.imread(maskimg)
self.tree = root
self.current_scene = []
self.confile = confile
self.conf = conf | python | def build_tree(self, directory):
'''build scene tree from images'''
confile = os.path.join(directory, 'config.yml')
conf = {}
if os.path.exists(confile):
conf = yaml.load(open(confile).read())
class node(defaultdict):
name = ''
parent = None
tmpl = None
rect = None
mask = None
def __str__(self):
obj = self
names = []
while obj.parent is not None:
names.append(obj.name)
obj = obj.parent
return '-'.join(names[::-1])
def tree():
return node(tree)
root = tree()
for s in os.listdir(directory):
if not s.endswith('.png') or s.endswith('_mask.png'):
continue
obj = root
for i in s[:-4].split('-'):
obj[i].name = i
obj[i].parent = obj
obj = obj[i]
obj.tmpl = cv2.imread(os.path.join(directory, s))
obj.rect = conf.get(s[:-4], {}).get('rect')
maskimg = conf.get(s[:-4], {}).get('mask')
if maskimg is not None:
maskimg = os.path.join(directory, maskimg)
if os.path.exists(maskimg):
obj.mask = cv2.imread(maskimg)
self.tree = root
self.current_scene = []
self.confile = confile
self.conf = conf | [
"def",
"build_tree",
"(",
"self",
",",
"directory",
")",
":",
"confile",
"=",
"os",
".",
"path",
".",
"join",
"(",
"directory",
",",
"'config.yml'",
")",
"conf",
"=",
"{",
"}",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"confile",
")",
":",
"conf... | build scene tree from images | [
"build",
"scene",
"tree",
"from",
"images"
] | f4415c57b45cb0730e08899cbc92a2af1c047ffb | https://github.com/NetEaseGame/ATX/blob/f4415c57b45cb0730e08899cbc92a2af1c047ffb/atx/record/scene_detector.py#L81-L126 | train | 222,537 |
NetEaseGame/ATX | atx/adbkit/openstf/service.py | pack | def pack(mtype, request, rid=None):
'''pack request to delimited data'''
envelope = wire.Envelope()
if rid is not None:
envelope.id = rid
envelope.type = mtype
envelope.message = request.SerializeToString()
data = envelope.SerializeToString()
data = encoder._VarintBytes(len(data)) + data
return data | python | def pack(mtype, request, rid=None):
'''pack request to delimited data'''
envelope = wire.Envelope()
if rid is not None:
envelope.id = rid
envelope.type = mtype
envelope.message = request.SerializeToString()
data = envelope.SerializeToString()
data = encoder._VarintBytes(len(data)) + data
return data | [
"def",
"pack",
"(",
"mtype",
",",
"request",
",",
"rid",
"=",
"None",
")",
":",
"envelope",
"=",
"wire",
".",
"Envelope",
"(",
")",
"if",
"rid",
"is",
"not",
"None",
":",
"envelope",
".",
"id",
"=",
"rid",
"envelope",
".",
"type",
"=",
"mtype",
"... | pack request to delimited data | [
"pack",
"request",
"to",
"delimited",
"data"
] | f4415c57b45cb0730e08899cbc92a2af1c047ffb | https://github.com/NetEaseGame/ATX/blob/f4415c57b45cb0730e08899cbc92a2af1c047ffb/atx/adbkit/openstf/service.py#L75-L84 | train | 222,538 |
NetEaseGame/ATX | atx/adbkit/openstf/service.py | unpack | def unpack(data):
'''unpack from delimited data'''
size, position = decoder._DecodeVarint(data, 0)
envelope = wire.Envelope()
envelope.ParseFromString(data[position:position+size])
return envelope | python | def unpack(data):
'''unpack from delimited data'''
size, position = decoder._DecodeVarint(data, 0)
envelope = wire.Envelope()
envelope.ParseFromString(data[position:position+size])
return envelope | [
"def",
"unpack",
"(",
"data",
")",
":",
"size",
",",
"position",
"=",
"decoder",
".",
"_DecodeVarint",
"(",
"data",
",",
"0",
")",
"envelope",
"=",
"wire",
".",
"Envelope",
"(",
")",
"envelope",
".",
"ParseFromString",
"(",
"data",
"[",
"position",
":"... | unpack from delimited data | [
"unpack",
"from",
"delimited",
"data"
] | f4415c57b45cb0730e08899cbc92a2af1c047ffb | https://github.com/NetEaseGame/ATX/blob/f4415c57b45cb0730e08899cbc92a2af1c047ffb/atx/adbkit/openstf/service.py#L86-L91 | train | 222,539 |
NetEaseGame/ATX | atx/adbkit/openstf/service.py | check_stf_agent | def check_stf_agent(adbprefix=None, kill=False):
'''return True if agent is alive.'''
if adbprefix is None:
adbprefix = ['adb']
command = adbprefix + ['shell', 'ps']
out = subprocess.check_output(command).strip()
out = out.splitlines()
if len(out) > 1:
first, out = out[0], out[1:]
idx = first.split().index('PID')
pid = None
for line in out:
if 'stf.agent' in line:
pid = line.split()[idx]
print 'stf.agent is running, pid is', pid
break
if pid is not None:
if kill:
print 'killing', pid
command = adbprefix + ['shell', 'kill', '-9', pid]
subprocess.call(command)
return False
return True
return False | python | def check_stf_agent(adbprefix=None, kill=False):
'''return True if agent is alive.'''
if adbprefix is None:
adbprefix = ['adb']
command = adbprefix + ['shell', 'ps']
out = subprocess.check_output(command).strip()
out = out.splitlines()
if len(out) > 1:
first, out = out[0], out[1:]
idx = first.split().index('PID')
pid = None
for line in out:
if 'stf.agent' in line:
pid = line.split()[idx]
print 'stf.agent is running, pid is', pid
break
if pid is not None:
if kill:
print 'killing', pid
command = adbprefix + ['shell', 'kill', '-9', pid]
subprocess.call(command)
return False
return True
return False | [
"def",
"check_stf_agent",
"(",
"adbprefix",
"=",
"None",
",",
"kill",
"=",
"False",
")",
":",
"if",
"adbprefix",
"is",
"None",
":",
"adbprefix",
"=",
"[",
"'adb'",
"]",
"command",
"=",
"adbprefix",
"+",
"[",
"'shell'",
",",
"'ps'",
"]",
"out",
"=",
"... | return True if agent is alive. | [
"return",
"True",
"if",
"agent",
"is",
"alive",
"."
] | f4415c57b45cb0730e08899cbc92a2af1c047ffb | https://github.com/NetEaseGame/ATX/blob/f4415c57b45cb0730e08899cbc92a2af1c047ffb/atx/adbkit/openstf/service.py#L182-L205 | train | 222,540 |
NetEaseGame/ATX | atx/cmds/tkgui.py | insert_code | def insert_code(filename, code, save=True, marker='# ATX CODE END'):
""" Auto append code """
content = ''
found = False
for line in open(filename, 'rb'):
if not found and line.strip() == marker:
found = True
cnt = line.find(marker)
content += line[:cnt] + code
content += line
if not found:
if not content.endswith('\n'):
content += '\n'
content += code + marker + '\n'
if save:
with open(filename, 'wb') as f:
f.write(content)
return content | python | def insert_code(filename, code, save=True, marker='# ATX CODE END'):
""" Auto append code """
content = ''
found = False
for line in open(filename, 'rb'):
if not found and line.strip() == marker:
found = True
cnt = line.find(marker)
content += line[:cnt] + code
content += line
if not found:
if not content.endswith('\n'):
content += '\n'
content += code + marker + '\n'
if save:
with open(filename, 'wb') as f:
f.write(content)
return content | [
"def",
"insert_code",
"(",
"filename",
",",
"code",
",",
"save",
"=",
"True",
",",
"marker",
"=",
"'# ATX CODE END'",
")",
":",
"content",
"=",
"''",
"found",
"=",
"False",
"for",
"line",
"in",
"open",
"(",
"filename",
",",
"'rb'",
")",
":",
"if",
"n... | Auto append code | [
"Auto",
"append",
"code"
] | f4415c57b45cb0730e08899cbc92a2af1c047ffb | https://github.com/NetEaseGame/ATX/blob/f4415c57b45cb0730e08899cbc92a2af1c047ffb/atx/cmds/tkgui.py#L41-L58 | train | 222,541 |
NetEaseGame/ATX | scripts/image.py | find_image_position | def find_image_position(origin='origin.png', query='query.png', outfile=None):
'''
find all image positions
@return None if not found else a tuple: (origin.shape, query.shape, postions)
might raise Exception
'''
img1 = cv2.imread(query, 0) # query image(small)
img2 = cv2.imread(origin, 0) # train image(big)
# Initiate SIFT detector
sift = cv2.SIFT()
# find the keypoints and descriptors with SIFT
kp1, des1 = sift.detectAndCompute(img1,None)
kp2, des2 = sift.detectAndCompute(img2,None)
print len(kp1), len(kp2)
FLANN_INDEX_KDTREE = 0
index_params = dict(algorithm = FLANN_INDEX_KDTREE, trees = 5)
search_params = dict(checks = 50)
# flann
flann = cv2.FlannBasedMatcher(index_params, search_params)
matches = flann.knnMatch(des1, des2, k=2)
# store all the good matches as per Lowe's ratio test.
good = []
for m,n in matches:
if m.distance < 0.7*n.distance:
good.append(m)
print len(kp1), len(kp2), 'good cnt:', len(good)
if len(good)*1.0/len(kp1) < 0.5:
#if len(good)<MIN_MATCH_COUNT:
print "Not enough matches are found - %d/%d" % (len(good),MIN_MATCH_COUNT)
return img2.shape, img1.shape, []
queryPts = []
trainPts = []
for dm in good:
queryPts.append(kp1[dm.queryIdx])
trainPts.append(kp2[dm.trainIdx])
img3 = cv2.drawKeypoints(img1, queryPts)
cv2.imwrite('image/query.png', img3)
img3 = cv2.drawKeypoints(img2, trainPts)
point = _middlePoint(trainPts)
print 'position in', point
if outfile:
edge = 10
top_left = (point[0]-edge, point[1]-edge)
bottom_right = (point[0]+edge, point[1]+edge)
cv2.rectangle(img3, top_left, bottom_right, 255, 2)
cv2.imwrite(outfile, img3)
return img2.shape, img1.shape, [point] | python | def find_image_position(origin='origin.png', query='query.png', outfile=None):
'''
find all image positions
@return None if not found else a tuple: (origin.shape, query.shape, postions)
might raise Exception
'''
img1 = cv2.imread(query, 0) # query image(small)
img2 = cv2.imread(origin, 0) # train image(big)
# Initiate SIFT detector
sift = cv2.SIFT()
# find the keypoints and descriptors with SIFT
kp1, des1 = sift.detectAndCompute(img1,None)
kp2, des2 = sift.detectAndCompute(img2,None)
print len(kp1), len(kp2)
FLANN_INDEX_KDTREE = 0
index_params = dict(algorithm = FLANN_INDEX_KDTREE, trees = 5)
search_params = dict(checks = 50)
# flann
flann = cv2.FlannBasedMatcher(index_params, search_params)
matches = flann.knnMatch(des1, des2, k=2)
# store all the good matches as per Lowe's ratio test.
good = []
for m,n in matches:
if m.distance < 0.7*n.distance:
good.append(m)
print len(kp1), len(kp2), 'good cnt:', len(good)
if len(good)*1.0/len(kp1) < 0.5:
#if len(good)<MIN_MATCH_COUNT:
print "Not enough matches are found - %d/%d" % (len(good),MIN_MATCH_COUNT)
return img2.shape, img1.shape, []
queryPts = []
trainPts = []
for dm in good:
queryPts.append(kp1[dm.queryIdx])
trainPts.append(kp2[dm.trainIdx])
img3 = cv2.drawKeypoints(img1, queryPts)
cv2.imwrite('image/query.png', img3)
img3 = cv2.drawKeypoints(img2, trainPts)
point = _middlePoint(trainPts)
print 'position in', point
if outfile:
edge = 10
top_left = (point[0]-edge, point[1]-edge)
bottom_right = (point[0]+edge, point[1]+edge)
cv2.rectangle(img3, top_left, bottom_right, 255, 2)
cv2.imwrite(outfile, img3)
return img2.shape, img1.shape, [point] | [
"def",
"find_image_position",
"(",
"origin",
"=",
"'origin.png'",
",",
"query",
"=",
"'query.png'",
",",
"outfile",
"=",
"None",
")",
":",
"img1",
"=",
"cv2",
".",
"imread",
"(",
"query",
",",
"0",
")",
"# query image(small)",
"img2",
"=",
"cv2",
".",
"i... | find all image positions
@return None if not found else a tuple: (origin.shape, query.shape, postions)
might raise Exception | [
"find",
"all",
"image",
"positions"
] | f4415c57b45cb0730e08899cbc92a2af1c047ffb | https://github.com/NetEaseGame/ATX/blob/f4415c57b45cb0730e08899cbc92a2af1c047ffb/scripts/image.py#L46-L102 | train | 222,542 |
NetEaseGame/ATX | atx/taskqueue/__main__.py | TaskQueueHandler.get | def get(self, udid):
''' get new task '''
timeout = self.get_argument('timeout', 20.0)
if timeout is not None:
timeout = float(timeout)
que = self.ques[udid]
try:
item = yield que.get(timeout=time.time()+timeout) # timeout is a timestamp, strange
print 'get from queue:', item
self.write(item)
que.task_done()
except gen.TimeoutError:
print 'timeout'
self.write('')
finally:
self.finish() | python | def get(self, udid):
''' get new task '''
timeout = self.get_argument('timeout', 20.0)
if timeout is not None:
timeout = float(timeout)
que = self.ques[udid]
try:
item = yield que.get(timeout=time.time()+timeout) # timeout is a timestamp, strange
print 'get from queue:', item
self.write(item)
que.task_done()
except gen.TimeoutError:
print 'timeout'
self.write('')
finally:
self.finish() | [
"def",
"get",
"(",
"self",
",",
"udid",
")",
":",
"timeout",
"=",
"self",
".",
"get_argument",
"(",
"'timeout'",
",",
"20.0",
")",
"if",
"timeout",
"is",
"not",
"None",
":",
"timeout",
"=",
"float",
"(",
"timeout",
")",
"que",
"=",
"self",
".",
"qu... | get new task | [
"get",
"new",
"task"
] | f4415c57b45cb0730e08899cbc92a2af1c047ffb | https://github.com/NetEaseGame/ATX/blob/f4415c57b45cb0730e08899cbc92a2af1c047ffb/atx/taskqueue/__main__.py#L42-L57 | train | 222,543 |
NetEaseGame/ATX | atx/taskqueue/__main__.py | TaskQueueHandler.post | def post(self, udid):
''' add new task '''
que = self.ques[udid]
timeout = self.get_argument('timeout', 10.0)
if timeout is not None:
timeout = float(timeout)
data = tornado.escape.json_decode(self.request.body)
data = {'id': str(uuid.uuid1()), 'data': data}
yield que.put(data, timeout=time.time()+timeout)
print 'post, queue size:', que.qsize()
self.write({'id': data['id']})
self.finish() | python | def post(self, udid):
''' add new task '''
que = self.ques[udid]
timeout = self.get_argument('timeout', 10.0)
if timeout is not None:
timeout = float(timeout)
data = tornado.escape.json_decode(self.request.body)
data = {'id': str(uuid.uuid1()), 'data': data}
yield que.put(data, timeout=time.time()+timeout)
print 'post, queue size:', que.qsize()
self.write({'id': data['id']})
self.finish() | [
"def",
"post",
"(",
"self",
",",
"udid",
")",
":",
"que",
"=",
"self",
".",
"ques",
"[",
"udid",
"]",
"timeout",
"=",
"self",
".",
"get_argument",
"(",
"'timeout'",
",",
"10.0",
")",
"if",
"timeout",
"is",
"not",
"None",
":",
"timeout",
"=",
"float... | add new task | [
"add",
"new",
"task"
] | f4415c57b45cb0730e08899cbc92a2af1c047ffb | https://github.com/NetEaseGame/ATX/blob/f4415c57b45cb0730e08899cbc92a2af1c047ffb/atx/taskqueue/__main__.py#L60-L71 | train | 222,544 |
NetEaseGame/ATX | atx/record/android_hooks.py | InputParser._process_touch_batch | def _process_touch_batch(self):
'''a batch syncs in about 0.001 seconds.'''
if not self._touch_batch:
return
_time = self._temp_status_time
changed = False
for (_time, _device, _type, _code, _value) in self._touch_batch:
if _code == 'ABS_MT_TRACKING_ID':
if _value == 0xffffffff:
self._temp_status[self._curr_slot] = -INF
changed = True
else:
pass
elif _code == 'ABS_MT_SLOT':
self._curr_slot = _value
else:
if _code == 'ABS_MT_POSITION_X':
self._temp_status[self._curr_slot,_X] = _value
changed = True
elif _code == 'ABS_MT_POSITION_Y':
self._temp_status[self._curr_slot,_Y] = _value
changed = True
elif _code == 'ABS_MT_PRESSURE':
self._temp_status[self._curr_slot,_PR] = _value
elif _code == 'ABS_MT_TOUCH_MAJOR':
self._temp_status[self._curr_slot,_MJ] = _value
else:
print 'Unknown code', _code
self._temp_status_time = _time
self._touch_batch = []
if not changed:
return
# check differences, if position changes are big enough then emit events
diff = self._temp_status - self._status
dt = self._temp_status_time - self._status_time
emitted = False
for i in range(SLOT_NUM):
arr = self._temp_status[i]
oldarr = self._status[i]
dx, dy = diff[i,_X], diff[i,_Y]
if dx > INF or dy > INF:
# touch begin
event = TouchEvent(_time, HC.TOUCH_DOWN, i, arr[_X], arr[_Y], arr[_PR], arr[_MJ])
self.emit_touch_event(event)
emitted = True
elif dx < -INF or dy < -INF:
# touch end
event = TouchEvent(_time, HC.TOUCH_UP, i, oldarr[_X], oldarr[_Y], oldarr[_PR], oldarr[_MJ])
self.emit_touch_event(event)
emitted = True
else:
r, a = radang(float(dx), float(dy))
if r > self._move_radius:
v = r / dt
event = TouchEvent(_time, HC.TOUCH_MOVE, i, arr[_X], arr[_Y], arr[_PR], arr[_MJ], angle=a, velocity=v)
self.emit_touch_event(event)
emitted = True
if not emitted:
return
self._status = self._temp_status.copy()
self._status_time = self._temp_status_time | python | def _process_touch_batch(self):
'''a batch syncs in about 0.001 seconds.'''
if not self._touch_batch:
return
_time = self._temp_status_time
changed = False
for (_time, _device, _type, _code, _value) in self._touch_batch:
if _code == 'ABS_MT_TRACKING_ID':
if _value == 0xffffffff:
self._temp_status[self._curr_slot] = -INF
changed = True
else:
pass
elif _code == 'ABS_MT_SLOT':
self._curr_slot = _value
else:
if _code == 'ABS_MT_POSITION_X':
self._temp_status[self._curr_slot,_X] = _value
changed = True
elif _code == 'ABS_MT_POSITION_Y':
self._temp_status[self._curr_slot,_Y] = _value
changed = True
elif _code == 'ABS_MT_PRESSURE':
self._temp_status[self._curr_slot,_PR] = _value
elif _code == 'ABS_MT_TOUCH_MAJOR':
self._temp_status[self._curr_slot,_MJ] = _value
else:
print 'Unknown code', _code
self._temp_status_time = _time
self._touch_batch = []
if not changed:
return
# check differences, if position changes are big enough then emit events
diff = self._temp_status - self._status
dt = self._temp_status_time - self._status_time
emitted = False
for i in range(SLOT_NUM):
arr = self._temp_status[i]
oldarr = self._status[i]
dx, dy = diff[i,_X], diff[i,_Y]
if dx > INF or dy > INF:
# touch begin
event = TouchEvent(_time, HC.TOUCH_DOWN, i, arr[_X], arr[_Y], arr[_PR], arr[_MJ])
self.emit_touch_event(event)
emitted = True
elif dx < -INF or dy < -INF:
# touch end
event = TouchEvent(_time, HC.TOUCH_UP, i, oldarr[_X], oldarr[_Y], oldarr[_PR], oldarr[_MJ])
self.emit_touch_event(event)
emitted = True
else:
r, a = radang(float(dx), float(dy))
if r > self._move_radius:
v = r / dt
event = TouchEvent(_time, HC.TOUCH_MOVE, i, arr[_X], arr[_Y], arr[_PR], arr[_MJ], angle=a, velocity=v)
self.emit_touch_event(event)
emitted = True
if not emitted:
return
self._status = self._temp_status.copy()
self._status_time = self._temp_status_time | [
"def",
"_process_touch_batch",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_touch_batch",
":",
"return",
"_time",
"=",
"self",
".",
"_temp_status_time",
"changed",
"=",
"False",
"for",
"(",
"_time",
",",
"_device",
",",
"_type",
",",
"_code",
",",
... | a batch syncs in about 0.001 seconds. | [
"a",
"batch",
"syncs",
"in",
"about",
"0",
".",
"001",
"seconds",
"."
] | f4415c57b45cb0730e08899cbc92a2af1c047ffb | https://github.com/NetEaseGame/ATX/blob/f4415c57b45cb0730e08899cbc92a2af1c047ffb/atx/record/android_hooks.py#L218-L283 | train | 222,545 |
NetEaseGame/ATX | atx/record/android_hooks.py | GestureRecognizer.process | def process(self):
'''handle events and trigger time-related events'''
timediff = 0
while True:
try:
time.sleep(0.001)
event = self.queue.get_nowait()
self.handle_event(event)
if event.msg & HC.KEY_ANY:
continue
if timediff == 0:
timediff = time.time() - event.time
self.touches[event.slotid] = event
except Queue.Empty:
if not self.running:
break
now = time.time() - timediff
for i in range(SLOT_NUM):
e = self.touches[i]
if e is None:
continue
if e.msg == HC.TOUCH_DOWN and now - e.time > self.long_press_delay:
self.analyze_tracks(TouchTimeoutEvent(now, HC.TOUCH_PRESS_TIMEOUT, i))
self.touches[i] = None
elif e.msg == HC.TOUCH_UP and now - e.time > self.double_tap_delay:
self.analyze_tracks(TouchTimeoutEvent(now, HC.TOUCH_FOLLOW_TIMEOUT, i))
self.touches[i] = None
elif e.msg == HC.TOUCH_MOVE and now - e.time > self.move_stop_delay:
self.analyze_tracks(TouchTimeoutEvent(now, HC.TOUCH_MOVESTOP_TIMEOUT, i))
self.touches[i] = None
except:
traceback.print_exc()
print 'process done.' | python | def process(self):
'''handle events and trigger time-related events'''
timediff = 0
while True:
try:
time.sleep(0.001)
event = self.queue.get_nowait()
self.handle_event(event)
if event.msg & HC.KEY_ANY:
continue
if timediff == 0:
timediff = time.time() - event.time
self.touches[event.slotid] = event
except Queue.Empty:
if not self.running:
break
now = time.time() - timediff
for i in range(SLOT_NUM):
e = self.touches[i]
if e is None:
continue
if e.msg == HC.TOUCH_DOWN and now - e.time > self.long_press_delay:
self.analyze_tracks(TouchTimeoutEvent(now, HC.TOUCH_PRESS_TIMEOUT, i))
self.touches[i] = None
elif e.msg == HC.TOUCH_UP and now - e.time > self.double_tap_delay:
self.analyze_tracks(TouchTimeoutEvent(now, HC.TOUCH_FOLLOW_TIMEOUT, i))
self.touches[i] = None
elif e.msg == HC.TOUCH_MOVE and now - e.time > self.move_stop_delay:
self.analyze_tracks(TouchTimeoutEvent(now, HC.TOUCH_MOVESTOP_TIMEOUT, i))
self.touches[i] = None
except:
traceback.print_exc()
print 'process done.' | [
"def",
"process",
"(",
"self",
")",
":",
"timediff",
"=",
"0",
"while",
"True",
":",
"try",
":",
"time",
".",
"sleep",
"(",
"0.001",
")",
"event",
"=",
"self",
".",
"queue",
".",
"get_nowait",
"(",
")",
"self",
".",
"handle_event",
"(",
"event",
")... | handle events and trigger time-related events | [
"handle",
"events",
"and",
"trigger",
"time",
"-",
"related",
"events"
] | f4415c57b45cb0730e08899cbc92a2af1c047ffb | https://github.com/NetEaseGame/ATX/blob/f4415c57b45cb0730e08899cbc92a2af1c047ffb/atx/record/android_hooks.py#L334-L367 | train | 222,546 |
NetEaseGame/ATX | atx/drivers/mixin.py | DeviceMixin.exists | def exists(self, pattern, **match_kwargs):
"""Check if image exists in screen
Returns:
If exists, return FindPoint, or
return None if result.confidence < self.image_match_threshold
"""
ret = self.match(pattern, **match_kwargs)
if ret is None:
return None
if not ret.matched:
return None
return ret | python | def exists(self, pattern, **match_kwargs):
"""Check if image exists in screen
Returns:
If exists, return FindPoint, or
return None if result.confidence < self.image_match_threshold
"""
ret = self.match(pattern, **match_kwargs)
if ret is None:
return None
if not ret.matched:
return None
return ret | [
"def",
"exists",
"(",
"self",
",",
"pattern",
",",
"*",
"*",
"match_kwargs",
")",
":",
"ret",
"=",
"self",
".",
"match",
"(",
"pattern",
",",
"*",
"*",
"match_kwargs",
")",
"if",
"ret",
"is",
"None",
":",
"return",
"None",
"if",
"not",
"ret",
".",
... | Check if image exists in screen
Returns:
If exists, return FindPoint, or
return None if result.confidence < self.image_match_threshold | [
"Check",
"if",
"image",
"exists",
"in",
"screen"
] | f4415c57b45cb0730e08899cbc92a2af1c047ffb | https://github.com/NetEaseGame/ATX/blob/f4415c57b45cb0730e08899cbc92a2af1c047ffb/atx/drivers/mixin.py#L143-L155 | train | 222,547 |
NetEaseGame/ATX | atx/drivers/mixin.py | DeviceMixin._match_auto | def _match_auto(self, screen, search_img, threshold):
"""Maybe not a good idea
"""
# 1. try template first
ret = ac.find_template(screen, search_img)
if ret and ret['confidence'] > threshold:
return FindPoint(ret['result'], ret['confidence'], consts.IMAGE_MATCH_METHOD_TMPL, matched=True)
# 2. try sift
ret = ac.find_sift(screen, search_img, min_match_count=10)
if ret is None:
return None
matches, total = ret['confidence']
if 1.0*matches/total > 0.5: # FIXME(ssx): sift just write here
return FindPoint(ret['result'], ret['confidence'], consts.IMAGE_MATCH_METHOD_SIFT, matched=True)
return None | python | def _match_auto(self, screen, search_img, threshold):
"""Maybe not a good idea
"""
# 1. try template first
ret = ac.find_template(screen, search_img)
if ret and ret['confidence'] > threshold:
return FindPoint(ret['result'], ret['confidence'], consts.IMAGE_MATCH_METHOD_TMPL, matched=True)
# 2. try sift
ret = ac.find_sift(screen, search_img, min_match_count=10)
if ret is None:
return None
matches, total = ret['confidence']
if 1.0*matches/total > 0.5: # FIXME(ssx): sift just write here
return FindPoint(ret['result'], ret['confidence'], consts.IMAGE_MATCH_METHOD_SIFT, matched=True)
return None | [
"def",
"_match_auto",
"(",
"self",
",",
"screen",
",",
"search_img",
",",
"threshold",
")",
":",
"# 1. try template first",
"ret",
"=",
"ac",
".",
"find_template",
"(",
"screen",
",",
"search_img",
")",
"if",
"ret",
"and",
"ret",
"[",
"'confidence'",
"]",
... | Maybe not a good idea | [
"Maybe",
"not",
"a",
"good",
"idea"
] | f4415c57b45cb0730e08899cbc92a2af1c047ffb | https://github.com/NetEaseGame/ATX/blob/f4415c57b45cb0730e08899cbc92a2af1c047ffb/atx/drivers/mixin.py#L217-L233 | train | 222,548 |
NetEaseGame/ATX | atx/drivers/mixin.py | DeviceMixin.match_all | def match_all(self, pattern):
"""
Test method, not suggested to use
"""
pattern = self.pattern_open(pattern)
search_img = pattern.image
screen = self.region_screenshot()
screen = imutils.from_pillow(screen)
points = ac.find_all_template(screen, search_img, maxcnt=10)
return points | python | def match_all(self, pattern):
"""
Test method, not suggested to use
"""
pattern = self.pattern_open(pattern)
search_img = pattern.image
screen = self.region_screenshot()
screen = imutils.from_pillow(screen)
points = ac.find_all_template(screen, search_img, maxcnt=10)
return points | [
"def",
"match_all",
"(",
"self",
",",
"pattern",
")",
":",
"pattern",
"=",
"self",
".",
"pattern_open",
"(",
"pattern",
")",
"search_img",
"=",
"pattern",
".",
"image",
"screen",
"=",
"self",
".",
"region_screenshot",
"(",
")",
"screen",
"=",
"imutils",
... | Test method, not suggested to use | [
"Test",
"method",
"not",
"suggested",
"to",
"use"
] | f4415c57b45cb0730e08899cbc92a2af1c047ffb | https://github.com/NetEaseGame/ATX/blob/f4415c57b45cb0730e08899cbc92a2af1c047ffb/atx/drivers/mixin.py#L235-L244 | train | 222,549 |
NetEaseGame/ATX | atx/drivers/mixin.py | DeviceMixin.region_screenshot | def region_screenshot(self, filename=None):
"""Deprecated
Take part of the screenshot
"""
# warnings.warn("deprecated, use screenshot().crop(bounds) instead", DeprecationWarning)
screen = self.__last_screen if self.__keep_screen else self.screenshot()
if self.bounds:
screen = screen.crop(self.bounds)
if filename:
screen.save(filename)
return screen | python | def region_screenshot(self, filename=None):
"""Deprecated
Take part of the screenshot
"""
# warnings.warn("deprecated, use screenshot().crop(bounds) instead", DeprecationWarning)
screen = self.__last_screen if self.__keep_screen else self.screenshot()
if self.bounds:
screen = screen.crop(self.bounds)
if filename:
screen.save(filename)
return screen | [
"def",
"region_screenshot",
"(",
"self",
",",
"filename",
"=",
"None",
")",
":",
"# warnings.warn(\"deprecated, use screenshot().crop(bounds) instead\", DeprecationWarning)",
"screen",
"=",
"self",
".",
"__last_screen",
"if",
"self",
".",
"__keep_screen",
"else",
"self",
... | Deprecated
Take part of the screenshot | [
"Deprecated",
"Take",
"part",
"of",
"the",
"screenshot"
] | f4415c57b45cb0730e08899cbc92a2af1c047ffb | https://github.com/NetEaseGame/ATX/blob/f4415c57b45cb0730e08899cbc92a2af1c047ffb/atx/drivers/mixin.py#L375-L385 | train | 222,550 |
NetEaseGame/ATX | atx/drivers/mixin.py | DeviceMixin.screenshot | def screenshot(self, filename=None):
"""
Take screen snapshot
Args:
- filename: filename where save to, optional
Returns:
PIL.Image object
Raises:
TypeError, IOError
"""
if self.__keep_screen:
return self.__last_screen
try:
screen = self._take_screenshot()
except IOError:
# try taks screenshot again
log.warn("warning, screenshot failed [2/1], retry again")
screen = self._take_screenshot()
self.__last_screen = screen
if filename:
save_dir = os.path.dirname(filename) or '.'
if not os.path.exists(save_dir):
os.makedirs(save_dir)
screen.save(filename)
return screen | python | def screenshot(self, filename=None):
"""
Take screen snapshot
Args:
- filename: filename where save to, optional
Returns:
PIL.Image object
Raises:
TypeError, IOError
"""
if self.__keep_screen:
return self.__last_screen
try:
screen = self._take_screenshot()
except IOError:
# try taks screenshot again
log.warn("warning, screenshot failed [2/1], retry again")
screen = self._take_screenshot()
self.__last_screen = screen
if filename:
save_dir = os.path.dirname(filename) or '.'
if not os.path.exists(save_dir):
os.makedirs(save_dir)
screen.save(filename)
return screen | [
"def",
"screenshot",
"(",
"self",
",",
"filename",
"=",
"None",
")",
":",
"if",
"self",
".",
"__keep_screen",
":",
"return",
"self",
".",
"__last_screen",
"try",
":",
"screen",
"=",
"self",
".",
"_take_screenshot",
"(",
")",
"except",
"IOError",
":",
"# ... | Take screen snapshot
Args:
- filename: filename where save to, optional
Returns:
PIL.Image object
Raises:
TypeError, IOError | [
"Take",
"screen",
"snapshot"
] | f4415c57b45cb0730e08899cbc92a2af1c047ffb | https://github.com/NetEaseGame/ATX/blob/f4415c57b45cb0730e08899cbc92a2af1c047ffb/atx/drivers/mixin.py#L388-L415 | train | 222,551 |
NetEaseGame/ATX | atx/drivers/mixin.py | DeviceMixin.click_nowait | def click_nowait(self, pattern, action='click', desc=None, **match_kwargs):
""" Return immediately if no image found
Args:
- pattern (str or Pattern): filename or an opencv image object.
- action (str): click or long_click
Returns:
Click point or None
"""
point = self.match(pattern, **match_kwargs)
if not point or not point.matched:
return None
func = getattr(self, action)
func(*point.pos)
return point | python | def click_nowait(self, pattern, action='click', desc=None, **match_kwargs):
""" Return immediately if no image found
Args:
- pattern (str or Pattern): filename or an opencv image object.
- action (str): click or long_click
Returns:
Click point or None
"""
point = self.match(pattern, **match_kwargs)
if not point or not point.matched:
return None
func = getattr(self, action)
func(*point.pos)
return point | [
"def",
"click_nowait",
"(",
"self",
",",
"pattern",
",",
"action",
"=",
"'click'",
",",
"desc",
"=",
"None",
",",
"*",
"*",
"match_kwargs",
")",
":",
"point",
"=",
"self",
".",
"match",
"(",
"pattern",
",",
"*",
"*",
"match_kwargs",
")",
"if",
"not",... | Return immediately if no image found
Args:
- pattern (str or Pattern): filename or an opencv image object.
- action (str): click or long_click
Returns:
Click point or None | [
"Return",
"immediately",
"if",
"no",
"image",
"found"
] | f4415c57b45cb0730e08899cbc92a2af1c047ffb | https://github.com/NetEaseGame/ATX/blob/f4415c57b45cb0730e08899cbc92a2af1c047ffb/atx/drivers/mixin.py#L471-L487 | train | 222,552 |
NetEaseGame/ATX | atx/drivers/mixin.py | DeviceMixin.click_image | def click_image(self, pattern, timeout=20.0, action='click', safe=False, desc=None, delay=None, **match_kwargs):
"""Simulate click according image position
Args:
- pattern (str or Pattern): filename or an opencv image object.
- timeout (float): if image not found during this time, ImageNotFoundError will raise.
- action (str): click or long_click
- safe (bool): if safe is True, Exception will not raise and return None instead.
- method (str): image match method, choice of <template|sift>
- delay (float): wait for a moment then perform click
Returns:
None
Raises:
ImageNotFoundError: An error occured when img not found in current screen.
"""
pattern = self.pattern_open(pattern)
log.info('click image:%s %s', desc or '', pattern)
start_time = time.time()
found = False
point = None
while time.time() - start_time < timeout:
point = self.match(pattern, **match_kwargs)
if point is None:
sys.stdout.write('.')
sys.stdout.flush()
continue
log.debug('confidence: %s', point.confidence)
if not point.matched:
log.info('Ignore confidence: %s', point.confidence)
continue
# wait for program ready
if delay and delay > 0:
self.delay(delay)
func = getattr(self, action)
func(*point.pos)
found = True
break
sys.stdout.write('\n')
if not found:
if safe:
log.info("Image(%s) not found, safe=True, skip", pattern)
return None
raise errors.ImageNotFoundError('Not found image %s' % pattern, point)
# FIXME(ssx): maybe this function is too complex
return point | python | def click_image(self, pattern, timeout=20.0, action='click', safe=False, desc=None, delay=None, **match_kwargs):
"""Simulate click according image position
Args:
- pattern (str or Pattern): filename or an opencv image object.
- timeout (float): if image not found during this time, ImageNotFoundError will raise.
- action (str): click or long_click
- safe (bool): if safe is True, Exception will not raise and return None instead.
- method (str): image match method, choice of <template|sift>
- delay (float): wait for a moment then perform click
Returns:
None
Raises:
ImageNotFoundError: An error occured when img not found in current screen.
"""
pattern = self.pattern_open(pattern)
log.info('click image:%s %s', desc or '', pattern)
start_time = time.time()
found = False
point = None
while time.time() - start_time < timeout:
point = self.match(pattern, **match_kwargs)
if point is None:
sys.stdout.write('.')
sys.stdout.flush()
continue
log.debug('confidence: %s', point.confidence)
if not point.matched:
log.info('Ignore confidence: %s', point.confidence)
continue
# wait for program ready
if delay and delay > 0:
self.delay(delay)
func = getattr(self, action)
func(*point.pos)
found = True
break
sys.stdout.write('\n')
if not found:
if safe:
log.info("Image(%s) not found, safe=True, skip", pattern)
return None
raise errors.ImageNotFoundError('Not found image %s' % pattern, point)
# FIXME(ssx): maybe this function is too complex
return point | [
"def",
"click_image",
"(",
"self",
",",
"pattern",
",",
"timeout",
"=",
"20.0",
",",
"action",
"=",
"'click'",
",",
"safe",
"=",
"False",
",",
"desc",
"=",
"None",
",",
"delay",
"=",
"None",
",",
"*",
"*",
"match_kwargs",
")",
":",
"pattern",
"=",
... | Simulate click according image position
Args:
- pattern (str or Pattern): filename or an opencv image object.
- timeout (float): if image not found during this time, ImageNotFoundError will raise.
- action (str): click or long_click
- safe (bool): if safe is True, Exception will not raise and return None instead.
- method (str): image match method, choice of <template|sift>
- delay (float): wait for a moment then perform click
Returns:
None
Raises:
ImageNotFoundError: An error occured when img not found in current screen. | [
"Simulate",
"click",
"according",
"image",
"position"
] | f4415c57b45cb0730e08899cbc92a2af1c047ffb | https://github.com/NetEaseGame/ATX/blob/f4415c57b45cb0730e08899cbc92a2af1c047ffb/atx/drivers/mixin.py#L503-L555 | train | 222,553 |
NetEaseGame/ATX | atx/base.py | list_images | def list_images(path=['.']):
""" Return list of image files """
for image_dir in set(path):
if not os.path.isdir(image_dir):
continue
for filename in os.listdir(image_dir):
bname, ext = os.path.splitext(filename)
if ext.lower() not in VALID_IMAGE_EXTS:
continue
filepath = os.path.join(image_dir, filename)
yield strutils.decode(filepath) | python | def list_images(path=['.']):
""" Return list of image files """
for image_dir in set(path):
if not os.path.isdir(image_dir):
continue
for filename in os.listdir(image_dir):
bname, ext = os.path.splitext(filename)
if ext.lower() not in VALID_IMAGE_EXTS:
continue
filepath = os.path.join(image_dir, filename)
yield strutils.decode(filepath) | [
"def",
"list_images",
"(",
"path",
"=",
"[",
"'.'",
"]",
")",
":",
"for",
"image_dir",
"in",
"set",
"(",
"path",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"image_dir",
")",
":",
"continue",
"for",
"filename",
"in",
"os",
".",
"... | Return list of image files | [
"Return",
"list",
"of",
"image",
"files"
] | f4415c57b45cb0730e08899cbc92a2af1c047ffb | https://github.com/NetEaseGame/ATX/blob/f4415c57b45cb0730e08899cbc92a2af1c047ffb/atx/base.py#L94-L105 | train | 222,554 |
NetEaseGame/ATX | atx/base.py | list_all_image | def list_all_image(path, valid_exts=VALID_IMAGE_EXTS):
"""List all images under path
@return unicode list
"""
for filename in os.listdir(path):
bname, ext = os.path.splitext(filename)
if ext.lower() not in VALID_IMAGE_EXTS:
continue
filepath = os.path.join(path, filename)
yield strutils.decode(filepath) | python | def list_all_image(path, valid_exts=VALID_IMAGE_EXTS):
"""List all images under path
@return unicode list
"""
for filename in os.listdir(path):
bname, ext = os.path.splitext(filename)
if ext.lower() not in VALID_IMAGE_EXTS:
continue
filepath = os.path.join(path, filename)
yield strutils.decode(filepath) | [
"def",
"list_all_image",
"(",
"path",
",",
"valid_exts",
"=",
"VALID_IMAGE_EXTS",
")",
":",
"for",
"filename",
"in",
"os",
".",
"listdir",
"(",
"path",
")",
":",
"bname",
",",
"ext",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"filename",
")",
"if",
... | List all images under path
@return unicode list | [
"List",
"all",
"images",
"under",
"path"
] | f4415c57b45cb0730e08899cbc92a2af1c047ffb | https://github.com/NetEaseGame/ATX/blob/f4415c57b45cb0730e08899cbc92a2af1c047ffb/atx/base.py#L108-L118 | train | 222,555 |
NetEaseGame/ATX | atx/base.py | search_image | def search_image(name=None, path=['.']):
"""
look for the image real path, if name is None, then return all images under path.
@return system encoded path string
FIXME(ssx): this code is just looking wired.
"""
name = strutils.decode(name)
for image_dir in path:
if not os.path.isdir(image_dir):
continue
image_dir = strutils.decode(image_dir)
image_path = os.path.join(image_dir, name)
if os.path.isfile(image_path):
return strutils.encode(image_path)
for image_path in list_all_image(image_dir):
if not image_name_match(name, image_path):
continue
return strutils.encode(image_path)
return None | python | def search_image(name=None, path=['.']):
"""
look for the image real path, if name is None, then return all images under path.
@return system encoded path string
FIXME(ssx): this code is just looking wired.
"""
name = strutils.decode(name)
for image_dir in path:
if not os.path.isdir(image_dir):
continue
image_dir = strutils.decode(image_dir)
image_path = os.path.join(image_dir, name)
if os.path.isfile(image_path):
return strutils.encode(image_path)
for image_path in list_all_image(image_dir):
if not image_name_match(name, image_path):
continue
return strutils.encode(image_path)
return None | [
"def",
"search_image",
"(",
"name",
"=",
"None",
",",
"path",
"=",
"[",
"'.'",
"]",
")",
":",
"name",
"=",
"strutils",
".",
"decode",
"(",
"name",
")",
"for",
"image_dir",
"in",
"path",
":",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"ima... | look for the image real path, if name is None, then return all images under path.
@return system encoded path string
FIXME(ssx): this code is just looking wired. | [
"look",
"for",
"the",
"image",
"real",
"path",
"if",
"name",
"is",
"None",
"then",
"return",
"all",
"images",
"under",
"path",
"."
] | f4415c57b45cb0730e08899cbc92a2af1c047ffb | https://github.com/NetEaseGame/ATX/blob/f4415c57b45cb0730e08899cbc92a2af1c047ffb/atx/base.py#L145-L165 | train | 222,556 |
NetEaseGame/ATX | atx/adbkit/device.py | Device.run_cmd | def run_cmd(self, *args, **kwargs):
"""
Unix style output, already replace \r\n to \n
Args:
- timeout (float): timeout for a command exec
"""
timeout = kwargs.pop('timeout', None)
p = self.raw_cmd(*args, **kwargs)
return p.communicate(timeout=timeout)[0].decode('utf-8').replace('\r\n', '\n') | python | def run_cmd(self, *args, **kwargs):
"""
Unix style output, already replace \r\n to \n
Args:
- timeout (float): timeout for a command exec
"""
timeout = kwargs.pop('timeout', None)
p = self.raw_cmd(*args, **kwargs)
return p.communicate(timeout=timeout)[0].decode('utf-8').replace('\r\n', '\n') | [
"def",
"run_cmd",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"timeout",
"=",
"kwargs",
".",
"pop",
"(",
"'timeout'",
",",
"None",
")",
"p",
"=",
"self",
".",
"raw_cmd",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"ret... | Unix style output, already replace \r\n to \n
Args:
- timeout (float): timeout for a command exec | [
"Unix",
"style",
"output",
"already",
"replace",
"\\",
"r",
"\\",
"n",
"to",
"\\",
"n"
] | f4415c57b45cb0730e08899cbc92a2af1c047ffb | https://github.com/NetEaseGame/ATX/blob/f4415c57b45cb0730e08899cbc92a2af1c047ffb/atx/adbkit/device.py#L47-L56 | train | 222,557 |
NetEaseGame/ATX | atx/adbkit/device.py | Device.shell | def shell(self, *args, **kwargs):
"""
Run command `adb shell`
"""
args = ['shell'] + list(args)
return self.run_cmd(*args, **kwargs) | python | def shell(self, *args, **kwargs):
"""
Run command `adb shell`
"""
args = ['shell'] + list(args)
return self.run_cmd(*args, **kwargs) | [
"def",
"shell",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"args",
"=",
"[",
"'shell'",
"]",
"+",
"list",
"(",
"args",
")",
"return",
"self",
".",
"run_cmd",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | Run command `adb shell` | [
"Run",
"command",
"adb",
"shell"
] | f4415c57b45cb0730e08899cbc92a2af1c047ffb | https://github.com/NetEaseGame/ATX/blob/f4415c57b45cb0730e08899cbc92a2af1c047ffb/atx/adbkit/device.py#L58-L63 | train | 222,558 |
NetEaseGame/ATX | atx/adbkit/device.py | Device.remove | def remove(self, filename):
"""
Remove file from device
"""
output = self.shell('rm', filename)
# any output means rm failed.
return False if output else True | python | def remove(self, filename):
"""
Remove file from device
"""
output = self.shell('rm', filename)
# any output means rm failed.
return False if output else True | [
"def",
"remove",
"(",
"self",
",",
"filename",
")",
":",
"output",
"=",
"self",
".",
"shell",
"(",
"'rm'",
",",
"filename",
")",
"# any output means rm failed.",
"return",
"False",
"if",
"output",
"else",
"True"
] | Remove file from device | [
"Remove",
"file",
"from",
"device"
] | f4415c57b45cb0730e08899cbc92a2af1c047ffb | https://github.com/NetEaseGame/ATX/blob/f4415c57b45cb0730e08899cbc92a2af1c047ffb/atx/adbkit/device.py#L69-L75 | train | 222,559 |
NetEaseGame/ATX | atx/adbkit/device.py | Device.display | def display(self):
'''
Return device width, height, rotation
'''
w, h = (0, 0)
for line in self.shell('dumpsys', 'display').splitlines():
m = _DISPLAY_RE.search(line, 0)
if not m:
continue
w = int(m.group('width'))
h = int(m.group('height'))
o = int(m.group('orientation'))
w, h = min(w, h), max(w, h)
return self.Display(w, h, o)
output = self.shell('LD_LIBRARY_PATH=/data/local/tmp', self.__minicap, '-i')
try:
data = json.loads(output)
(w, h, o) = (data['width'], data['height'], data['rotation']/90)
return self.Display(w, h, o)
except ValueError:
pass | python | def display(self):
'''
Return device width, height, rotation
'''
w, h = (0, 0)
for line in self.shell('dumpsys', 'display').splitlines():
m = _DISPLAY_RE.search(line, 0)
if not m:
continue
w = int(m.group('width'))
h = int(m.group('height'))
o = int(m.group('orientation'))
w, h = min(w, h), max(w, h)
return self.Display(w, h, o)
output = self.shell('LD_LIBRARY_PATH=/data/local/tmp', self.__minicap, '-i')
try:
data = json.loads(output)
(w, h, o) = (data['width'], data['height'], data['rotation']/90)
return self.Display(w, h, o)
except ValueError:
pass | [
"def",
"display",
"(",
"self",
")",
":",
"w",
",",
"h",
"=",
"(",
"0",
",",
"0",
")",
"for",
"line",
"in",
"self",
".",
"shell",
"(",
"'dumpsys'",
",",
"'display'",
")",
".",
"splitlines",
"(",
")",
":",
"m",
"=",
"_DISPLAY_RE",
".",
"search",
... | Return device width, height, rotation | [
"Return",
"device",
"width",
"height",
"rotation"
] | f4415c57b45cb0730e08899cbc92a2af1c047ffb | https://github.com/NetEaseGame/ATX/blob/f4415c57b45cb0730e08899cbc92a2af1c047ffb/atx/adbkit/device.py#L105-L126 | train | 222,560 |
NetEaseGame/ATX | atx/adbkit/device.py | Device.packages | def packages(self):
"""
Show all packages
"""
pattern = re.compile(r'package:(/[^=]+\.apk)=([^\s]+)')
packages = []
for line in self.shell('pm', 'list', 'packages', '-f').splitlines():
m = pattern.match(line)
if not m:
continue
path, name = m.group(1), m.group(2)
packages.append(self.Package(name, path))
return packages | python | def packages(self):
"""
Show all packages
"""
pattern = re.compile(r'package:(/[^=]+\.apk)=([^\s]+)')
packages = []
for line in self.shell('pm', 'list', 'packages', '-f').splitlines():
m = pattern.match(line)
if not m:
continue
path, name = m.group(1), m.group(2)
packages.append(self.Package(name, path))
return packages | [
"def",
"packages",
"(",
"self",
")",
":",
"pattern",
"=",
"re",
".",
"compile",
"(",
"r'package:(/[^=]+\\.apk)=([^\\s]+)'",
")",
"packages",
"=",
"[",
"]",
"for",
"line",
"in",
"self",
".",
"shell",
"(",
"'pm'",
",",
"'list'",
",",
"'packages'",
",",
"'-... | Show all packages | [
"Show",
"all",
"packages"
] | f4415c57b45cb0730e08899cbc92a2af1c047ffb | https://github.com/NetEaseGame/ATX/blob/f4415c57b45cb0730e08899cbc92a2af1c047ffb/atx/adbkit/device.py#L153-L165 | train | 222,561 |
NetEaseGame/ATX | atx/adbkit/device.py | Device._adb_screencap | def _adb_screencap(self, scale=1.0):
"""
capture screen with adb shell screencap
"""
remote_file = tempfile.mktemp(dir='/data/local/tmp/', prefix='screencap-', suffix='.png')
local_file = tempfile.mktemp(prefix='atx-screencap-', suffix='.png')
self.shell('screencap', '-p', remote_file)
try:
self.pull(remote_file, local_file)
image = imutils.open_as_pillow(local_file)
if scale is not None and scale != 1.0:
image = image.resize([int(scale * s) for s in image.size], Image.BICUBIC)
rotation = self.rotation()
if rotation:
method = getattr(Image, 'ROTATE_{}'.format(rotation*90))
image = image.transpose(method)
return image
finally:
self.remove(remote_file)
os.unlink(local_file) | python | def _adb_screencap(self, scale=1.0):
"""
capture screen with adb shell screencap
"""
remote_file = tempfile.mktemp(dir='/data/local/tmp/', prefix='screencap-', suffix='.png')
local_file = tempfile.mktemp(prefix='atx-screencap-', suffix='.png')
self.shell('screencap', '-p', remote_file)
try:
self.pull(remote_file, local_file)
image = imutils.open_as_pillow(local_file)
if scale is not None and scale != 1.0:
image = image.resize([int(scale * s) for s in image.size], Image.BICUBIC)
rotation = self.rotation()
if rotation:
method = getattr(Image, 'ROTATE_{}'.format(rotation*90))
image = image.transpose(method)
return image
finally:
self.remove(remote_file)
os.unlink(local_file) | [
"def",
"_adb_screencap",
"(",
"self",
",",
"scale",
"=",
"1.0",
")",
":",
"remote_file",
"=",
"tempfile",
".",
"mktemp",
"(",
"dir",
"=",
"'/data/local/tmp/'",
",",
"prefix",
"=",
"'screencap-'",
",",
"suffix",
"=",
"'.png'",
")",
"local_file",
"=",
"tempf... | capture screen with adb shell screencap | [
"capture",
"screen",
"with",
"adb",
"shell",
"screencap"
] | f4415c57b45cb0730e08899cbc92a2af1c047ffb | https://github.com/NetEaseGame/ATX/blob/f4415c57b45cb0730e08899cbc92a2af1c047ffb/atx/adbkit/device.py#L167-L186 | train | 222,562 |
NetEaseGame/ATX | atx/adbkit/device.py | Device._adb_minicap | def _adb_minicap(self, scale=1.0):
"""
capture screen with minicap
https://github.com/openstf/minicap
"""
remote_file = tempfile.mktemp(dir='/data/local/tmp/', prefix='minicap-', suffix='.jpg')
local_file = tempfile.mktemp(prefix='atx-minicap-', suffix='.jpg')
(w, h, r) = self.display
params = '{x}x{y}@{rx}x{ry}/{r}'.format(x=w, y=h, rx=int(w*scale), ry=int(h*scale), r=r*90)
try:
self.shell('LD_LIBRARY_PATH=/data/local/tmp', self.__minicap, '-s', '-P', params, '>', remote_file)
self.pull(remote_file, local_file)
image = imutils.open_as_pillow(local_file)
return image
finally:
self.remove(remote_file)
os.unlink(local_file) | python | def _adb_minicap(self, scale=1.0):
"""
capture screen with minicap
https://github.com/openstf/minicap
"""
remote_file = tempfile.mktemp(dir='/data/local/tmp/', prefix='minicap-', suffix='.jpg')
local_file = tempfile.mktemp(prefix='atx-minicap-', suffix='.jpg')
(w, h, r) = self.display
params = '{x}x{y}@{rx}x{ry}/{r}'.format(x=w, y=h, rx=int(w*scale), ry=int(h*scale), r=r*90)
try:
self.shell('LD_LIBRARY_PATH=/data/local/tmp', self.__minicap, '-s', '-P', params, '>', remote_file)
self.pull(remote_file, local_file)
image = imutils.open_as_pillow(local_file)
return image
finally:
self.remove(remote_file)
os.unlink(local_file) | [
"def",
"_adb_minicap",
"(",
"self",
",",
"scale",
"=",
"1.0",
")",
":",
"remote_file",
"=",
"tempfile",
".",
"mktemp",
"(",
"dir",
"=",
"'/data/local/tmp/'",
",",
"prefix",
"=",
"'minicap-'",
",",
"suffix",
"=",
"'.jpg'",
")",
"local_file",
"=",
"tempfile"... | capture screen with minicap
https://github.com/openstf/minicap | [
"capture",
"screen",
"with",
"minicap"
] | f4415c57b45cb0730e08899cbc92a2af1c047ffb | https://github.com/NetEaseGame/ATX/blob/f4415c57b45cb0730e08899cbc92a2af1c047ffb/atx/adbkit/device.py#L188-L205 | train | 222,563 |
NetEaseGame/ATX | atx/adbkit/device.py | Device.screenshot | def screenshot(self, filename=None, scale=1.0, method=None):
"""
Take device screenshot
Args:
- filename(string): optional, save int filename
- scale(float): scale size
- method(string): one of minicap,screencap
Return:
PIL.Image
"""
image = None
method = method or self._screenshot_method
if method == 'minicap':
try:
image = self._adb_minicap(scale)
except Exception as e:
logger.warn("use minicap failed, fallback to screencap. error detail: %s", e)
self._screenshot_method = 'screencap'
return self.screenshot(filename=filename, scale=scale)
elif method == 'screencap':
image = self._adb_screencap(scale)
else:
raise RuntimeError("No such method(%s)" % method)
if filename:
image.save(filename)
return image | python | def screenshot(self, filename=None, scale=1.0, method=None):
"""
Take device screenshot
Args:
- filename(string): optional, save int filename
- scale(float): scale size
- method(string): one of minicap,screencap
Return:
PIL.Image
"""
image = None
method = method or self._screenshot_method
if method == 'minicap':
try:
image = self._adb_minicap(scale)
except Exception as e:
logger.warn("use minicap failed, fallback to screencap. error detail: %s", e)
self._screenshot_method = 'screencap'
return self.screenshot(filename=filename, scale=scale)
elif method == 'screencap':
image = self._adb_screencap(scale)
else:
raise RuntimeError("No such method(%s)" % method)
if filename:
image.save(filename)
return image | [
"def",
"screenshot",
"(",
"self",
",",
"filename",
"=",
"None",
",",
"scale",
"=",
"1.0",
",",
"method",
"=",
"None",
")",
":",
"image",
"=",
"None",
"method",
"=",
"method",
"or",
"self",
".",
"_screenshot_method",
"if",
"method",
"==",
"'minicap'",
"... | Take device screenshot
Args:
- filename(string): optional, save int filename
- scale(float): scale size
- method(string): one of minicap,screencap
Return:
PIL.Image | [
"Take",
"device",
"screenshot"
] | f4415c57b45cb0730e08899cbc92a2af1c047ffb | https://github.com/NetEaseGame/ATX/blob/f4415c57b45cb0730e08899cbc92a2af1c047ffb/atx/adbkit/device.py#L207-L235 | train | 222,564 |
NetEaseGame/ATX | atx/record/android_layout.py | AndroidLayout.get_index_node | def get_index_node(self, idx):
'''get node with iterindex `idx`'''
idx = self.node_index.index(idx)
return self.nodes[idx] | python | def get_index_node(self, idx):
'''get node with iterindex `idx`'''
idx = self.node_index.index(idx)
return self.nodes[idx] | [
"def",
"get_index_node",
"(",
"self",
",",
"idx",
")",
":",
"idx",
"=",
"self",
".",
"node_index",
".",
"index",
"(",
"idx",
")",
"return",
"self",
".",
"nodes",
"[",
"idx",
"]"
] | get node with iterindex `idx` | [
"get",
"node",
"with",
"iterindex",
"idx"
] | f4415c57b45cb0730e08899cbc92a2af1c047ffb | https://github.com/NetEaseGame/ATX/blob/f4415c57b45cb0730e08899cbc92a2af1c047ffb/atx/record/android_layout.py#L178-L181 | train | 222,565 |
NetEaseGame/ATX | atx/record/base.py | BaseRecorder.start | def start(self):
'''start running in background.'''
self.update_device_info()
self.get_device_status(0) # start addons.
self.hook()
self.thread = threading.Thread(target=self._run)
self.thread.start()
self.running = True | python | def start(self):
'''start running in background.'''
self.update_device_info()
self.get_device_status(0) # start addons.
self.hook()
self.thread = threading.Thread(target=self._run)
self.thread.start()
self.running = True | [
"def",
"start",
"(",
"self",
")",
":",
"self",
".",
"update_device_info",
"(",
")",
"self",
".",
"get_device_status",
"(",
"0",
")",
"# start addons.\r",
"self",
".",
"hook",
"(",
")",
"self",
".",
"thread",
"=",
"threading",
".",
"Thread",
"(",
"target"... | start running in background. | [
"start",
"running",
"in",
"background",
"."
] | f4415c57b45cb0730e08899cbc92a2af1c047ffb | https://github.com/NetEaseGame/ATX/blob/f4415c57b45cb0730e08899cbc92a2af1c047ffb/atx/record/base.py#L66-L73 | train | 222,566 |
NetEaseGame/ATX | atx/record/base.py | BaseRecorder.analyze_frames | def analyze_frames(cls, workdir):
'''generate draft from recorded frames'''
record = cls(None, workdir)
obj = {}
with open(os.path.join(workdir, 'frames', 'frames.json')) as f:
obj = json.load(f)
record.device_info = obj['device']
record.frames = obj['frames']
record.analyze_all()
record.save() | python | def analyze_frames(cls, workdir):
'''generate draft from recorded frames'''
record = cls(None, workdir)
obj = {}
with open(os.path.join(workdir, 'frames', 'frames.json')) as f:
obj = json.load(f)
record.device_info = obj['device']
record.frames = obj['frames']
record.analyze_all()
record.save() | [
"def",
"analyze_frames",
"(",
"cls",
",",
"workdir",
")",
":",
"record",
"=",
"cls",
"(",
"None",
",",
"workdir",
")",
"obj",
"=",
"{",
"}",
"with",
"open",
"(",
"os",
".",
"path",
".",
"join",
"(",
"workdir",
",",
"'frames'",
",",
"'frames.json'",
... | generate draft from recorded frames | [
"generate",
"draft",
"from",
"recorded",
"frames"
] | f4415c57b45cb0730e08899cbc92a2af1c047ffb | https://github.com/NetEaseGame/ATX/blob/f4415c57b45cb0730e08899cbc92a2af1c047ffb/atx/record/base.py#L180-L189 | train | 222,567 |
NetEaseGame/ATX | atx/record/base.py | BaseRecorder.process_casefile | def process_casefile(cls, workdir):
'''generate code from case.json'''
record = cls(None, workdir)
obj = {}
with open(os.path.join(workdir, 'frames', 'frames.json')) as f:
obj = json.load(f)
record.device_info = obj['device']
record.frames = obj['frames']
casedir = os.path.join(workdir, 'case')
with open(os.path.join(casedir, 'case.json')) as f:
record.case_draft = json.load(f)
# remove old files
for f in os.listdir(casedir):
if f != 'case.json':
os.remove(os.path.join(casedir, f))
record.generate_script() | python | def process_casefile(cls, workdir):
'''generate code from case.json'''
record = cls(None, workdir)
obj = {}
with open(os.path.join(workdir, 'frames', 'frames.json')) as f:
obj = json.load(f)
record.device_info = obj['device']
record.frames = obj['frames']
casedir = os.path.join(workdir, 'case')
with open(os.path.join(casedir, 'case.json')) as f:
record.case_draft = json.load(f)
# remove old files
for f in os.listdir(casedir):
if f != 'case.json':
os.remove(os.path.join(casedir, f))
record.generate_script() | [
"def",
"process_casefile",
"(",
"cls",
",",
"workdir",
")",
":",
"record",
"=",
"cls",
"(",
"None",
",",
"workdir",
")",
"obj",
"=",
"{",
"}",
"with",
"open",
"(",
"os",
".",
"path",
".",
"join",
"(",
"workdir",
",",
"'frames'",
",",
"'frames.json'",... | generate code from case.json | [
"generate",
"code",
"from",
"case",
".",
"json"
] | f4415c57b45cb0730e08899cbc92a2af1c047ffb | https://github.com/NetEaseGame/ATX/blob/f4415c57b45cb0730e08899cbc92a2af1c047ffb/atx/record/base.py#L192-L210 | train | 222,568 |
NetEaseGame/ATX | atx/adbkit/client.py | Client.adb_path | def adb_path(cls):
"""return adb binary full path"""
if cls.__adb_cmd is None:
if "ANDROID_HOME" in os.environ:
filename = "adb.exe" if os.name == 'nt' else "adb"
adb_dir = os.path.join(os.environ["ANDROID_HOME"], "platform-tools")
adb_cmd = os.path.join(adb_dir, filename)
if not os.path.exists(adb_cmd):
raise EnvironmentError(
"Adb not found in $ANDROID_HOME/platform-tools path: %s." % adb_dir)
else:
import distutils
if "spawn" not in dir(distutils):
import distutils.spawn
adb_cmd = distutils.spawn.find_executable("adb")
if adb_cmd:
adb_cmd = os.path.realpath(adb_cmd)
else:
raise EnvironmentError("$ANDROID_HOME environment not set.")
cls.__adb_cmd = adb_cmd
return cls.__adb_cmd | python | def adb_path(cls):
"""return adb binary full path"""
if cls.__adb_cmd is None:
if "ANDROID_HOME" in os.environ:
filename = "adb.exe" if os.name == 'nt' else "adb"
adb_dir = os.path.join(os.environ["ANDROID_HOME"], "platform-tools")
adb_cmd = os.path.join(adb_dir, filename)
if not os.path.exists(adb_cmd):
raise EnvironmentError(
"Adb not found in $ANDROID_HOME/platform-tools path: %s." % adb_dir)
else:
import distutils
if "spawn" not in dir(distutils):
import distutils.spawn
adb_cmd = distutils.spawn.find_executable("adb")
if adb_cmd:
adb_cmd = os.path.realpath(adb_cmd)
else:
raise EnvironmentError("$ANDROID_HOME environment not set.")
cls.__adb_cmd = adb_cmd
return cls.__adb_cmd | [
"def",
"adb_path",
"(",
"cls",
")",
":",
"if",
"cls",
".",
"__adb_cmd",
"is",
"None",
":",
"if",
"\"ANDROID_HOME\"",
"in",
"os",
".",
"environ",
":",
"filename",
"=",
"\"adb.exe\"",
"if",
"os",
".",
"name",
"==",
"'nt'",
"else",
"\"adb\"",
"adb_dir",
"... | return adb binary full path | [
"return",
"adb",
"binary",
"full",
"path"
] | f4415c57b45cb0730e08899cbc92a2af1c047ffb | https://github.com/NetEaseGame/ATX/blob/f4415c57b45cb0730e08899cbc92a2af1c047ffb/atx/adbkit/client.py#L52-L72 | train | 222,569 |
NetEaseGame/ATX | atx/adbkit/client.py | Client.connect | def connect(self, addr):
'''
Call adb connect
Return true when connect success
'''
if addr.find(':') == -1:
addr += ':5555'
output = self.run_cmd('connect', addr)
return 'unable to connect' not in output | python | def connect(self, addr):
'''
Call adb connect
Return true when connect success
'''
if addr.find(':') == -1:
addr += ':5555'
output = self.run_cmd('connect', addr)
return 'unable to connect' not in output | [
"def",
"connect",
"(",
"self",
",",
"addr",
")",
":",
"if",
"addr",
".",
"find",
"(",
"':'",
")",
"==",
"-",
"1",
":",
"addr",
"+=",
"':5555'",
"output",
"=",
"self",
".",
"run_cmd",
"(",
"'connect'",
",",
"addr",
")",
"return",
"'unable to connect'"... | Call adb connect
Return true when connect success | [
"Call",
"adb",
"connect",
"Return",
"true",
"when",
"connect",
"success"
] | f4415c57b45cb0730e08899cbc92a2af1c047ffb | https://github.com/NetEaseGame/ATX/blob/f4415c57b45cb0730e08899cbc92a2af1c047ffb/atx/adbkit/client.py#L137-L145 | train | 222,570 |
NetEaseGame/ATX | atx/cmds/screencap.py | main | def main(host=None, port=None, serial=None, scale=1.0, out='screenshot.png', method='minicap'):
"""
If minicap not avaliable then use uiautomator instead
Disable scale for now.
Because -s scale is conflict of -s serial
"""
print('Started screencap')
start = time.time()
client = adbkit.Client(host=host, port=port)
device = client.device(serial)
im = device.screenshot(scale=scale)
im.save(out)
print('Time spend: %.2fs' % (time.time() - start))
print('File saved to "%s"' % out)
try:
import win32clipboard
output = StringIO()
im.convert("RGB").save(output, "BMP")
data = output.getvalue()[14:]
output.close()
win32clipboard.OpenClipboard()
win32clipboard.EmptyClipboard()
win32clipboard.SetClipboardData(win32clipboard.CF_DIB, data)
win32clipboard.CloseClipboard()
print('Copied to clipboard')
except:
pass | python | def main(host=None, port=None, serial=None, scale=1.0, out='screenshot.png', method='minicap'):
"""
If minicap not avaliable then use uiautomator instead
Disable scale for now.
Because -s scale is conflict of -s serial
"""
print('Started screencap')
start = time.time()
client = adbkit.Client(host=host, port=port)
device = client.device(serial)
im = device.screenshot(scale=scale)
im.save(out)
print('Time spend: %.2fs' % (time.time() - start))
print('File saved to "%s"' % out)
try:
import win32clipboard
output = StringIO()
im.convert("RGB").save(output, "BMP")
data = output.getvalue()[14:]
output.close()
win32clipboard.OpenClipboard()
win32clipboard.EmptyClipboard()
win32clipboard.SetClipboardData(win32clipboard.CF_DIB, data)
win32clipboard.CloseClipboard()
print('Copied to clipboard')
except:
pass | [
"def",
"main",
"(",
"host",
"=",
"None",
",",
"port",
"=",
"None",
",",
"serial",
"=",
"None",
",",
"scale",
"=",
"1.0",
",",
"out",
"=",
"'screenshot.png'",
",",
"method",
"=",
"'minicap'",
")",
":",
"print",
"(",
"'Started screencap'",
")",
"start",
... | If minicap not avaliable then use uiautomator instead
Disable scale for now.
Because -s scale is conflict of -s serial | [
"If",
"minicap",
"not",
"avaliable",
"then",
"use",
"uiautomator",
"instead",
"Disable",
"scale",
"for",
"now",
".",
"Because",
"-",
"s",
"scale",
"is",
"conflict",
"of",
"-",
"s",
"serial"
] | f4415c57b45cb0730e08899cbc92a2af1c047ffb | https://github.com/NetEaseGame/ATX/blob/f4415c57b45cb0730e08899cbc92a2af1c047ffb/atx/cmds/screencap.py#L14-L45 | train | 222,571 |
NetEaseGame/ATX | atx/drivers/android.py | AndroidDevice.rotation | def rotation(self):
"""
Rotaion of the phone
0: normal
1: home key on the right
2: home key on the top
3: home key on the left
"""
if self.screen_rotation in range(4):
return self.screen_rotation
return self.adb_device.rotation() or self.info['displayRotation'] | python | def rotation(self):
"""
Rotaion of the phone
0: normal
1: home key on the right
2: home key on the top
3: home key on the left
"""
if self.screen_rotation in range(4):
return self.screen_rotation
return self.adb_device.rotation() or self.info['displayRotation'] | [
"def",
"rotation",
"(",
"self",
")",
":",
"if",
"self",
".",
"screen_rotation",
"in",
"range",
"(",
"4",
")",
":",
"return",
"self",
".",
"screen_rotation",
"return",
"self",
".",
"adb_device",
".",
"rotation",
"(",
")",
"or",
"self",
".",
"info",
"[",... | Rotaion of the phone
0: normal
1: home key on the right
2: home key on the top
3: home key on the left | [
"Rotaion",
"of",
"the",
"phone"
] | f4415c57b45cb0730e08899cbc92a2af1c047ffb | https://github.com/NetEaseGame/ATX/blob/f4415c57b45cb0730e08899cbc92a2af1c047ffb/atx/drivers/android.py#L192-L203 | train | 222,572 |
NetEaseGame/ATX | atx/drivers/android.py | AndroidDevice.properties | def properties(self):
'''
Android Properties, extracted from `adb shell getprop`
Returns:
dict of props, for
example:
{'ro.bluetooth.dun': 'true'}
'''
props = {}
for line in self.adb_shell(['getprop']).splitlines():
m = _PROP_PATTERN.match(line)
if m:
props[m.group('key')] = m.group('value')
return props | python | def properties(self):
'''
Android Properties, extracted from `adb shell getprop`
Returns:
dict of props, for
example:
{'ro.bluetooth.dun': 'true'}
'''
props = {}
for line in self.adb_shell(['getprop']).splitlines():
m = _PROP_PATTERN.match(line)
if m:
props[m.group('key')] = m.group('value')
return props | [
"def",
"properties",
"(",
"self",
")",
":",
"props",
"=",
"{",
"}",
"for",
"line",
"in",
"self",
".",
"adb_shell",
"(",
"[",
"'getprop'",
"]",
")",
".",
"splitlines",
"(",
")",
":",
"m",
"=",
"_PROP_PATTERN",
".",
"match",
"(",
"line",
")",
"if",
... | Android Properties, extracted from `adb shell getprop`
Returns:
dict of props, for
example:
{'ro.bluetooth.dun': 'true'} | [
"Android",
"Properties",
"extracted",
"from",
"adb",
"shell",
"getprop"
] | f4415c57b45cb0730e08899cbc92a2af1c047ffb | https://github.com/NetEaseGame/ATX/blob/f4415c57b45cb0730e08899cbc92a2af1c047ffb/atx/drivers/android.py#L265-L280 | train | 222,573 |
NetEaseGame/ATX | atx/drivers/android.py | AndroidDevice.type | def type(self, s, enter=False, clear=False):
"""Input some text, this method has been tested not very stable on some device.
"Hi world" maybe spell into "H iworld"
Args:
- s: string (text to input), better to be unicode
- enter(bool): input enter at last
- next(bool): perform editor action Next
- clear(bool): clear text before type
- ui_select_kwargs(**): tap then type
The android source code show that
space need to change to %s
insteresting thing is that if want to input %s, it is really unconvinent.
android source code can be found here.
https://android.googlesource.com/platform/frameworks/base/+/android-4.4.2_r1/cmds/input/src/com/android/commands/input/Input.java#159
app source see here: https://github.com/openatx/android-unicode
"""
if clear:
self.clear_text()
self._uiauto.send_keys(s)
if enter:
self.keyevent('KEYCODE_ENTER') | python | def type(self, s, enter=False, clear=False):
"""Input some text, this method has been tested not very stable on some device.
"Hi world" maybe spell into "H iworld"
Args:
- s: string (text to input), better to be unicode
- enter(bool): input enter at last
- next(bool): perform editor action Next
- clear(bool): clear text before type
- ui_select_kwargs(**): tap then type
The android source code show that
space need to change to %s
insteresting thing is that if want to input %s, it is really unconvinent.
android source code can be found here.
https://android.googlesource.com/platform/frameworks/base/+/android-4.4.2_r1/cmds/input/src/com/android/commands/input/Input.java#159
app source see here: https://github.com/openatx/android-unicode
"""
if clear:
self.clear_text()
self._uiauto.send_keys(s)
if enter:
self.keyevent('KEYCODE_ENTER') | [
"def",
"type",
"(",
"self",
",",
"s",
",",
"enter",
"=",
"False",
",",
"clear",
"=",
"False",
")",
":",
"if",
"clear",
":",
"self",
".",
"clear_text",
"(",
")",
"self",
".",
"_uiauto",
".",
"send_keys",
"(",
"s",
")",
"if",
"enter",
":",
"self",
... | Input some text, this method has been tested not very stable on some device.
"Hi world" maybe spell into "H iworld"
Args:
- s: string (text to input), better to be unicode
- enter(bool): input enter at last
- next(bool): perform editor action Next
- clear(bool): clear text before type
- ui_select_kwargs(**): tap then type
The android source code show that
space need to change to %s
insteresting thing is that if want to input %s, it is really unconvinent.
android source code can be found here.
https://android.googlesource.com/platform/frameworks/base/+/android-4.4.2_r1/cmds/input/src/com/android/commands/input/Input.java#159
app source see here: https://github.com/openatx/android-unicode | [
"Input",
"some",
"text",
"this",
"method",
"has",
"been",
"tested",
"not",
"very",
"stable",
"on",
"some",
"device",
".",
"Hi",
"world",
"maybe",
"spell",
"into",
"H",
"iworld"
] | f4415c57b45cb0730e08899cbc92a2af1c047ffb | https://github.com/NetEaseGame/ATX/blob/f4415c57b45cb0730e08899cbc92a2af1c047ffb/atx/drivers/android.py#L436-L461 | train | 222,574 |
NetEaseGame/ATX | atx/drivers/android.py | AndroidDevice.input_methods | def input_methods(self):
"""
Get all input methods
Return example: ['com.sohu.inputmethod.sogou/.SogouIME', 'android.unicode.ime/.Utf7ImeService']
"""
imes = []
for line in self.adb_shell(['ime', 'list', '-s', '-a']).splitlines():
line = line.strip()
if re.match('^.+/.+$', line):
imes.append(line)
return imes | python | def input_methods(self):
"""
Get all input methods
Return example: ['com.sohu.inputmethod.sogou/.SogouIME', 'android.unicode.ime/.Utf7ImeService']
"""
imes = []
for line in self.adb_shell(['ime', 'list', '-s', '-a']).splitlines():
line = line.strip()
if re.match('^.+/.+$', line):
imes.append(line)
return imes | [
"def",
"input_methods",
"(",
"self",
")",
":",
"imes",
"=",
"[",
"]",
"for",
"line",
"in",
"self",
".",
"adb_shell",
"(",
"[",
"'ime'",
",",
"'list'",
",",
"'-s'",
",",
"'-a'",
"]",
")",
".",
"splitlines",
"(",
")",
":",
"line",
"=",
"line",
".",... | Get all input methods
Return example: ['com.sohu.inputmethod.sogou/.SogouIME', 'android.unicode.ime/.Utf7ImeService'] | [
"Get",
"all",
"input",
"methods"
] | f4415c57b45cb0730e08899cbc92a2af1c047ffb | https://github.com/NetEaseGame/ATX/blob/f4415c57b45cb0730e08899cbc92a2af1c047ffb/atx/drivers/android.py#L473-L484 | train | 222,575 |
NetEaseGame/ATX | atx/drivers/android.py | AndroidDevice.current_ime | def current_ime(self):
''' Get current input method '''
dumpout = self.adb_shell(['dumpsys', 'input_method'])
m = _INPUT_METHOD_RE.search(dumpout)
if m:
return m.group(1) | python | def current_ime(self):
''' Get current input method '''
dumpout = self.adb_shell(['dumpsys', 'input_method'])
m = _INPUT_METHOD_RE.search(dumpout)
if m:
return m.group(1) | [
"def",
"current_ime",
"(",
"self",
")",
":",
"dumpout",
"=",
"self",
".",
"adb_shell",
"(",
"[",
"'dumpsys'",
",",
"'input_method'",
"]",
")",
"m",
"=",
"_INPUT_METHOD_RE",
".",
"search",
"(",
"dumpout",
")",
"if",
"m",
":",
"return",
"m",
".",
"group"... | Get current input method | [
"Get",
"current",
"input",
"method"
] | f4415c57b45cb0730e08899cbc92a2af1c047ffb | https://github.com/NetEaseGame/ATX/blob/f4415c57b45cb0730e08899cbc92a2af1c047ffb/atx/drivers/android.py#L486-L491 | train | 222,576 |
NetEaseGame/ATX | atx/imutils.py | open_as_pillow | def open_as_pillow(filename):
""" This way can delete file immediately """
with __sys_open(filename, 'rb') as f:
data = BytesIO(f.read())
return Image.open(data) | python | def open_as_pillow(filename):
""" This way can delete file immediately """
with __sys_open(filename, 'rb') as f:
data = BytesIO(f.read())
return Image.open(data) | [
"def",
"open_as_pillow",
"(",
"filename",
")",
":",
"with",
"__sys_open",
"(",
"filename",
",",
"'rb'",
")",
"as",
"f",
":",
"data",
"=",
"BytesIO",
"(",
"f",
".",
"read",
"(",
")",
")",
"return",
"Image",
".",
"open",
"(",
"data",
")"
] | This way can delete file immediately | [
"This",
"way",
"can",
"delete",
"file",
"immediately"
] | f4415c57b45cb0730e08899cbc92a2af1c047ffb | https://github.com/NetEaseGame/ATX/blob/f4415c57b45cb0730e08899cbc92a2af1c047ffb/atx/imutils.py#L71-L75 | train | 222,577 |
NetEaseGame/ATX | atx/imutils.py | from_pillow | def from_pillow(pil_image):
""" Convert from pillow image to opencv """
# convert PIL to OpenCV
pil_image = pil_image.convert('RGB')
cv2_image = np.array(pil_image)
# Convert RGB to BGR
cv2_image = cv2_image[:, :, ::-1].copy()
return cv2_image | python | def from_pillow(pil_image):
""" Convert from pillow image to opencv """
# convert PIL to OpenCV
pil_image = pil_image.convert('RGB')
cv2_image = np.array(pil_image)
# Convert RGB to BGR
cv2_image = cv2_image[:, :, ::-1].copy()
return cv2_image | [
"def",
"from_pillow",
"(",
"pil_image",
")",
":",
"# convert PIL to OpenCV",
"pil_image",
"=",
"pil_image",
".",
"convert",
"(",
"'RGB'",
")",
"cv2_image",
"=",
"np",
".",
"array",
"(",
"pil_image",
")",
"# Convert RGB to BGR ",
"cv2_image",
"=",
"cv2_image",
"[... | Convert from pillow image to opencv | [
"Convert",
"from",
"pillow",
"image",
"to",
"opencv"
] | f4415c57b45cb0730e08899cbc92a2af1c047ffb | https://github.com/NetEaseGame/ATX/blob/f4415c57b45cb0730e08899cbc92a2af1c047ffb/atx/imutils.py#L81-L88 | train | 222,578 |
NetEaseGame/ATX | atx/imutils.py | url_to_image | def url_to_image(url, flag=cv2.IMREAD_COLOR):
""" download the image, convert it to a NumPy array, and then read
it into OpenCV format """
resp = urlopen(url)
image = np.asarray(bytearray(resp.read()), dtype="uint8")
image = cv2.imdecode(image, flag)
return image | python | def url_to_image(url, flag=cv2.IMREAD_COLOR):
""" download the image, convert it to a NumPy array, and then read
it into OpenCV format """
resp = urlopen(url)
image = np.asarray(bytearray(resp.read()), dtype="uint8")
image = cv2.imdecode(image, flag)
return image | [
"def",
"url_to_image",
"(",
"url",
",",
"flag",
"=",
"cv2",
".",
"IMREAD_COLOR",
")",
":",
"resp",
"=",
"urlopen",
"(",
"url",
")",
"image",
"=",
"np",
".",
"asarray",
"(",
"bytearray",
"(",
"resp",
".",
"read",
"(",
")",
")",
",",
"dtype",
"=",
... | download the image, convert it to a NumPy array, and then read
it into OpenCV format | [
"download",
"the",
"image",
"convert",
"it",
"to",
"a",
"NumPy",
"array",
"and",
"then",
"read",
"it",
"into",
"OpenCV",
"format"
] | f4415c57b45cb0730e08899cbc92a2af1c047ffb | https://github.com/NetEaseGame/ATX/blob/f4415c57b45cb0730e08899cbc92a2af1c047ffb/atx/imutils.py#L97-L103 | train | 222,579 |
NetEaseGame/ATX | atx/imutils.py | mark_point | def mark_point(img, x, y):
"""
Mark a point
Args:
- img(numpy): the source image
- x, y(int): position
"""
overlay = img.copy()
output = img.copy()
alpha = 0.5
radius = max(5, min(img.shape[:2])//15)
center = int(x), int(y)
color = (0, 0, 255)
cv2.circle(overlay, center, radius, color, -1)
cv2.addWeighted(overlay, alpha, output, 1-alpha, 0, output)
return output | python | def mark_point(img, x, y):
"""
Mark a point
Args:
- img(numpy): the source image
- x, y(int): position
"""
overlay = img.copy()
output = img.copy()
alpha = 0.5
radius = max(5, min(img.shape[:2])//15)
center = int(x), int(y)
color = (0, 0, 255)
cv2.circle(overlay, center, radius, color, -1)
cv2.addWeighted(overlay, alpha, output, 1-alpha, 0, output)
return output | [
"def",
"mark_point",
"(",
"img",
",",
"x",
",",
"y",
")",
":",
"overlay",
"=",
"img",
".",
"copy",
"(",
")",
"output",
"=",
"img",
".",
"copy",
"(",
")",
"alpha",
"=",
"0.5",
"radius",
"=",
"max",
"(",
"5",
",",
"min",
"(",
"img",
".",
"shape... | Mark a point
Args:
- img(numpy): the source image
- x, y(int): position | [
"Mark",
"a",
"point"
] | f4415c57b45cb0730e08899cbc92a2af1c047ffb | https://github.com/NetEaseGame/ATX/blob/f4415c57b45cb0730e08899cbc92a2af1c047ffb/atx/imutils.py#L139-L157 | train | 222,580 |
NetEaseGame/ATX | atx/drivers/ios_webdriveragent.py | IOSDevice.display | def display(self):
""" Get screen width and height """
w, h = self.session.window_size()
return Display(w*self.scale, h*self.scale) | python | def display(self):
""" Get screen width and height """
w, h = self.session.window_size()
return Display(w*self.scale, h*self.scale) | [
"def",
"display",
"(",
"self",
")",
":",
"w",
",",
"h",
"=",
"self",
".",
"session",
".",
"window_size",
"(",
")",
"return",
"Display",
"(",
"w",
"*",
"self",
".",
"scale",
",",
"h",
"*",
"self",
".",
"scale",
")"
] | Get screen width and height | [
"Get",
"screen",
"width",
"and",
"height"
] | f4415c57b45cb0730e08899cbc92a2af1c047ffb | https://github.com/NetEaseGame/ATX/blob/f4415c57b45cb0730e08899cbc92a2af1c047ffb/atx/drivers/ios_webdriveragent.py#L99-L102 | train | 222,581 |
NetEaseGame/ATX | scripts/adb_old.py | Adb.forward | def forward(self, device_port, local_port=None):
'''adb port forward. return local_port'''
if local_port is None:
for s, lp, rp in self.forward_list():
if s == self.device_serial() and rp == 'tcp:%d' % device_port:
return int(lp[4:])
return self.forward(device_port, next_local_port(self.server_host))
else:
self.cmd("forward", "tcp:%d" % local_port, "tcp:%d" % device_port).wait()
return local_port | python | def forward(self, device_port, local_port=None):
'''adb port forward. return local_port'''
if local_port is None:
for s, lp, rp in self.forward_list():
if s == self.device_serial() and rp == 'tcp:%d' % device_port:
return int(lp[4:])
return self.forward(device_port, next_local_port(self.server_host))
else:
self.cmd("forward", "tcp:%d" % local_port, "tcp:%d" % device_port).wait()
return local_port | [
"def",
"forward",
"(",
"self",
",",
"device_port",
",",
"local_port",
"=",
"None",
")",
":",
"if",
"local_port",
"is",
"None",
":",
"for",
"s",
",",
"lp",
",",
"rp",
"in",
"self",
".",
"forward_list",
"(",
")",
":",
"if",
"s",
"==",
"self",
".",
... | adb port forward. return local_port | [
"adb",
"port",
"forward",
".",
"return",
"local_port"
] | f4415c57b45cb0730e08899cbc92a2af1c047ffb | https://github.com/NetEaseGame/ATX/blob/f4415c57b45cb0730e08899cbc92a2af1c047ffb/scripts/adb_old.py#L178-L187 | train | 222,582 |
NetEaseGame/ATX | atx/record/android.py | touch2screen | def touch2screen(w, h, o, x, y):
'''convert touch position'''
if o == 0:
return x, y
elif o == 1: # landscape-right
return y, w-x
elif o == 2: # upsidedown
return w-x, h-y
elif o == 3: # landscape-left
return h-y, x
return x, y | python | def touch2screen(w, h, o, x, y):
'''convert touch position'''
if o == 0:
return x, y
elif o == 1: # landscape-right
return y, w-x
elif o == 2: # upsidedown
return w-x, h-y
elif o == 3: # landscape-left
return h-y, x
return x, y | [
"def",
"touch2screen",
"(",
"w",
",",
"h",
",",
"o",
",",
"x",
",",
"y",
")",
":",
"if",
"o",
"==",
"0",
":",
"return",
"x",
",",
"y",
"elif",
"o",
"==",
"1",
":",
"# landscape-right\r",
"return",
"y",
",",
"w",
"-",
"x",
"elif",
"o",
"==",
... | convert touch position | [
"convert",
"touch",
"position"
] | f4415c57b45cb0730e08899cbc92a2af1c047ffb | https://github.com/NetEaseGame/ATX/blob/f4415c57b45cb0730e08899cbc92a2af1c047ffb/atx/record/android.py#L342-L352 | train | 222,583 |
NetEaseGame/ATX | atx/ext/report/__init__.py | Report.patch_wda | def patch_wda(self):
"""
Record steps of WebDriverAgent
"""
import wda
def _click(that):
rawx, rawy = that.bounds.center
x, y = self.d.scale*rawx, self.d.scale*rawy
screen_before = self._save_screenshot()
orig_click = pt.get_original(wda.Selector, 'click')
screen_after = self._save_screenshot()
self.add_step('click',
screen_before=screen_before,
screen_after=screen_after,
position={'x': x, 'y': y})
return orig_click(that)
pt.patch_item(wda.Selector, 'click', _click) | python | def patch_wda(self):
"""
Record steps of WebDriverAgent
"""
import wda
def _click(that):
rawx, rawy = that.bounds.center
x, y = self.d.scale*rawx, self.d.scale*rawy
screen_before = self._save_screenshot()
orig_click = pt.get_original(wda.Selector, 'click')
screen_after = self._save_screenshot()
self.add_step('click',
screen_before=screen_before,
screen_after=screen_after,
position={'x': x, 'y': y})
return orig_click(that)
pt.patch_item(wda.Selector, 'click', _click) | [
"def",
"patch_wda",
"(",
"self",
")",
":",
"import",
"wda",
"def",
"_click",
"(",
"that",
")",
":",
"rawx",
",",
"rawy",
"=",
"that",
".",
"bounds",
".",
"center",
"x",
",",
"y",
"=",
"self",
".",
"d",
".",
"scale",
"*",
"rawx",
",",
"self",
".... | Record steps of WebDriverAgent | [
"Record",
"steps",
"of",
"WebDriverAgent"
] | f4415c57b45cb0730e08899cbc92a2af1c047ffb | https://github.com/NetEaseGame/ATX/blob/f4415c57b45cb0730e08899cbc92a2af1c047ffb/atx/ext/report/__init__.py#L109-L127 | train | 222,584 |
NetEaseGame/ATX | atx/ext/report/__init__.py | Report._take_screenshot | def _take_screenshot(self, screenshot=False, name_prefix='unknown'):
"""
This is different from _save_screenshot.
The return value maybe None or the screenshot path
Args:
screenshot: bool or PIL image
"""
if isinstance(screenshot, bool):
if not screenshot:
return
return self._save_screenshot(name_prefix=name_prefix)
if isinstance(screenshot, Image.Image):
return self._save_screenshot(screen=screenshot, name_prefix=name_prefix)
raise TypeError("invalid type for func _take_screenshot: "+ type(screenshot)) | python | def _take_screenshot(self, screenshot=False, name_prefix='unknown'):
"""
This is different from _save_screenshot.
The return value maybe None or the screenshot path
Args:
screenshot: bool or PIL image
"""
if isinstance(screenshot, bool):
if not screenshot:
return
return self._save_screenshot(name_prefix=name_prefix)
if isinstance(screenshot, Image.Image):
return self._save_screenshot(screen=screenshot, name_prefix=name_prefix)
raise TypeError("invalid type for func _take_screenshot: "+ type(screenshot)) | [
"def",
"_take_screenshot",
"(",
"self",
",",
"screenshot",
"=",
"False",
",",
"name_prefix",
"=",
"'unknown'",
")",
":",
"if",
"isinstance",
"(",
"screenshot",
",",
"bool",
")",
":",
"if",
"not",
"screenshot",
":",
"return",
"return",
"self",
".",
"_save_s... | This is different from _save_screenshot.
The return value maybe None or the screenshot path
Args:
screenshot: bool or PIL image | [
"This",
"is",
"different",
"from",
"_save_screenshot",
".",
"The",
"return",
"value",
"maybe",
"None",
"or",
"the",
"screenshot",
"path"
] | f4415c57b45cb0730e08899cbc92a2af1c047ffb | https://github.com/NetEaseGame/ATX/blob/f4415c57b45cb0730e08899cbc92a2af1c047ffb/atx/ext/report/__init__.py#L223-L238 | train | 222,585 |
NetEaseGame/ATX | atx/ext/report/__init__.py | Report._add_assert | def _add_assert(self, **kwargs):
"""
if screenshot is None, only failed case will take screenshot
"""
# convert screenshot to relative path from <None|True|False|PIL.Image>
screenshot = kwargs.get('screenshot')
is_success = kwargs.get('success')
screenshot = (not is_success) if screenshot is None else screenshot
kwargs['screenshot'] = self._take_screenshot(screenshot=screenshot, name_prefix='assert')
action = kwargs.pop('action', 'assert')
self.add_step(action, **kwargs)
if not is_success:
message = kwargs.get('message')
frame, filename, line_number, function_name, lines, index = inspect.stack()[2]
print('Assert [%s: %d] WARN: %s' % (filename, line_number, message))
if not kwargs.get('safe', False):
raise AssertionError(message) | python | def _add_assert(self, **kwargs):
"""
if screenshot is None, only failed case will take screenshot
"""
# convert screenshot to relative path from <None|True|False|PIL.Image>
screenshot = kwargs.get('screenshot')
is_success = kwargs.get('success')
screenshot = (not is_success) if screenshot is None else screenshot
kwargs['screenshot'] = self._take_screenshot(screenshot=screenshot, name_prefix='assert')
action = kwargs.pop('action', 'assert')
self.add_step(action, **kwargs)
if not is_success:
message = kwargs.get('message')
frame, filename, line_number, function_name, lines, index = inspect.stack()[2]
print('Assert [%s: %d] WARN: %s' % (filename, line_number, message))
if not kwargs.get('safe', False):
raise AssertionError(message) | [
"def",
"_add_assert",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"# convert screenshot to relative path from <None|True|False|PIL.Image>",
"screenshot",
"=",
"kwargs",
".",
"get",
"(",
"'screenshot'",
")",
"is_success",
"=",
"kwargs",
".",
"get",
"(",
"'success... | if screenshot is None, only failed case will take screenshot | [
"if",
"screenshot",
"is",
"None",
"only",
"failed",
"case",
"will",
"take",
"screenshot"
] | f4415c57b45cb0730e08899cbc92a2af1c047ffb | https://github.com/NetEaseGame/ATX/blob/f4415c57b45cb0730e08899cbc92a2af1c047ffb/atx/ext/report/__init__.py#L251-L267 | train | 222,586 |
Phylliade/ikpy | src/ikpy/plot_utils.py | plot_chain | def plot_chain(chain, joints, ax, target=None, show=False):
"""Plots the chain"""
# LIst of nodes and orientations
nodes = []
axes = []
transformation_matrixes = chain.forward_kinematics(joints, full_kinematics=True)
# Get the nodes and the orientation from the tranformation matrix
for (index, link) in enumerate(chain.links):
(node, rotation) = geometry_utils.from_transformation_matrix(transformation_matrixes[index])
nodes.append(node)
rotation_axis = link._get_rotation_axis()
if index == 0:
axes.append(rotation_axis)
else:
axes.append(geometry_utils.homogeneous_to_cartesian_vectors(np.dot(transformation_matrixes[index - 1], rotation_axis)))
# Plot the chain
ax.plot([x[0] for x in nodes], [x[1] for x in nodes], [x[2] for x in nodes])
# Plot of the nodes of the chain
ax.scatter([x[0] for x in nodes], [x[1] for x in nodes], [x[2] for x in nodes])
# Plot rotation axes
for index, axe in enumerate(axes):
ax.plot([nodes[index][0], axe[0]], [nodes[index][1], axe[1]], [nodes[index][2], axe[2]]) | python | def plot_chain(chain, joints, ax, target=None, show=False):
"""Plots the chain"""
# LIst of nodes and orientations
nodes = []
axes = []
transformation_matrixes = chain.forward_kinematics(joints, full_kinematics=True)
# Get the nodes and the orientation from the tranformation matrix
for (index, link) in enumerate(chain.links):
(node, rotation) = geometry_utils.from_transformation_matrix(transformation_matrixes[index])
nodes.append(node)
rotation_axis = link._get_rotation_axis()
if index == 0:
axes.append(rotation_axis)
else:
axes.append(geometry_utils.homogeneous_to_cartesian_vectors(np.dot(transformation_matrixes[index - 1], rotation_axis)))
# Plot the chain
ax.plot([x[0] for x in nodes], [x[1] for x in nodes], [x[2] for x in nodes])
# Plot of the nodes of the chain
ax.scatter([x[0] for x in nodes], [x[1] for x in nodes], [x[2] for x in nodes])
# Plot rotation axes
for index, axe in enumerate(axes):
ax.plot([nodes[index][0], axe[0]], [nodes[index][1], axe[1]], [nodes[index][2], axe[2]]) | [
"def",
"plot_chain",
"(",
"chain",
",",
"joints",
",",
"ax",
",",
"target",
"=",
"None",
",",
"show",
"=",
"False",
")",
":",
"# LIst of nodes and orientations",
"nodes",
"=",
"[",
"]",
"axes",
"=",
"[",
"]",
"transformation_matrixes",
"=",
"chain",
".",
... | Plots the chain | [
"Plots",
"the",
"chain"
] | 60e36d6163136942bf520d952db17123c658d0b6 | https://github.com/Phylliade/ikpy/blob/60e36d6163136942bf520d952db17123c658d0b6/src/ikpy/plot_utils.py#L29-L54 | train | 222,587 |
Phylliade/ikpy | src/ikpy/plot_utils.py | plot_target | def plot_target(target, ax):
"""Ajoute la target au plot"""
ax.scatter(target[0], target[1], target[2], c="red", s=80) | python | def plot_target(target, ax):
"""Ajoute la target au plot"""
ax.scatter(target[0], target[1], target[2], c="red", s=80) | [
"def",
"plot_target",
"(",
"target",
",",
"ax",
")",
":",
"ax",
".",
"scatter",
"(",
"target",
"[",
"0",
"]",
",",
"target",
"[",
"1",
"]",
",",
"target",
"[",
"2",
"]",
",",
"c",
"=",
"\"red\"",
",",
"s",
"=",
"80",
")"
] | Ajoute la target au plot | [
"Ajoute",
"la",
"target",
"au",
"plot"
] | 60e36d6163136942bf520d952db17123c658d0b6 | https://github.com/Phylliade/ikpy/blob/60e36d6163136942bf520d952db17123c658d0b6/src/ikpy/plot_utils.py#L57-L59 | train | 222,588 |
Phylliade/ikpy | src/ikpy/geometry_utils.py | Rx_matrix | def Rx_matrix(theta):
"""Rotation matrix around the X axis"""
return np.array([
[1, 0, 0],
[0, np.cos(theta), -np.sin(theta)],
[0, np.sin(theta), np.cos(theta)]
]) | python | def Rx_matrix(theta):
"""Rotation matrix around the X axis"""
return np.array([
[1, 0, 0],
[0, np.cos(theta), -np.sin(theta)],
[0, np.sin(theta), np.cos(theta)]
]) | [
"def",
"Rx_matrix",
"(",
"theta",
")",
":",
"return",
"np",
".",
"array",
"(",
"[",
"[",
"1",
",",
"0",
",",
"0",
"]",
",",
"[",
"0",
",",
"np",
".",
"cos",
"(",
"theta",
")",
",",
"-",
"np",
".",
"sin",
"(",
"theta",
")",
"]",
",",
"[",
... | Rotation matrix around the X axis | [
"Rotation",
"matrix",
"around",
"the",
"X",
"axis"
] | 60e36d6163136942bf520d952db17123c658d0b6 | https://github.com/Phylliade/ikpy/blob/60e36d6163136942bf520d952db17123c658d0b6/src/ikpy/geometry_utils.py#L10-L16 | train | 222,589 |
Phylliade/ikpy | src/ikpy/geometry_utils.py | Rz_matrix | def Rz_matrix(theta):
"""Rotation matrix around the Z axis"""
return np.array([
[np.cos(theta), -np.sin(theta), 0],
[np.sin(theta), np.cos(theta), 0],
[0, 0, 1]
]) | python | def Rz_matrix(theta):
"""Rotation matrix around the Z axis"""
return np.array([
[np.cos(theta), -np.sin(theta), 0],
[np.sin(theta), np.cos(theta), 0],
[0, 0, 1]
]) | [
"def",
"Rz_matrix",
"(",
"theta",
")",
":",
"return",
"np",
".",
"array",
"(",
"[",
"[",
"np",
".",
"cos",
"(",
"theta",
")",
",",
"-",
"np",
".",
"sin",
"(",
"theta",
")",
",",
"0",
"]",
",",
"[",
"np",
".",
"sin",
"(",
"theta",
")",
",",
... | Rotation matrix around the Z axis | [
"Rotation",
"matrix",
"around",
"the",
"Z",
"axis"
] | 60e36d6163136942bf520d952db17123c658d0b6 | https://github.com/Phylliade/ikpy/blob/60e36d6163136942bf520d952db17123c658d0b6/src/ikpy/geometry_utils.py#L19-L25 | train | 222,590 |
Phylliade/ikpy | src/ikpy/geometry_utils.py | symbolic_Rz_matrix | def symbolic_Rz_matrix(symbolic_theta):
"""Matrice symbolique de rotation autour de l'axe Z"""
return sympy.Matrix([
[sympy.cos(symbolic_theta), -sympy.sin(symbolic_theta), 0],
[sympy.sin(symbolic_theta), sympy.cos(symbolic_theta), 0],
[0, 0, 1]
]) | python | def symbolic_Rz_matrix(symbolic_theta):
"""Matrice symbolique de rotation autour de l'axe Z"""
return sympy.Matrix([
[sympy.cos(symbolic_theta), -sympy.sin(symbolic_theta), 0],
[sympy.sin(symbolic_theta), sympy.cos(symbolic_theta), 0],
[0, 0, 1]
]) | [
"def",
"symbolic_Rz_matrix",
"(",
"symbolic_theta",
")",
":",
"return",
"sympy",
".",
"Matrix",
"(",
"[",
"[",
"sympy",
".",
"cos",
"(",
"symbolic_theta",
")",
",",
"-",
"sympy",
".",
"sin",
"(",
"symbolic_theta",
")",
",",
"0",
"]",
",",
"[",
"sympy",... | Matrice symbolique de rotation autour de l'axe Z | [
"Matrice",
"symbolique",
"de",
"rotation",
"autour",
"de",
"l",
"axe",
"Z"
] | 60e36d6163136942bf520d952db17123c658d0b6 | https://github.com/Phylliade/ikpy/blob/60e36d6163136942bf520d952db17123c658d0b6/src/ikpy/geometry_utils.py#L28-L34 | train | 222,591 |
Phylliade/ikpy | src/ikpy/geometry_utils.py | Ry_matrix | def Ry_matrix(theta):
"""Rotation matrix around the Y axis"""
return np.array([
[np.cos(theta), 0, np.sin(theta)],
[0, 1, 0],
[-np.sin(theta), 0, np.cos(theta)]
]) | python | def Ry_matrix(theta):
"""Rotation matrix around the Y axis"""
return np.array([
[np.cos(theta), 0, np.sin(theta)],
[0, 1, 0],
[-np.sin(theta), 0, np.cos(theta)]
]) | [
"def",
"Ry_matrix",
"(",
"theta",
")",
":",
"return",
"np",
".",
"array",
"(",
"[",
"[",
"np",
".",
"cos",
"(",
"theta",
")",
",",
"0",
",",
"np",
".",
"sin",
"(",
"theta",
")",
"]",
",",
"[",
"0",
",",
"1",
",",
"0",
"]",
",",
"[",
"-",
... | Rotation matrix around the Y axis | [
"Rotation",
"matrix",
"around",
"the",
"Y",
"axis"
] | 60e36d6163136942bf520d952db17123c658d0b6 | https://github.com/Phylliade/ikpy/blob/60e36d6163136942bf520d952db17123c658d0b6/src/ikpy/geometry_utils.py#L37-L43 | train | 222,592 |
Phylliade/ikpy | src/ikpy/geometry_utils.py | rpy_matrix | def rpy_matrix(roll, pitch, yaw):
"""Returns a rotation matrix described by the extrinsinc roll, pitch, yaw coordinates"""
return np.dot(Rz_matrix(yaw), np.dot(Ry_matrix(pitch), Rx_matrix(roll))) | python | def rpy_matrix(roll, pitch, yaw):
"""Returns a rotation matrix described by the extrinsinc roll, pitch, yaw coordinates"""
return np.dot(Rz_matrix(yaw), np.dot(Ry_matrix(pitch), Rx_matrix(roll))) | [
"def",
"rpy_matrix",
"(",
"roll",
",",
"pitch",
",",
"yaw",
")",
":",
"return",
"np",
".",
"dot",
"(",
"Rz_matrix",
"(",
"yaw",
")",
",",
"np",
".",
"dot",
"(",
"Ry_matrix",
"(",
"pitch",
")",
",",
"Rx_matrix",
"(",
"roll",
")",
")",
")"
] | Returns a rotation matrix described by the extrinsinc roll, pitch, yaw coordinates | [
"Returns",
"a",
"rotation",
"matrix",
"described",
"by",
"the",
"extrinsinc",
"roll",
"pitch",
"yaw",
"coordinates"
] | 60e36d6163136942bf520d952db17123c658d0b6 | https://github.com/Phylliade/ikpy/blob/60e36d6163136942bf520d952db17123c658d0b6/src/ikpy/geometry_utils.py#L56-L58 | train | 222,593 |
Phylliade/ikpy | src/ikpy/geometry_utils.py | cartesian_to_homogeneous | def cartesian_to_homogeneous(cartesian_matrix, matrix_type="numpy"):
"""Converts a cartesian matrix to an homogenous matrix"""
dimension_x, dimension_y = cartesian_matrix.shape
# Square matrix
# Manage different types fo input matrixes
if matrix_type == "numpy":
homogeneous_matrix = np.eye(dimension_x + 1)
elif matrix_type == "sympy":
homogeneous_matrix = sympy.eye(dimension_x + 1)
# Add a column filled with 0 and finishing with 1 to the cartesian matrix to transform it into an homogeneous one
homogeneous_matrix[:-1, :-1] = cartesian_matrix
return homogeneous_matrix | python | def cartesian_to_homogeneous(cartesian_matrix, matrix_type="numpy"):
"""Converts a cartesian matrix to an homogenous matrix"""
dimension_x, dimension_y = cartesian_matrix.shape
# Square matrix
# Manage different types fo input matrixes
if matrix_type == "numpy":
homogeneous_matrix = np.eye(dimension_x + 1)
elif matrix_type == "sympy":
homogeneous_matrix = sympy.eye(dimension_x + 1)
# Add a column filled with 0 and finishing with 1 to the cartesian matrix to transform it into an homogeneous one
homogeneous_matrix[:-1, :-1] = cartesian_matrix
return homogeneous_matrix | [
"def",
"cartesian_to_homogeneous",
"(",
"cartesian_matrix",
",",
"matrix_type",
"=",
"\"numpy\"",
")",
":",
"dimension_x",
",",
"dimension_y",
"=",
"cartesian_matrix",
".",
"shape",
"# Square matrix",
"# Manage different types fo input matrixes",
"if",
"matrix_type",
"==",
... | Converts a cartesian matrix to an homogenous matrix | [
"Converts",
"a",
"cartesian",
"matrix",
"to",
"an",
"homogenous",
"matrix"
] | 60e36d6163136942bf520d952db17123c658d0b6 | https://github.com/Phylliade/ikpy/blob/60e36d6163136942bf520d952db17123c658d0b6/src/ikpy/geometry_utils.py#L112-L124 | train | 222,594 |
Phylliade/ikpy | src/ikpy/geometry_utils.py | cartesian_to_homogeneous_vectors | def cartesian_to_homogeneous_vectors(cartesian_vector, matrix_type="numpy"):
"""Converts a cartesian vector to an homogenous vector"""
dimension_x = cartesian_vector.shape[0]
# Vector
if matrix_type == "numpy":
homogeneous_vector = np.zeros(dimension_x + 1)
# Last item is a 1
homogeneous_vector[-1] = 1
homogeneous_vector[:-1] = cartesian_vector
return homogeneous_vector | python | def cartesian_to_homogeneous_vectors(cartesian_vector, matrix_type="numpy"):
"""Converts a cartesian vector to an homogenous vector"""
dimension_x = cartesian_vector.shape[0]
# Vector
if matrix_type == "numpy":
homogeneous_vector = np.zeros(dimension_x + 1)
# Last item is a 1
homogeneous_vector[-1] = 1
homogeneous_vector[:-1] = cartesian_vector
return homogeneous_vector | [
"def",
"cartesian_to_homogeneous_vectors",
"(",
"cartesian_vector",
",",
"matrix_type",
"=",
"\"numpy\"",
")",
":",
"dimension_x",
"=",
"cartesian_vector",
".",
"shape",
"[",
"0",
"]",
"# Vector",
"if",
"matrix_type",
"==",
"\"numpy\"",
":",
"homogeneous_vector",
"=... | Converts a cartesian vector to an homogenous vector | [
"Converts",
"a",
"cartesian",
"vector",
"to",
"an",
"homogenous",
"vector"
] | 60e36d6163136942bf520d952db17123c658d0b6 | https://github.com/Phylliade/ikpy/blob/60e36d6163136942bf520d952db17123c658d0b6/src/ikpy/geometry_utils.py#L127-L136 | train | 222,595 |
Phylliade/ikpy | src/ikpy/URDF_utils.py | find_next_joint | def find_next_joint(root, current_link, next_joint_name):
"""
Find the next joint in the URDF tree
Parameters
----------
root
current_link: xml.etree.ElementTree
The current URDF link
next_joint_name: str
Optional : The name of the next joint. If not provided, find it automatically as the first child of the link.
"""
# Find the joint attached to the link
has_next = False
next_joint = None
search_by_name = True
current_link_name = None
if next_joint_name is None:
# If no next joint is provided, find it automatically
search_by_name = False
current_link_name = current_link.attrib["name"]
for joint in root.iter("joint"):
# Iterate through all joints to find the good one
if search_by_name:
# Find the joint given its name
if joint.attrib["name"] == next_joint_name:
has_next = True
next_joint = joint
else:
# Find the first joint whose parent is the current_link
# FIXME: We are not sending a warning when we have two children for the same link
# Even if this is not possible, we should ensure something coherent
if joint.find("parent").attrib["link"] == current_link_name:
has_next = True
next_joint = joint
break
return has_next, next_joint | python | def find_next_joint(root, current_link, next_joint_name):
"""
Find the next joint in the URDF tree
Parameters
----------
root
current_link: xml.etree.ElementTree
The current URDF link
next_joint_name: str
Optional : The name of the next joint. If not provided, find it automatically as the first child of the link.
"""
# Find the joint attached to the link
has_next = False
next_joint = None
search_by_name = True
current_link_name = None
if next_joint_name is None:
# If no next joint is provided, find it automatically
search_by_name = False
current_link_name = current_link.attrib["name"]
for joint in root.iter("joint"):
# Iterate through all joints to find the good one
if search_by_name:
# Find the joint given its name
if joint.attrib["name"] == next_joint_name:
has_next = True
next_joint = joint
else:
# Find the first joint whose parent is the current_link
# FIXME: We are not sending a warning when we have two children for the same link
# Even if this is not possible, we should ensure something coherent
if joint.find("parent").attrib["link"] == current_link_name:
has_next = True
next_joint = joint
break
return has_next, next_joint | [
"def",
"find_next_joint",
"(",
"root",
",",
"current_link",
",",
"next_joint_name",
")",
":",
"# Find the joint attached to the link",
"has_next",
"=",
"False",
"next_joint",
"=",
"None",
"search_by_name",
"=",
"True",
"current_link_name",
"=",
"None",
"if",
"next_joi... | Find the next joint in the URDF tree
Parameters
----------
root
current_link: xml.etree.ElementTree
The current URDF link
next_joint_name: str
Optional : The name of the next joint. If not provided, find it automatically as the first child of the link. | [
"Find",
"the",
"next",
"joint",
"in",
"the",
"URDF",
"tree"
] | 60e36d6163136942bf520d952db17123c658d0b6 | https://github.com/Phylliade/ikpy/blob/60e36d6163136942bf520d952db17123c658d0b6/src/ikpy/URDF_utils.py#L16-L55 | train | 222,596 |
Phylliade/ikpy | src/ikpy/URDF_utils.py | find_next_link | def find_next_link(root, current_joint, next_link_name):
"""
Find the next link in the URDF tree
Parameters
----------
root
current_joint: xml.etree.ElementTree
The current URDF joint
next_link_name: str
Optional : The name of the next link. If not provided, find it automatically as the first child of the joint.
"""
has_next = False
next_link = None
# If no next link, find it automatically
if next_link_name is None:
# If the name of the next link is not provided, find it
next_link_name = current_joint.find("child").attrib["link"]
for urdf_link in root.iter("link"):
if urdf_link.attrib["name"] == next_link_name:
next_link = urdf_link
has_next = True
return has_next, next_link | python | def find_next_link(root, current_joint, next_link_name):
"""
Find the next link in the URDF tree
Parameters
----------
root
current_joint: xml.etree.ElementTree
The current URDF joint
next_link_name: str
Optional : The name of the next link. If not provided, find it automatically as the first child of the joint.
"""
has_next = False
next_link = None
# If no next link, find it automatically
if next_link_name is None:
# If the name of the next link is not provided, find it
next_link_name = current_joint.find("child").attrib["link"]
for urdf_link in root.iter("link"):
if urdf_link.attrib["name"] == next_link_name:
next_link = urdf_link
has_next = True
return has_next, next_link | [
"def",
"find_next_link",
"(",
"root",
",",
"current_joint",
",",
"next_link_name",
")",
":",
"has_next",
"=",
"False",
"next_link",
"=",
"None",
"# If no next link, find it automatically",
"if",
"next_link_name",
"is",
"None",
":",
"# If the name of the next link is not p... | Find the next link in the URDF tree
Parameters
----------
root
current_joint: xml.etree.ElementTree
The current URDF joint
next_link_name: str
Optional : The name of the next link. If not provided, find it automatically as the first child of the joint. | [
"Find",
"the",
"next",
"link",
"in",
"the",
"URDF",
"tree"
] | 60e36d6163136942bf520d952db17123c658d0b6 | https://github.com/Phylliade/ikpy/blob/60e36d6163136942bf520d952db17123c658d0b6/src/ikpy/URDF_utils.py#L58-L82 | train | 222,597 |
Phylliade/ikpy | src/ikpy/URDF_utils.py | get_urdf_parameters | def get_urdf_parameters(urdf_file, base_elements=None, last_link_vector=None, base_element_type="link"):
"""
Returns translated parameters from the given URDF file
Parameters
----------
urdf_file: str
The path of the URDF file
base_elements: list of strings
List of the links beginning the chain
last_link_vector: numpy.array
Optional : The translation vector of the tip.
base_element_type: str
Returns
-------
list[ikpy.link.URDFLink]
"""
tree = ET.parse(urdf_file)
root = tree.getroot()
base_elements = list(base_elements)
if base_elements is None:
base_elements = ["base_link"]
elif base_elements is []:
raise ValueError("base_elements can't be the empty list []")
joints = []
links = []
has_next = True
current_joint = None
current_link = None
# Initialize the tree traversal
if base_element_type == "link":
# The first element is a link, so its (virtual) parent should be a joint
node_type = "joint"
elif base_element_type == "joint":
# The same as before, but swap link and joint
node_type = "link"
else:
raise ValueError("Unknown type: {}".format(base_element_type))
# Parcours récursif de la structure de la chain
while has_next:
if len(base_elements) != 0:
next_element = base_elements.pop(0)
else:
next_element = None
if node_type == "link":
# Current element is a link, find child joint
(has_next, current_joint) = find_next_joint(root, current_link, next_element)
node_type = "joint"
if has_next:
joints.append(current_joint)
elif node_type == "joint":
# Current element is a joint, find child link
(has_next, current_link) = find_next_link(root, current_joint, next_element)
node_type = "link"
if has_next:
links.append(current_link)
parameters = []
# Save the joints in the good format
for joint in joints:
translation = [0, 0, 0]
orientation = [0, 0, 0]
rotation = [1, 0, 0]
bounds = [None, None]
origin = joint.find("origin")
if origin is not None:
if origin.attrib["xyz"]:
translation = [float(x) for x in origin.attrib["xyz"].split()]
if origin.attrib["rpy"]:
orientation = [float(x) for x in origin.attrib["rpy"].split()]
axis = joint.find("axis")
if axis is not None:
rotation = [float(x) for x in axis.attrib["xyz"].split()]
limit = joint.find("limit")
if limit is not None:
if limit.attrib["lower"]:
bounds[0] = float(limit.attrib["lower"])
if limit.attrib["upper"]:
bounds[1] = float(limit.attrib["upper"])
parameters.append(lib_link.URDFLink(
name=joint.attrib["name"],
bounds=tuple(bounds),
translation_vector=translation,
orientation=orientation,
rotation=rotation,
))
# Add last_link_vector to parameters
if last_link_vector is not None:
parameters.append(lib_link.URDFLink(
translation_vector=last_link_vector,
orientation=[0, 0, 0],
rotation=[1, 0, 0],
name="last_joint"
))
return parameters | python | def get_urdf_parameters(urdf_file, base_elements=None, last_link_vector=None, base_element_type="link"):
"""
Returns translated parameters from the given URDF file
Parameters
----------
urdf_file: str
The path of the URDF file
base_elements: list of strings
List of the links beginning the chain
last_link_vector: numpy.array
Optional : The translation vector of the tip.
base_element_type: str
Returns
-------
list[ikpy.link.URDFLink]
"""
tree = ET.parse(urdf_file)
root = tree.getroot()
base_elements = list(base_elements)
if base_elements is None:
base_elements = ["base_link"]
elif base_elements is []:
raise ValueError("base_elements can't be the empty list []")
joints = []
links = []
has_next = True
current_joint = None
current_link = None
# Initialize the tree traversal
if base_element_type == "link":
# The first element is a link, so its (virtual) parent should be a joint
node_type = "joint"
elif base_element_type == "joint":
# The same as before, but swap link and joint
node_type = "link"
else:
raise ValueError("Unknown type: {}".format(base_element_type))
# Parcours récursif de la structure de la chain
while has_next:
if len(base_elements) != 0:
next_element = base_elements.pop(0)
else:
next_element = None
if node_type == "link":
# Current element is a link, find child joint
(has_next, current_joint) = find_next_joint(root, current_link, next_element)
node_type = "joint"
if has_next:
joints.append(current_joint)
elif node_type == "joint":
# Current element is a joint, find child link
(has_next, current_link) = find_next_link(root, current_joint, next_element)
node_type = "link"
if has_next:
links.append(current_link)
parameters = []
# Save the joints in the good format
for joint in joints:
translation = [0, 0, 0]
orientation = [0, 0, 0]
rotation = [1, 0, 0]
bounds = [None, None]
origin = joint.find("origin")
if origin is not None:
if origin.attrib["xyz"]:
translation = [float(x) for x in origin.attrib["xyz"].split()]
if origin.attrib["rpy"]:
orientation = [float(x) for x in origin.attrib["rpy"].split()]
axis = joint.find("axis")
if axis is not None:
rotation = [float(x) for x in axis.attrib["xyz"].split()]
limit = joint.find("limit")
if limit is not None:
if limit.attrib["lower"]:
bounds[0] = float(limit.attrib["lower"])
if limit.attrib["upper"]:
bounds[1] = float(limit.attrib["upper"])
parameters.append(lib_link.URDFLink(
name=joint.attrib["name"],
bounds=tuple(bounds),
translation_vector=translation,
orientation=orientation,
rotation=rotation,
))
# Add last_link_vector to parameters
if last_link_vector is not None:
parameters.append(lib_link.URDFLink(
translation_vector=last_link_vector,
orientation=[0, 0, 0],
rotation=[1, 0, 0],
name="last_joint"
))
return parameters | [
"def",
"get_urdf_parameters",
"(",
"urdf_file",
",",
"base_elements",
"=",
"None",
",",
"last_link_vector",
"=",
"None",
",",
"base_element_type",
"=",
"\"link\"",
")",
":",
"tree",
"=",
"ET",
".",
"parse",
"(",
"urdf_file",
")",
"root",
"=",
"tree",
".",
... | Returns translated parameters from the given URDF file
Parameters
----------
urdf_file: str
The path of the URDF file
base_elements: list of strings
List of the links beginning the chain
last_link_vector: numpy.array
Optional : The translation vector of the tip.
base_element_type: str
Returns
-------
list[ikpy.link.URDFLink] | [
"Returns",
"translated",
"parameters",
"from",
"the",
"given",
"URDF",
"file"
] | 60e36d6163136942bf520d952db17123c658d0b6 | https://github.com/Phylliade/ikpy/blob/60e36d6163136942bf520d952db17123c658d0b6/src/ikpy/URDF_utils.py#L103-L210 | train | 222,598 |
Phylliade/ikpy | src/ikpy/URDF_utils.py | _convert_angle_limit | def _convert_angle_limit(angle, joint, **kwargs):
"""Converts the limit angle of the PyPot JSON file to the internal format"""
angle_pypot = angle
# No need to take care of orientation
if joint["orientation"] == "indirect":
angle_pypot = 1 * angle_pypot
# angle_pypot = angle_pypot + offset
return angle_pypot * np.pi / 180 | python | def _convert_angle_limit(angle, joint, **kwargs):
"""Converts the limit angle of the PyPot JSON file to the internal format"""
angle_pypot = angle
# No need to take care of orientation
if joint["orientation"] == "indirect":
angle_pypot = 1 * angle_pypot
# angle_pypot = angle_pypot + offset
return angle_pypot * np.pi / 180 | [
"def",
"_convert_angle_limit",
"(",
"angle",
",",
"joint",
",",
"*",
"*",
"kwargs",
")",
":",
"angle_pypot",
"=",
"angle",
"# No need to take care of orientation",
"if",
"joint",
"[",
"\"orientation\"",
"]",
"==",
"\"indirect\"",
":",
"angle_pypot",
"=",
"1",
"*... | Converts the limit angle of the PyPot JSON file to the internal format | [
"Converts",
"the",
"limit",
"angle",
"of",
"the",
"PyPot",
"JSON",
"file",
"to",
"the",
"internal",
"format"
] | 60e36d6163136942bf520d952db17123c658d0b6 | https://github.com/Phylliade/ikpy/blob/60e36d6163136942bf520d952db17123c658d0b6/src/ikpy/URDF_utils.py#L261-L271 | train | 222,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.