id
int32 0
252k
| repo
stringlengths 7
55
| path
stringlengths 4
127
| func_name
stringlengths 1
88
| original_string
stringlengths 75
19.8k
| language
stringclasses 1
value | code
stringlengths 75
19.8k
| code_tokens
list | docstring
stringlengths 3
17.3k
| docstring_tokens
list | sha
stringlengths 40
40
| url
stringlengths 87
242
|
|---|---|---|---|---|---|---|---|---|---|---|---|
6,700
|
konstantint/PassportEye
|
passporteye/mrz/image.py
|
read_mrz
|
def read_mrz(file, save_roi=False, extra_cmdline_params=''):
"""The main interface function to this module, encapsulating the recognition pipeline.
Given an image filename, runs MRZPipeline on it, returning the parsed MRZ object.
:param file: A filename or a stream to read the file data from.
:param save_roi: when this is True, the .aux['roi'] field will contain the Region of Interest where the MRZ was parsed from.
:param extra_cmdline_params:extra parameters to the ocr.py
"""
p = MRZPipeline(file, extra_cmdline_params)
mrz = p.result
if mrz is not None:
mrz.aux['text'] = p['text']
if save_roi:
mrz.aux['roi'] = p['roi']
return mrz
|
python
|
def read_mrz(file, save_roi=False, extra_cmdline_params=''):
"""The main interface function to this module, encapsulating the recognition pipeline.
Given an image filename, runs MRZPipeline on it, returning the parsed MRZ object.
:param file: A filename or a stream to read the file data from.
:param save_roi: when this is True, the .aux['roi'] field will contain the Region of Interest where the MRZ was parsed from.
:param extra_cmdline_params:extra parameters to the ocr.py
"""
p = MRZPipeline(file, extra_cmdline_params)
mrz = p.result
if mrz is not None:
mrz.aux['text'] = p['text']
if save_roi:
mrz.aux['roi'] = p['roi']
return mrz
|
[
"def",
"read_mrz",
"(",
"file",
",",
"save_roi",
"=",
"False",
",",
"extra_cmdline_params",
"=",
"''",
")",
":",
"p",
"=",
"MRZPipeline",
"(",
"file",
",",
"extra_cmdline_params",
")",
"mrz",
"=",
"p",
".",
"result",
"if",
"mrz",
"is",
"not",
"None",
":",
"mrz",
".",
"aux",
"[",
"'text'",
"]",
"=",
"p",
"[",
"'text'",
"]",
"if",
"save_roi",
":",
"mrz",
".",
"aux",
"[",
"'roi'",
"]",
"=",
"p",
"[",
"'roi'",
"]",
"return",
"mrz"
] |
The main interface function to this module, encapsulating the recognition pipeline.
Given an image filename, runs MRZPipeline on it, returning the parsed MRZ object.
:param file: A filename or a stream to read the file data from.
:param save_roi: when this is True, the .aux['roi'] field will contain the Region of Interest where the MRZ was parsed from.
:param extra_cmdline_params:extra parameters to the ocr.py
|
[
"The",
"main",
"interface",
"function",
"to",
"this",
"module",
"encapsulating",
"the",
"recognition",
"pipeline",
".",
"Given",
"an",
"image",
"filename",
"runs",
"MRZPipeline",
"on",
"it",
"returning",
"the",
"parsed",
"MRZ",
"object",
"."
] |
b32afba0f5dc4eb600c4edc4f49e5d49959c5415
|
https://github.com/konstantint/PassportEye/blob/b32afba0f5dc4eb600c4edc4f49e5d49959c5415/passporteye/mrz/image.py#L328-L343
|
6,701
|
konstantint/PassportEye
|
passporteye/mrz/image.py
|
Loader._imread
|
def _imread(self, file):
"""Proxy to skimage.io.imread with some fixes."""
# For now, we have to select the imageio plugin to read image from byte stream
# When ski-image v0.15 is released, imageio will be the default plugin, so this
# code can be simplified at that time. See issue report and pull request:
# https://github.com/scikit-image/scikit-image/issues/2889
# https://github.com/scikit-image/scikit-image/pull/3126
img = skimage_io.imread(file, as_gray=self.as_gray, plugin='imageio')
if img is not None and len(img.shape) != 2:
# The PIL plugin somewhy fails to load some images
img = skimage_io.imread(file, as_gray=self.as_gray, plugin='matplotlib')
return img
|
python
|
def _imread(self, file):
"""Proxy to skimage.io.imread with some fixes."""
# For now, we have to select the imageio plugin to read image from byte stream
# When ski-image v0.15 is released, imageio will be the default plugin, so this
# code can be simplified at that time. See issue report and pull request:
# https://github.com/scikit-image/scikit-image/issues/2889
# https://github.com/scikit-image/scikit-image/pull/3126
img = skimage_io.imread(file, as_gray=self.as_gray, plugin='imageio')
if img is not None and len(img.shape) != 2:
# The PIL plugin somewhy fails to load some images
img = skimage_io.imread(file, as_gray=self.as_gray, plugin='matplotlib')
return img
|
[
"def",
"_imread",
"(",
"self",
",",
"file",
")",
":",
"# For now, we have to select the imageio plugin to read image from byte stream",
"# When ski-image v0.15 is released, imageio will be the default plugin, so this",
"# code can be simplified at that time. See issue report and pull request:",
"# https://github.com/scikit-image/scikit-image/issues/2889",
"# https://github.com/scikit-image/scikit-image/pull/3126",
"img",
"=",
"skimage_io",
".",
"imread",
"(",
"file",
",",
"as_gray",
"=",
"self",
".",
"as_gray",
",",
"plugin",
"=",
"'imageio'",
")",
"if",
"img",
"is",
"not",
"None",
"and",
"len",
"(",
"img",
".",
"shape",
")",
"!=",
"2",
":",
"# The PIL plugin somewhy fails to load some images",
"img",
"=",
"skimage_io",
".",
"imread",
"(",
"file",
",",
"as_gray",
"=",
"self",
".",
"as_gray",
",",
"plugin",
"=",
"'matplotlib'",
")",
"return",
"img"
] |
Proxy to skimage.io.imread with some fixes.
|
[
"Proxy",
"to",
"skimage",
".",
"io",
".",
"imread",
"with",
"some",
"fixes",
"."
] |
b32afba0f5dc4eb600c4edc4f49e5d49959c5415
|
https://github.com/konstantint/PassportEye/blob/b32afba0f5dc4eb600c4edc4f49e5d49959c5415/passporteye/mrz/image.py#L30-L41
|
6,702
|
konstantint/PassportEye
|
passporteye/mrz/image.py
|
MRZBoxLocator._are_aligned_angles
|
def _are_aligned_angles(self, b1, b2):
"Are two boxes aligned according to their angle?"
return abs(b1 - b2) <= self.angle_tol or abs(np.pi - abs(b1 - b2)) <= self.angle_tol
|
python
|
def _are_aligned_angles(self, b1, b2):
"Are two boxes aligned according to their angle?"
return abs(b1 - b2) <= self.angle_tol or abs(np.pi - abs(b1 - b2)) <= self.angle_tol
|
[
"def",
"_are_aligned_angles",
"(",
"self",
",",
"b1",
",",
"b2",
")",
":",
"return",
"abs",
"(",
"b1",
"-",
"b2",
")",
"<=",
"self",
".",
"angle_tol",
"or",
"abs",
"(",
"np",
".",
"pi",
"-",
"abs",
"(",
"b1",
"-",
"b2",
")",
")",
"<=",
"self",
".",
"angle_tol"
] |
Are two boxes aligned according to their angle?
|
[
"Are",
"two",
"boxes",
"aligned",
"according",
"to",
"their",
"angle?"
] |
b32afba0f5dc4eb600c4edc4f49e5d49959c5415
|
https://github.com/konstantint/PassportEye/blob/b32afba0f5dc4eb600c4edc4f49e5d49959c5415/passporteye/mrz/image.py#L136-L138
|
6,703
|
konstantint/PassportEye
|
passporteye/mrz/image.py
|
MRZBoxLocator._are_nearby_parallel_boxes
|
def _are_nearby_parallel_boxes(self, b1, b2):
"Are two boxes nearby, parallel, and similar in width?"
if not self._are_aligned_angles(b1.angle, b2.angle):
return False
# Otherwise pick the smaller angle and see whether the two boxes are close according to the "up" direction wrt that angle
angle = min(b1.angle, b2.angle)
return abs(np.dot(b1.center - b2.center, [-np.sin(angle), np.cos(angle)])) < self.lineskip_tol * (
b1.height + b2.height) and (b1.width > 0) and (b2.width > 0) and (0.5 < b1.width / b2.width < 2.0)
|
python
|
def _are_nearby_parallel_boxes(self, b1, b2):
"Are two boxes nearby, parallel, and similar in width?"
if not self._are_aligned_angles(b1.angle, b2.angle):
return False
# Otherwise pick the smaller angle and see whether the two boxes are close according to the "up" direction wrt that angle
angle = min(b1.angle, b2.angle)
return abs(np.dot(b1.center - b2.center, [-np.sin(angle), np.cos(angle)])) < self.lineskip_tol * (
b1.height + b2.height) and (b1.width > 0) and (b2.width > 0) and (0.5 < b1.width / b2.width < 2.0)
|
[
"def",
"_are_nearby_parallel_boxes",
"(",
"self",
",",
"b1",
",",
"b2",
")",
":",
"if",
"not",
"self",
".",
"_are_aligned_angles",
"(",
"b1",
".",
"angle",
",",
"b2",
".",
"angle",
")",
":",
"return",
"False",
"# Otherwise pick the smaller angle and see whether the two boxes are close according to the \"up\" direction wrt that angle",
"angle",
"=",
"min",
"(",
"b1",
".",
"angle",
",",
"b2",
".",
"angle",
")",
"return",
"abs",
"(",
"np",
".",
"dot",
"(",
"b1",
".",
"center",
"-",
"b2",
".",
"center",
",",
"[",
"-",
"np",
".",
"sin",
"(",
"angle",
")",
",",
"np",
".",
"cos",
"(",
"angle",
")",
"]",
")",
")",
"<",
"self",
".",
"lineskip_tol",
"*",
"(",
"b1",
".",
"height",
"+",
"b2",
".",
"height",
")",
"and",
"(",
"b1",
".",
"width",
">",
"0",
")",
"and",
"(",
"b2",
".",
"width",
">",
"0",
")",
"and",
"(",
"0.5",
"<",
"b1",
".",
"width",
"/",
"b2",
".",
"width",
"<",
"2.0",
")"
] |
Are two boxes nearby, parallel, and similar in width?
|
[
"Are",
"two",
"boxes",
"nearby",
"parallel",
"and",
"similar",
"in",
"width?"
] |
b32afba0f5dc4eb600c4edc4f49e5d49959c5415
|
https://github.com/konstantint/PassportEye/blob/b32afba0f5dc4eb600c4edc4f49e5d49959c5415/passporteye/mrz/image.py#L140-L147
|
6,704
|
konstantint/PassportEye
|
passporteye/mrz/image.py
|
MRZBoxLocator._merge_any_two_boxes
|
def _merge_any_two_boxes(self, box_list):
"""Given a list of boxes, finds two nearby parallel ones and merges them. Returns false if none found."""
n = len(box_list)
for i in range(n):
for j in range(i + 1, n):
if self._are_nearby_parallel_boxes(box_list[i], box_list[j]):
# Remove the two boxes from the list, add a new one
a, b = box_list[i], box_list[j]
merged_points = np.vstack([a.points, b.points])
merged_box = RotatedBox.from_points(merged_points, self.box_type)
if merged_box.width / merged_box.height >= self.min_box_aspect:
box_list.remove(a)
box_list.remove(b)
box_list.append(merged_box)
return True
return False
|
python
|
def _merge_any_two_boxes(self, box_list):
"""Given a list of boxes, finds two nearby parallel ones and merges them. Returns false if none found."""
n = len(box_list)
for i in range(n):
for j in range(i + 1, n):
if self._are_nearby_parallel_boxes(box_list[i], box_list[j]):
# Remove the two boxes from the list, add a new one
a, b = box_list[i], box_list[j]
merged_points = np.vstack([a.points, b.points])
merged_box = RotatedBox.from_points(merged_points, self.box_type)
if merged_box.width / merged_box.height >= self.min_box_aspect:
box_list.remove(a)
box_list.remove(b)
box_list.append(merged_box)
return True
return False
|
[
"def",
"_merge_any_two_boxes",
"(",
"self",
",",
"box_list",
")",
":",
"n",
"=",
"len",
"(",
"box_list",
")",
"for",
"i",
"in",
"range",
"(",
"n",
")",
":",
"for",
"j",
"in",
"range",
"(",
"i",
"+",
"1",
",",
"n",
")",
":",
"if",
"self",
".",
"_are_nearby_parallel_boxes",
"(",
"box_list",
"[",
"i",
"]",
",",
"box_list",
"[",
"j",
"]",
")",
":",
"# Remove the two boxes from the list, add a new one",
"a",
",",
"b",
"=",
"box_list",
"[",
"i",
"]",
",",
"box_list",
"[",
"j",
"]",
"merged_points",
"=",
"np",
".",
"vstack",
"(",
"[",
"a",
".",
"points",
",",
"b",
".",
"points",
"]",
")",
"merged_box",
"=",
"RotatedBox",
".",
"from_points",
"(",
"merged_points",
",",
"self",
".",
"box_type",
")",
"if",
"merged_box",
".",
"width",
"/",
"merged_box",
".",
"height",
">=",
"self",
".",
"min_box_aspect",
":",
"box_list",
".",
"remove",
"(",
"a",
")",
"box_list",
".",
"remove",
"(",
"b",
")",
"box_list",
".",
"append",
"(",
"merged_box",
")",
"return",
"True",
"return",
"False"
] |
Given a list of boxes, finds two nearby parallel ones and merges them. Returns false if none found.
|
[
"Given",
"a",
"list",
"of",
"boxes",
"finds",
"two",
"nearby",
"parallel",
"ones",
"and",
"merges",
"them",
".",
"Returns",
"false",
"if",
"none",
"found",
"."
] |
b32afba0f5dc4eb600c4edc4f49e5d49959c5415
|
https://github.com/konstantint/PassportEye/blob/b32afba0f5dc4eb600c4edc4f49e5d49959c5415/passporteye/mrz/image.py#L149-L164
|
6,705
|
konstantint/PassportEye
|
passporteye/mrz/image.py
|
BoxToMRZ._try_larger_image
|
def _try_larger_image(self, roi, cur_text, cur_mrz, filter_order=3):
"""Attempts to improve the OCR result by scaling the image. If the new mrz is better, returns it, otherwise returns
the old mrz."""
if roi.shape[1] <= 700:
scale_by = int(1050.0 / roi.shape[1] + 0.5)
roi_lg = transform.rescale(roi, scale_by, order=filter_order, mode='constant', multichannel=False,
anti_aliasing=True)
new_text = ocr(roi_lg, extra_cmdline_params=self.extra_cmdline_params)
new_mrz = MRZ.from_ocr(new_text)
new_mrz.aux['method'] = 'rescaled(%d)' % filter_order
if new_mrz.valid_score > cur_mrz.valid_score:
cur_mrz = new_mrz
cur_text = new_text
return cur_text, cur_mrz
|
python
|
def _try_larger_image(self, roi, cur_text, cur_mrz, filter_order=3):
"""Attempts to improve the OCR result by scaling the image. If the new mrz is better, returns it, otherwise returns
the old mrz."""
if roi.shape[1] <= 700:
scale_by = int(1050.0 / roi.shape[1] + 0.5)
roi_lg = transform.rescale(roi, scale_by, order=filter_order, mode='constant', multichannel=False,
anti_aliasing=True)
new_text = ocr(roi_lg, extra_cmdline_params=self.extra_cmdline_params)
new_mrz = MRZ.from_ocr(new_text)
new_mrz.aux['method'] = 'rescaled(%d)' % filter_order
if new_mrz.valid_score > cur_mrz.valid_score:
cur_mrz = new_mrz
cur_text = new_text
return cur_text, cur_mrz
|
[
"def",
"_try_larger_image",
"(",
"self",
",",
"roi",
",",
"cur_text",
",",
"cur_mrz",
",",
"filter_order",
"=",
"3",
")",
":",
"if",
"roi",
".",
"shape",
"[",
"1",
"]",
"<=",
"700",
":",
"scale_by",
"=",
"int",
"(",
"1050.0",
"/",
"roi",
".",
"shape",
"[",
"1",
"]",
"+",
"0.5",
")",
"roi_lg",
"=",
"transform",
".",
"rescale",
"(",
"roi",
",",
"scale_by",
",",
"order",
"=",
"filter_order",
",",
"mode",
"=",
"'constant'",
",",
"multichannel",
"=",
"False",
",",
"anti_aliasing",
"=",
"True",
")",
"new_text",
"=",
"ocr",
"(",
"roi_lg",
",",
"extra_cmdline_params",
"=",
"self",
".",
"extra_cmdline_params",
")",
"new_mrz",
"=",
"MRZ",
".",
"from_ocr",
"(",
"new_text",
")",
"new_mrz",
".",
"aux",
"[",
"'method'",
"]",
"=",
"'rescaled(%d)'",
"%",
"filter_order",
"if",
"new_mrz",
".",
"valid_score",
">",
"cur_mrz",
".",
"valid_score",
":",
"cur_mrz",
"=",
"new_mrz",
"cur_text",
"=",
"new_text",
"return",
"cur_text",
",",
"cur_mrz"
] |
Attempts to improve the OCR result by scaling the image. If the new mrz is better, returns it, otherwise returns
the old mrz.
|
[
"Attempts",
"to",
"improve",
"the",
"OCR",
"result",
"by",
"scaling",
"the",
"image",
".",
"If",
"the",
"new",
"mrz",
"is",
"better",
"returns",
"it",
"otherwise",
"returns",
"the",
"old",
"mrz",
"."
] |
b32afba0f5dc4eb600c4edc4f49e5d49959c5415
|
https://github.com/konstantint/PassportEye/blob/b32afba0f5dc4eb600c4edc4f49e5d49959c5415/passporteye/mrz/image.py#L254-L267
|
6,706
|
konstantint/PassportEye
|
passporteye/mrz/scripts.py
|
mrz
|
def mrz():
"""
Command-line script for extracting MRZ from a given image
"""
parser = argparse.ArgumentParser(description='Run the MRZ OCR recognition algorithm on the given image.')
parser.add_argument('filename')
parser.add_argument('--json', action='store_true', help='Produce JSON (rather than tabular) output')
parser.add_argument('--legacy', action='store_true',
help='Use the "legacy" Tesseract OCR engine (--oem 0). Despite the name, it most often results in better '
'results. It is not the default option, because it will only work if '
'your Tesseract installation includes the legacy *.traineddata files. You can download them at '
'https://github.com/tesseract-ocr/tesseract/wiki/Data-Files#data-files-for-version-400-november-29-2016')
parser.add_argument('-r', '--save-roi', default=None,
help='Output the region of the image that is detected to contain the MRZ to the given png file')
parser.add_argument('--version', action='version', version='PassportEye MRZ v%s' % passporteye.__version__)
args = parser.parse_args()
try:
extra_params = '--oem 0' if args.legacy else ''
filename, mrz_, walltime = process_file((args.filename, args.save_roi is not None, extra_params))
except TesseractNotFoundError:
sys.stderr.write("ERROR: The tesseract executable was not found.\n"
"Please, make sure Tesseract is installed and the appropriate directory is included "
"in your PATH environment variable.\n")
sys.exit(1)
except TesseractError as ex:
sys.stderr.write("ERROR: %s" % ex.message)
sys.exit(ex.status)
d = mrz_.to_dict() if mrz_ is not None else {'mrz_type': None, 'valid': False, 'valid_score': 0}
d['walltime'] = walltime
d['filename'] = filename
if args.save_roi is not None and mrz_ is not None and 'roi' in mrz_.aux:
io.imsave(args.save_roi, mrz_.aux['roi'])
if not args.json:
for k in d:
print("%s\t%s" % (k, str(d[k])))
else:
print(json.dumps(d, indent=2))
|
python
|
def mrz():
"""
Command-line script for extracting MRZ from a given image
"""
parser = argparse.ArgumentParser(description='Run the MRZ OCR recognition algorithm on the given image.')
parser.add_argument('filename')
parser.add_argument('--json', action='store_true', help='Produce JSON (rather than tabular) output')
parser.add_argument('--legacy', action='store_true',
help='Use the "legacy" Tesseract OCR engine (--oem 0). Despite the name, it most often results in better '
'results. It is not the default option, because it will only work if '
'your Tesseract installation includes the legacy *.traineddata files. You can download them at '
'https://github.com/tesseract-ocr/tesseract/wiki/Data-Files#data-files-for-version-400-november-29-2016')
parser.add_argument('-r', '--save-roi', default=None,
help='Output the region of the image that is detected to contain the MRZ to the given png file')
parser.add_argument('--version', action='version', version='PassportEye MRZ v%s' % passporteye.__version__)
args = parser.parse_args()
try:
extra_params = '--oem 0' if args.legacy else ''
filename, mrz_, walltime = process_file((args.filename, args.save_roi is not None, extra_params))
except TesseractNotFoundError:
sys.stderr.write("ERROR: The tesseract executable was not found.\n"
"Please, make sure Tesseract is installed and the appropriate directory is included "
"in your PATH environment variable.\n")
sys.exit(1)
except TesseractError as ex:
sys.stderr.write("ERROR: %s" % ex.message)
sys.exit(ex.status)
d = mrz_.to_dict() if mrz_ is not None else {'mrz_type': None, 'valid': False, 'valid_score': 0}
d['walltime'] = walltime
d['filename'] = filename
if args.save_roi is not None and mrz_ is not None and 'roi' in mrz_.aux:
io.imsave(args.save_roi, mrz_.aux['roi'])
if not args.json:
for k in d:
print("%s\t%s" % (k, str(d[k])))
else:
print(json.dumps(d, indent=2))
|
[
"def",
"mrz",
"(",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"'Run the MRZ OCR recognition algorithm on the given image.'",
")",
"parser",
".",
"add_argument",
"(",
"'filename'",
")",
"parser",
".",
"add_argument",
"(",
"'--json'",
",",
"action",
"=",
"'store_true'",
",",
"help",
"=",
"'Produce JSON (rather than tabular) output'",
")",
"parser",
".",
"add_argument",
"(",
"'--legacy'",
",",
"action",
"=",
"'store_true'",
",",
"help",
"=",
"'Use the \"legacy\" Tesseract OCR engine (--oem 0). Despite the name, it most often results in better '",
"'results. It is not the default option, because it will only work if '",
"'your Tesseract installation includes the legacy *.traineddata files. You can download them at '",
"'https://github.com/tesseract-ocr/tesseract/wiki/Data-Files#data-files-for-version-400-november-29-2016'",
")",
"parser",
".",
"add_argument",
"(",
"'-r'",
",",
"'--save-roi'",
",",
"default",
"=",
"None",
",",
"help",
"=",
"'Output the region of the image that is detected to contain the MRZ to the given png file'",
")",
"parser",
".",
"add_argument",
"(",
"'--version'",
",",
"action",
"=",
"'version'",
",",
"version",
"=",
"'PassportEye MRZ v%s'",
"%",
"passporteye",
".",
"__version__",
")",
"args",
"=",
"parser",
".",
"parse_args",
"(",
")",
"try",
":",
"extra_params",
"=",
"'--oem 0'",
"if",
"args",
".",
"legacy",
"else",
"''",
"filename",
",",
"mrz_",
",",
"walltime",
"=",
"process_file",
"(",
"(",
"args",
".",
"filename",
",",
"args",
".",
"save_roi",
"is",
"not",
"None",
",",
"extra_params",
")",
")",
"except",
"TesseractNotFoundError",
":",
"sys",
".",
"stderr",
".",
"write",
"(",
"\"ERROR: The tesseract executable was not found.\\n\"",
"\"Please, make sure Tesseract is installed and the appropriate directory is included \"",
"\"in your PATH environment variable.\\n\"",
")",
"sys",
".",
"exit",
"(",
"1",
")",
"except",
"TesseractError",
"as",
"ex",
":",
"sys",
".",
"stderr",
".",
"write",
"(",
"\"ERROR: %s\"",
"%",
"ex",
".",
"message",
")",
"sys",
".",
"exit",
"(",
"ex",
".",
"status",
")",
"d",
"=",
"mrz_",
".",
"to_dict",
"(",
")",
"if",
"mrz_",
"is",
"not",
"None",
"else",
"{",
"'mrz_type'",
":",
"None",
",",
"'valid'",
":",
"False",
",",
"'valid_score'",
":",
"0",
"}",
"d",
"[",
"'walltime'",
"]",
"=",
"walltime",
"d",
"[",
"'filename'",
"]",
"=",
"filename",
"if",
"args",
".",
"save_roi",
"is",
"not",
"None",
"and",
"mrz_",
"is",
"not",
"None",
"and",
"'roi'",
"in",
"mrz_",
".",
"aux",
":",
"io",
".",
"imsave",
"(",
"args",
".",
"save_roi",
",",
"mrz_",
".",
"aux",
"[",
"'roi'",
"]",
")",
"if",
"not",
"args",
".",
"json",
":",
"for",
"k",
"in",
"d",
":",
"print",
"(",
"\"%s\\t%s\"",
"%",
"(",
"k",
",",
"str",
"(",
"d",
"[",
"k",
"]",
")",
")",
")",
"else",
":",
"print",
"(",
"json",
".",
"dumps",
"(",
"d",
",",
"indent",
"=",
"2",
")",
")"
] |
Command-line script for extracting MRZ from a given image
|
[
"Command",
"-",
"line",
"script",
"for",
"extracting",
"MRZ",
"from",
"a",
"given",
"image"
] |
b32afba0f5dc4eb600c4edc4f49e5d49959c5415
|
https://github.com/konstantint/PassportEye/blob/b32afba0f5dc4eb600c4edc4f49e5d49959c5415/passporteye/mrz/scripts.py#L134-L174
|
6,707
|
glitchassassin/lackey
|
lackey/PlatformManagerWindows.py
|
PlatformManagerWindows._check_count
|
def _check_count(self, result, func, args):
#pylint: disable=unused-argument
""" Private function to return ctypes errors cleanly """
if result == 0:
raise ctypes.WinError(ctypes.get_last_error())
return args
|
python
|
def _check_count(self, result, func, args):
#pylint: disable=unused-argument
""" Private function to return ctypes errors cleanly """
if result == 0:
raise ctypes.WinError(ctypes.get_last_error())
return args
|
[
"def",
"_check_count",
"(",
"self",
",",
"result",
",",
"func",
",",
"args",
")",
":",
"#pylint: disable=unused-argument",
"if",
"result",
"==",
"0",
":",
"raise",
"ctypes",
".",
"WinError",
"(",
"ctypes",
".",
"get_last_error",
"(",
")",
")",
"return",
"args"
] |
Private function to return ctypes errors cleanly
|
[
"Private",
"function",
"to",
"return",
"ctypes",
"errors",
"cleanly"
] |
7adadfacd7f45d81186710be992f5668b15399fe
|
https://github.com/glitchassassin/lackey/blob/7adadfacd7f45d81186710be992f5668b15399fe/lackey/PlatformManagerWindows.py#L210-L215
|
6,708
|
glitchassassin/lackey
|
lackey/PlatformManagerWindows.py
|
PlatformManagerWindows._getMonitorInfo
|
def _getMonitorInfo(self):
""" Returns info about the attached monitors, in device order
[0] is always the primary monitor
"""
monitors = []
CCHDEVICENAME = 32
def _MonitorEnumProcCallback(hMonitor, hdcMonitor, lprcMonitor, dwData):
class MONITORINFOEX(ctypes.Structure):
_fields_ = [("cbSize", ctypes.wintypes.DWORD),
("rcMonitor", ctypes.wintypes.RECT),
("rcWork", ctypes.wintypes.RECT),
("dwFlags", ctypes.wintypes.DWORD),
("szDevice", ctypes.wintypes.WCHAR*CCHDEVICENAME)]
lpmi = MONITORINFOEX()
lpmi.cbSize = ctypes.sizeof(MONITORINFOEX)
self._user32.GetMonitorInfoW(hMonitor, ctypes.byref(lpmi))
#hdc = self._gdi32.CreateDCA(ctypes.c_char_p(lpmi.szDevice), 0, 0, 0)
monitors.append({
"hmon": hMonitor,
#"hdc": hdc,
"rect": (lprcMonitor.contents.left,
lprcMonitor.contents.top,
lprcMonitor.contents.right,
lprcMonitor.contents.bottom),
"name": lpmi.szDevice
})
return True
MonitorEnumProc = ctypes.WINFUNCTYPE(
ctypes.c_bool,
ctypes.c_ulong,
ctypes.c_ulong,
ctypes.POINTER(ctypes.wintypes.RECT),
ctypes.c_int)
callback = MonitorEnumProc(_MonitorEnumProcCallback)
if self._user32.EnumDisplayMonitors(0, 0, callback, 0) == 0:
raise WindowsError("Unable to enumerate monitors")
# Clever magic to make the screen with origin of (0,0) [the primary monitor]
# the first in the list
# Sort by device ID - 0 is primary, 1 is next, etc.
monitors.sort(key=lambda x: (not (x["rect"][0] == 0 and x["rect"][1] == 0), x["name"]))
return monitors
|
python
|
def _getMonitorInfo(self):
""" Returns info about the attached monitors, in device order
[0] is always the primary monitor
"""
monitors = []
CCHDEVICENAME = 32
def _MonitorEnumProcCallback(hMonitor, hdcMonitor, lprcMonitor, dwData):
class MONITORINFOEX(ctypes.Structure):
_fields_ = [("cbSize", ctypes.wintypes.DWORD),
("rcMonitor", ctypes.wintypes.RECT),
("rcWork", ctypes.wintypes.RECT),
("dwFlags", ctypes.wintypes.DWORD),
("szDevice", ctypes.wintypes.WCHAR*CCHDEVICENAME)]
lpmi = MONITORINFOEX()
lpmi.cbSize = ctypes.sizeof(MONITORINFOEX)
self._user32.GetMonitorInfoW(hMonitor, ctypes.byref(lpmi))
#hdc = self._gdi32.CreateDCA(ctypes.c_char_p(lpmi.szDevice), 0, 0, 0)
monitors.append({
"hmon": hMonitor,
#"hdc": hdc,
"rect": (lprcMonitor.contents.left,
lprcMonitor.contents.top,
lprcMonitor.contents.right,
lprcMonitor.contents.bottom),
"name": lpmi.szDevice
})
return True
MonitorEnumProc = ctypes.WINFUNCTYPE(
ctypes.c_bool,
ctypes.c_ulong,
ctypes.c_ulong,
ctypes.POINTER(ctypes.wintypes.RECT),
ctypes.c_int)
callback = MonitorEnumProc(_MonitorEnumProcCallback)
if self._user32.EnumDisplayMonitors(0, 0, callback, 0) == 0:
raise WindowsError("Unable to enumerate monitors")
# Clever magic to make the screen with origin of (0,0) [the primary monitor]
# the first in the list
# Sort by device ID - 0 is primary, 1 is next, etc.
monitors.sort(key=lambda x: (not (x["rect"][0] == 0 and x["rect"][1] == 0), x["name"]))
return monitors
|
[
"def",
"_getMonitorInfo",
"(",
"self",
")",
":",
"monitors",
"=",
"[",
"]",
"CCHDEVICENAME",
"=",
"32",
"def",
"_MonitorEnumProcCallback",
"(",
"hMonitor",
",",
"hdcMonitor",
",",
"lprcMonitor",
",",
"dwData",
")",
":",
"class",
"MONITORINFOEX",
"(",
"ctypes",
".",
"Structure",
")",
":",
"_fields_",
"=",
"[",
"(",
"\"cbSize\"",
",",
"ctypes",
".",
"wintypes",
".",
"DWORD",
")",
",",
"(",
"\"rcMonitor\"",
",",
"ctypes",
".",
"wintypes",
".",
"RECT",
")",
",",
"(",
"\"rcWork\"",
",",
"ctypes",
".",
"wintypes",
".",
"RECT",
")",
",",
"(",
"\"dwFlags\"",
",",
"ctypes",
".",
"wintypes",
".",
"DWORD",
")",
",",
"(",
"\"szDevice\"",
",",
"ctypes",
".",
"wintypes",
".",
"WCHAR",
"*",
"CCHDEVICENAME",
")",
"]",
"lpmi",
"=",
"MONITORINFOEX",
"(",
")",
"lpmi",
".",
"cbSize",
"=",
"ctypes",
".",
"sizeof",
"(",
"MONITORINFOEX",
")",
"self",
".",
"_user32",
".",
"GetMonitorInfoW",
"(",
"hMonitor",
",",
"ctypes",
".",
"byref",
"(",
"lpmi",
")",
")",
"#hdc = self._gdi32.CreateDCA(ctypes.c_char_p(lpmi.szDevice), 0, 0, 0)",
"monitors",
".",
"append",
"(",
"{",
"\"hmon\"",
":",
"hMonitor",
",",
"#\"hdc\": hdc,",
"\"rect\"",
":",
"(",
"lprcMonitor",
".",
"contents",
".",
"left",
",",
"lprcMonitor",
".",
"contents",
".",
"top",
",",
"lprcMonitor",
".",
"contents",
".",
"right",
",",
"lprcMonitor",
".",
"contents",
".",
"bottom",
")",
",",
"\"name\"",
":",
"lpmi",
".",
"szDevice",
"}",
")",
"return",
"True",
"MonitorEnumProc",
"=",
"ctypes",
".",
"WINFUNCTYPE",
"(",
"ctypes",
".",
"c_bool",
",",
"ctypes",
".",
"c_ulong",
",",
"ctypes",
".",
"c_ulong",
",",
"ctypes",
".",
"POINTER",
"(",
"ctypes",
".",
"wintypes",
".",
"RECT",
")",
",",
"ctypes",
".",
"c_int",
")",
"callback",
"=",
"MonitorEnumProc",
"(",
"_MonitorEnumProcCallback",
")",
"if",
"self",
".",
"_user32",
".",
"EnumDisplayMonitors",
"(",
"0",
",",
"0",
",",
"callback",
",",
"0",
")",
"==",
"0",
":",
"raise",
"WindowsError",
"(",
"\"Unable to enumerate monitors\"",
")",
"# Clever magic to make the screen with origin of (0,0) [the primary monitor]",
"# the first in the list",
"# Sort by device ID - 0 is primary, 1 is next, etc.",
"monitors",
".",
"sort",
"(",
"key",
"=",
"lambda",
"x",
":",
"(",
"not",
"(",
"x",
"[",
"\"rect\"",
"]",
"[",
"0",
"]",
"==",
"0",
"and",
"x",
"[",
"\"rect\"",
"]",
"[",
"1",
"]",
"==",
"0",
")",
",",
"x",
"[",
"\"name\"",
"]",
")",
")",
"return",
"monitors"
] |
Returns info about the attached monitors, in device order
[0] is always the primary monitor
|
[
"Returns",
"info",
"about",
"the",
"attached",
"monitors",
"in",
"device",
"order"
] |
7adadfacd7f45d81186710be992f5668b15399fe
|
https://github.com/glitchassassin/lackey/blob/7adadfacd7f45d81186710be992f5668b15399fe/lackey/PlatformManagerWindows.py#L401-L443
|
6,709
|
glitchassassin/lackey
|
lackey/PlatformManagerWindows.py
|
PlatformManagerWindows._getVirtualScreenRect
|
def _getVirtualScreenRect(self):
""" The virtual screen is the bounding box containing all monitors.
Not all regions in the virtual screen are actually visible. The (0,0) coordinate
is the top left corner of the primary screen rather than the whole bounding box, so
some regions of the virtual screen may have negative coordinates if another screen
is positioned in Windows as further to the left or above the primary screen.
Returns the rect as (x, y, w, h)
"""
SM_XVIRTUALSCREEN = 76 # Left of virtual screen
SM_YVIRTUALSCREEN = 77 # Top of virtual screen
SM_CXVIRTUALSCREEN = 78 # Width of virtual screen
SM_CYVIRTUALSCREEN = 79 # Height of virtual screen
return (self._user32.GetSystemMetrics(SM_XVIRTUALSCREEN), \
self._user32.GetSystemMetrics(SM_YVIRTUALSCREEN), \
self._user32.GetSystemMetrics(SM_CXVIRTUALSCREEN), \
self._user32.GetSystemMetrics(SM_CYVIRTUALSCREEN))
|
python
|
def _getVirtualScreenRect(self):
""" The virtual screen is the bounding box containing all monitors.
Not all regions in the virtual screen are actually visible. The (0,0) coordinate
is the top left corner of the primary screen rather than the whole bounding box, so
some regions of the virtual screen may have negative coordinates if another screen
is positioned in Windows as further to the left or above the primary screen.
Returns the rect as (x, y, w, h)
"""
SM_XVIRTUALSCREEN = 76 # Left of virtual screen
SM_YVIRTUALSCREEN = 77 # Top of virtual screen
SM_CXVIRTUALSCREEN = 78 # Width of virtual screen
SM_CYVIRTUALSCREEN = 79 # Height of virtual screen
return (self._user32.GetSystemMetrics(SM_XVIRTUALSCREEN), \
self._user32.GetSystemMetrics(SM_YVIRTUALSCREEN), \
self._user32.GetSystemMetrics(SM_CXVIRTUALSCREEN), \
self._user32.GetSystemMetrics(SM_CYVIRTUALSCREEN))
|
[
"def",
"_getVirtualScreenRect",
"(",
"self",
")",
":",
"SM_XVIRTUALSCREEN",
"=",
"76",
"# Left of virtual screen",
"SM_YVIRTUALSCREEN",
"=",
"77",
"# Top of virtual screen",
"SM_CXVIRTUALSCREEN",
"=",
"78",
"# Width of virtual screen",
"SM_CYVIRTUALSCREEN",
"=",
"79",
"# Height of virtual screen",
"return",
"(",
"self",
".",
"_user32",
".",
"GetSystemMetrics",
"(",
"SM_XVIRTUALSCREEN",
")",
",",
"self",
".",
"_user32",
".",
"GetSystemMetrics",
"(",
"SM_YVIRTUALSCREEN",
")",
",",
"self",
".",
"_user32",
".",
"GetSystemMetrics",
"(",
"SM_CXVIRTUALSCREEN",
")",
",",
"self",
".",
"_user32",
".",
"GetSystemMetrics",
"(",
"SM_CYVIRTUALSCREEN",
")",
")"
] |
The virtual screen is the bounding box containing all monitors.
Not all regions in the virtual screen are actually visible. The (0,0) coordinate
is the top left corner of the primary screen rather than the whole bounding box, so
some regions of the virtual screen may have negative coordinates if another screen
is positioned in Windows as further to the left or above the primary screen.
Returns the rect as (x, y, w, h)
|
[
"The",
"virtual",
"screen",
"is",
"the",
"bounding",
"box",
"containing",
"all",
"monitors",
"."
] |
7adadfacd7f45d81186710be992f5668b15399fe
|
https://github.com/glitchassassin/lackey/blob/7adadfacd7f45d81186710be992f5668b15399fe/lackey/PlatformManagerWindows.py#L444-L462
|
6,710
|
glitchassassin/lackey
|
lackey/PlatformManagerWindows.py
|
PlatformManagerWindows.osPaste
|
def osPaste(self):
""" Triggers the OS "paste" keyboard shortcut """
from .InputEmulation import Keyboard
k = Keyboard()
k.keyDown("{CTRL}")
k.type("v")
k.keyUp("{CTRL}")
|
python
|
def osPaste(self):
""" Triggers the OS "paste" keyboard shortcut """
from .InputEmulation import Keyboard
k = Keyboard()
k.keyDown("{CTRL}")
k.type("v")
k.keyUp("{CTRL}")
|
[
"def",
"osPaste",
"(",
"self",
")",
":",
"from",
".",
"InputEmulation",
"import",
"Keyboard",
"k",
"=",
"Keyboard",
"(",
")",
"k",
".",
"keyDown",
"(",
"\"{CTRL}\"",
")",
"k",
".",
"type",
"(",
"\"v\"",
")",
"k",
".",
"keyUp",
"(",
"\"{CTRL}\"",
")"
] |
Triggers the OS "paste" keyboard shortcut
|
[
"Triggers",
"the",
"OS",
"paste",
"keyboard",
"shortcut"
] |
7adadfacd7f45d81186710be992f5668b15399fe
|
https://github.com/glitchassassin/lackey/blob/7adadfacd7f45d81186710be992f5668b15399fe/lackey/PlatformManagerWindows.py#L497-L503
|
6,711
|
glitchassassin/lackey
|
lackey/PlatformManagerWindows.py
|
PlatformManagerWindows.focusWindow
|
def focusWindow(self, hwnd):
""" Brings specified window to the front """
Debug.log(3, "Focusing window: " + str(hwnd))
SW_RESTORE = 9
if ctypes.windll.user32.IsIconic(hwnd):
ctypes.windll.user32.ShowWindow(hwnd, SW_RESTORE)
ctypes.windll.user32.SetForegroundWindow(hwnd)
|
python
|
def focusWindow(self, hwnd):
""" Brings specified window to the front """
Debug.log(3, "Focusing window: " + str(hwnd))
SW_RESTORE = 9
if ctypes.windll.user32.IsIconic(hwnd):
ctypes.windll.user32.ShowWindow(hwnd, SW_RESTORE)
ctypes.windll.user32.SetForegroundWindow(hwnd)
|
[
"def",
"focusWindow",
"(",
"self",
",",
"hwnd",
")",
":",
"Debug",
".",
"log",
"(",
"3",
",",
"\"Focusing window: \"",
"+",
"str",
"(",
"hwnd",
")",
")",
"SW_RESTORE",
"=",
"9",
"if",
"ctypes",
".",
"windll",
".",
"user32",
".",
"IsIconic",
"(",
"hwnd",
")",
":",
"ctypes",
".",
"windll",
".",
"user32",
".",
"ShowWindow",
"(",
"hwnd",
",",
"SW_RESTORE",
")",
"ctypes",
".",
"windll",
".",
"user32",
".",
"SetForegroundWindow",
"(",
"hwnd",
")"
] |
Brings specified window to the front
|
[
"Brings",
"specified",
"window",
"to",
"the",
"front"
] |
7adadfacd7f45d81186710be992f5668b15399fe
|
https://github.com/glitchassassin/lackey/blob/7adadfacd7f45d81186710be992f5668b15399fe/lackey/PlatformManagerWindows.py#L557-L563
|
6,712
|
glitchassassin/lackey
|
lackey/PlatformManagerWindows.py
|
PlatformManagerWindows.isPIDValid
|
def isPIDValid(self, pid):
""" Checks if a PID is associated with a running process """
## Slightly copied wholesale from http://stackoverflow.com/questions/568271/how-to-check-if-there-exists-a-process-with-a-given-pid
## Thanks to http://stackoverflow.com/users/1777162/ntrrgc and http://stackoverflow.com/users/234270/speedplane
class ExitCodeProcess(ctypes.Structure):
_fields_ = [('hProcess', ctypes.c_void_p),
('lpExitCode', ctypes.POINTER(ctypes.c_ulong))]
SYNCHRONIZE = 0x100000
PROCESS_QUERY_LIMITED_INFORMATION = 0x1000
process = self._kernel32.OpenProcess(SYNCHRONIZE|PROCESS_QUERY_LIMITED_INFORMATION, 0, pid)
if not process:
return False
ec = ExitCodeProcess()
out = self._kernel32.GetExitCodeProcess(process, ctypes.byref(ec))
if not out:
err = self._kernel32.GetLastError()
if self._kernel32.GetLastError() == 5:
# Access is denied.
logging.warning("Access is denied to get pid info.")
self._kernel32.CloseHandle(process)
return False
elif bool(ec.lpExitCode):
# There is an exit code, it quit
self._kernel32.CloseHandle(process)
return False
# No exit code, it's running.
self._kernel32.CloseHandle(process)
return True
|
python
|
def isPIDValid(self, pid):
""" Checks if a PID is associated with a running process """
## Slightly copied wholesale from http://stackoverflow.com/questions/568271/how-to-check-if-there-exists-a-process-with-a-given-pid
## Thanks to http://stackoverflow.com/users/1777162/ntrrgc and http://stackoverflow.com/users/234270/speedplane
class ExitCodeProcess(ctypes.Structure):
_fields_ = [('hProcess', ctypes.c_void_p),
('lpExitCode', ctypes.POINTER(ctypes.c_ulong))]
SYNCHRONIZE = 0x100000
PROCESS_QUERY_LIMITED_INFORMATION = 0x1000
process = self._kernel32.OpenProcess(SYNCHRONIZE|PROCESS_QUERY_LIMITED_INFORMATION, 0, pid)
if not process:
return False
ec = ExitCodeProcess()
out = self._kernel32.GetExitCodeProcess(process, ctypes.byref(ec))
if not out:
err = self._kernel32.GetLastError()
if self._kernel32.GetLastError() == 5:
# Access is denied.
logging.warning("Access is denied to get pid info.")
self._kernel32.CloseHandle(process)
return False
elif bool(ec.lpExitCode):
# There is an exit code, it quit
self._kernel32.CloseHandle(process)
return False
# No exit code, it's running.
self._kernel32.CloseHandle(process)
return True
|
[
"def",
"isPIDValid",
"(",
"self",
",",
"pid",
")",
":",
"## Slightly copied wholesale from http://stackoverflow.com/questions/568271/how-to-check-if-there-exists-a-process-with-a-given-pid",
"## Thanks to http://stackoverflow.com/users/1777162/ntrrgc and http://stackoverflow.com/users/234270/speedplane",
"class",
"ExitCodeProcess",
"(",
"ctypes",
".",
"Structure",
")",
":",
"_fields_",
"=",
"[",
"(",
"'hProcess'",
",",
"ctypes",
".",
"c_void_p",
")",
",",
"(",
"'lpExitCode'",
",",
"ctypes",
".",
"POINTER",
"(",
"ctypes",
".",
"c_ulong",
")",
")",
"]",
"SYNCHRONIZE",
"=",
"0x100000",
"PROCESS_QUERY_LIMITED_INFORMATION",
"=",
"0x1000",
"process",
"=",
"self",
".",
"_kernel32",
".",
"OpenProcess",
"(",
"SYNCHRONIZE",
"|",
"PROCESS_QUERY_LIMITED_INFORMATION",
",",
"0",
",",
"pid",
")",
"if",
"not",
"process",
":",
"return",
"False",
"ec",
"=",
"ExitCodeProcess",
"(",
")",
"out",
"=",
"self",
".",
"_kernel32",
".",
"GetExitCodeProcess",
"(",
"process",
",",
"ctypes",
".",
"byref",
"(",
"ec",
")",
")",
"if",
"not",
"out",
":",
"err",
"=",
"self",
".",
"_kernel32",
".",
"GetLastError",
"(",
")",
"if",
"self",
".",
"_kernel32",
".",
"GetLastError",
"(",
")",
"==",
"5",
":",
"# Access is denied.",
"logging",
".",
"warning",
"(",
"\"Access is denied to get pid info.\"",
")",
"self",
".",
"_kernel32",
".",
"CloseHandle",
"(",
"process",
")",
"return",
"False",
"elif",
"bool",
"(",
"ec",
".",
"lpExitCode",
")",
":",
"# There is an exit code, it quit",
"self",
".",
"_kernel32",
".",
"CloseHandle",
"(",
"process",
")",
"return",
"False",
"# No exit code, it's running.",
"self",
".",
"_kernel32",
".",
"CloseHandle",
"(",
"process",
")",
"return",
"True"
] |
Checks if a PID is associated with a running process
|
[
"Checks",
"if",
"a",
"PID",
"is",
"associated",
"with",
"a",
"running",
"process"
] |
7adadfacd7f45d81186710be992f5668b15399fe
|
https://github.com/glitchassassin/lackey/blob/7adadfacd7f45d81186710be992f5668b15399fe/lackey/PlatformManagerWindows.py#L608-L635
|
6,713
|
glitchassassin/lackey
|
lackey/RegionMatching.py
|
Pattern.similar
|
def similar(self, similarity):
""" Returns a new Pattern with the specified similarity threshold """
pattern = Pattern(self.path)
pattern.similarity = similarity
return pattern
|
python
|
def similar(self, similarity):
""" Returns a new Pattern with the specified similarity threshold """
pattern = Pattern(self.path)
pattern.similarity = similarity
return pattern
|
[
"def",
"similar",
"(",
"self",
",",
"similarity",
")",
":",
"pattern",
"=",
"Pattern",
"(",
"self",
".",
"path",
")",
"pattern",
".",
"similarity",
"=",
"similarity",
"return",
"pattern"
] |
Returns a new Pattern with the specified similarity threshold
|
[
"Returns",
"a",
"new",
"Pattern",
"with",
"the",
"specified",
"similarity",
"threshold"
] |
7adadfacd7f45d81186710be992f5668b15399fe
|
https://github.com/glitchassassin/lackey/blob/7adadfacd7f45d81186710be992f5668b15399fe/lackey/RegionMatching.py#L73-L77
|
6,714
|
glitchassassin/lackey
|
lackey/RegionMatching.py
|
Pattern.targetOffset
|
def targetOffset(self, dx, dy):
""" Returns a new Pattern with the given target offset """
pattern = Pattern(self.path)
pattern.similarity = self.similarity
pattern.offset = Location(dx, dy)
return pattern
|
python
|
def targetOffset(self, dx, dy):
""" Returns a new Pattern with the given target offset """
pattern = Pattern(self.path)
pattern.similarity = self.similarity
pattern.offset = Location(dx, dy)
return pattern
|
[
"def",
"targetOffset",
"(",
"self",
",",
"dx",
",",
"dy",
")",
":",
"pattern",
"=",
"Pattern",
"(",
"self",
".",
"path",
")",
"pattern",
".",
"similarity",
"=",
"self",
".",
"similarity",
"pattern",
".",
"offset",
"=",
"Location",
"(",
"dx",
",",
"dy",
")",
"return",
"pattern"
] |
Returns a new Pattern with the given target offset
|
[
"Returns",
"a",
"new",
"Pattern",
"with",
"the",
"given",
"target",
"offset"
] |
7adadfacd7f45d81186710be992f5668b15399fe
|
https://github.com/glitchassassin/lackey/blob/7adadfacd7f45d81186710be992f5668b15399fe/lackey/RegionMatching.py#L88-L93
|
6,715
|
glitchassassin/lackey
|
lackey/RegionMatching.py
|
Pattern.debugPreview
|
def debugPreview(self, title="Debug"):
""" Loads and displays the image at ``Pattern.path`` """
haystack = Image.open(self.path)
haystack.show()
|
python
|
def debugPreview(self, title="Debug"):
""" Loads and displays the image at ``Pattern.path`` """
haystack = Image.open(self.path)
haystack.show()
|
[
"def",
"debugPreview",
"(",
"self",
",",
"title",
"=",
"\"Debug\"",
")",
":",
"haystack",
"=",
"Image",
".",
"open",
"(",
"self",
".",
"path",
")",
"haystack",
".",
"show",
"(",
")"
] |
Loads and displays the image at ``Pattern.path``
|
[
"Loads",
"and",
"displays",
"the",
"image",
"at",
"Pattern",
".",
"path"
] |
7adadfacd7f45d81186710be992f5668b15399fe
|
https://github.com/glitchassassin/lackey/blob/7adadfacd7f45d81186710be992f5668b15399fe/lackey/RegionMatching.py#L127-L130
|
6,716
|
glitchassassin/lackey
|
lackey/RegionMatching.py
|
Region.setLocation
|
def setLocation(self, location):
""" Change the upper left-hand corner to a new ``Location``
Doesn't change width or height
"""
if not location or not isinstance(location, Location):
raise ValueError("setLocation expected a Location object")
self.x = location.x
self.y = location.y
return self
|
python
|
def setLocation(self, location):
""" Change the upper left-hand corner to a new ``Location``
Doesn't change width or height
"""
if not location or not isinstance(location, Location):
raise ValueError("setLocation expected a Location object")
self.x = location.x
self.y = location.y
return self
|
[
"def",
"setLocation",
"(",
"self",
",",
"location",
")",
":",
"if",
"not",
"location",
"or",
"not",
"isinstance",
"(",
"location",
",",
"Location",
")",
":",
"raise",
"ValueError",
"(",
"\"setLocation expected a Location object\"",
")",
"self",
".",
"x",
"=",
"location",
".",
"x",
"self",
".",
"y",
"=",
"location",
".",
"y",
"return",
"self"
] |
Change the upper left-hand corner to a new ``Location``
Doesn't change width or height
|
[
"Change",
"the",
"upper",
"left",
"-",
"hand",
"corner",
"to",
"a",
"new",
"Location"
] |
7adadfacd7f45d81186710be992f5668b15399fe
|
https://github.com/glitchassassin/lackey/blob/7adadfacd7f45d81186710be992f5668b15399fe/lackey/RegionMatching.py#L222-L231
|
6,717
|
glitchassassin/lackey
|
lackey/RegionMatching.py
|
Region.contains
|
def contains(self, point_or_region):
""" Checks if ``point_or_region`` is within this region """
if isinstance(point_or_region, Location):
return (self.x < point_or_region.x < self.x + self.w) and (self.y < point_or_region.y < self.y + self.h)
elif isinstance(point_or_region, Region):
return ((self.x < point_or_region.getX() < self.x + self.w) and
(self.y < point_or_region.getY() < self.y + self.h) and
(self.x < point_or_region.getX() + point_or_region.getW() < self.x + self.w) and
(self.y < point_or_region.getY() + point_or_region.getH() < self.y + self.h))
else:
raise TypeError("Unrecognized argument type for contains()")
|
python
|
def contains(self, point_or_region):
""" Checks if ``point_or_region`` is within this region """
if isinstance(point_or_region, Location):
return (self.x < point_or_region.x < self.x + self.w) and (self.y < point_or_region.y < self.y + self.h)
elif isinstance(point_or_region, Region):
return ((self.x < point_or_region.getX() < self.x + self.w) and
(self.y < point_or_region.getY() < self.y + self.h) and
(self.x < point_or_region.getX() + point_or_region.getW() < self.x + self.w) and
(self.y < point_or_region.getY() + point_or_region.getH() < self.y + self.h))
else:
raise TypeError("Unrecognized argument type for contains()")
|
[
"def",
"contains",
"(",
"self",
",",
"point_or_region",
")",
":",
"if",
"isinstance",
"(",
"point_or_region",
",",
"Location",
")",
":",
"return",
"(",
"self",
".",
"x",
"<",
"point_or_region",
".",
"x",
"<",
"self",
".",
"x",
"+",
"self",
".",
"w",
")",
"and",
"(",
"self",
".",
"y",
"<",
"point_or_region",
".",
"y",
"<",
"self",
".",
"y",
"+",
"self",
".",
"h",
")",
"elif",
"isinstance",
"(",
"point_or_region",
",",
"Region",
")",
":",
"return",
"(",
"(",
"self",
".",
"x",
"<",
"point_or_region",
".",
"getX",
"(",
")",
"<",
"self",
".",
"x",
"+",
"self",
".",
"w",
")",
"and",
"(",
"self",
".",
"y",
"<",
"point_or_region",
".",
"getY",
"(",
")",
"<",
"self",
".",
"y",
"+",
"self",
".",
"h",
")",
"and",
"(",
"self",
".",
"x",
"<",
"point_or_region",
".",
"getX",
"(",
")",
"+",
"point_or_region",
".",
"getW",
"(",
")",
"<",
"self",
".",
"x",
"+",
"self",
".",
"w",
")",
"and",
"(",
"self",
".",
"y",
"<",
"point_or_region",
".",
"getY",
"(",
")",
"+",
"point_or_region",
".",
"getH",
"(",
")",
"<",
"self",
".",
"y",
"+",
"self",
".",
"h",
")",
")",
"else",
":",
"raise",
"TypeError",
"(",
"\"Unrecognized argument type for contains()\"",
")"
] |
Checks if ``point_or_region`` is within this region
|
[
"Checks",
"if",
"point_or_region",
"is",
"within",
"this",
"region"
] |
7adadfacd7f45d81186710be992f5668b15399fe
|
https://github.com/glitchassassin/lackey/blob/7adadfacd7f45d81186710be992f5668b15399fe/lackey/RegionMatching.py#L251-L261
|
6,718
|
glitchassassin/lackey
|
lackey/RegionMatching.py
|
Region.morphTo
|
def morphTo(self, region):
""" Change shape of this region to match the given ``Region`` object """
if not region or not isinstance(region, Region):
raise TypeError("morphTo expected a Region object")
self.setROI(region)
return self
|
python
|
def morphTo(self, region):
""" Change shape of this region to match the given ``Region`` object """
if not region or not isinstance(region, Region):
raise TypeError("morphTo expected a Region object")
self.setROI(region)
return self
|
[
"def",
"morphTo",
"(",
"self",
",",
"region",
")",
":",
"if",
"not",
"region",
"or",
"not",
"isinstance",
"(",
"region",
",",
"Region",
")",
":",
"raise",
"TypeError",
"(",
"\"morphTo expected a Region object\"",
")",
"self",
".",
"setROI",
"(",
"region",
")",
"return",
"self"
] |
Change shape of this region to match the given ``Region`` object
|
[
"Change",
"shape",
"of",
"this",
"region",
"to",
"match",
"the",
"given",
"Region",
"object"
] |
7adadfacd7f45d81186710be992f5668b15399fe
|
https://github.com/glitchassassin/lackey/blob/7adadfacd7f45d81186710be992f5668b15399fe/lackey/RegionMatching.py#L264-L269
|
6,719
|
glitchassassin/lackey
|
lackey/RegionMatching.py
|
Region.getCenter
|
def getCenter(self):
""" Return the ``Location`` of the center of this region """
return Location(self.x+(self.w/2), self.y+(self.h/2))
|
python
|
def getCenter(self):
""" Return the ``Location`` of the center of this region """
return Location(self.x+(self.w/2), self.y+(self.h/2))
|
[
"def",
"getCenter",
"(",
"self",
")",
":",
"return",
"Location",
"(",
"self",
".",
"x",
"+",
"(",
"self",
".",
"w",
"/",
"2",
")",
",",
"self",
".",
"y",
"+",
"(",
"self",
".",
"h",
"/",
"2",
")",
")"
] |
Return the ``Location`` of the center of this region
|
[
"Return",
"the",
"Location",
"of",
"the",
"center",
"of",
"this",
"region"
] |
7adadfacd7f45d81186710be992f5668b15399fe
|
https://github.com/glitchassassin/lackey/blob/7adadfacd7f45d81186710be992f5668b15399fe/lackey/RegionMatching.py#L280-L282
|
6,720
|
glitchassassin/lackey
|
lackey/RegionMatching.py
|
Region.getBottomRight
|
def getBottomRight(self):
""" Return the ``Location`` of the bottom right corner of this region """
return Location(self.x+self.w, self.y+self.h)
|
python
|
def getBottomRight(self):
""" Return the ``Location`` of the bottom right corner of this region """
return Location(self.x+self.w, self.y+self.h)
|
[
"def",
"getBottomRight",
"(",
"self",
")",
":",
"return",
"Location",
"(",
"self",
".",
"x",
"+",
"self",
".",
"w",
",",
"self",
".",
"y",
"+",
"self",
".",
"h",
")"
] |
Return the ``Location`` of the bottom right corner of this region
|
[
"Return",
"the",
"Location",
"of",
"the",
"bottom",
"right",
"corner",
"of",
"this",
"region"
] |
7adadfacd7f45d81186710be992f5668b15399fe
|
https://github.com/glitchassassin/lackey/blob/7adadfacd7f45d81186710be992f5668b15399fe/lackey/RegionMatching.py#L292-L294
|
6,721
|
glitchassassin/lackey
|
lackey/RegionMatching.py
|
Region.offset
|
def offset(self, location, dy=0):
""" Returns a new ``Region`` offset from this one by ``location``
Width and height remain the same
"""
if not isinstance(location, Location):
# Assume variables passed were dx,dy
location = Location(location, dy)
r = Region(self.x+location.x, self.y+location.y, self.w, self.h).clipRegionToScreen()
if r is None:
raise ValueError("Specified region is not visible on any screen")
return None
return r
|
python
|
def offset(self, location, dy=0):
""" Returns a new ``Region`` offset from this one by ``location``
Width and height remain the same
"""
if not isinstance(location, Location):
# Assume variables passed were dx,dy
location = Location(location, dy)
r = Region(self.x+location.x, self.y+location.y, self.w, self.h).clipRegionToScreen()
if r is None:
raise ValueError("Specified region is not visible on any screen")
return None
return r
|
[
"def",
"offset",
"(",
"self",
",",
"location",
",",
"dy",
"=",
"0",
")",
":",
"if",
"not",
"isinstance",
"(",
"location",
",",
"Location",
")",
":",
"# Assume variables passed were dx,dy",
"location",
"=",
"Location",
"(",
"location",
",",
"dy",
")",
"r",
"=",
"Region",
"(",
"self",
".",
"x",
"+",
"location",
".",
"x",
",",
"self",
".",
"y",
"+",
"location",
".",
"y",
",",
"self",
".",
"w",
",",
"self",
".",
"h",
")",
".",
"clipRegionToScreen",
"(",
")",
"if",
"r",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"Specified region is not visible on any screen\"",
")",
"return",
"None",
"return",
"r"
] |
Returns a new ``Region`` offset from this one by ``location``
Width and height remain the same
|
[
"Returns",
"a",
"new",
"Region",
"offset",
"from",
"this",
"one",
"by",
"location"
] |
7adadfacd7f45d81186710be992f5668b15399fe
|
https://github.com/glitchassassin/lackey/blob/7adadfacd7f45d81186710be992f5668b15399fe/lackey/RegionMatching.py#L331-L343
|
6,722
|
glitchassassin/lackey
|
lackey/RegionMatching.py
|
Region.grow
|
def grow(self, width, height=None):
""" Expands the region by ``width`` on both sides and ``height`` on the top and bottom.
If only one value is provided, expands the region by that amount on all sides.
Equivalent to ``nearby()``.
"""
if height is None:
return self.nearby(width)
else:
return Region(
self.x-width,
self.y-height,
self.w+(2*width),
self.h+(2*height)).clipRegionToScreen()
|
python
|
def grow(self, width, height=None):
""" Expands the region by ``width`` on both sides and ``height`` on the top and bottom.
If only one value is provided, expands the region by that amount on all sides.
Equivalent to ``nearby()``.
"""
if height is None:
return self.nearby(width)
else:
return Region(
self.x-width,
self.y-height,
self.w+(2*width),
self.h+(2*height)).clipRegionToScreen()
|
[
"def",
"grow",
"(",
"self",
",",
"width",
",",
"height",
"=",
"None",
")",
":",
"if",
"height",
"is",
"None",
":",
"return",
"self",
".",
"nearby",
"(",
"width",
")",
"else",
":",
"return",
"Region",
"(",
"self",
".",
"x",
"-",
"width",
",",
"self",
".",
"y",
"-",
"height",
",",
"self",
".",
"w",
"+",
"(",
"2",
"*",
"width",
")",
",",
"self",
".",
"h",
"+",
"(",
"2",
"*",
"height",
")",
")",
".",
"clipRegionToScreen",
"(",
")"
] |
Expands the region by ``width`` on both sides and ``height`` on the top and bottom.
If only one value is provided, expands the region by that amount on all sides.
Equivalent to ``nearby()``.
|
[
"Expands",
"the",
"region",
"by",
"width",
"on",
"both",
"sides",
"and",
"height",
"on",
"the",
"top",
"and",
"bottom",
"."
] |
7adadfacd7f45d81186710be992f5668b15399fe
|
https://github.com/glitchassassin/lackey/blob/7adadfacd7f45d81186710be992f5668b15399fe/lackey/RegionMatching.py#L344-L357
|
6,723
|
glitchassassin/lackey
|
lackey/RegionMatching.py
|
Region.nearby
|
def nearby(self, expand=50):
""" Returns a new Region that includes the nearby neighbourhood of the the current region.
The new region is defined by extending the current region's dimensions
all directions by range number of pixels. The center of the new region remains the
same.
"""
return Region(
self.x-expand,
self.y-expand,
self.w+(2*expand),
self.h+(2*expand)).clipRegionToScreen()
|
python
|
def nearby(self, expand=50):
""" Returns a new Region that includes the nearby neighbourhood of the the current region.
The new region is defined by extending the current region's dimensions
all directions by range number of pixels. The center of the new region remains the
same.
"""
return Region(
self.x-expand,
self.y-expand,
self.w+(2*expand),
self.h+(2*expand)).clipRegionToScreen()
|
[
"def",
"nearby",
"(",
"self",
",",
"expand",
"=",
"50",
")",
":",
"return",
"Region",
"(",
"self",
".",
"x",
"-",
"expand",
",",
"self",
".",
"y",
"-",
"expand",
",",
"self",
".",
"w",
"+",
"(",
"2",
"*",
"expand",
")",
",",
"self",
".",
"h",
"+",
"(",
"2",
"*",
"expand",
")",
")",
".",
"clipRegionToScreen",
"(",
")"
] |
Returns a new Region that includes the nearby neighbourhood of the the current region.
The new region is defined by extending the current region's dimensions
all directions by range number of pixels. The center of the new region remains the
same.
|
[
"Returns",
"a",
"new",
"Region",
"that",
"includes",
"the",
"nearby",
"neighbourhood",
"of",
"the",
"the",
"current",
"region",
"."
] |
7adadfacd7f45d81186710be992f5668b15399fe
|
https://github.com/glitchassassin/lackey/blob/7adadfacd7f45d81186710be992f5668b15399fe/lackey/RegionMatching.py#L361-L372
|
6,724
|
glitchassassin/lackey
|
lackey/RegionMatching.py
|
Region.left
|
def left(self, expand=None):
""" Returns a new Region left of the current region with a width of ``expand`` pixels.
Does not include the current region. If range is omitted, it reaches to the left border
of the screen. The new region has the same height and y-position as the current region.
"""
if expand == None:
x = 0
y = self.y
w = self.x
h = self.h
else:
x = self.x-expand
y = self.y
w = expand
h = self.h
return Region(x, y, w, h).clipRegionToScreen()
|
python
|
def left(self, expand=None):
""" Returns a new Region left of the current region with a width of ``expand`` pixels.
Does not include the current region. If range is omitted, it reaches to the left border
of the screen. The new region has the same height and y-position as the current region.
"""
if expand == None:
x = 0
y = self.y
w = self.x
h = self.h
else:
x = self.x-expand
y = self.y
w = expand
h = self.h
return Region(x, y, w, h).clipRegionToScreen()
|
[
"def",
"left",
"(",
"self",
",",
"expand",
"=",
"None",
")",
":",
"if",
"expand",
"==",
"None",
":",
"x",
"=",
"0",
"y",
"=",
"self",
".",
"y",
"w",
"=",
"self",
".",
"x",
"h",
"=",
"self",
".",
"h",
"else",
":",
"x",
"=",
"self",
".",
"x",
"-",
"expand",
"y",
"=",
"self",
".",
"y",
"w",
"=",
"expand",
"h",
"=",
"self",
".",
"h",
"return",
"Region",
"(",
"x",
",",
"y",
",",
"w",
",",
"h",
")",
".",
"clipRegionToScreen",
"(",
")"
] |
Returns a new Region left of the current region with a width of ``expand`` pixels.
Does not include the current region. If range is omitted, it reaches to the left border
of the screen. The new region has the same height and y-position as the current region.
|
[
"Returns",
"a",
"new",
"Region",
"left",
"of",
"the",
"current",
"region",
"with",
"a",
"width",
"of",
"expand",
"pixels",
"."
] |
7adadfacd7f45d81186710be992f5668b15399fe
|
https://github.com/glitchassassin/lackey/blob/7adadfacd7f45d81186710be992f5668b15399fe/lackey/RegionMatching.py#L407-L423
|
6,725
|
glitchassassin/lackey
|
lackey/RegionMatching.py
|
Region.right
|
def right(self, expand=None):
""" Returns a new Region right of the current region with a width of ``expand`` pixels.
Does not include the current region. If range is omitted, it reaches to the right border
of the screen. The new region has the same height and y-position as the current region.
"""
if expand == None:
x = self.x+self.w
y = self.y
w = self.getScreen().getBounds()[2] - x
h = self.h
else:
x = self.x+self.w
y = self.y
w = expand
h = self.h
return Region(x, y, w, h).clipRegionToScreen()
|
python
|
def right(self, expand=None):
""" Returns a new Region right of the current region with a width of ``expand`` pixels.
Does not include the current region. If range is omitted, it reaches to the right border
of the screen. The new region has the same height and y-position as the current region.
"""
if expand == None:
x = self.x+self.w
y = self.y
w = self.getScreen().getBounds()[2] - x
h = self.h
else:
x = self.x+self.w
y = self.y
w = expand
h = self.h
return Region(x, y, w, h).clipRegionToScreen()
|
[
"def",
"right",
"(",
"self",
",",
"expand",
"=",
"None",
")",
":",
"if",
"expand",
"==",
"None",
":",
"x",
"=",
"self",
".",
"x",
"+",
"self",
".",
"w",
"y",
"=",
"self",
".",
"y",
"w",
"=",
"self",
".",
"getScreen",
"(",
")",
".",
"getBounds",
"(",
")",
"[",
"2",
"]",
"-",
"x",
"h",
"=",
"self",
".",
"h",
"else",
":",
"x",
"=",
"self",
".",
"x",
"+",
"self",
".",
"w",
"y",
"=",
"self",
".",
"y",
"w",
"=",
"expand",
"h",
"=",
"self",
".",
"h",
"return",
"Region",
"(",
"x",
",",
"y",
",",
"w",
",",
"h",
")",
".",
"clipRegionToScreen",
"(",
")"
] |
Returns a new Region right of the current region with a width of ``expand`` pixels.
Does not include the current region. If range is omitted, it reaches to the right border
of the screen. The new region has the same height and y-position as the current region.
|
[
"Returns",
"a",
"new",
"Region",
"right",
"of",
"the",
"current",
"region",
"with",
"a",
"width",
"of",
"expand",
"pixels",
"."
] |
7adadfacd7f45d81186710be992f5668b15399fe
|
https://github.com/glitchassassin/lackey/blob/7adadfacd7f45d81186710be992f5668b15399fe/lackey/RegionMatching.py#L424-L440
|
6,726
|
glitchassassin/lackey
|
lackey/RegionMatching.py
|
Region.getBitmap
|
def getBitmap(self):
""" Captures screen area of this region, at least the part that is on the screen
Returns image as numpy array
"""
return PlatformManager.getBitmapFromRect(self.x, self.y, self.w, self.h)
|
python
|
def getBitmap(self):
""" Captures screen area of this region, at least the part that is on the screen
Returns image as numpy array
"""
return PlatformManager.getBitmapFromRect(self.x, self.y, self.w, self.h)
|
[
"def",
"getBitmap",
"(",
"self",
")",
":",
"return",
"PlatformManager",
".",
"getBitmapFromRect",
"(",
"self",
".",
"x",
",",
"self",
".",
"y",
",",
"self",
".",
"w",
",",
"self",
".",
"h",
")"
] |
Captures screen area of this region, at least the part that is on the screen
Returns image as numpy array
|
[
"Captures",
"screen",
"area",
"of",
"this",
"region",
"at",
"least",
"the",
"part",
"that",
"is",
"on",
"the",
"screen"
] |
7adadfacd7f45d81186710be992f5668b15399fe
|
https://github.com/glitchassassin/lackey/blob/7adadfacd7f45d81186710be992f5668b15399fe/lackey/RegionMatching.py#L449-L454
|
6,727
|
glitchassassin/lackey
|
lackey/RegionMatching.py
|
Region.debugPreview
|
def debugPreview(self, title="Debug"):
""" Displays the region in a preview window.
If the region is a Match, circles the target area. If the region is larger than half the
primary screen in either dimension, scales it down to half size.
"""
region = self
haystack = self.getBitmap()
if isinstance(region, Match):
cv2.circle(
haystack,
(region.getTarget().x - self.x, region.getTarget().y - self.y),
5,
255)
if haystack.shape[0] > (Screen(0).getBounds()[2]/2) or haystack.shape[1] > (Screen(0).getBounds()[3]/2):
# Image is bigger than half the screen; scale it down
haystack = cv2.resize(haystack, (0, 0), fx=0.5, fy=0.5)
Image.fromarray(haystack).show()
|
python
|
def debugPreview(self, title="Debug"):
""" Displays the region in a preview window.
If the region is a Match, circles the target area. If the region is larger than half the
primary screen in either dimension, scales it down to half size.
"""
region = self
haystack = self.getBitmap()
if isinstance(region, Match):
cv2.circle(
haystack,
(region.getTarget().x - self.x, region.getTarget().y - self.y),
5,
255)
if haystack.shape[0] > (Screen(0).getBounds()[2]/2) or haystack.shape[1] > (Screen(0).getBounds()[3]/2):
# Image is bigger than half the screen; scale it down
haystack = cv2.resize(haystack, (0, 0), fx=0.5, fy=0.5)
Image.fromarray(haystack).show()
|
[
"def",
"debugPreview",
"(",
"self",
",",
"title",
"=",
"\"Debug\"",
")",
":",
"region",
"=",
"self",
"haystack",
"=",
"self",
".",
"getBitmap",
"(",
")",
"if",
"isinstance",
"(",
"region",
",",
"Match",
")",
":",
"cv2",
".",
"circle",
"(",
"haystack",
",",
"(",
"region",
".",
"getTarget",
"(",
")",
".",
"x",
"-",
"self",
".",
"x",
",",
"region",
".",
"getTarget",
"(",
")",
".",
"y",
"-",
"self",
".",
"y",
")",
",",
"5",
",",
"255",
")",
"if",
"haystack",
".",
"shape",
"[",
"0",
"]",
">",
"(",
"Screen",
"(",
"0",
")",
".",
"getBounds",
"(",
")",
"[",
"2",
"]",
"/",
"2",
")",
"or",
"haystack",
".",
"shape",
"[",
"1",
"]",
">",
"(",
"Screen",
"(",
"0",
")",
".",
"getBounds",
"(",
")",
"[",
"3",
"]",
"/",
"2",
")",
":",
"# Image is bigger than half the screen; scale it down",
"haystack",
"=",
"cv2",
".",
"resize",
"(",
"haystack",
",",
"(",
"0",
",",
"0",
")",
",",
"fx",
"=",
"0.5",
",",
"fy",
"=",
"0.5",
")",
"Image",
".",
"fromarray",
"(",
"haystack",
")",
".",
"show",
"(",
")"
] |
Displays the region in a preview window.
If the region is a Match, circles the target area. If the region is larger than half the
primary screen in either dimension, scales it down to half size.
|
[
"Displays",
"the",
"region",
"in",
"a",
"preview",
"window",
"."
] |
7adadfacd7f45d81186710be992f5668b15399fe
|
https://github.com/glitchassassin/lackey/blob/7adadfacd7f45d81186710be992f5668b15399fe/lackey/RegionMatching.py#L455-L472
|
6,728
|
glitchassassin/lackey
|
lackey/RegionMatching.py
|
Region.wait
|
def wait(self, pattern, seconds=None):
""" Searches for an image pattern in the given region, given a specified timeout period
Functionally identical to find(). If a number is passed instead of a pattern,
just waits the specified number of seconds.
Sikuli supports OCR search with a text parameter. This does not (yet).
"""
if isinstance(pattern, (int, float)):
if pattern == FOREVER:
while True:
time.sleep(1) # Infinite loop
time.sleep(pattern)
return None
if seconds is None:
seconds = self.autoWaitTimeout
findFailedRetry = True
timeout = time.time() + seconds
while findFailedRetry:
while True:
match = self.exists(pattern)
if match:
return match
if time.time() >= timeout:
break
path = pattern.path if isinstance(pattern, Pattern) else pattern
findFailedRetry = self._raiseFindFailed("Could not find pattern '{}'".format(path))
if findFailedRetry:
time.sleep(self._repeatWaitTime)
return None
|
python
|
def wait(self, pattern, seconds=None):
""" Searches for an image pattern in the given region, given a specified timeout period
Functionally identical to find(). If a number is passed instead of a pattern,
just waits the specified number of seconds.
Sikuli supports OCR search with a text parameter. This does not (yet).
"""
if isinstance(pattern, (int, float)):
if pattern == FOREVER:
while True:
time.sleep(1) # Infinite loop
time.sleep(pattern)
return None
if seconds is None:
seconds = self.autoWaitTimeout
findFailedRetry = True
timeout = time.time() + seconds
while findFailedRetry:
while True:
match = self.exists(pattern)
if match:
return match
if time.time() >= timeout:
break
path = pattern.path if isinstance(pattern, Pattern) else pattern
findFailedRetry = self._raiseFindFailed("Could not find pattern '{}'".format(path))
if findFailedRetry:
time.sleep(self._repeatWaitTime)
return None
|
[
"def",
"wait",
"(",
"self",
",",
"pattern",
",",
"seconds",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"pattern",
",",
"(",
"int",
",",
"float",
")",
")",
":",
"if",
"pattern",
"==",
"FOREVER",
":",
"while",
"True",
":",
"time",
".",
"sleep",
"(",
"1",
")",
"# Infinite loop",
"time",
".",
"sleep",
"(",
"pattern",
")",
"return",
"None",
"if",
"seconds",
"is",
"None",
":",
"seconds",
"=",
"self",
".",
"autoWaitTimeout",
"findFailedRetry",
"=",
"True",
"timeout",
"=",
"time",
".",
"time",
"(",
")",
"+",
"seconds",
"while",
"findFailedRetry",
":",
"while",
"True",
":",
"match",
"=",
"self",
".",
"exists",
"(",
"pattern",
")",
"if",
"match",
":",
"return",
"match",
"if",
"time",
".",
"time",
"(",
")",
">=",
"timeout",
":",
"break",
"path",
"=",
"pattern",
".",
"path",
"if",
"isinstance",
"(",
"pattern",
",",
"Pattern",
")",
"else",
"pattern",
"findFailedRetry",
"=",
"self",
".",
"_raiseFindFailed",
"(",
"\"Could not find pattern '{}'\"",
".",
"format",
"(",
"path",
")",
")",
"if",
"findFailedRetry",
":",
"time",
".",
"sleep",
"(",
"self",
".",
"_repeatWaitTime",
")",
"return",
"None"
] |
Searches for an image pattern in the given region, given a specified timeout period
Functionally identical to find(). If a number is passed instead of a pattern,
just waits the specified number of seconds.
Sikuli supports OCR search with a text parameter. This does not (yet).
|
[
"Searches",
"for",
"an",
"image",
"pattern",
"in",
"the",
"given",
"region",
"given",
"a",
"specified",
"timeout",
"period"
] |
7adadfacd7f45d81186710be992f5668b15399fe
|
https://github.com/glitchassassin/lackey/blob/7adadfacd7f45d81186710be992f5668b15399fe/lackey/RegionMatching.py#L566-L596
|
6,729
|
glitchassassin/lackey
|
lackey/RegionMatching.py
|
Region.waitVanish
|
def waitVanish(self, pattern, seconds=None):
""" Waits until the specified pattern is not visible on screen.
If ``seconds`` pass and the pattern is still visible, raises FindFailed exception.
Sikuli supports OCR search with a text parameter. This does not (yet).
"""
r = self.clipRegionToScreen()
if r is None:
raise ValueError("Region outside all visible screens")
return None
if seconds is None:
seconds = self.autoWaitTimeout
if not isinstance(pattern, Pattern):
if not isinstance(pattern, basestring):
raise TypeError("find expected a string [image path] or Pattern object")
pattern = Pattern(pattern)
needle = cv2.imread(pattern.path)
match = True
timeout = time.time() + seconds
while match and time.time() < timeout:
matcher = TemplateMatcher(r.getBitmap())
# When needle disappears, matcher returns None
match = matcher.findBestMatch(needle, pattern.similarity)
time.sleep(1/self._defaultScanRate if self._defaultScanRate is not None else 1/Settings.WaitScanRate)
if match:
return False
|
python
|
def waitVanish(self, pattern, seconds=None):
""" Waits until the specified pattern is not visible on screen.
If ``seconds`` pass and the pattern is still visible, raises FindFailed exception.
Sikuli supports OCR search with a text parameter. This does not (yet).
"""
r = self.clipRegionToScreen()
if r is None:
raise ValueError("Region outside all visible screens")
return None
if seconds is None:
seconds = self.autoWaitTimeout
if not isinstance(pattern, Pattern):
if not isinstance(pattern, basestring):
raise TypeError("find expected a string [image path] or Pattern object")
pattern = Pattern(pattern)
needle = cv2.imread(pattern.path)
match = True
timeout = time.time() + seconds
while match and time.time() < timeout:
matcher = TemplateMatcher(r.getBitmap())
# When needle disappears, matcher returns None
match = matcher.findBestMatch(needle, pattern.similarity)
time.sleep(1/self._defaultScanRate if self._defaultScanRate is not None else 1/Settings.WaitScanRate)
if match:
return False
|
[
"def",
"waitVanish",
"(",
"self",
",",
"pattern",
",",
"seconds",
"=",
"None",
")",
":",
"r",
"=",
"self",
".",
"clipRegionToScreen",
"(",
")",
"if",
"r",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"Region outside all visible screens\"",
")",
"return",
"None",
"if",
"seconds",
"is",
"None",
":",
"seconds",
"=",
"self",
".",
"autoWaitTimeout",
"if",
"not",
"isinstance",
"(",
"pattern",
",",
"Pattern",
")",
":",
"if",
"not",
"isinstance",
"(",
"pattern",
",",
"basestring",
")",
":",
"raise",
"TypeError",
"(",
"\"find expected a string [image path] or Pattern object\"",
")",
"pattern",
"=",
"Pattern",
"(",
"pattern",
")",
"needle",
"=",
"cv2",
".",
"imread",
"(",
"pattern",
".",
"path",
")",
"match",
"=",
"True",
"timeout",
"=",
"time",
".",
"time",
"(",
")",
"+",
"seconds",
"while",
"match",
"and",
"time",
".",
"time",
"(",
")",
"<",
"timeout",
":",
"matcher",
"=",
"TemplateMatcher",
"(",
"r",
".",
"getBitmap",
"(",
")",
")",
"# When needle disappears, matcher returns None",
"match",
"=",
"matcher",
".",
"findBestMatch",
"(",
"needle",
",",
"pattern",
".",
"similarity",
")",
"time",
".",
"sleep",
"(",
"1",
"/",
"self",
".",
"_defaultScanRate",
"if",
"self",
".",
"_defaultScanRate",
"is",
"not",
"None",
"else",
"1",
"/",
"Settings",
".",
"WaitScanRate",
")",
"if",
"match",
":",
"return",
"False"
] |
Waits until the specified pattern is not visible on screen.
If ``seconds`` pass and the pattern is still visible, raises FindFailed exception.
Sikuli supports OCR search with a text parameter. This does not (yet).
|
[
"Waits",
"until",
"the",
"specified",
"pattern",
"is",
"not",
"visible",
"on",
"screen",
"."
] |
7adadfacd7f45d81186710be992f5668b15399fe
|
https://github.com/glitchassassin/lackey/blob/7adadfacd7f45d81186710be992f5668b15399fe/lackey/RegionMatching.py#L597-L624
|
6,730
|
glitchassassin/lackey
|
lackey/RegionMatching.py
|
Region.click
|
def click(self, target=None, modifiers=""):
""" Moves the cursor to the target location and clicks the default mouse button. """
if target is None:
target = self._lastMatch or self # Whichever one is not None
target_location = None
if isinstance(target, Pattern):
target_location = self.find(target).getTarget()
elif isinstance(target, basestring):
target_location = self.find(target).getTarget()
elif isinstance(target, Match):
target_location = target.getTarget()
elif isinstance(target, Region):
target_location = target.getCenter()
elif isinstance(target, Location):
target_location = target
else:
raise TypeError("click expected Pattern, String, Match, Region, or Location object")
if modifiers != "":
keyboard.keyDown(modifiers)
Mouse.moveSpeed(target_location, Settings.MoveMouseDelay)
time.sleep(0.1) # For responsiveness
if Settings.ClickDelay > 0:
time.sleep(min(1.0, Settings.ClickDelay))
Settings.ClickDelay = 0.0
Mouse.click()
time.sleep(0.1)
if modifiers != 0:
keyboard.keyUp(modifiers)
Debug.history("Clicked at {}".format(target_location))
|
python
|
def click(self, target=None, modifiers=""):
""" Moves the cursor to the target location and clicks the default mouse button. """
if target is None:
target = self._lastMatch or self # Whichever one is not None
target_location = None
if isinstance(target, Pattern):
target_location = self.find(target).getTarget()
elif isinstance(target, basestring):
target_location = self.find(target).getTarget()
elif isinstance(target, Match):
target_location = target.getTarget()
elif isinstance(target, Region):
target_location = target.getCenter()
elif isinstance(target, Location):
target_location = target
else:
raise TypeError("click expected Pattern, String, Match, Region, or Location object")
if modifiers != "":
keyboard.keyDown(modifiers)
Mouse.moveSpeed(target_location, Settings.MoveMouseDelay)
time.sleep(0.1) # For responsiveness
if Settings.ClickDelay > 0:
time.sleep(min(1.0, Settings.ClickDelay))
Settings.ClickDelay = 0.0
Mouse.click()
time.sleep(0.1)
if modifiers != 0:
keyboard.keyUp(modifiers)
Debug.history("Clicked at {}".format(target_location))
|
[
"def",
"click",
"(",
"self",
",",
"target",
"=",
"None",
",",
"modifiers",
"=",
"\"\"",
")",
":",
"if",
"target",
"is",
"None",
":",
"target",
"=",
"self",
".",
"_lastMatch",
"or",
"self",
"# Whichever one is not None",
"target_location",
"=",
"None",
"if",
"isinstance",
"(",
"target",
",",
"Pattern",
")",
":",
"target_location",
"=",
"self",
".",
"find",
"(",
"target",
")",
".",
"getTarget",
"(",
")",
"elif",
"isinstance",
"(",
"target",
",",
"basestring",
")",
":",
"target_location",
"=",
"self",
".",
"find",
"(",
"target",
")",
".",
"getTarget",
"(",
")",
"elif",
"isinstance",
"(",
"target",
",",
"Match",
")",
":",
"target_location",
"=",
"target",
".",
"getTarget",
"(",
")",
"elif",
"isinstance",
"(",
"target",
",",
"Region",
")",
":",
"target_location",
"=",
"target",
".",
"getCenter",
"(",
")",
"elif",
"isinstance",
"(",
"target",
",",
"Location",
")",
":",
"target_location",
"=",
"target",
"else",
":",
"raise",
"TypeError",
"(",
"\"click expected Pattern, String, Match, Region, or Location object\"",
")",
"if",
"modifiers",
"!=",
"\"\"",
":",
"keyboard",
".",
"keyDown",
"(",
"modifiers",
")",
"Mouse",
".",
"moveSpeed",
"(",
"target_location",
",",
"Settings",
".",
"MoveMouseDelay",
")",
"time",
".",
"sleep",
"(",
"0.1",
")",
"# For responsiveness",
"if",
"Settings",
".",
"ClickDelay",
">",
"0",
":",
"time",
".",
"sleep",
"(",
"min",
"(",
"1.0",
",",
"Settings",
".",
"ClickDelay",
")",
")",
"Settings",
".",
"ClickDelay",
"=",
"0.0",
"Mouse",
".",
"click",
"(",
")",
"time",
".",
"sleep",
"(",
"0.1",
")",
"if",
"modifiers",
"!=",
"0",
":",
"keyboard",
".",
"keyUp",
"(",
"modifiers",
")",
"Debug",
".",
"history",
"(",
"\"Clicked at {}\"",
".",
"format",
"(",
"target_location",
")",
")"
] |
Moves the cursor to the target location and clicks the default mouse button.
|
[
"Moves",
"the",
"cursor",
"to",
"the",
"target",
"location",
"and",
"clicks",
"the",
"default",
"mouse",
"button",
"."
] |
7adadfacd7f45d81186710be992f5668b15399fe
|
https://github.com/glitchassassin/lackey/blob/7adadfacd7f45d81186710be992f5668b15399fe/lackey/RegionMatching.py#L686-L717
|
6,731
|
glitchassassin/lackey
|
lackey/RegionMatching.py
|
Region.hover
|
def hover(self, target=None):
""" Moves the cursor to the target location """
if target is None:
target = self._lastMatch or self # Whichever one is not None
target_location = None
if isinstance(target, Pattern):
target_location = self.find(target).getTarget()
elif isinstance(target, basestring):
target_location = self.find(target).getTarget()
elif isinstance(target, Match):
target_location = target.getTarget()
elif isinstance(target, Region):
target_location = target.getCenter()
elif isinstance(target, Location):
target_location = target
else:
raise TypeError("hover expected Pattern, String, Match, Region, or Location object")
Mouse.moveSpeed(target_location, Settings.MoveMouseDelay)
|
python
|
def hover(self, target=None):
""" Moves the cursor to the target location """
if target is None:
target = self._lastMatch or self # Whichever one is not None
target_location = None
if isinstance(target, Pattern):
target_location = self.find(target).getTarget()
elif isinstance(target, basestring):
target_location = self.find(target).getTarget()
elif isinstance(target, Match):
target_location = target.getTarget()
elif isinstance(target, Region):
target_location = target.getCenter()
elif isinstance(target, Location):
target_location = target
else:
raise TypeError("hover expected Pattern, String, Match, Region, or Location object")
Mouse.moveSpeed(target_location, Settings.MoveMouseDelay)
|
[
"def",
"hover",
"(",
"self",
",",
"target",
"=",
"None",
")",
":",
"if",
"target",
"is",
"None",
":",
"target",
"=",
"self",
".",
"_lastMatch",
"or",
"self",
"# Whichever one is not None",
"target_location",
"=",
"None",
"if",
"isinstance",
"(",
"target",
",",
"Pattern",
")",
":",
"target_location",
"=",
"self",
".",
"find",
"(",
"target",
")",
".",
"getTarget",
"(",
")",
"elif",
"isinstance",
"(",
"target",
",",
"basestring",
")",
":",
"target_location",
"=",
"self",
".",
"find",
"(",
"target",
")",
".",
"getTarget",
"(",
")",
"elif",
"isinstance",
"(",
"target",
",",
"Match",
")",
":",
"target_location",
"=",
"target",
".",
"getTarget",
"(",
")",
"elif",
"isinstance",
"(",
"target",
",",
"Region",
")",
":",
"target_location",
"=",
"target",
".",
"getCenter",
"(",
")",
"elif",
"isinstance",
"(",
"target",
",",
"Location",
")",
":",
"target_location",
"=",
"target",
"else",
":",
"raise",
"TypeError",
"(",
"\"hover expected Pattern, String, Match, Region, or Location object\"",
")",
"Mouse",
".",
"moveSpeed",
"(",
"target_location",
",",
"Settings",
".",
"MoveMouseDelay",
")"
] |
Moves the cursor to the target location
|
[
"Moves",
"the",
"cursor",
"to",
"the",
"target",
"location"
] |
7adadfacd7f45d81186710be992f5668b15399fe
|
https://github.com/glitchassassin/lackey/blob/7adadfacd7f45d81186710be992f5668b15399fe/lackey/RegionMatching.py#L785-L803
|
6,732
|
glitchassassin/lackey
|
lackey/RegionMatching.py
|
Region.drag
|
def drag(self, dragFrom=None):
""" Starts a dragDrop operation.
Moves the cursor to the target location and clicks the mouse in preparation to drag
a screen element """
if dragFrom is None:
dragFrom = self._lastMatch or self # Whichever one is not None
dragFromLocation = None
if isinstance(dragFrom, Pattern):
dragFromLocation = self.find(dragFrom).getTarget()
elif isinstance(dragFrom, basestring):
dragFromLocation = self.find(dragFrom).getTarget()
elif isinstance(dragFrom, Match):
dragFromLocation = dragFrom.getTarget()
elif isinstance(dragFrom, Region):
dragFromLocation = dragFrom.getCenter()
elif isinstance(dragFrom, Location):
dragFromLocation = dragFrom
else:
raise TypeError("drag expected dragFrom to be Pattern, String, Match, Region, or Location object")
Mouse.moveSpeed(dragFromLocation, Settings.MoveMouseDelay)
time.sleep(Settings.DelayBeforeMouseDown)
Mouse.buttonDown()
Debug.history("Began drag at {}".format(dragFromLocation))
|
python
|
def drag(self, dragFrom=None):
""" Starts a dragDrop operation.
Moves the cursor to the target location and clicks the mouse in preparation to drag
a screen element """
if dragFrom is None:
dragFrom = self._lastMatch or self # Whichever one is not None
dragFromLocation = None
if isinstance(dragFrom, Pattern):
dragFromLocation = self.find(dragFrom).getTarget()
elif isinstance(dragFrom, basestring):
dragFromLocation = self.find(dragFrom).getTarget()
elif isinstance(dragFrom, Match):
dragFromLocation = dragFrom.getTarget()
elif isinstance(dragFrom, Region):
dragFromLocation = dragFrom.getCenter()
elif isinstance(dragFrom, Location):
dragFromLocation = dragFrom
else:
raise TypeError("drag expected dragFrom to be Pattern, String, Match, Region, or Location object")
Mouse.moveSpeed(dragFromLocation, Settings.MoveMouseDelay)
time.sleep(Settings.DelayBeforeMouseDown)
Mouse.buttonDown()
Debug.history("Began drag at {}".format(dragFromLocation))
|
[
"def",
"drag",
"(",
"self",
",",
"dragFrom",
"=",
"None",
")",
":",
"if",
"dragFrom",
"is",
"None",
":",
"dragFrom",
"=",
"self",
".",
"_lastMatch",
"or",
"self",
"# Whichever one is not None",
"dragFromLocation",
"=",
"None",
"if",
"isinstance",
"(",
"dragFrom",
",",
"Pattern",
")",
":",
"dragFromLocation",
"=",
"self",
".",
"find",
"(",
"dragFrom",
")",
".",
"getTarget",
"(",
")",
"elif",
"isinstance",
"(",
"dragFrom",
",",
"basestring",
")",
":",
"dragFromLocation",
"=",
"self",
".",
"find",
"(",
"dragFrom",
")",
".",
"getTarget",
"(",
")",
"elif",
"isinstance",
"(",
"dragFrom",
",",
"Match",
")",
":",
"dragFromLocation",
"=",
"dragFrom",
".",
"getTarget",
"(",
")",
"elif",
"isinstance",
"(",
"dragFrom",
",",
"Region",
")",
":",
"dragFromLocation",
"=",
"dragFrom",
".",
"getCenter",
"(",
")",
"elif",
"isinstance",
"(",
"dragFrom",
",",
"Location",
")",
":",
"dragFromLocation",
"=",
"dragFrom",
"else",
":",
"raise",
"TypeError",
"(",
"\"drag expected dragFrom to be Pattern, String, Match, Region, or Location object\"",
")",
"Mouse",
".",
"moveSpeed",
"(",
"dragFromLocation",
",",
"Settings",
".",
"MoveMouseDelay",
")",
"time",
".",
"sleep",
"(",
"Settings",
".",
"DelayBeforeMouseDown",
")",
"Mouse",
".",
"buttonDown",
"(",
")",
"Debug",
".",
"history",
"(",
"\"Began drag at {}\"",
".",
"format",
"(",
"dragFromLocation",
")",
")"
] |
Starts a dragDrop operation.
Moves the cursor to the target location and clicks the mouse in preparation to drag
a screen element
|
[
"Starts",
"a",
"dragDrop",
"operation",
"."
] |
7adadfacd7f45d81186710be992f5668b15399fe
|
https://github.com/glitchassassin/lackey/blob/7adadfacd7f45d81186710be992f5668b15399fe/lackey/RegionMatching.py#L804-L827
|
6,733
|
glitchassassin/lackey
|
lackey/RegionMatching.py
|
Region.dropAt
|
def dropAt(self, dragTo=None, delay=None):
""" Completes a dragDrop operation
Moves the cursor to the target location, waits ``delay`` seconds, and releases the mouse
button """
if dragTo is None:
dragTo = self._lastMatch or self # Whichever one is not None
if isinstance(dragTo, Pattern):
dragToLocation = self.find(dragTo).getTarget()
elif isinstance(dragTo, basestring):
dragToLocation = self.find(dragTo).getTarget()
elif isinstance(dragTo, Match):
dragToLocation = dragTo.getTarget()
elif isinstance(dragTo, Region):
dragToLocation = dragTo.getCenter()
elif isinstance(dragTo, Location):
dragToLocation = dragTo
else:
raise TypeError("dragDrop expected dragTo to be Pattern, String, Match, Region, or Location object")
Mouse.moveSpeed(dragToLocation, Settings.MoveMouseDelay)
time.sleep(delay if delay is not None else Settings.DelayBeforeDrop)
Mouse.buttonUp()
Debug.history("Ended drag at {}".format(dragToLocation))
|
python
|
def dropAt(self, dragTo=None, delay=None):
""" Completes a dragDrop operation
Moves the cursor to the target location, waits ``delay`` seconds, and releases the mouse
button """
if dragTo is None:
dragTo = self._lastMatch or self # Whichever one is not None
if isinstance(dragTo, Pattern):
dragToLocation = self.find(dragTo).getTarget()
elif isinstance(dragTo, basestring):
dragToLocation = self.find(dragTo).getTarget()
elif isinstance(dragTo, Match):
dragToLocation = dragTo.getTarget()
elif isinstance(dragTo, Region):
dragToLocation = dragTo.getCenter()
elif isinstance(dragTo, Location):
dragToLocation = dragTo
else:
raise TypeError("dragDrop expected dragTo to be Pattern, String, Match, Region, or Location object")
Mouse.moveSpeed(dragToLocation, Settings.MoveMouseDelay)
time.sleep(delay if delay is not None else Settings.DelayBeforeDrop)
Mouse.buttonUp()
Debug.history("Ended drag at {}".format(dragToLocation))
|
[
"def",
"dropAt",
"(",
"self",
",",
"dragTo",
"=",
"None",
",",
"delay",
"=",
"None",
")",
":",
"if",
"dragTo",
"is",
"None",
":",
"dragTo",
"=",
"self",
".",
"_lastMatch",
"or",
"self",
"# Whichever one is not None",
"if",
"isinstance",
"(",
"dragTo",
",",
"Pattern",
")",
":",
"dragToLocation",
"=",
"self",
".",
"find",
"(",
"dragTo",
")",
".",
"getTarget",
"(",
")",
"elif",
"isinstance",
"(",
"dragTo",
",",
"basestring",
")",
":",
"dragToLocation",
"=",
"self",
".",
"find",
"(",
"dragTo",
")",
".",
"getTarget",
"(",
")",
"elif",
"isinstance",
"(",
"dragTo",
",",
"Match",
")",
":",
"dragToLocation",
"=",
"dragTo",
".",
"getTarget",
"(",
")",
"elif",
"isinstance",
"(",
"dragTo",
",",
"Region",
")",
":",
"dragToLocation",
"=",
"dragTo",
".",
"getCenter",
"(",
")",
"elif",
"isinstance",
"(",
"dragTo",
",",
"Location",
")",
":",
"dragToLocation",
"=",
"dragTo",
"else",
":",
"raise",
"TypeError",
"(",
"\"dragDrop expected dragTo to be Pattern, String, Match, Region, or Location object\"",
")",
"Mouse",
".",
"moveSpeed",
"(",
"dragToLocation",
",",
"Settings",
".",
"MoveMouseDelay",
")",
"time",
".",
"sleep",
"(",
"delay",
"if",
"delay",
"is",
"not",
"None",
"else",
"Settings",
".",
"DelayBeforeDrop",
")",
"Mouse",
".",
"buttonUp",
"(",
")",
"Debug",
".",
"history",
"(",
"\"Ended drag at {}\"",
".",
"format",
"(",
"dragToLocation",
")",
")"
] |
Completes a dragDrop operation
Moves the cursor to the target location, waits ``delay`` seconds, and releases the mouse
button
|
[
"Completes",
"a",
"dragDrop",
"operation"
] |
7adadfacd7f45d81186710be992f5668b15399fe
|
https://github.com/glitchassassin/lackey/blob/7adadfacd7f45d81186710be992f5668b15399fe/lackey/RegionMatching.py#L828-L851
|
6,734
|
glitchassassin/lackey
|
lackey/RegionMatching.py
|
Region.dragDrop
|
def dragDrop(self, target, target2=None, modifiers=""):
""" Performs a dragDrop operation.
Holds down the mouse button on ``dragFrom``, moves the mouse to ``dragTo``, and releases
the mouse button.
``modifiers`` may be a typeKeys() compatible string. The specified keys will be held
during the drag-drop operation.
"""
if modifiers != "":
keyboard.keyDown(modifiers)
if target2 is None:
dragFrom = self._lastMatch
dragTo = target
else:
dragFrom = target
dragTo = target2
self.drag(dragFrom)
time.sleep(Settings.DelayBeforeDrag)
self.dropAt(dragTo)
if modifiers != "":
keyboard.keyUp(modifiers)
|
python
|
def dragDrop(self, target, target2=None, modifiers=""):
""" Performs a dragDrop operation.
Holds down the mouse button on ``dragFrom``, moves the mouse to ``dragTo``, and releases
the mouse button.
``modifiers`` may be a typeKeys() compatible string. The specified keys will be held
during the drag-drop operation.
"""
if modifiers != "":
keyboard.keyDown(modifiers)
if target2 is None:
dragFrom = self._lastMatch
dragTo = target
else:
dragFrom = target
dragTo = target2
self.drag(dragFrom)
time.sleep(Settings.DelayBeforeDrag)
self.dropAt(dragTo)
if modifiers != "":
keyboard.keyUp(modifiers)
|
[
"def",
"dragDrop",
"(",
"self",
",",
"target",
",",
"target2",
"=",
"None",
",",
"modifiers",
"=",
"\"\"",
")",
":",
"if",
"modifiers",
"!=",
"\"\"",
":",
"keyboard",
".",
"keyDown",
"(",
"modifiers",
")",
"if",
"target2",
"is",
"None",
":",
"dragFrom",
"=",
"self",
".",
"_lastMatch",
"dragTo",
"=",
"target",
"else",
":",
"dragFrom",
"=",
"target",
"dragTo",
"=",
"target2",
"self",
".",
"drag",
"(",
"dragFrom",
")",
"time",
".",
"sleep",
"(",
"Settings",
".",
"DelayBeforeDrag",
")",
"self",
".",
"dropAt",
"(",
"dragTo",
")",
"if",
"modifiers",
"!=",
"\"\"",
":",
"keyboard",
".",
"keyUp",
"(",
"modifiers",
")"
] |
Performs a dragDrop operation.
Holds down the mouse button on ``dragFrom``, moves the mouse to ``dragTo``, and releases
the mouse button.
``modifiers`` may be a typeKeys() compatible string. The specified keys will be held
during the drag-drop operation.
|
[
"Performs",
"a",
"dragDrop",
"operation",
"."
] |
7adadfacd7f45d81186710be992f5668b15399fe
|
https://github.com/glitchassassin/lackey/blob/7adadfacd7f45d81186710be992f5668b15399fe/lackey/RegionMatching.py#L852-L876
|
6,735
|
glitchassassin/lackey
|
lackey/RegionMatching.py
|
Region.mouseMove
|
def mouseMove(self, PSRML=None, dy=0):
""" Low-level mouse actions """
if PSRML is None:
PSRML = self._lastMatch or self # Whichever one is not None
if isinstance(PSRML, Pattern):
move_location = self.find(PSRML).getTarget()
elif isinstance(PSRML, basestring):
move_location = self.find(PSRML).getTarget()
elif isinstance(PSRML, Match):
move_location = PSRML.getTarget()
elif isinstance(PSRML, Region):
move_location = PSRML.getCenter()
elif isinstance(PSRML, Location):
move_location = PSRML
elif isinstance(PSRML, int):
# Assume called as mouseMove(dx, dy)
offset = Location(PSRML, dy)
move_location = Mouse.getPos().offset(offset)
else:
raise TypeError("doubleClick expected Pattern, String, Match, Region, or Location object")
Mouse.moveSpeed(move_location)
|
python
|
def mouseMove(self, PSRML=None, dy=0):
""" Low-level mouse actions """
if PSRML is None:
PSRML = self._lastMatch or self # Whichever one is not None
if isinstance(PSRML, Pattern):
move_location = self.find(PSRML).getTarget()
elif isinstance(PSRML, basestring):
move_location = self.find(PSRML).getTarget()
elif isinstance(PSRML, Match):
move_location = PSRML.getTarget()
elif isinstance(PSRML, Region):
move_location = PSRML.getCenter()
elif isinstance(PSRML, Location):
move_location = PSRML
elif isinstance(PSRML, int):
# Assume called as mouseMove(dx, dy)
offset = Location(PSRML, dy)
move_location = Mouse.getPos().offset(offset)
else:
raise TypeError("doubleClick expected Pattern, String, Match, Region, or Location object")
Mouse.moveSpeed(move_location)
|
[
"def",
"mouseMove",
"(",
"self",
",",
"PSRML",
"=",
"None",
",",
"dy",
"=",
"0",
")",
":",
"if",
"PSRML",
"is",
"None",
":",
"PSRML",
"=",
"self",
".",
"_lastMatch",
"or",
"self",
"# Whichever one is not None",
"if",
"isinstance",
"(",
"PSRML",
",",
"Pattern",
")",
":",
"move_location",
"=",
"self",
".",
"find",
"(",
"PSRML",
")",
".",
"getTarget",
"(",
")",
"elif",
"isinstance",
"(",
"PSRML",
",",
"basestring",
")",
":",
"move_location",
"=",
"self",
".",
"find",
"(",
"PSRML",
")",
".",
"getTarget",
"(",
")",
"elif",
"isinstance",
"(",
"PSRML",
",",
"Match",
")",
":",
"move_location",
"=",
"PSRML",
".",
"getTarget",
"(",
")",
"elif",
"isinstance",
"(",
"PSRML",
",",
"Region",
")",
":",
"move_location",
"=",
"PSRML",
".",
"getCenter",
"(",
")",
"elif",
"isinstance",
"(",
"PSRML",
",",
"Location",
")",
":",
"move_location",
"=",
"PSRML",
"elif",
"isinstance",
"(",
"PSRML",
",",
"int",
")",
":",
"# Assume called as mouseMove(dx, dy)",
"offset",
"=",
"Location",
"(",
"PSRML",
",",
"dy",
")",
"move_location",
"=",
"Mouse",
".",
"getPos",
"(",
")",
".",
"offset",
"(",
"offset",
")",
"else",
":",
"raise",
"TypeError",
"(",
"\"doubleClick expected Pattern, String, Match, Region, or Location object\"",
")",
"Mouse",
".",
"moveSpeed",
"(",
"move_location",
")"
] |
Low-level mouse actions
|
[
"Low",
"-",
"level",
"mouse",
"actions"
] |
7adadfacd7f45d81186710be992f5668b15399fe
|
https://github.com/glitchassassin/lackey/blob/7adadfacd7f45d81186710be992f5668b15399fe/lackey/RegionMatching.py#L959-L979
|
6,736
|
glitchassassin/lackey
|
lackey/RegionMatching.py
|
Region.isRegionValid
|
def isRegionValid(self):
""" Returns false if the whole region is not even partially inside any screen, otherwise true """
screens = PlatformManager.getScreenDetails()
for screen in screens:
s_x, s_y, s_w, s_h = screen["rect"]
if self.x+self.w >= s_x and s_x+s_w >= self.x and self.y+self.h >= s_y and s_y+s_h >= self.y:
# Rects overlap
return True
return False
|
python
|
def isRegionValid(self):
""" Returns false if the whole region is not even partially inside any screen, otherwise true """
screens = PlatformManager.getScreenDetails()
for screen in screens:
s_x, s_y, s_w, s_h = screen["rect"]
if self.x+self.w >= s_x and s_x+s_w >= self.x and self.y+self.h >= s_y and s_y+s_h >= self.y:
# Rects overlap
return True
return False
|
[
"def",
"isRegionValid",
"(",
"self",
")",
":",
"screens",
"=",
"PlatformManager",
".",
"getScreenDetails",
"(",
")",
"for",
"screen",
"in",
"screens",
":",
"s_x",
",",
"s_y",
",",
"s_w",
",",
"s_h",
"=",
"screen",
"[",
"\"rect\"",
"]",
"if",
"self",
".",
"x",
"+",
"self",
".",
"w",
">=",
"s_x",
"and",
"s_x",
"+",
"s_w",
">=",
"self",
".",
"x",
"and",
"self",
".",
"y",
"+",
"self",
".",
"h",
">=",
"s_y",
"and",
"s_y",
"+",
"s_h",
">=",
"self",
".",
"y",
":",
"# Rects overlap",
"return",
"True",
"return",
"False"
] |
Returns false if the whole region is not even partially inside any screen, otherwise true
|
[
"Returns",
"false",
"if",
"the",
"whole",
"region",
"is",
"not",
"even",
"partially",
"inside",
"any",
"screen",
"otherwise",
"true"
] |
7adadfacd7f45d81186710be992f5668b15399fe
|
https://github.com/glitchassassin/lackey/blob/7adadfacd7f45d81186710be992f5668b15399fe/lackey/RegionMatching.py#L1017-L1025
|
6,737
|
glitchassassin/lackey
|
lackey/RegionMatching.py
|
Region.clipRegionToScreen
|
def clipRegionToScreen(self):
""" Returns the part of the region that is visible on a screen
If the region equals to all visible screens, returns Screen(-1).
If the region is visible on multiple screens, returns the screen with the smallest ID.
Returns None if the region is outside the screen.
"""
if not self.isRegionValid():
return None
screens = PlatformManager.getScreenDetails()
total_x, total_y, total_w, total_h = Screen(-1).getBounds()
containing_screen = None
for screen in screens:
s_x, s_y, s_w, s_h = screen["rect"]
if self.x >= s_x and self.x+self.w <= s_x+s_w and self.y >= s_y and self.y+self.h <= s_y+s_h:
# Region completely inside screen
return self
elif self.x+self.w <= s_x or s_x+s_w <= self.x or self.y+self.h <= s_y or s_y+s_h <= self.y:
# Region completely outside screen
continue
elif self.x == total_x and self.y == total_y and self.w == total_w and self.h == total_h:
# Region equals all screens, Screen(-1)
return self
else:
# Region partially inside screen
x = max(self.x, s_x)
y = max(self.y, s_y)
w = min(self.w, s_w)
h = min(self.h, s_h)
return Region(x, y, w, h)
return None
|
python
|
def clipRegionToScreen(self):
""" Returns the part of the region that is visible on a screen
If the region equals to all visible screens, returns Screen(-1).
If the region is visible on multiple screens, returns the screen with the smallest ID.
Returns None if the region is outside the screen.
"""
if not self.isRegionValid():
return None
screens = PlatformManager.getScreenDetails()
total_x, total_y, total_w, total_h = Screen(-1).getBounds()
containing_screen = None
for screen in screens:
s_x, s_y, s_w, s_h = screen["rect"]
if self.x >= s_x and self.x+self.w <= s_x+s_w and self.y >= s_y and self.y+self.h <= s_y+s_h:
# Region completely inside screen
return self
elif self.x+self.w <= s_x or s_x+s_w <= self.x or self.y+self.h <= s_y or s_y+s_h <= self.y:
# Region completely outside screen
continue
elif self.x == total_x and self.y == total_y and self.w == total_w and self.h == total_h:
# Region equals all screens, Screen(-1)
return self
else:
# Region partially inside screen
x = max(self.x, s_x)
y = max(self.y, s_y)
w = min(self.w, s_w)
h = min(self.h, s_h)
return Region(x, y, w, h)
return None
|
[
"def",
"clipRegionToScreen",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"isRegionValid",
"(",
")",
":",
"return",
"None",
"screens",
"=",
"PlatformManager",
".",
"getScreenDetails",
"(",
")",
"total_x",
",",
"total_y",
",",
"total_w",
",",
"total_h",
"=",
"Screen",
"(",
"-",
"1",
")",
".",
"getBounds",
"(",
")",
"containing_screen",
"=",
"None",
"for",
"screen",
"in",
"screens",
":",
"s_x",
",",
"s_y",
",",
"s_w",
",",
"s_h",
"=",
"screen",
"[",
"\"rect\"",
"]",
"if",
"self",
".",
"x",
">=",
"s_x",
"and",
"self",
".",
"x",
"+",
"self",
".",
"w",
"<=",
"s_x",
"+",
"s_w",
"and",
"self",
".",
"y",
">=",
"s_y",
"and",
"self",
".",
"y",
"+",
"self",
".",
"h",
"<=",
"s_y",
"+",
"s_h",
":",
"# Region completely inside screen",
"return",
"self",
"elif",
"self",
".",
"x",
"+",
"self",
".",
"w",
"<=",
"s_x",
"or",
"s_x",
"+",
"s_w",
"<=",
"self",
".",
"x",
"or",
"self",
".",
"y",
"+",
"self",
".",
"h",
"<=",
"s_y",
"or",
"s_y",
"+",
"s_h",
"<=",
"self",
".",
"y",
":",
"# Region completely outside screen",
"continue",
"elif",
"self",
".",
"x",
"==",
"total_x",
"and",
"self",
".",
"y",
"==",
"total_y",
"and",
"self",
".",
"w",
"==",
"total_w",
"and",
"self",
".",
"h",
"==",
"total_h",
":",
"# Region equals all screens, Screen(-1)",
"return",
"self",
"else",
":",
"# Region partially inside screen",
"x",
"=",
"max",
"(",
"self",
".",
"x",
",",
"s_x",
")",
"y",
"=",
"max",
"(",
"self",
".",
"y",
",",
"s_y",
")",
"w",
"=",
"min",
"(",
"self",
".",
"w",
",",
"s_w",
")",
"h",
"=",
"min",
"(",
"self",
".",
"h",
",",
"s_h",
")",
"return",
"Region",
"(",
"x",
",",
"y",
",",
"w",
",",
"h",
")",
"return",
"None"
] |
Returns the part of the region that is visible on a screen
If the region equals to all visible screens, returns Screen(-1).
If the region is visible on multiple screens, returns the screen with the smallest ID.
Returns None if the region is outside the screen.
|
[
"Returns",
"the",
"part",
"of",
"the",
"region",
"that",
"is",
"visible",
"on",
"a",
"screen"
] |
7adadfacd7f45d81186710be992f5668b15399fe
|
https://github.com/glitchassassin/lackey/blob/7adadfacd7f45d81186710be992f5668b15399fe/lackey/RegionMatching.py#L1027-L1057
|
6,738
|
glitchassassin/lackey
|
lackey/RegionMatching.py
|
Region.get
|
def get(self, part):
""" Returns a section of the region as a new region
Accepts partitioning constants, e.g. Region.NORTH, Region.NORTH_WEST, etc.
Also accepts an int 200-999:
* First digit: Raster (*n* rows by *n* columns)
* Second digit: Row index (if equal to raster, gets the whole row)
* Third digit: Column index (if equal to raster, gets the whole column)
Region.get(522) will use a raster of 5 rows and 5 columns and return
the cell in the middle.
Region.get(525) will use a raster of 5 rows and 5 columns and return the row in the middle.
"""
if part == self.MID_VERTICAL:
return Region(self.x+(self.w/4), y, self.w/2, self.h)
elif part == self.MID_HORIZONTAL:
return Region(self.x, self.y+(self.h/4), self.w, self.h/2)
elif part == self.MID_BIG:
return Region(self.x+(self.w/4), self.y+(self.h/4), self.w/2, self.h/2)
elif isinstance(part, int) and part >= 200 and part <= 999:
raster, row, column = str(part)
self.setRaster(raster, raster)
if row == raster and column == raster:
return self
elif row == raster:
return self.getCol(column)
elif column == raster:
return self.getRow(row)
else:
return self.getCell(row,column)
else:
return self
|
python
|
def get(self, part):
""" Returns a section of the region as a new region
Accepts partitioning constants, e.g. Region.NORTH, Region.NORTH_WEST, etc.
Also accepts an int 200-999:
* First digit: Raster (*n* rows by *n* columns)
* Second digit: Row index (if equal to raster, gets the whole row)
* Third digit: Column index (if equal to raster, gets the whole column)
Region.get(522) will use a raster of 5 rows and 5 columns and return
the cell in the middle.
Region.get(525) will use a raster of 5 rows and 5 columns and return the row in the middle.
"""
if part == self.MID_VERTICAL:
return Region(self.x+(self.w/4), y, self.w/2, self.h)
elif part == self.MID_HORIZONTAL:
return Region(self.x, self.y+(self.h/4), self.w, self.h/2)
elif part == self.MID_BIG:
return Region(self.x+(self.w/4), self.y+(self.h/4), self.w/2, self.h/2)
elif isinstance(part, int) and part >= 200 and part <= 999:
raster, row, column = str(part)
self.setRaster(raster, raster)
if row == raster and column == raster:
return self
elif row == raster:
return self.getCol(column)
elif column == raster:
return self.getRow(row)
else:
return self.getCell(row,column)
else:
return self
|
[
"def",
"get",
"(",
"self",
",",
"part",
")",
":",
"if",
"part",
"==",
"self",
".",
"MID_VERTICAL",
":",
"return",
"Region",
"(",
"self",
".",
"x",
"+",
"(",
"self",
".",
"w",
"/",
"4",
")",
",",
"y",
",",
"self",
".",
"w",
"/",
"2",
",",
"self",
".",
"h",
")",
"elif",
"part",
"==",
"self",
".",
"MID_HORIZONTAL",
":",
"return",
"Region",
"(",
"self",
".",
"x",
",",
"self",
".",
"y",
"+",
"(",
"self",
".",
"h",
"/",
"4",
")",
",",
"self",
".",
"w",
",",
"self",
".",
"h",
"/",
"2",
")",
"elif",
"part",
"==",
"self",
".",
"MID_BIG",
":",
"return",
"Region",
"(",
"self",
".",
"x",
"+",
"(",
"self",
".",
"w",
"/",
"4",
")",
",",
"self",
".",
"y",
"+",
"(",
"self",
".",
"h",
"/",
"4",
")",
",",
"self",
".",
"w",
"/",
"2",
",",
"self",
".",
"h",
"/",
"2",
")",
"elif",
"isinstance",
"(",
"part",
",",
"int",
")",
"and",
"part",
">=",
"200",
"and",
"part",
"<=",
"999",
":",
"raster",
",",
"row",
",",
"column",
"=",
"str",
"(",
"part",
")",
"self",
".",
"setRaster",
"(",
"raster",
",",
"raster",
")",
"if",
"row",
"==",
"raster",
"and",
"column",
"==",
"raster",
":",
"return",
"self",
"elif",
"row",
"==",
"raster",
":",
"return",
"self",
".",
"getCol",
"(",
"column",
")",
"elif",
"column",
"==",
"raster",
":",
"return",
"self",
".",
"getRow",
"(",
"row",
")",
"else",
":",
"return",
"self",
".",
"getCell",
"(",
"row",
",",
"column",
")",
"else",
":",
"return",
"self"
] |
Returns a section of the region as a new region
Accepts partitioning constants, e.g. Region.NORTH, Region.NORTH_WEST, etc.
Also accepts an int 200-999:
* First digit: Raster (*n* rows by *n* columns)
* Second digit: Row index (if equal to raster, gets the whole row)
* Third digit: Column index (if equal to raster, gets the whole column)
Region.get(522) will use a raster of 5 rows and 5 columns and return
the cell in the middle.
Region.get(525) will use a raster of 5 rows and 5 columns and return the row in the middle.
|
[
"Returns",
"a",
"section",
"of",
"the",
"region",
"as",
"a",
"new",
"region"
] |
7adadfacd7f45d81186710be992f5668b15399fe
|
https://github.com/glitchassassin/lackey/blob/7adadfacd7f45d81186710be992f5668b15399fe/lackey/RegionMatching.py#L1160-L1192
|
6,739
|
glitchassassin/lackey
|
lackey/RegionMatching.py
|
Region.setCenter
|
def setCenter(self, loc):
""" Move this region so it is centered on ``loc`` """
offset = self.getCenter().getOffset(loc) # Calculate offset from current center
return self.setLocation(self.getTopLeft().offset(offset)) # Move top left corner by the same offset
|
python
|
def setCenter(self, loc):
""" Move this region so it is centered on ``loc`` """
offset = self.getCenter().getOffset(loc) # Calculate offset from current center
return self.setLocation(self.getTopLeft().offset(offset)) # Move top left corner by the same offset
|
[
"def",
"setCenter",
"(",
"self",
",",
"loc",
")",
":",
"offset",
"=",
"self",
".",
"getCenter",
"(",
")",
".",
"getOffset",
"(",
"loc",
")",
"# Calculate offset from current center",
"return",
"self",
".",
"setLocation",
"(",
"self",
".",
"getTopLeft",
"(",
")",
".",
"offset",
"(",
"offset",
")",
")",
"# Move top left corner by the same offset"
] |
Move this region so it is centered on ``loc``
|
[
"Move",
"this",
"region",
"so",
"it",
"is",
"centered",
"on",
"loc"
] |
7adadfacd7f45d81186710be992f5668b15399fe
|
https://github.com/glitchassassin/lackey/blob/7adadfacd7f45d81186710be992f5668b15399fe/lackey/RegionMatching.py#L1226-L1229
|
6,740
|
glitchassassin/lackey
|
lackey/RegionMatching.py
|
Region.setTopRight
|
def setTopRight(self, loc):
""" Move this region so its top right corner is on ``loc`` """
offset = self.getTopRight().getOffset(loc) # Calculate offset from current top right
return self.setLocation(self.getTopLeft().offset(offset)) # Move top left corner by the same offset
|
python
|
def setTopRight(self, loc):
""" Move this region so its top right corner is on ``loc`` """
offset = self.getTopRight().getOffset(loc) # Calculate offset from current top right
return self.setLocation(self.getTopLeft().offset(offset)) # Move top left corner by the same offset
|
[
"def",
"setTopRight",
"(",
"self",
",",
"loc",
")",
":",
"offset",
"=",
"self",
".",
"getTopRight",
"(",
")",
".",
"getOffset",
"(",
"loc",
")",
"# Calculate offset from current top right",
"return",
"self",
".",
"setLocation",
"(",
"self",
".",
"getTopLeft",
"(",
")",
".",
"offset",
"(",
"offset",
")",
")",
"# Move top left corner by the same offset"
] |
Move this region so its top right corner is on ``loc``
|
[
"Move",
"this",
"region",
"so",
"its",
"top",
"right",
"corner",
"is",
"on",
"loc"
] |
7adadfacd7f45d81186710be992f5668b15399fe
|
https://github.com/glitchassassin/lackey/blob/7adadfacd7f45d81186710be992f5668b15399fe/lackey/RegionMatching.py#L1233-L1236
|
6,741
|
glitchassassin/lackey
|
lackey/RegionMatching.py
|
Region.setBottomLeft
|
def setBottomLeft(self, loc):
""" Move this region so its bottom left corner is on ``loc`` """
offset = self.getBottomLeft().getOffset(loc) # Calculate offset from current bottom left
return self.setLocation(self.getTopLeft().offset(offset)) # Move top left corner by the same offset
|
python
|
def setBottomLeft(self, loc):
""" Move this region so its bottom left corner is on ``loc`` """
offset = self.getBottomLeft().getOffset(loc) # Calculate offset from current bottom left
return self.setLocation(self.getTopLeft().offset(offset)) # Move top left corner by the same offset
|
[
"def",
"setBottomLeft",
"(",
"self",
",",
"loc",
")",
":",
"offset",
"=",
"self",
".",
"getBottomLeft",
"(",
")",
".",
"getOffset",
"(",
"loc",
")",
"# Calculate offset from current bottom left",
"return",
"self",
".",
"setLocation",
"(",
"self",
".",
"getTopLeft",
"(",
")",
".",
"offset",
"(",
"offset",
")",
")",
"# Move top left corner by the same offset"
] |
Move this region so its bottom left corner is on ``loc``
|
[
"Move",
"this",
"region",
"so",
"its",
"bottom",
"left",
"corner",
"is",
"on",
"loc"
] |
7adadfacd7f45d81186710be992f5668b15399fe
|
https://github.com/glitchassassin/lackey/blob/7adadfacd7f45d81186710be992f5668b15399fe/lackey/RegionMatching.py#L1237-L1240
|
6,742
|
glitchassassin/lackey
|
lackey/RegionMatching.py
|
Region.setBottomRight
|
def setBottomRight(self, loc):
""" Move this region so its bottom right corner is on ``loc`` """
offset = self.getBottomRight().getOffset(loc) # Calculate offset from current bottom right
return self.setLocation(self.getTopLeft().offset(offset)) # Move top left corner by the same offset
|
python
|
def setBottomRight(self, loc):
""" Move this region so its bottom right corner is on ``loc`` """
offset = self.getBottomRight().getOffset(loc) # Calculate offset from current bottom right
return self.setLocation(self.getTopLeft().offset(offset)) # Move top left corner by the same offset
|
[
"def",
"setBottomRight",
"(",
"self",
",",
"loc",
")",
":",
"offset",
"=",
"self",
".",
"getBottomRight",
"(",
")",
".",
"getOffset",
"(",
"loc",
")",
"# Calculate offset from current bottom right",
"return",
"self",
".",
"setLocation",
"(",
"self",
".",
"getTopLeft",
"(",
")",
".",
"offset",
"(",
"offset",
")",
")",
"# Move top left corner by the same offset"
] |
Move this region so its bottom right corner is on ``loc``
|
[
"Move",
"this",
"region",
"so",
"its",
"bottom",
"right",
"corner",
"is",
"on",
"loc"
] |
7adadfacd7f45d81186710be992f5668b15399fe
|
https://github.com/glitchassassin/lackey/blob/7adadfacd7f45d81186710be992f5668b15399fe/lackey/RegionMatching.py#L1241-L1244
|
6,743
|
glitchassassin/lackey
|
lackey/RegionMatching.py
|
Region.setSize
|
def setSize(self, w, h):
""" Sets the new size of the region """
self.setW(w)
self.setH(h)
return self
|
python
|
def setSize(self, w, h):
""" Sets the new size of the region """
self.setW(w)
self.setH(h)
return self
|
[
"def",
"setSize",
"(",
"self",
",",
"w",
",",
"h",
")",
":",
"self",
".",
"setW",
"(",
"w",
")",
"self",
".",
"setH",
"(",
"h",
")",
"return",
"self"
] |
Sets the new size of the region
|
[
"Sets",
"the",
"new",
"size",
"of",
"the",
"region"
] |
7adadfacd7f45d81186710be992f5668b15399fe
|
https://github.com/glitchassassin/lackey/blob/7adadfacd7f45d81186710be992f5668b15399fe/lackey/RegionMatching.py#L1245-L1249
|
6,744
|
glitchassassin/lackey
|
lackey/RegionMatching.py
|
Region.saveScreenCapture
|
def saveScreenCapture(self, path=None, name=None):
""" Saves the region's bitmap """
bitmap = self.getBitmap()
target_file = None
if path is None and name is None:
_, target_file = tempfile.mkstemp(".png")
elif name is None:
_, tpath = tempfile.mkstemp(".png")
target_file = os.path.join(path, tfile)
else:
target_file = os.path.join(path, name+".png")
cv2.imwrite(target_file, bitmap)
return target_file
|
python
|
def saveScreenCapture(self, path=None, name=None):
""" Saves the region's bitmap """
bitmap = self.getBitmap()
target_file = None
if path is None and name is None:
_, target_file = tempfile.mkstemp(".png")
elif name is None:
_, tpath = tempfile.mkstemp(".png")
target_file = os.path.join(path, tfile)
else:
target_file = os.path.join(path, name+".png")
cv2.imwrite(target_file, bitmap)
return target_file
|
[
"def",
"saveScreenCapture",
"(",
"self",
",",
"path",
"=",
"None",
",",
"name",
"=",
"None",
")",
":",
"bitmap",
"=",
"self",
".",
"getBitmap",
"(",
")",
"target_file",
"=",
"None",
"if",
"path",
"is",
"None",
"and",
"name",
"is",
"None",
":",
"_",
",",
"target_file",
"=",
"tempfile",
".",
"mkstemp",
"(",
"\".png\"",
")",
"elif",
"name",
"is",
"None",
":",
"_",
",",
"tpath",
"=",
"tempfile",
".",
"mkstemp",
"(",
"\".png\"",
")",
"target_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"tfile",
")",
"else",
":",
"target_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"name",
"+",
"\".png\"",
")",
"cv2",
".",
"imwrite",
"(",
"target_file",
",",
"bitmap",
")",
"return",
"target_file"
] |
Saves the region's bitmap
|
[
"Saves",
"the",
"region",
"s",
"bitmap"
] |
7adadfacd7f45d81186710be992f5668b15399fe
|
https://github.com/glitchassassin/lackey/blob/7adadfacd7f45d81186710be992f5668b15399fe/lackey/RegionMatching.py#L1277-L1289
|
6,745
|
glitchassassin/lackey
|
lackey/RegionMatching.py
|
Region.saveLastScreenImage
|
def saveLastScreenImage(self):
""" Saves the last image taken on this region's screen to a temporary file """
bitmap = self.getLastScreenImage()
_, target_file = tempfile.mkstemp(".png")
cv2.imwrite(target_file, bitmap)
|
python
|
def saveLastScreenImage(self):
""" Saves the last image taken on this region's screen to a temporary file """
bitmap = self.getLastScreenImage()
_, target_file = tempfile.mkstemp(".png")
cv2.imwrite(target_file, bitmap)
|
[
"def",
"saveLastScreenImage",
"(",
"self",
")",
":",
"bitmap",
"=",
"self",
".",
"getLastScreenImage",
"(",
")",
"_",
",",
"target_file",
"=",
"tempfile",
".",
"mkstemp",
"(",
"\".png\"",
")",
"cv2",
".",
"imwrite",
"(",
"target_file",
",",
"bitmap",
")"
] |
Saves the last image taken on this region's screen to a temporary file
|
[
"Saves",
"the",
"last",
"image",
"taken",
"on",
"this",
"region",
"s",
"screen",
"to",
"a",
"temporary",
"file"
] |
7adadfacd7f45d81186710be992f5668b15399fe
|
https://github.com/glitchassassin/lackey/blob/7adadfacd7f45d81186710be992f5668b15399fe/lackey/RegionMatching.py#L1293-L1297
|
6,746
|
glitchassassin/lackey
|
lackey/RegionMatching.py
|
Region.onChange
|
def onChange(self, min_changed_pixels=None, handler=None):
""" Registers an event to call ``handler`` when at least ``min_changed_pixels``
change in this region.
(Default for min_changed_pixels is set in Settings.ObserveMinChangedPixels)
The ``handler`` function should take one parameter, an ObserveEvent object
(see below). This event is ignored in the future unless the handler calls
the repeat() method on the provided ObserveEvent object.
Returns the event's ID as a string.
"""
if isinstance(min_changed_pixels, int) and (callable(handler) or handler is None):
return self._observer.register_event(
"CHANGE",
pattern=(min_changed_pixels, self.getBitmap()),
handler=handler)
elif (callable(min_changed_pixels) or min_changed_pixels is None) and (callable(handler) or handler is None):
handler = min_changed_pixels or handler
return self._observer.register_event(
"CHANGE",
pattern=(Settings.ObserveMinChangedPixels, self.getBitmap()),
handler=handler)
else:
raise ValueError("Unsupported arguments for onChange method")
|
python
|
def onChange(self, min_changed_pixels=None, handler=None):
""" Registers an event to call ``handler`` when at least ``min_changed_pixels``
change in this region.
(Default for min_changed_pixels is set in Settings.ObserveMinChangedPixels)
The ``handler`` function should take one parameter, an ObserveEvent object
(see below). This event is ignored in the future unless the handler calls
the repeat() method on the provided ObserveEvent object.
Returns the event's ID as a string.
"""
if isinstance(min_changed_pixels, int) and (callable(handler) or handler is None):
return self._observer.register_event(
"CHANGE",
pattern=(min_changed_pixels, self.getBitmap()),
handler=handler)
elif (callable(min_changed_pixels) or min_changed_pixels is None) and (callable(handler) or handler is None):
handler = min_changed_pixels or handler
return self._observer.register_event(
"CHANGE",
pattern=(Settings.ObserveMinChangedPixels, self.getBitmap()),
handler=handler)
else:
raise ValueError("Unsupported arguments for onChange method")
|
[
"def",
"onChange",
"(",
"self",
",",
"min_changed_pixels",
"=",
"None",
",",
"handler",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"min_changed_pixels",
",",
"int",
")",
"and",
"(",
"callable",
"(",
"handler",
")",
"or",
"handler",
"is",
"None",
")",
":",
"return",
"self",
".",
"_observer",
".",
"register_event",
"(",
"\"CHANGE\"",
",",
"pattern",
"=",
"(",
"min_changed_pixels",
",",
"self",
".",
"getBitmap",
"(",
")",
")",
",",
"handler",
"=",
"handler",
")",
"elif",
"(",
"callable",
"(",
"min_changed_pixels",
")",
"or",
"min_changed_pixels",
"is",
"None",
")",
"and",
"(",
"callable",
"(",
"handler",
")",
"or",
"handler",
"is",
"None",
")",
":",
"handler",
"=",
"min_changed_pixels",
"or",
"handler",
"return",
"self",
".",
"_observer",
".",
"register_event",
"(",
"\"CHANGE\"",
",",
"pattern",
"=",
"(",
"Settings",
".",
"ObserveMinChangedPixels",
",",
"self",
".",
"getBitmap",
"(",
")",
")",
",",
"handler",
"=",
"handler",
")",
"else",
":",
"raise",
"ValueError",
"(",
"\"Unsupported arguments for onChange method\"",
")"
] |
Registers an event to call ``handler`` when at least ``min_changed_pixels``
change in this region.
(Default for min_changed_pixels is set in Settings.ObserveMinChangedPixels)
The ``handler`` function should take one parameter, an ObserveEvent object
(see below). This event is ignored in the future unless the handler calls
the repeat() method on the provided ObserveEvent object.
Returns the event's ID as a string.
|
[
"Registers",
"an",
"event",
"to",
"call",
"handler",
"when",
"at",
"least",
"min_changed_pixels",
"change",
"in",
"this",
"region",
"."
] |
7adadfacd7f45d81186710be992f5668b15399fe
|
https://github.com/glitchassassin/lackey/blob/7adadfacd7f45d81186710be992f5668b15399fe/lackey/RegionMatching.py#L1400-L1424
|
6,747
|
glitchassassin/lackey
|
lackey/RegionMatching.py
|
Region.isChanged
|
def isChanged(self, min_changed_pixels, screen_state):
""" Returns true if at least ``min_changed_pixels`` are different between
``screen_state`` and the current state.
"""
r = self.clipRegionToScreen()
current_state = r.getBitmap()
diff = numpy.subtract(current_state, screen_state)
return (numpy.count_nonzero(diff) >= min_changed_pixels)
|
python
|
def isChanged(self, min_changed_pixels, screen_state):
""" Returns true if at least ``min_changed_pixels`` are different between
``screen_state`` and the current state.
"""
r = self.clipRegionToScreen()
current_state = r.getBitmap()
diff = numpy.subtract(current_state, screen_state)
return (numpy.count_nonzero(diff) >= min_changed_pixels)
|
[
"def",
"isChanged",
"(",
"self",
",",
"min_changed_pixels",
",",
"screen_state",
")",
":",
"r",
"=",
"self",
".",
"clipRegionToScreen",
"(",
")",
"current_state",
"=",
"r",
".",
"getBitmap",
"(",
")",
"diff",
"=",
"numpy",
".",
"subtract",
"(",
"current_state",
",",
"screen_state",
")",
"return",
"(",
"numpy",
".",
"count_nonzero",
"(",
"diff",
")",
">=",
"min_changed_pixels",
")"
] |
Returns true if at least ``min_changed_pixels`` are different between
``screen_state`` and the current state.
|
[
"Returns",
"true",
"if",
"at",
"least",
"min_changed_pixels",
"are",
"different",
"between",
"screen_state",
"and",
"the",
"current",
"state",
"."
] |
7adadfacd7f45d81186710be992f5668b15399fe
|
https://github.com/glitchassassin/lackey/blob/7adadfacd7f45d81186710be992f5668b15399fe/lackey/RegionMatching.py#L1425-L1432
|
6,748
|
glitchassassin/lackey
|
lackey/RegionMatching.py
|
Region.stopObserver
|
def stopObserver(self):
""" Stops this region's observer loop.
If this is running in a subprocess, the subprocess will end automatically.
"""
self._observer.isStopped = True
self._observer.isRunning = False
|
python
|
def stopObserver(self):
""" Stops this region's observer loop.
If this is running in a subprocess, the subprocess will end automatically.
"""
self._observer.isStopped = True
self._observer.isRunning = False
|
[
"def",
"stopObserver",
"(",
"self",
")",
":",
"self",
".",
"_observer",
".",
"isStopped",
"=",
"True",
"self",
".",
"_observer",
".",
"isRunning",
"=",
"False"
] |
Stops this region's observer loop.
If this is running in a subprocess, the subprocess will end automatically.
|
[
"Stops",
"this",
"region",
"s",
"observer",
"loop",
"."
] |
7adadfacd7f45d81186710be992f5668b15399fe
|
https://github.com/glitchassassin/lackey/blob/7adadfacd7f45d81186710be992f5668b15399fe/lackey/RegionMatching.py#L1486-L1492
|
6,749
|
glitchassassin/lackey
|
lackey/RegionMatching.py
|
Region.getEvents
|
def getEvents(self):
""" Returns a list of all events that have occurred.
Empties the internal queue.
"""
caught_events = self._observer.caught_events
self._observer.caught_events = []
for event in caught_events:
self._observer.activate_event(event["name"])
return caught_events
|
python
|
def getEvents(self):
""" Returns a list of all events that have occurred.
Empties the internal queue.
"""
caught_events = self._observer.caught_events
self._observer.caught_events = []
for event in caught_events:
self._observer.activate_event(event["name"])
return caught_events
|
[
"def",
"getEvents",
"(",
"self",
")",
":",
"caught_events",
"=",
"self",
".",
"_observer",
".",
"caught_events",
"self",
".",
"_observer",
".",
"caught_events",
"=",
"[",
"]",
"for",
"event",
"in",
"caught_events",
":",
"self",
".",
"_observer",
".",
"activate_event",
"(",
"event",
"[",
"\"name\"",
"]",
")",
"return",
"caught_events"
] |
Returns a list of all events that have occurred.
Empties the internal queue.
|
[
"Returns",
"a",
"list",
"of",
"all",
"events",
"that",
"have",
"occurred",
"."
] |
7adadfacd7f45d81186710be992f5668b15399fe
|
https://github.com/glitchassassin/lackey/blob/7adadfacd7f45d81186710be992f5668b15399fe/lackey/RegionMatching.py#L1506-L1515
|
6,750
|
glitchassassin/lackey
|
lackey/RegionMatching.py
|
Region.getEvent
|
def getEvent(self, name):
""" Returns the named event.
Removes it from the internal queue.
"""
to_return = None
for event in self._observer.caught_events:
if event["name"] == name:
to_return = event
break
if to_return:
self._observer.caught_events.remove(to_return)
self._observer.activate_event(to_return["name"])
return to_return
|
python
|
def getEvent(self, name):
""" Returns the named event.
Removes it from the internal queue.
"""
to_return = None
for event in self._observer.caught_events:
if event["name"] == name:
to_return = event
break
if to_return:
self._observer.caught_events.remove(to_return)
self._observer.activate_event(to_return["name"])
return to_return
|
[
"def",
"getEvent",
"(",
"self",
",",
"name",
")",
":",
"to_return",
"=",
"None",
"for",
"event",
"in",
"self",
".",
"_observer",
".",
"caught_events",
":",
"if",
"event",
"[",
"\"name\"",
"]",
"==",
"name",
":",
"to_return",
"=",
"event",
"break",
"if",
"to_return",
":",
"self",
".",
"_observer",
".",
"caught_events",
".",
"remove",
"(",
"to_return",
")",
"self",
".",
"_observer",
".",
"activate_event",
"(",
"to_return",
"[",
"\"name\"",
"]",
")",
"return",
"to_return"
] |
Returns the named event.
Removes it from the internal queue.
|
[
"Returns",
"the",
"named",
"event",
"."
] |
7adadfacd7f45d81186710be992f5668b15399fe
|
https://github.com/glitchassassin/lackey/blob/7adadfacd7f45d81186710be992f5668b15399fe/lackey/RegionMatching.py#L1516-L1529
|
6,751
|
glitchassassin/lackey
|
lackey/RegionMatching.py
|
Region.setFindFailedResponse
|
def setFindFailedResponse(self, response):
""" Set the response to a FindFailed exception in this region.
Can be ABORT, SKIP, PROMPT, or RETRY. """
valid_responses = ("ABORT", "SKIP", "PROMPT", "RETRY")
if response not in valid_responses:
raise ValueError("Invalid response - expected one of ({})".format(", ".join(valid_responses)))
self._findFailedResponse = response
|
python
|
def setFindFailedResponse(self, response):
""" Set the response to a FindFailed exception in this region.
Can be ABORT, SKIP, PROMPT, or RETRY. """
valid_responses = ("ABORT", "SKIP", "PROMPT", "RETRY")
if response not in valid_responses:
raise ValueError("Invalid response - expected one of ({})".format(", ".join(valid_responses)))
self._findFailedResponse = response
|
[
"def",
"setFindFailedResponse",
"(",
"self",
",",
"response",
")",
":",
"valid_responses",
"=",
"(",
"\"ABORT\"",
",",
"\"SKIP\"",
",",
"\"PROMPT\"",
",",
"\"RETRY\"",
")",
"if",
"response",
"not",
"in",
"valid_responses",
":",
"raise",
"ValueError",
"(",
"\"Invalid response - expected one of ({})\"",
".",
"format",
"(",
"\", \"",
".",
"join",
"(",
"valid_responses",
")",
")",
")",
"self",
".",
"_findFailedResponse",
"=",
"response"
] |
Set the response to a FindFailed exception in this region.
Can be ABORT, SKIP, PROMPT, or RETRY.
|
[
"Set",
"the",
"response",
"to",
"a",
"FindFailed",
"exception",
"in",
"this",
"region",
".",
"Can",
"be",
"ABORT",
"SKIP",
"PROMPT",
"or",
"RETRY",
"."
] |
7adadfacd7f45d81186710be992f5668b15399fe
|
https://github.com/glitchassassin/lackey/blob/7adadfacd7f45d81186710be992f5668b15399fe/lackey/RegionMatching.py#L1569-L1576
|
6,752
|
glitchassassin/lackey
|
lackey/RegionMatching.py
|
Region.setThrowException
|
def setThrowException(self, setting):
""" Defines whether an exception should be thrown for FindFailed operations.
``setting`` should be True or False. """
if setting:
self._throwException = True
self._findFailedResponse = "ABORT"
else:
self._throwException = False
self._findFailedResponse = "SKIP"
|
python
|
def setThrowException(self, setting):
""" Defines whether an exception should be thrown for FindFailed operations.
``setting`` should be True or False. """
if setting:
self._throwException = True
self._findFailedResponse = "ABORT"
else:
self._throwException = False
self._findFailedResponse = "SKIP"
|
[
"def",
"setThrowException",
"(",
"self",
",",
"setting",
")",
":",
"if",
"setting",
":",
"self",
".",
"_throwException",
"=",
"True",
"self",
".",
"_findFailedResponse",
"=",
"\"ABORT\"",
"else",
":",
"self",
".",
"_throwException",
"=",
"False",
"self",
".",
"_findFailedResponse",
"=",
"\"SKIP\""
] |
Defines whether an exception should be thrown for FindFailed operations.
``setting`` should be True or False.
|
[
"Defines",
"whether",
"an",
"exception",
"should",
"be",
"thrown",
"for",
"FindFailed",
"operations",
"."
] |
7adadfacd7f45d81186710be992f5668b15399fe
|
https://github.com/glitchassassin/lackey/blob/7adadfacd7f45d81186710be992f5668b15399fe/lackey/RegionMatching.py#L1586-L1595
|
6,753
|
glitchassassin/lackey
|
lackey/RegionMatching.py
|
Observer.register_event
|
def register_event(self, event_type, pattern, handler):
""" When ``event_type`` is observed for ``pattern``, triggers ``handler``.
For "CHANGE" events, ``pattern`` should be a tuple of ``min_changed_pixels`` and
the base screen state.
"""
if event_type not in self._supported_events:
raise ValueError("Unsupported event type {}".format(event_type))
if event_type != "CHANGE" and not isinstance(pattern, Pattern) and not isinstance(pattern, basestring):
raise ValueError("Expected pattern to be a Pattern or string")
if event_type == "CHANGE" and not (len(pattern)==2 and isinstance(pattern[0], int) and isinstance(pattern[1], numpy.ndarray)):
raise ValueError("For \"CHANGE\" events, ``pattern`` should be a tuple of ``min_changed_pixels`` and the base screen state.")
# Create event object
event = {
"pattern": pattern,
"event_type": event_type,
"count": 0,
"handler": handler,
"name": uuid.uuid4(),
"active": True
}
self._events[event["name"]] = event
return event["name"]
|
python
|
def register_event(self, event_type, pattern, handler):
""" When ``event_type`` is observed for ``pattern``, triggers ``handler``.
For "CHANGE" events, ``pattern`` should be a tuple of ``min_changed_pixels`` and
the base screen state.
"""
if event_type not in self._supported_events:
raise ValueError("Unsupported event type {}".format(event_type))
if event_type != "CHANGE" and not isinstance(pattern, Pattern) and not isinstance(pattern, basestring):
raise ValueError("Expected pattern to be a Pattern or string")
if event_type == "CHANGE" and not (len(pattern)==2 and isinstance(pattern[0], int) and isinstance(pattern[1], numpy.ndarray)):
raise ValueError("For \"CHANGE\" events, ``pattern`` should be a tuple of ``min_changed_pixels`` and the base screen state.")
# Create event object
event = {
"pattern": pattern,
"event_type": event_type,
"count": 0,
"handler": handler,
"name": uuid.uuid4(),
"active": True
}
self._events[event["name"]] = event
return event["name"]
|
[
"def",
"register_event",
"(",
"self",
",",
"event_type",
",",
"pattern",
",",
"handler",
")",
":",
"if",
"event_type",
"not",
"in",
"self",
".",
"_supported_events",
":",
"raise",
"ValueError",
"(",
"\"Unsupported event type {}\"",
".",
"format",
"(",
"event_type",
")",
")",
"if",
"event_type",
"!=",
"\"CHANGE\"",
"and",
"not",
"isinstance",
"(",
"pattern",
",",
"Pattern",
")",
"and",
"not",
"isinstance",
"(",
"pattern",
",",
"basestring",
")",
":",
"raise",
"ValueError",
"(",
"\"Expected pattern to be a Pattern or string\"",
")",
"if",
"event_type",
"==",
"\"CHANGE\"",
"and",
"not",
"(",
"len",
"(",
"pattern",
")",
"==",
"2",
"and",
"isinstance",
"(",
"pattern",
"[",
"0",
"]",
",",
"int",
")",
"and",
"isinstance",
"(",
"pattern",
"[",
"1",
"]",
",",
"numpy",
".",
"ndarray",
")",
")",
":",
"raise",
"ValueError",
"(",
"\"For \\\"CHANGE\\\" events, ``pattern`` should be a tuple of ``min_changed_pixels`` and the base screen state.\"",
")",
"# Create event object",
"event",
"=",
"{",
"\"pattern\"",
":",
"pattern",
",",
"\"event_type\"",
":",
"event_type",
",",
"\"count\"",
":",
"0",
",",
"\"handler\"",
":",
"handler",
",",
"\"name\"",
":",
"uuid",
".",
"uuid4",
"(",
")",
",",
"\"active\"",
":",
"True",
"}",
"self",
".",
"_events",
"[",
"event",
"[",
"\"name\"",
"]",
"]",
"=",
"event",
"return",
"event",
"[",
"\"name\"",
"]"
] |
When ``event_type`` is observed for ``pattern``, triggers ``handler``.
For "CHANGE" events, ``pattern`` should be a tuple of ``min_changed_pixels`` and
the base screen state.
|
[
"When",
"event_type",
"is",
"observed",
"for",
"pattern",
"triggers",
"handler",
"."
] |
7adadfacd7f45d81186710be992f5668b15399fe
|
https://github.com/glitchassassin/lackey/blob/7adadfacd7f45d81186710be992f5668b15399fe/lackey/RegionMatching.py#L1650-L1673
|
6,754
|
glitchassassin/lackey
|
lackey/RegionMatching.py
|
Screen.capture
|
def capture(self, *args): #x=None, y=None, w=None, h=None):
""" Captures the region as an image """
if len(args) == 0:
# Capture screen region
region = self
elif isinstance(args[0], Region):
# Capture specified region
region = args[0]
elif isinstance(args[0], tuple):
# Capture region defined by specified tuple
region = Region(*args[0])
elif isinstance(args[0], basestring):
# Interactive mode
raise NotImplementedError("Interactive capture mode not defined")
elif isinstance(args[0], int):
# Capture region defined by provided x,y,w,h
region = Region(*args)
self.lastScreenImage = region.getBitmap()
return self.lastScreenImage
|
python
|
def capture(self, *args): #x=None, y=None, w=None, h=None):
""" Captures the region as an image """
if len(args) == 0:
# Capture screen region
region = self
elif isinstance(args[0], Region):
# Capture specified region
region = args[0]
elif isinstance(args[0], tuple):
# Capture region defined by specified tuple
region = Region(*args[0])
elif isinstance(args[0], basestring):
# Interactive mode
raise NotImplementedError("Interactive capture mode not defined")
elif isinstance(args[0], int):
# Capture region defined by provided x,y,w,h
region = Region(*args)
self.lastScreenImage = region.getBitmap()
return self.lastScreenImage
|
[
"def",
"capture",
"(",
"self",
",",
"*",
"args",
")",
":",
"#x=None, y=None, w=None, h=None):",
"if",
"len",
"(",
"args",
")",
"==",
"0",
":",
"# Capture screen region",
"region",
"=",
"self",
"elif",
"isinstance",
"(",
"args",
"[",
"0",
"]",
",",
"Region",
")",
":",
"# Capture specified region",
"region",
"=",
"args",
"[",
"0",
"]",
"elif",
"isinstance",
"(",
"args",
"[",
"0",
"]",
",",
"tuple",
")",
":",
"# Capture region defined by specified tuple",
"region",
"=",
"Region",
"(",
"*",
"args",
"[",
"0",
"]",
")",
"elif",
"isinstance",
"(",
"args",
"[",
"0",
"]",
",",
"basestring",
")",
":",
"# Interactive mode",
"raise",
"NotImplementedError",
"(",
"\"Interactive capture mode not defined\"",
")",
"elif",
"isinstance",
"(",
"args",
"[",
"0",
"]",
",",
"int",
")",
":",
"# Capture region defined by provided x,y,w,h",
"region",
"=",
"Region",
"(",
"*",
"args",
")",
"self",
".",
"lastScreenImage",
"=",
"region",
".",
"getBitmap",
"(",
")",
"return",
"self",
".",
"lastScreenImage"
] |
Captures the region as an image
|
[
"Captures",
"the",
"region",
"as",
"an",
"image"
] |
7adadfacd7f45d81186710be992f5668b15399fe
|
https://github.com/glitchassassin/lackey/blob/7adadfacd7f45d81186710be992f5668b15399fe/lackey/RegionMatching.py#L1854-L1872
|
6,755
|
glitchassassin/lackey
|
lackey/RegionMatching.py
|
Screen.showMonitors
|
def showMonitors(cls):
""" Prints debug information about currently detected screens """
Debug.info("*** monitor configuration [ {} Screen(s)] ***".format(cls.getNumberScreens()))
Debug.info("*** Primary is Screen {}".format(cls.primaryScreen))
for index, screen in enumerate(PlatformManager.getScreenDetails()):
Debug.info("Screen {}: ({}, {}, {}, {})".format(index, *screen["rect"]))
Debug.info("*** end monitor configuration ***")
|
python
|
def showMonitors(cls):
""" Prints debug information about currently detected screens """
Debug.info("*** monitor configuration [ {} Screen(s)] ***".format(cls.getNumberScreens()))
Debug.info("*** Primary is Screen {}".format(cls.primaryScreen))
for index, screen in enumerate(PlatformManager.getScreenDetails()):
Debug.info("Screen {}: ({}, {}, {}, {})".format(index, *screen["rect"]))
Debug.info("*** end monitor configuration ***")
|
[
"def",
"showMonitors",
"(",
"cls",
")",
":",
"Debug",
".",
"info",
"(",
"\"*** monitor configuration [ {} Screen(s)] ***\"",
".",
"format",
"(",
"cls",
".",
"getNumberScreens",
"(",
")",
")",
")",
"Debug",
".",
"info",
"(",
"\"*** Primary is Screen {}\"",
".",
"format",
"(",
"cls",
".",
"primaryScreen",
")",
")",
"for",
"index",
",",
"screen",
"in",
"enumerate",
"(",
"PlatformManager",
".",
"getScreenDetails",
"(",
")",
")",
":",
"Debug",
".",
"info",
"(",
"\"Screen {}: ({}, {}, {}, {})\"",
".",
"format",
"(",
"index",
",",
"*",
"screen",
"[",
"\"rect\"",
"]",
")",
")",
"Debug",
".",
"info",
"(",
"\"*** end monitor configuration ***\"",
")"
] |
Prints debug information about currently detected screens
|
[
"Prints",
"debug",
"information",
"about",
"currently",
"detected",
"screens"
] |
7adadfacd7f45d81186710be992f5668b15399fe
|
https://github.com/glitchassassin/lackey/blob/7adadfacd7f45d81186710be992f5668b15399fe/lackey/RegionMatching.py#L1908-L1914
|
6,756
|
glitchassassin/lackey
|
lackey/RegionMatching.py
|
Screen.resetMonitors
|
def resetMonitors(self):
""" Recalculates screen based on changed monitor setup """
Debug.error("*** BE AWARE: experimental - might not work ***")
Debug.error("Re-evaluation of the monitor setup has been requested")
Debug.error("... Current Region/Screen objects might not be valid any longer")
Debug.error("... Use existing Region/Screen objects only if you know what you are doing!")
self.__init__(self._screenId)
self.showMonitors()
|
python
|
def resetMonitors(self):
""" Recalculates screen based on changed monitor setup """
Debug.error("*** BE AWARE: experimental - might not work ***")
Debug.error("Re-evaluation of the monitor setup has been requested")
Debug.error("... Current Region/Screen objects might not be valid any longer")
Debug.error("... Use existing Region/Screen objects only if you know what you are doing!")
self.__init__(self._screenId)
self.showMonitors()
|
[
"def",
"resetMonitors",
"(",
"self",
")",
":",
"Debug",
".",
"error",
"(",
"\"*** BE AWARE: experimental - might not work ***\"",
")",
"Debug",
".",
"error",
"(",
"\"Re-evaluation of the monitor setup has been requested\"",
")",
"Debug",
".",
"error",
"(",
"\"... Current Region/Screen objects might not be valid any longer\"",
")",
"Debug",
".",
"error",
"(",
"\"... Use existing Region/Screen objects only if you know what you are doing!\"",
")",
"self",
".",
"__init__",
"(",
"self",
".",
"_screenId",
")",
"self",
".",
"showMonitors",
"(",
")"
] |
Recalculates screen based on changed monitor setup
|
[
"Recalculates",
"screen",
"based",
"on",
"changed",
"monitor",
"setup"
] |
7adadfacd7f45d81186710be992f5668b15399fe
|
https://github.com/glitchassassin/lackey/blob/7adadfacd7f45d81186710be992f5668b15399fe/lackey/RegionMatching.py#L1915-L1922
|
6,757
|
glitchassassin/lackey
|
lackey/RegionMatching.py
|
Screen.newRegion
|
def newRegion(self, loc, width, height):
""" Creates a new region on the current screen at the specified offset with the specified
width and height. """
return Region.create(self.getTopLeft().offset(loc), width, height)
|
python
|
def newRegion(self, loc, width, height):
""" Creates a new region on the current screen at the specified offset with the specified
width and height. """
return Region.create(self.getTopLeft().offset(loc), width, height)
|
[
"def",
"newRegion",
"(",
"self",
",",
"loc",
",",
"width",
",",
"height",
")",
":",
"return",
"Region",
".",
"create",
"(",
"self",
".",
"getTopLeft",
"(",
")",
".",
"offset",
"(",
"loc",
")",
",",
"width",
",",
"height",
")"
] |
Creates a new region on the current screen at the specified offset with the specified
width and height.
|
[
"Creates",
"a",
"new",
"region",
"on",
"the",
"current",
"screen",
"at",
"the",
"specified",
"offset",
"with",
"the",
"specified",
"width",
"and",
"height",
"."
] |
7adadfacd7f45d81186710be992f5668b15399fe
|
https://github.com/glitchassassin/lackey/blob/7adadfacd7f45d81186710be992f5668b15399fe/lackey/RegionMatching.py#L1923-L1926
|
6,758
|
glitchassassin/lackey
|
lackey/SettingsDebug.py
|
DebugMaster.history
|
def history(self, message):
""" Records an Action-level log message
Uses the log path defined by ``Debug.setUserLogFile()``. If no log file is
defined, sends to STDOUT
"""
if Settings.ActionLogs:
self._write_log("action", Settings.LogTime, message)
|
python
|
def history(self, message):
""" Records an Action-level log message
Uses the log path defined by ``Debug.setUserLogFile()``. If no log file is
defined, sends to STDOUT
"""
if Settings.ActionLogs:
self._write_log("action", Settings.LogTime, message)
|
[
"def",
"history",
"(",
"self",
",",
"message",
")",
":",
"if",
"Settings",
".",
"ActionLogs",
":",
"self",
".",
"_write_log",
"(",
"\"action\"",
",",
"Settings",
".",
"LogTime",
",",
"message",
")"
] |
Records an Action-level log message
Uses the log path defined by ``Debug.setUserLogFile()``. If no log file is
defined, sends to STDOUT
|
[
"Records",
"an",
"Action",
"-",
"level",
"log",
"message"
] |
7adadfacd7f45d81186710be992f5668b15399fe
|
https://github.com/glitchassassin/lackey/blob/7adadfacd7f45d81186710be992f5668b15399fe/lackey/SettingsDebug.py#L34-L41
|
6,759
|
glitchassassin/lackey
|
lackey/SettingsDebug.py
|
DebugMaster.error
|
def error(self, message):
""" Records an Error-level log message
Uses the log path defined by ``Debug.setUserLogFile()``. If no log file is
defined, sends to STDOUT
"""
if Settings.ErrorLogs:
self._write_log("error", Settings.LogTime, message)
|
python
|
def error(self, message):
""" Records an Error-level log message
Uses the log path defined by ``Debug.setUserLogFile()``. If no log file is
defined, sends to STDOUT
"""
if Settings.ErrorLogs:
self._write_log("error", Settings.LogTime, message)
|
[
"def",
"error",
"(",
"self",
",",
"message",
")",
":",
"if",
"Settings",
".",
"ErrorLogs",
":",
"self",
".",
"_write_log",
"(",
"\"error\"",
",",
"Settings",
".",
"LogTime",
",",
"message",
")"
] |
Records an Error-level log message
Uses the log path defined by ``Debug.setUserLogFile()``. If no log file is
defined, sends to STDOUT
|
[
"Records",
"an",
"Error",
"-",
"level",
"log",
"message"
] |
7adadfacd7f45d81186710be992f5668b15399fe
|
https://github.com/glitchassassin/lackey/blob/7adadfacd7f45d81186710be992f5668b15399fe/lackey/SettingsDebug.py#L42-L49
|
6,760
|
glitchassassin/lackey
|
lackey/SettingsDebug.py
|
DebugMaster.info
|
def info(self, message):
""" Records an Info-level log message
Uses the log path defined by ``Debug.setUserLogFile()``. If no log file is
defined, sends to STDOUT
"""
if Settings.InfoLogs:
self._write_log("info", Settings.LogTime, message)
|
python
|
def info(self, message):
""" Records an Info-level log message
Uses the log path defined by ``Debug.setUserLogFile()``. If no log file is
defined, sends to STDOUT
"""
if Settings.InfoLogs:
self._write_log("info", Settings.LogTime, message)
|
[
"def",
"info",
"(",
"self",
",",
"message",
")",
":",
"if",
"Settings",
".",
"InfoLogs",
":",
"self",
".",
"_write_log",
"(",
"\"info\"",
",",
"Settings",
".",
"LogTime",
",",
"message",
")"
] |
Records an Info-level log message
Uses the log path defined by ``Debug.setUserLogFile()``. If no log file is
defined, sends to STDOUT
|
[
"Records",
"an",
"Info",
"-",
"level",
"log",
"message"
] |
7adadfacd7f45d81186710be992f5668b15399fe
|
https://github.com/glitchassassin/lackey/blob/7adadfacd7f45d81186710be992f5668b15399fe/lackey/SettingsDebug.py#L50-L57
|
6,761
|
glitchassassin/lackey
|
lackey/SettingsDebug.py
|
DebugMaster.on
|
def on(self, level):
""" Turns on all debugging messages up to the specified level
0 = None; 1 = User;
"""
if isinstance(level, int) and level >= 0 and level <= 3:
self._debug_level = level
|
python
|
def on(self, level):
""" Turns on all debugging messages up to the specified level
0 = None; 1 = User;
"""
if isinstance(level, int) and level >= 0 and level <= 3:
self._debug_level = level
|
[
"def",
"on",
"(",
"self",
",",
"level",
")",
":",
"if",
"isinstance",
"(",
"level",
",",
"int",
")",
"and",
"level",
">=",
"0",
"and",
"level",
"<=",
"3",
":",
"self",
".",
"_debug_level",
"=",
"level"
] |
Turns on all debugging messages up to the specified level
0 = None; 1 = User;
|
[
"Turns",
"on",
"all",
"debugging",
"messages",
"up",
"to",
"the",
"specified",
"level"
] |
7adadfacd7f45d81186710be992f5668b15399fe
|
https://github.com/glitchassassin/lackey/blob/7adadfacd7f45d81186710be992f5668b15399fe/lackey/SettingsDebug.py#L58-L64
|
6,762
|
glitchassassin/lackey
|
lackey/SettingsDebug.py
|
DebugMaster.setLogFile
|
def setLogFile(self, filepath):
""" Defines the file to which output log messages should be sent.
Set to `None` to print to STDOUT instead.
"""
if filepath is None:
self._log_file = None
return
parsed_path = os.path.abspath(filepath)
# Checks if the provided log filename is in a real directory, and that
# the filename itself is not a directory.
if os.path.isdir(os.path.dirname(parsed_path)) and not os.path.isdir(parsed_path):
self._log_file = parsed_path
else:
raise IOError("File not found: " + filepath)
|
python
|
def setLogFile(self, filepath):
""" Defines the file to which output log messages should be sent.
Set to `None` to print to STDOUT instead.
"""
if filepath is None:
self._log_file = None
return
parsed_path = os.path.abspath(filepath)
# Checks if the provided log filename is in a real directory, and that
# the filename itself is not a directory.
if os.path.isdir(os.path.dirname(parsed_path)) and not os.path.isdir(parsed_path):
self._log_file = parsed_path
else:
raise IOError("File not found: " + filepath)
|
[
"def",
"setLogFile",
"(",
"self",
",",
"filepath",
")",
":",
"if",
"filepath",
"is",
"None",
":",
"self",
".",
"_log_file",
"=",
"None",
"return",
"parsed_path",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"filepath",
")",
"# Checks if the provided log filename is in a real directory, and that",
"# the filename itself is not a directory.",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"parsed_path",
")",
")",
"and",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"parsed_path",
")",
":",
"self",
".",
"_log_file",
"=",
"parsed_path",
"else",
":",
"raise",
"IOError",
"(",
"\"File not found: \"",
"+",
"filepath",
")"
] |
Defines the file to which output log messages should be sent.
Set to `None` to print to STDOUT instead.
|
[
"Defines",
"the",
"file",
"to",
"which",
"output",
"log",
"messages",
"should",
"be",
"sent",
"."
] |
7adadfacd7f45d81186710be992f5668b15399fe
|
https://github.com/glitchassassin/lackey/blob/7adadfacd7f45d81186710be992f5668b15399fe/lackey/SettingsDebug.py#L102-L116
|
6,763
|
glitchassassin/lackey
|
lackey/SettingsDebug.py
|
DebugMaster._write_log
|
def _write_log(self, log_type, log_time, message):
""" Private method to abstract log writing for different types of logs """
timestamp = datetime.datetime.now().strftime(" %Y-%m-%d %H:%M:%S")
log_entry = "[{}{}] {}".format(log_type, timestamp if log_time else "", message)
if self._logger and callable(getattr(self._logger, self._logger_methods[log_type], None)):
# Check for log handler (sends message only if _logger_no_prefix is True)
getattr(
self._logger,
self._logger_methods[log_type],
None
)(message if self._logger_no_prefix else log_entry)
elif self._log_file:
# Otherwise write to file, if a file has been specified
with open(self._log_file, 'a') as logfile:
try:
logfile.write(unicode(log_entry + "\n"))
except NameError: # `unicode` only works in Python 2
logfile.write(log_entry + "\n")
else:
# Otherwise, print to STDOUT
print(log_entry)
|
python
|
def _write_log(self, log_type, log_time, message):
""" Private method to abstract log writing for different types of logs """
timestamp = datetime.datetime.now().strftime(" %Y-%m-%d %H:%M:%S")
log_entry = "[{}{}] {}".format(log_type, timestamp if log_time else "", message)
if self._logger and callable(getattr(self._logger, self._logger_methods[log_type], None)):
# Check for log handler (sends message only if _logger_no_prefix is True)
getattr(
self._logger,
self._logger_methods[log_type],
None
)(message if self._logger_no_prefix else log_entry)
elif self._log_file:
# Otherwise write to file, if a file has been specified
with open(self._log_file, 'a') as logfile:
try:
logfile.write(unicode(log_entry + "\n"))
except NameError: # `unicode` only works in Python 2
logfile.write(log_entry + "\n")
else:
# Otherwise, print to STDOUT
print(log_entry)
|
[
"def",
"_write_log",
"(",
"self",
",",
"log_type",
",",
"log_time",
",",
"message",
")",
":",
"timestamp",
"=",
"datetime",
".",
"datetime",
".",
"now",
"(",
")",
".",
"strftime",
"(",
"\" %Y-%m-%d %H:%M:%S\"",
")",
"log_entry",
"=",
"\"[{}{}] {}\"",
".",
"format",
"(",
"log_type",
",",
"timestamp",
"if",
"log_time",
"else",
"\"\"",
",",
"message",
")",
"if",
"self",
".",
"_logger",
"and",
"callable",
"(",
"getattr",
"(",
"self",
".",
"_logger",
",",
"self",
".",
"_logger_methods",
"[",
"log_type",
"]",
",",
"None",
")",
")",
":",
"# Check for log handler (sends message only if _logger_no_prefix is True)",
"getattr",
"(",
"self",
".",
"_logger",
",",
"self",
".",
"_logger_methods",
"[",
"log_type",
"]",
",",
"None",
")",
"(",
"message",
"if",
"self",
".",
"_logger_no_prefix",
"else",
"log_entry",
")",
"elif",
"self",
".",
"_log_file",
":",
"# Otherwise write to file, if a file has been specified",
"with",
"open",
"(",
"self",
".",
"_log_file",
",",
"'a'",
")",
"as",
"logfile",
":",
"try",
":",
"logfile",
".",
"write",
"(",
"unicode",
"(",
"log_entry",
"+",
"\"\\n\"",
")",
")",
"except",
"NameError",
":",
"# `unicode` only works in Python 2",
"logfile",
".",
"write",
"(",
"log_entry",
"+",
"\"\\n\"",
")",
"else",
":",
"# Otherwise, print to STDOUT",
"print",
"(",
"log_entry",
")"
] |
Private method to abstract log writing for different types of logs
|
[
"Private",
"method",
"to",
"abstract",
"log",
"writing",
"for",
"different",
"types",
"of",
"logs"
] |
7adadfacd7f45d81186710be992f5668b15399fe
|
https://github.com/glitchassassin/lackey/blob/7adadfacd7f45d81186710be992f5668b15399fe/lackey/SettingsDebug.py#L117-L137
|
6,764
|
glitchassassin/lackey
|
lackey/__init__.py
|
addImagePath
|
def addImagePath(new_path):
""" Convenience function. Adds a path to the list of paths to search for images.
Can be a URL (but must be accessible). """
if os.path.exists(new_path):
Settings.ImagePaths.append(new_path)
elif "http://" in new_path or "https://" in new_path:
request = requests.get(new_path)
if request.status_code < 400:
# Path exists
Settings.ImagePaths.append(new_path)
else:
raise OSError("Unable to connect to " + new_path)
else:
raise OSError("File not found: " + new_path)
|
python
|
def addImagePath(new_path):
""" Convenience function. Adds a path to the list of paths to search for images.
Can be a URL (but must be accessible). """
if os.path.exists(new_path):
Settings.ImagePaths.append(new_path)
elif "http://" in new_path or "https://" in new_path:
request = requests.get(new_path)
if request.status_code < 400:
# Path exists
Settings.ImagePaths.append(new_path)
else:
raise OSError("Unable to connect to " + new_path)
else:
raise OSError("File not found: " + new_path)
|
[
"def",
"addImagePath",
"(",
"new_path",
")",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"new_path",
")",
":",
"Settings",
".",
"ImagePaths",
".",
"append",
"(",
"new_path",
")",
"elif",
"\"http://\"",
"in",
"new_path",
"or",
"\"https://\"",
"in",
"new_path",
":",
"request",
"=",
"requests",
".",
"get",
"(",
"new_path",
")",
"if",
"request",
".",
"status_code",
"<",
"400",
":",
"# Path exists",
"Settings",
".",
"ImagePaths",
".",
"append",
"(",
"new_path",
")",
"else",
":",
"raise",
"OSError",
"(",
"\"Unable to connect to \"",
"+",
"new_path",
")",
"else",
":",
"raise",
"OSError",
"(",
"\"File not found: \"",
"+",
"new_path",
")"
] |
Convenience function. Adds a path to the list of paths to search for images.
Can be a URL (but must be accessible).
|
[
"Convenience",
"function",
".",
"Adds",
"a",
"path",
"to",
"the",
"list",
"of",
"paths",
"to",
"search",
"for",
"images",
"."
] |
7adadfacd7f45d81186710be992f5668b15399fe
|
https://github.com/glitchassassin/lackey/blob/7adadfacd7f45d81186710be992f5668b15399fe/lackey/__init__.py#L107-L121
|
6,765
|
glitchassassin/lackey
|
lackey/__init__.py
|
unzip
|
def unzip(from_file, to_folder):
""" Convenience function.
Extracts files from the zip file `fromFile` into the folder `toFolder`. """
with ZipFile(os.path.abspath(from_file), 'r') as to_unzip:
to_unzip.extractall(os.path.abspath(to_folder))
|
python
|
def unzip(from_file, to_folder):
""" Convenience function.
Extracts files from the zip file `fromFile` into the folder `toFolder`. """
with ZipFile(os.path.abspath(from_file), 'r') as to_unzip:
to_unzip.extractall(os.path.abspath(to_folder))
|
[
"def",
"unzip",
"(",
"from_file",
",",
"to_folder",
")",
":",
"with",
"ZipFile",
"(",
"os",
".",
"path",
".",
"abspath",
"(",
"from_file",
")",
",",
"'r'",
")",
"as",
"to_unzip",
":",
"to_unzip",
".",
"extractall",
"(",
"os",
".",
"path",
".",
"abspath",
"(",
"to_folder",
")",
")"
] |
Convenience function.
Extracts files from the zip file `fromFile` into the folder `toFolder`.
|
[
"Convenience",
"function",
"."
] |
7adadfacd7f45d81186710be992f5668b15399fe
|
https://github.com/glitchassassin/lackey/blob/7adadfacd7f45d81186710be992f5668b15399fe/lackey/__init__.py#L146-L151
|
6,766
|
glitchassassin/lackey
|
lackey/__init__.py
|
popup
|
def popup(text, title="Lackey Info"):
""" Creates an info dialog with the specified text. """
root = tk.Tk()
root.withdraw()
tkMessageBox.showinfo(title, text)
|
python
|
def popup(text, title="Lackey Info"):
""" Creates an info dialog with the specified text. """
root = tk.Tk()
root.withdraw()
tkMessageBox.showinfo(title, text)
|
[
"def",
"popup",
"(",
"text",
",",
"title",
"=",
"\"Lackey Info\"",
")",
":",
"root",
"=",
"tk",
".",
"Tk",
"(",
")",
"root",
".",
"withdraw",
"(",
")",
"tkMessageBox",
".",
"showinfo",
"(",
"title",
",",
"text",
")"
] |
Creates an info dialog with the specified text.
|
[
"Creates",
"an",
"info",
"dialog",
"with",
"the",
"specified",
"text",
"."
] |
7adadfacd7f45d81186710be992f5668b15399fe
|
https://github.com/glitchassassin/lackey/blob/7adadfacd7f45d81186710be992f5668b15399fe/lackey/__init__.py#L176-L180
|
6,767
|
glitchassassin/lackey
|
lackey/__init__.py
|
popError
|
def popError(text, title="Lackey Error"):
""" Creates an error dialog with the specified text. """
root = tk.Tk()
root.withdraw()
tkMessageBox.showerror(title, text)
|
python
|
def popError(text, title="Lackey Error"):
""" Creates an error dialog with the specified text. """
root = tk.Tk()
root.withdraw()
tkMessageBox.showerror(title, text)
|
[
"def",
"popError",
"(",
"text",
",",
"title",
"=",
"\"Lackey Error\"",
")",
":",
"root",
"=",
"tk",
".",
"Tk",
"(",
")",
"root",
".",
"withdraw",
"(",
")",
"tkMessageBox",
".",
"showerror",
"(",
"title",
",",
"text",
")"
] |
Creates an error dialog with the specified text.
|
[
"Creates",
"an",
"error",
"dialog",
"with",
"the",
"specified",
"text",
"."
] |
7adadfacd7f45d81186710be992f5668b15399fe
|
https://github.com/glitchassassin/lackey/blob/7adadfacd7f45d81186710be992f5668b15399fe/lackey/__init__.py#L181-L185
|
6,768
|
glitchassassin/lackey
|
lackey/__init__.py
|
popAsk
|
def popAsk(text, title="Lackey Decision"):
""" Creates a yes-no dialog with the specified text. """
root = tk.Tk()
root.withdraw()
return tkMessageBox.askyesno(title, text)
|
python
|
def popAsk(text, title="Lackey Decision"):
""" Creates a yes-no dialog with the specified text. """
root = tk.Tk()
root.withdraw()
return tkMessageBox.askyesno(title, text)
|
[
"def",
"popAsk",
"(",
"text",
",",
"title",
"=",
"\"Lackey Decision\"",
")",
":",
"root",
"=",
"tk",
".",
"Tk",
"(",
")",
"root",
".",
"withdraw",
"(",
")",
"return",
"tkMessageBox",
".",
"askyesno",
"(",
"title",
",",
"text",
")"
] |
Creates a yes-no dialog with the specified text.
|
[
"Creates",
"a",
"yes",
"-",
"no",
"dialog",
"with",
"the",
"specified",
"text",
"."
] |
7adadfacd7f45d81186710be992f5668b15399fe
|
https://github.com/glitchassassin/lackey/blob/7adadfacd7f45d81186710be992f5668b15399fe/lackey/__init__.py#L186-L190
|
6,769
|
glitchassassin/lackey
|
lackey/__init__.py
|
input
|
def input(msg="", default="", title="Lackey Input", hidden=False):
""" Creates an input dialog with the specified message and default text.
If `hidden`, creates a password dialog instead. Returns the entered value. """
root = tk.Tk()
input_text = tk.StringVar()
input_text.set(default)
PopupInput(root, msg, title, hidden, input_text)
root.focus_force()
root.mainloop()
return str(input_text.get())
|
python
|
def input(msg="", default="", title="Lackey Input", hidden=False):
""" Creates an input dialog with the specified message and default text.
If `hidden`, creates a password dialog instead. Returns the entered value. """
root = tk.Tk()
input_text = tk.StringVar()
input_text.set(default)
PopupInput(root, msg, title, hidden, input_text)
root.focus_force()
root.mainloop()
return str(input_text.get())
|
[
"def",
"input",
"(",
"msg",
"=",
"\"\"",
",",
"default",
"=",
"\"\"",
",",
"title",
"=",
"\"Lackey Input\"",
",",
"hidden",
"=",
"False",
")",
":",
"root",
"=",
"tk",
".",
"Tk",
"(",
")",
"input_text",
"=",
"tk",
".",
"StringVar",
"(",
")",
"input_text",
".",
"set",
"(",
"default",
")",
"PopupInput",
"(",
"root",
",",
"msg",
",",
"title",
",",
"hidden",
",",
"input_text",
")",
"root",
".",
"focus_force",
"(",
")",
"root",
".",
"mainloop",
"(",
")",
"return",
"str",
"(",
"input_text",
".",
"get",
"(",
")",
")"
] |
Creates an input dialog with the specified message and default text.
If `hidden`, creates a password dialog instead. Returns the entered value.
|
[
"Creates",
"an",
"input",
"dialog",
"with",
"the",
"specified",
"message",
"and",
"default",
"text",
"."
] |
7adadfacd7f45d81186710be992f5668b15399fe
|
https://github.com/glitchassassin/lackey/blob/7adadfacd7f45d81186710be992f5668b15399fe/lackey/__init__.py#L193-L203
|
6,770
|
glitchassassin/lackey
|
lackey/__init__.py
|
inputText
|
def inputText(message="", title="Lackey Input", lines=9, width=20, text=""):
""" Creates a textarea dialog with the specified message and default text.
Returns the entered value. """
root = tk.Tk()
input_text = tk.StringVar()
input_text.set(text)
PopupTextarea(root, message, title, lines, width, input_text)
root.focus_force()
root.mainloop()
return str(input_text.get())
|
python
|
def inputText(message="", title="Lackey Input", lines=9, width=20, text=""):
""" Creates a textarea dialog with the specified message and default text.
Returns the entered value. """
root = tk.Tk()
input_text = tk.StringVar()
input_text.set(text)
PopupTextarea(root, message, title, lines, width, input_text)
root.focus_force()
root.mainloop()
return str(input_text.get())
|
[
"def",
"inputText",
"(",
"message",
"=",
"\"\"",
",",
"title",
"=",
"\"Lackey Input\"",
",",
"lines",
"=",
"9",
",",
"width",
"=",
"20",
",",
"text",
"=",
"\"\"",
")",
":",
"root",
"=",
"tk",
".",
"Tk",
"(",
")",
"input_text",
"=",
"tk",
".",
"StringVar",
"(",
")",
"input_text",
".",
"set",
"(",
"text",
")",
"PopupTextarea",
"(",
"root",
",",
"message",
",",
"title",
",",
"lines",
",",
"width",
",",
"input_text",
")",
"root",
".",
"focus_force",
"(",
")",
"root",
".",
"mainloop",
"(",
")",
"return",
"str",
"(",
"input_text",
".",
"get",
"(",
")",
")"
] |
Creates a textarea dialog with the specified message and default text.
Returns the entered value.
|
[
"Creates",
"a",
"textarea",
"dialog",
"with",
"the",
"specified",
"message",
"and",
"default",
"text",
"."
] |
7adadfacd7f45d81186710be992f5668b15399fe
|
https://github.com/glitchassassin/lackey/blob/7adadfacd7f45d81186710be992f5668b15399fe/lackey/__init__.py#L204-L214
|
6,771
|
glitchassassin/lackey
|
lackey/__init__.py
|
select
|
def select(message="", title="Lackey Input", options=None, default=None):
""" Creates a dropdown selection dialog with the specified message and options
`default` must be one of the options.
Returns the selected value. """
if options is None or len(options) == 0:
return ""
if default is None:
default = options[0]
if default not in options:
raise ValueError("<<default>> not in options[]")
root = tk.Tk()
input_text = tk.StringVar()
input_text.set(message)
PopupList(root, message, title, options, default, input_text)
root.focus_force()
root.mainloop()
return str(input_text.get())
|
python
|
def select(message="", title="Lackey Input", options=None, default=None):
""" Creates a dropdown selection dialog with the specified message and options
`default` must be one of the options.
Returns the selected value. """
if options is None or len(options) == 0:
return ""
if default is None:
default = options[0]
if default not in options:
raise ValueError("<<default>> not in options[]")
root = tk.Tk()
input_text = tk.StringVar()
input_text.set(message)
PopupList(root, message, title, options, default, input_text)
root.focus_force()
root.mainloop()
return str(input_text.get())
|
[
"def",
"select",
"(",
"message",
"=",
"\"\"",
",",
"title",
"=",
"\"Lackey Input\"",
",",
"options",
"=",
"None",
",",
"default",
"=",
"None",
")",
":",
"if",
"options",
"is",
"None",
"or",
"len",
"(",
"options",
")",
"==",
"0",
":",
"return",
"\"\"",
"if",
"default",
"is",
"None",
":",
"default",
"=",
"options",
"[",
"0",
"]",
"if",
"default",
"not",
"in",
"options",
":",
"raise",
"ValueError",
"(",
"\"<<default>> not in options[]\"",
")",
"root",
"=",
"tk",
".",
"Tk",
"(",
")",
"input_text",
"=",
"tk",
".",
"StringVar",
"(",
")",
"input_text",
".",
"set",
"(",
"message",
")",
"PopupList",
"(",
"root",
",",
"message",
",",
"title",
",",
"options",
",",
"default",
",",
"input_text",
")",
"root",
".",
"focus_force",
"(",
")",
"root",
".",
"mainloop",
"(",
")",
"return",
"str",
"(",
"input_text",
".",
"get",
"(",
")",
")"
] |
Creates a dropdown selection dialog with the specified message and options
`default` must be one of the options.
Returns the selected value.
|
[
"Creates",
"a",
"dropdown",
"selection",
"dialog",
"with",
"the",
"specified",
"message",
"and",
"options"
] |
7adadfacd7f45d81186710be992f5668b15399fe
|
https://github.com/glitchassassin/lackey/blob/7adadfacd7f45d81186710be992f5668b15399fe/lackey/__init__.py#L215-L233
|
6,772
|
glitchassassin/lackey
|
lackey/__init__.py
|
popFile
|
def popFile(title="Lackey Open File"):
""" Creates a file selection dialog with the specified message and options.
Returns the selected file. """
root = tk.Tk()
root.withdraw()
return str(tkFileDialog.askopenfilename(title=title))
|
python
|
def popFile(title="Lackey Open File"):
""" Creates a file selection dialog with the specified message and options.
Returns the selected file. """
root = tk.Tk()
root.withdraw()
return str(tkFileDialog.askopenfilename(title=title))
|
[
"def",
"popFile",
"(",
"title",
"=",
"\"Lackey Open File\"",
")",
":",
"root",
"=",
"tk",
".",
"Tk",
"(",
")",
"root",
".",
"withdraw",
"(",
")",
"return",
"str",
"(",
"tkFileDialog",
".",
"askopenfilename",
"(",
"title",
"=",
"title",
")",
")"
] |
Creates a file selection dialog with the specified message and options.
Returns the selected file.
|
[
"Creates",
"a",
"file",
"selection",
"dialog",
"with",
"the",
"specified",
"message",
"and",
"options",
"."
] |
7adadfacd7f45d81186710be992f5668b15399fe
|
https://github.com/glitchassassin/lackey/blob/7adadfacd7f45d81186710be992f5668b15399fe/lackey/__init__.py#L234-L240
|
6,773
|
glitchassassin/lackey
|
lackey/Geometry.py
|
Location.setLocation
|
def setLocation(self, x, y):
"""Set the location of this object to the specified coordinates."""
self.x = int(x)
self.y = int(y)
return self
|
python
|
def setLocation(self, x, y):
"""Set the location of this object to the specified coordinates."""
self.x = int(x)
self.y = int(y)
return self
|
[
"def",
"setLocation",
"(",
"self",
",",
"x",
",",
"y",
")",
":",
"self",
".",
"x",
"=",
"int",
"(",
"x",
")",
"self",
".",
"y",
"=",
"int",
"(",
"y",
")",
"return",
"self"
] |
Set the location of this object to the specified coordinates.
|
[
"Set",
"the",
"location",
"of",
"this",
"object",
"to",
"the",
"specified",
"coordinates",
"."
] |
7adadfacd7f45d81186710be992f5668b15399fe
|
https://github.com/glitchassassin/lackey/blob/7adadfacd7f45d81186710be992f5668b15399fe/lackey/Geometry.py#L15-L19
|
6,774
|
glitchassassin/lackey
|
lackey/Geometry.py
|
Location.offset
|
def offset(self, dx, dy):
"""Get a new location which is dx and dy pixels away horizontally and vertically
from the current location.
"""
return Location(self.x+dx, self.y+dy)
|
python
|
def offset(self, dx, dy):
"""Get a new location which is dx and dy pixels away horizontally and vertically
from the current location.
"""
return Location(self.x+dx, self.y+dy)
|
[
"def",
"offset",
"(",
"self",
",",
"dx",
",",
"dy",
")",
":",
"return",
"Location",
"(",
"self",
".",
"x",
"+",
"dx",
",",
"self",
".",
"y",
"+",
"dy",
")"
] |
Get a new location which is dx and dy pixels away horizontally and vertically
from the current location.
|
[
"Get",
"a",
"new",
"location",
"which",
"is",
"dx",
"and",
"dy",
"pixels",
"away",
"horizontally",
"and",
"vertically",
"from",
"the",
"current",
"location",
"."
] |
7adadfacd7f45d81186710be992f5668b15399fe
|
https://github.com/glitchassassin/lackey/blob/7adadfacd7f45d81186710be992f5668b15399fe/lackey/Geometry.py#L22-L26
|
6,775
|
glitchassassin/lackey
|
lackey/Geometry.py
|
Location.getOffset
|
def getOffset(self, loc):
""" Returns the offset between the given point and this point """
return Location(loc.x - self.x, loc.y - self.y)
|
python
|
def getOffset(self, loc):
""" Returns the offset between the given point and this point """
return Location(loc.x - self.x, loc.y - self.y)
|
[
"def",
"getOffset",
"(",
"self",
",",
"loc",
")",
":",
"return",
"Location",
"(",
"loc",
".",
"x",
"-",
"self",
".",
"x",
",",
"loc",
".",
"y",
"-",
"self",
".",
"y",
")"
] |
Returns the offset between the given point and this point
|
[
"Returns",
"the",
"offset",
"between",
"the",
"given",
"point",
"and",
"this",
"point"
] |
7adadfacd7f45d81186710be992f5668b15399fe
|
https://github.com/glitchassassin/lackey/blob/7adadfacd7f45d81186710be992f5668b15399fe/lackey/Geometry.py#L71-L73
|
6,776
|
glitchassassin/lackey
|
lackey/Geometry.py
|
Location.copyTo
|
def copyTo(self, screen):
""" Creates a new point with the same offset on the target screen as this point has on the
current screen """
from .RegionMatching import Screen
if not isinstance(screen, Screen):
screen = RegionMatching.Screen(screen)
return screen.getTopLeft().offset(self.getScreen().getTopLeft().getOffset(self))
|
python
|
def copyTo(self, screen):
""" Creates a new point with the same offset on the target screen as this point has on the
current screen """
from .RegionMatching import Screen
if not isinstance(screen, Screen):
screen = RegionMatching.Screen(screen)
return screen.getTopLeft().offset(self.getScreen().getTopLeft().getOffset(self))
|
[
"def",
"copyTo",
"(",
"self",
",",
"screen",
")",
":",
"from",
".",
"RegionMatching",
"import",
"Screen",
"if",
"not",
"isinstance",
"(",
"screen",
",",
"Screen",
")",
":",
"screen",
"=",
"RegionMatching",
".",
"Screen",
"(",
"screen",
")",
"return",
"screen",
".",
"getTopLeft",
"(",
")",
".",
"offset",
"(",
"self",
".",
"getScreen",
"(",
")",
".",
"getTopLeft",
"(",
")",
".",
"getOffset",
"(",
"self",
")",
")"
] |
Creates a new point with the same offset on the target screen as this point has on the
current screen
|
[
"Creates",
"a",
"new",
"point",
"with",
"the",
"same",
"offset",
"on",
"the",
"target",
"screen",
"as",
"this",
"point",
"has",
"on",
"the",
"current",
"screen"
] |
7adadfacd7f45d81186710be992f5668b15399fe
|
https://github.com/glitchassassin/lackey/blob/7adadfacd7f45d81186710be992f5668b15399fe/lackey/Geometry.py#L96-L102
|
6,777
|
glitchassassin/lackey
|
lackey/App.py
|
App.focusedWindow
|
def focusedWindow(cls):
""" Returns a Region corresponding to whatever window is in the foreground """
x, y, w, h = PlatformManager.getWindowRect(PlatformManager.getForegroundWindow())
return Region(x, y, w, h)
|
python
|
def focusedWindow(cls):
""" Returns a Region corresponding to whatever window is in the foreground """
x, y, w, h = PlatformManager.getWindowRect(PlatformManager.getForegroundWindow())
return Region(x, y, w, h)
|
[
"def",
"focusedWindow",
"(",
"cls",
")",
":",
"x",
",",
"y",
",",
"w",
",",
"h",
"=",
"PlatformManager",
".",
"getWindowRect",
"(",
"PlatformManager",
".",
"getForegroundWindow",
"(",
")",
")",
"return",
"Region",
"(",
"x",
",",
"y",
",",
"w",
",",
"h",
")"
] |
Returns a Region corresponding to whatever window is in the foreground
|
[
"Returns",
"a",
"Region",
"corresponding",
"to",
"whatever",
"window",
"is",
"in",
"the",
"foreground"
] |
7adadfacd7f45d81186710be992f5668b15399fe
|
https://github.com/glitchassassin/lackey/blob/7adadfacd7f45d81186710be992f5668b15399fe/lackey/App.py#L182-L185
|
6,778
|
glitchassassin/lackey
|
lackey/App.py
|
App.getWindow
|
def getWindow(self):
""" Returns the title of the main window of the currently open app.
Returns an empty string if no match could be found.
"""
if self.getPID() != -1:
return PlatformManager.getWindowTitle(PlatformManager.getWindowByPID(self.getPID()))
else:
return ""
|
python
|
def getWindow(self):
""" Returns the title of the main window of the currently open app.
Returns an empty string if no match could be found.
"""
if self.getPID() != -1:
return PlatformManager.getWindowTitle(PlatformManager.getWindowByPID(self.getPID()))
else:
return ""
|
[
"def",
"getWindow",
"(",
"self",
")",
":",
"if",
"self",
".",
"getPID",
"(",
")",
"!=",
"-",
"1",
":",
"return",
"PlatformManager",
".",
"getWindowTitle",
"(",
"PlatformManager",
".",
"getWindowByPID",
"(",
"self",
".",
"getPID",
"(",
")",
")",
")",
"else",
":",
"return",
"\"\""
] |
Returns the title of the main window of the currently open app.
Returns an empty string if no match could be found.
|
[
"Returns",
"the",
"title",
"of",
"the",
"main",
"window",
"of",
"the",
"currently",
"open",
"app",
"."
] |
7adadfacd7f45d81186710be992f5668b15399fe
|
https://github.com/glitchassassin/lackey/blob/7adadfacd7f45d81186710be992f5668b15399fe/lackey/App.py#L187-L195
|
6,779
|
glitchassassin/lackey
|
lackey/App.py
|
App.window
|
def window(self, windowNum=0):
""" Returns the region corresponding to the specified window of the app.
Defaults to the first window found for the corresponding PID.
"""
if self._pid == -1:
return None
x,y,w,h = PlatformManager.getWindowRect(PlatformManager.getWindowByPID(self._pid, windowNum))
return Region(x,y,w,h).clipRegionToScreen()
|
python
|
def window(self, windowNum=0):
""" Returns the region corresponding to the specified window of the app.
Defaults to the first window found for the corresponding PID.
"""
if self._pid == -1:
return None
x,y,w,h = PlatformManager.getWindowRect(PlatformManager.getWindowByPID(self._pid, windowNum))
return Region(x,y,w,h).clipRegionToScreen()
|
[
"def",
"window",
"(",
"self",
",",
"windowNum",
"=",
"0",
")",
":",
"if",
"self",
".",
"_pid",
"==",
"-",
"1",
":",
"return",
"None",
"x",
",",
"y",
",",
"w",
",",
"h",
"=",
"PlatformManager",
".",
"getWindowRect",
"(",
"PlatformManager",
".",
"getWindowByPID",
"(",
"self",
".",
"_pid",
",",
"windowNum",
")",
")",
"return",
"Region",
"(",
"x",
",",
"y",
",",
"w",
",",
"h",
")",
".",
"clipRegionToScreen",
"(",
")"
] |
Returns the region corresponding to the specified window of the app.
Defaults to the first window found for the corresponding PID.
|
[
"Returns",
"the",
"region",
"corresponding",
"to",
"the",
"specified",
"window",
"of",
"the",
"app",
"."
] |
7adadfacd7f45d81186710be992f5668b15399fe
|
https://github.com/glitchassassin/lackey/blob/7adadfacd7f45d81186710be992f5668b15399fe/lackey/App.py#L220-L228
|
6,780
|
glitchassassin/lackey
|
lackey/App.py
|
App.isRunning
|
def isRunning(self, waitTime=0):
""" If PID isn't set yet, checks if there is a window with the specified title. """
waitUntil = time.time() + waitTime
while True:
if self.getPID() > 0:
return True
else:
self._pid = PlatformManager.getWindowPID(PlatformManager.getWindowByTitle(re.escape(self._title)))
# Check if we've waited long enough
if time.time() > waitUntil:
break
else:
time.sleep(self._defaultScanRate)
return self.getPID() > 0
|
python
|
def isRunning(self, waitTime=0):
""" If PID isn't set yet, checks if there is a window with the specified title. """
waitUntil = time.time() + waitTime
while True:
if self.getPID() > 0:
return True
else:
self._pid = PlatformManager.getWindowPID(PlatformManager.getWindowByTitle(re.escape(self._title)))
# Check if we've waited long enough
if time.time() > waitUntil:
break
else:
time.sleep(self._defaultScanRate)
return self.getPID() > 0
|
[
"def",
"isRunning",
"(",
"self",
",",
"waitTime",
"=",
"0",
")",
":",
"waitUntil",
"=",
"time",
".",
"time",
"(",
")",
"+",
"waitTime",
"while",
"True",
":",
"if",
"self",
".",
"getPID",
"(",
")",
">",
"0",
":",
"return",
"True",
"else",
":",
"self",
".",
"_pid",
"=",
"PlatformManager",
".",
"getWindowPID",
"(",
"PlatformManager",
".",
"getWindowByTitle",
"(",
"re",
".",
"escape",
"(",
"self",
".",
"_title",
")",
")",
")",
"# Check if we've waited long enough",
"if",
"time",
".",
"time",
"(",
")",
">",
"waitUntil",
":",
"break",
"else",
":",
"time",
".",
"sleep",
"(",
"self",
".",
"_defaultScanRate",
")",
"return",
"self",
".",
"getPID",
"(",
")",
">",
"0"
] |
If PID isn't set yet, checks if there is a window with the specified title.
|
[
"If",
"PID",
"isn",
"t",
"set",
"yet",
"checks",
"if",
"there",
"is",
"a",
"window",
"with",
"the",
"specified",
"title",
"."
] |
7adadfacd7f45d81186710be992f5668b15399fe
|
https://github.com/glitchassassin/lackey/blob/7adadfacd7f45d81186710be992f5668b15399fe/lackey/App.py#L237-L251
|
6,781
|
glitchassassin/lackey
|
lackey/PlatformManagerDarwin.py
|
PlatformManagerDarwin._getVirtualScreenBitmap
|
def _getVirtualScreenBitmap(self):
""" Returns a bitmap of all attached screens """
filenames = []
screen_details = self.getScreenDetails()
for screen in screen_details:
fh, filepath = tempfile.mkstemp('.png')
filenames.append(filepath)
os.close(fh)
subprocess.call(['screencapture', '-x'] + filenames)
min_x, min_y, screen_w, screen_h = self._getVirtualScreenRect()
virtual_screen = Image.new("RGB", (screen_w, screen_h))
for filename, screen in zip(filenames, screen_details):
# Capture virtscreen coordinates of monitor
x, y, w, h = screen["rect"]
# Convert image size if needed
im = Image.open(filename)
im.load()
if im.size[0] != w or im.size[1] != h:
im = im.resize((int(w), int(h)), Image.ANTIALIAS)
# Convert to image-local coordinates
x = x - min_x
y = y - min_y
# Paste on the virtual screen
virtual_screen.paste(im, (x, y))
os.unlink(filename)
return virtual_screen
|
python
|
def _getVirtualScreenBitmap(self):
""" Returns a bitmap of all attached screens """
filenames = []
screen_details = self.getScreenDetails()
for screen in screen_details:
fh, filepath = tempfile.mkstemp('.png')
filenames.append(filepath)
os.close(fh)
subprocess.call(['screencapture', '-x'] + filenames)
min_x, min_y, screen_w, screen_h = self._getVirtualScreenRect()
virtual_screen = Image.new("RGB", (screen_w, screen_h))
for filename, screen in zip(filenames, screen_details):
# Capture virtscreen coordinates of monitor
x, y, w, h = screen["rect"]
# Convert image size if needed
im = Image.open(filename)
im.load()
if im.size[0] != w or im.size[1] != h:
im = im.resize((int(w), int(h)), Image.ANTIALIAS)
# Convert to image-local coordinates
x = x - min_x
y = y - min_y
# Paste on the virtual screen
virtual_screen.paste(im, (x, y))
os.unlink(filename)
return virtual_screen
|
[
"def",
"_getVirtualScreenBitmap",
"(",
"self",
")",
":",
"filenames",
"=",
"[",
"]",
"screen_details",
"=",
"self",
".",
"getScreenDetails",
"(",
")",
"for",
"screen",
"in",
"screen_details",
":",
"fh",
",",
"filepath",
"=",
"tempfile",
".",
"mkstemp",
"(",
"'.png'",
")",
"filenames",
".",
"append",
"(",
"filepath",
")",
"os",
".",
"close",
"(",
"fh",
")",
"subprocess",
".",
"call",
"(",
"[",
"'screencapture'",
",",
"'-x'",
"]",
"+",
"filenames",
")",
"min_x",
",",
"min_y",
",",
"screen_w",
",",
"screen_h",
"=",
"self",
".",
"_getVirtualScreenRect",
"(",
")",
"virtual_screen",
"=",
"Image",
".",
"new",
"(",
"\"RGB\"",
",",
"(",
"screen_w",
",",
"screen_h",
")",
")",
"for",
"filename",
",",
"screen",
"in",
"zip",
"(",
"filenames",
",",
"screen_details",
")",
":",
"# Capture virtscreen coordinates of monitor",
"x",
",",
"y",
",",
"w",
",",
"h",
"=",
"screen",
"[",
"\"rect\"",
"]",
"# Convert image size if needed",
"im",
"=",
"Image",
".",
"open",
"(",
"filename",
")",
"im",
".",
"load",
"(",
")",
"if",
"im",
".",
"size",
"[",
"0",
"]",
"!=",
"w",
"or",
"im",
".",
"size",
"[",
"1",
"]",
"!=",
"h",
":",
"im",
"=",
"im",
".",
"resize",
"(",
"(",
"int",
"(",
"w",
")",
",",
"int",
"(",
"h",
")",
")",
",",
"Image",
".",
"ANTIALIAS",
")",
"# Convert to image-local coordinates",
"x",
"=",
"x",
"-",
"min_x",
"y",
"=",
"y",
"-",
"min_y",
"# Paste on the virtual screen",
"virtual_screen",
".",
"paste",
"(",
"im",
",",
"(",
"x",
",",
"y",
")",
")",
"os",
".",
"unlink",
"(",
"filename",
")",
"return",
"virtual_screen"
] |
Returns a bitmap of all attached screens
|
[
"Returns",
"a",
"bitmap",
"of",
"all",
"attached",
"screens"
] |
7adadfacd7f45d81186710be992f5668b15399fe
|
https://github.com/glitchassassin/lackey/blob/7adadfacd7f45d81186710be992f5668b15399fe/lackey/PlatformManagerDarwin.py#L228-L254
|
6,782
|
glitchassassin/lackey
|
lackey/PlatformManagerDarwin.py
|
PlatformManagerDarwin.osCopy
|
def osCopy(self):
""" Triggers the OS "copy" keyboard shortcut """
k = Keyboard()
k.keyDown("{CTRL}")
k.type("c")
k.keyUp("{CTRL}")
|
python
|
def osCopy(self):
""" Triggers the OS "copy" keyboard shortcut """
k = Keyboard()
k.keyDown("{CTRL}")
k.type("c")
k.keyUp("{CTRL}")
|
[
"def",
"osCopy",
"(",
"self",
")",
":",
"k",
"=",
"Keyboard",
"(",
")",
"k",
".",
"keyDown",
"(",
"\"{CTRL}\"",
")",
"k",
".",
"type",
"(",
"\"c\"",
")",
"k",
".",
"keyUp",
"(",
"\"{CTRL}\"",
")"
] |
Triggers the OS "copy" keyboard shortcut
|
[
"Triggers",
"the",
"OS",
"copy",
"keyboard",
"shortcut"
] |
7adadfacd7f45d81186710be992f5668b15399fe
|
https://github.com/glitchassassin/lackey/blob/7adadfacd7f45d81186710be992f5668b15399fe/lackey/PlatformManagerDarwin.py#L287-L292
|
6,783
|
glitchassassin/lackey
|
lackey/PlatformManagerDarwin.py
|
PlatformManagerDarwin.getForegroundWindow
|
def getForegroundWindow(self):
""" Returns a handle to the window in the foreground """
active_app = NSWorkspace.sharedWorkspace().frontmostApplication().localizedName()
for w in self._get_window_list():
if "kCGWindowOwnerName" in w and w["kCGWindowOwnerName"] == active_app:
return w["kCGWindowNumber"]
|
python
|
def getForegroundWindow(self):
""" Returns a handle to the window in the foreground """
active_app = NSWorkspace.sharedWorkspace().frontmostApplication().localizedName()
for w in self._get_window_list():
if "kCGWindowOwnerName" in w and w["kCGWindowOwnerName"] == active_app:
return w["kCGWindowNumber"]
|
[
"def",
"getForegroundWindow",
"(",
"self",
")",
":",
"active_app",
"=",
"NSWorkspace",
".",
"sharedWorkspace",
"(",
")",
".",
"frontmostApplication",
"(",
")",
".",
"localizedName",
"(",
")",
"for",
"w",
"in",
"self",
".",
"_get_window_list",
"(",
")",
":",
"if",
"\"kCGWindowOwnerName\"",
"in",
"w",
"and",
"w",
"[",
"\"kCGWindowOwnerName\"",
"]",
"==",
"active_app",
":",
"return",
"w",
"[",
"\"kCGWindowNumber\"",
"]"
] |
Returns a handle to the window in the foreground
|
[
"Returns",
"a",
"handle",
"to",
"the",
"window",
"in",
"the",
"foreground"
] |
7adadfacd7f45d81186710be992f5668b15399fe
|
https://github.com/glitchassassin/lackey/blob/7adadfacd7f45d81186710be992f5668b15399fe/lackey/PlatformManagerDarwin.py#L347-L352
|
6,784
|
glitchassassin/lackey
|
lackey/PlatformManagerDarwin.py
|
PlatformManagerDarwin._get_window_list
|
def _get_window_list(self):
""" Returns a dictionary of details about open windows """
window_list = Quartz.CGWindowListCopyWindowInfo(Quartz.kCGWindowListExcludeDesktopElements, Quartz.kCGNullWindowID)
return window_list
|
python
|
def _get_window_list(self):
""" Returns a dictionary of details about open windows """
window_list = Quartz.CGWindowListCopyWindowInfo(Quartz.kCGWindowListExcludeDesktopElements, Quartz.kCGNullWindowID)
return window_list
|
[
"def",
"_get_window_list",
"(",
"self",
")",
":",
"window_list",
"=",
"Quartz",
".",
"CGWindowListCopyWindowInfo",
"(",
"Quartz",
".",
"kCGWindowListExcludeDesktopElements",
",",
"Quartz",
".",
"kCGNullWindowID",
")",
"return",
"window_list"
] |
Returns a dictionary of details about open windows
|
[
"Returns",
"a",
"dictionary",
"of",
"details",
"about",
"open",
"windows"
] |
7adadfacd7f45d81186710be992f5668b15399fe
|
https://github.com/glitchassassin/lackey/blob/7adadfacd7f45d81186710be992f5668b15399fe/lackey/PlatformManagerDarwin.py#L354-L357
|
6,785
|
glitchassassin/lackey
|
lackey/PlatformManagerDarwin.py
|
PlatformManagerDarwin.getProcessName
|
def getProcessName(self, pid):
""" Searches all processes for the given PID, then returns the originating command """
ps = subprocess.check_output(["ps", "aux"]).decode("ascii")
processes = ps.split("\n")
cols = len(processes[0].split()) - 1
for row in processes[1:]:
if row != "":
proc = row.split(None, cols)
if proc[1].strip() == str(pid):
return proc[-1]
|
python
|
def getProcessName(self, pid):
""" Searches all processes for the given PID, then returns the originating command """
ps = subprocess.check_output(["ps", "aux"]).decode("ascii")
processes = ps.split("\n")
cols = len(processes[0].split()) - 1
for row in processes[1:]:
if row != "":
proc = row.split(None, cols)
if proc[1].strip() == str(pid):
return proc[-1]
|
[
"def",
"getProcessName",
"(",
"self",
",",
"pid",
")",
":",
"ps",
"=",
"subprocess",
".",
"check_output",
"(",
"[",
"\"ps\"",
",",
"\"aux\"",
"]",
")",
".",
"decode",
"(",
"\"ascii\"",
")",
"processes",
"=",
"ps",
".",
"split",
"(",
"\"\\n\"",
")",
"cols",
"=",
"len",
"(",
"processes",
"[",
"0",
"]",
".",
"split",
"(",
")",
")",
"-",
"1",
"for",
"row",
"in",
"processes",
"[",
"1",
":",
"]",
":",
"if",
"row",
"!=",
"\"\"",
":",
"proc",
"=",
"row",
".",
"split",
"(",
"None",
",",
"cols",
")",
"if",
"proc",
"[",
"1",
"]",
".",
"strip",
"(",
")",
"==",
"str",
"(",
"pid",
")",
":",
"return",
"proc",
"[",
"-",
"1",
"]"
] |
Searches all processes for the given PID, then returns the originating command
|
[
"Searches",
"all",
"processes",
"for",
"the",
"given",
"PID",
"then",
"returns",
"the",
"originating",
"command"
] |
7adadfacd7f45d81186710be992f5668b15399fe
|
https://github.com/glitchassassin/lackey/blob/7adadfacd7f45d81186710be992f5668b15399fe/lackey/PlatformManagerDarwin.py#L407-L416
|
6,786
|
glitchassassin/lackey
|
lackey/InputEmulation.py
|
Mouse.moveSpeed
|
def moveSpeed(self, location, seconds=0.3):
""" Moves cursor to specified ``Location`` over ``seconds``.
If ``seconds`` is 0, moves the cursor immediately. Used for smooth
somewhat-human-like motion.
"""
self._lock.acquire()
original_location = mouse.get_position()
mouse.move(location.x, location.y, duration=seconds)
if mouse.get_position() == original_location and original_location != location.getTuple():
raise IOError("""
Unable to move mouse cursor. This may happen if you're trying to automate a
program running as Administrator with a script running as a non-elevated user.
""")
self._lock.release()
|
python
|
def moveSpeed(self, location, seconds=0.3):
""" Moves cursor to specified ``Location`` over ``seconds``.
If ``seconds`` is 0, moves the cursor immediately. Used for smooth
somewhat-human-like motion.
"""
self._lock.acquire()
original_location = mouse.get_position()
mouse.move(location.x, location.y, duration=seconds)
if mouse.get_position() == original_location and original_location != location.getTuple():
raise IOError("""
Unable to move mouse cursor. This may happen if you're trying to automate a
program running as Administrator with a script running as a non-elevated user.
""")
self._lock.release()
|
[
"def",
"moveSpeed",
"(",
"self",
",",
"location",
",",
"seconds",
"=",
"0.3",
")",
":",
"self",
".",
"_lock",
".",
"acquire",
"(",
")",
"original_location",
"=",
"mouse",
".",
"get_position",
"(",
")",
"mouse",
".",
"move",
"(",
"location",
".",
"x",
",",
"location",
".",
"y",
",",
"duration",
"=",
"seconds",
")",
"if",
"mouse",
".",
"get_position",
"(",
")",
"==",
"original_location",
"and",
"original_location",
"!=",
"location",
".",
"getTuple",
"(",
")",
":",
"raise",
"IOError",
"(",
"\"\"\"\n Unable to move mouse cursor. This may happen if you're trying to automate a \n program running as Administrator with a script running as a non-elevated user.\n \"\"\"",
")",
"self",
".",
"_lock",
".",
"release",
"(",
")"
] |
Moves cursor to specified ``Location`` over ``seconds``.
If ``seconds`` is 0, moves the cursor immediately. Used for smooth
somewhat-human-like motion.
|
[
"Moves",
"cursor",
"to",
"specified",
"Location",
"over",
"seconds",
"."
] |
7adadfacd7f45d81186710be992f5668b15399fe
|
https://github.com/glitchassassin/lackey/blob/7adadfacd7f45d81186710be992f5668b15399fe/lackey/InputEmulation.py#L59-L73
|
6,787
|
glitchassassin/lackey
|
lackey/InputEmulation.py
|
Mouse.click
|
def click(self, loc=None, button=mouse.LEFT):
""" Clicks the specified mouse button.
If ``loc`` is set, move the mouse to that Location first.
Use button constants Mouse.LEFT, Mouse.MIDDLE, Mouse.RIGHT
"""
if loc is not None:
self.moveSpeed(loc)
self._lock.acquire()
mouse.click(button)
self._lock.release()
|
python
|
def click(self, loc=None, button=mouse.LEFT):
""" Clicks the specified mouse button.
If ``loc`` is set, move the mouse to that Location first.
Use button constants Mouse.LEFT, Mouse.MIDDLE, Mouse.RIGHT
"""
if loc is not None:
self.moveSpeed(loc)
self._lock.acquire()
mouse.click(button)
self._lock.release()
|
[
"def",
"click",
"(",
"self",
",",
"loc",
"=",
"None",
",",
"button",
"=",
"mouse",
".",
"LEFT",
")",
":",
"if",
"loc",
"is",
"not",
"None",
":",
"self",
".",
"moveSpeed",
"(",
"loc",
")",
"self",
".",
"_lock",
".",
"acquire",
"(",
")",
"mouse",
".",
"click",
"(",
"button",
")",
"self",
".",
"_lock",
".",
"release",
"(",
")"
] |
Clicks the specified mouse button.
If ``loc`` is set, move the mouse to that Location first.
Use button constants Mouse.LEFT, Mouse.MIDDLE, Mouse.RIGHT
|
[
"Clicks",
"the",
"specified",
"mouse",
"button",
"."
] |
7adadfacd7f45d81186710be992f5668b15399fe
|
https://github.com/glitchassassin/lackey/blob/7adadfacd7f45d81186710be992f5668b15399fe/lackey/InputEmulation.py#L75-L86
|
6,788
|
glitchassassin/lackey
|
lackey/InputEmulation.py
|
Mouse.buttonDown
|
def buttonDown(self, button=mouse.LEFT):
""" Holds down the specified mouse button.
Use Mouse.LEFT, Mouse.MIDDLE, Mouse.RIGHT
"""
self._lock.acquire()
mouse.press(button)
self._lock.release()
|
python
|
def buttonDown(self, button=mouse.LEFT):
""" Holds down the specified mouse button.
Use Mouse.LEFT, Mouse.MIDDLE, Mouse.RIGHT
"""
self._lock.acquire()
mouse.press(button)
self._lock.release()
|
[
"def",
"buttonDown",
"(",
"self",
",",
"button",
"=",
"mouse",
".",
"LEFT",
")",
":",
"self",
".",
"_lock",
".",
"acquire",
"(",
")",
"mouse",
".",
"press",
"(",
"button",
")",
"self",
".",
"_lock",
".",
"release",
"(",
")"
] |
Holds down the specified mouse button.
Use Mouse.LEFT, Mouse.MIDDLE, Mouse.RIGHT
|
[
"Holds",
"down",
"the",
"specified",
"mouse",
"button",
"."
] |
7adadfacd7f45d81186710be992f5668b15399fe
|
https://github.com/glitchassassin/lackey/blob/7adadfacd7f45d81186710be992f5668b15399fe/lackey/InputEmulation.py#L87-L94
|
6,789
|
glitchassassin/lackey
|
lackey/InputEmulation.py
|
Mouse.buttonUp
|
def buttonUp(self, button=mouse.LEFT):
""" Releases the specified mouse button.
Use Mouse.LEFT, Mouse.MIDDLE, Mouse.RIGHT
"""
self._lock.acquire()
mouse.release(button)
self._lock.release()
|
python
|
def buttonUp(self, button=mouse.LEFT):
""" Releases the specified mouse button.
Use Mouse.LEFT, Mouse.MIDDLE, Mouse.RIGHT
"""
self._lock.acquire()
mouse.release(button)
self._lock.release()
|
[
"def",
"buttonUp",
"(",
"self",
",",
"button",
"=",
"mouse",
".",
"LEFT",
")",
":",
"self",
".",
"_lock",
".",
"acquire",
"(",
")",
"mouse",
".",
"release",
"(",
"button",
")",
"self",
".",
"_lock",
".",
"release",
"(",
")"
] |
Releases the specified mouse button.
Use Mouse.LEFT, Mouse.MIDDLE, Mouse.RIGHT
|
[
"Releases",
"the",
"specified",
"mouse",
"button",
"."
] |
7adadfacd7f45d81186710be992f5668b15399fe
|
https://github.com/glitchassassin/lackey/blob/7adadfacd7f45d81186710be992f5668b15399fe/lackey/InputEmulation.py#L96-L103
|
6,790
|
glitchassassin/lackey
|
lackey/InputEmulation.py
|
Mouse.wheel
|
def wheel(self, direction, steps):
""" Clicks the wheel the specified number of steps in the given direction.
Use Mouse.WHEEL_DOWN, Mouse.WHEEL_UP
"""
self._lock.acquire()
if direction == 1:
wheel_moved = steps
elif direction == 0:
wheel_moved = -1*steps
else:
raise ValueError("Expected direction to be 1 or 0")
self._lock.release()
return mouse.wheel(wheel_moved)
|
python
|
def wheel(self, direction, steps):
""" Clicks the wheel the specified number of steps in the given direction.
Use Mouse.WHEEL_DOWN, Mouse.WHEEL_UP
"""
self._lock.acquire()
if direction == 1:
wheel_moved = steps
elif direction == 0:
wheel_moved = -1*steps
else:
raise ValueError("Expected direction to be 1 or 0")
self._lock.release()
return mouse.wheel(wheel_moved)
|
[
"def",
"wheel",
"(",
"self",
",",
"direction",
",",
"steps",
")",
":",
"self",
".",
"_lock",
".",
"acquire",
"(",
")",
"if",
"direction",
"==",
"1",
":",
"wheel_moved",
"=",
"steps",
"elif",
"direction",
"==",
"0",
":",
"wheel_moved",
"=",
"-",
"1",
"*",
"steps",
"else",
":",
"raise",
"ValueError",
"(",
"\"Expected direction to be 1 or 0\"",
")",
"self",
".",
"_lock",
".",
"release",
"(",
")",
"return",
"mouse",
".",
"wheel",
"(",
"wheel_moved",
")"
] |
Clicks the wheel the specified number of steps in the given direction.
Use Mouse.WHEEL_DOWN, Mouse.WHEEL_UP
|
[
"Clicks",
"the",
"wheel",
"the",
"specified",
"number",
"of",
"steps",
"in",
"the",
"given",
"direction",
"."
] |
7adadfacd7f45d81186710be992f5668b15399fe
|
https://github.com/glitchassassin/lackey/blob/7adadfacd7f45d81186710be992f5668b15399fe/lackey/InputEmulation.py#L105-L118
|
6,791
|
glitchassassin/lackey
|
lackey/InputEmulation.py
|
Keyboard.type
|
def type(self, text, delay=0.1):
""" Translates a string into a series of keystrokes.
Respects Sikuli special codes, like "{ENTER}".
"""
in_special_code = False
special_code = ""
modifier_held = False
modifier_stuck = False
modifier_codes = []
for i in range(0, len(text)):
if text[i] == "{":
in_special_code = True
elif in_special_code and (text[i] == "}" or text[i] == " " or i == len(text)-1):
in_special_code = False
if special_code in self._SPECIAL_KEYCODES.keys():
# Found a special code
keyboard.press_and_release(self._SPECIAL_KEYCODES[special_code])
else:
# Wasn't a special code, just treat it as keystrokes
keyboard.press(self._SPECIAL_KEYCODES["SHIFT"])
keyboard.press_and_release(self._UPPERCASE_KEYCODES["{"])
keyboard.release(self._SPECIAL_KEYCODES["SHIFT"])
# Release the rest of the keys normally
self.type(special_code)
self.type(text[i])
special_code = ""
elif in_special_code:
special_code += text[i]
elif text[i] in self._REGULAR_KEYCODES.keys():
keyboard.press(self._REGULAR_KEYCODES[text[i]])
keyboard.release(self._REGULAR_KEYCODES[text[i]])
elif text[i] in self._UPPERCASE_KEYCODES.keys():
keyboard.press(self._SPECIAL_KEYCODES["SHIFT"])
keyboard.press_and_release(self._UPPERCASE_KEYCODES[text[i]])
keyboard.release(self._SPECIAL_KEYCODES["SHIFT"])
if delay and not in_special_code:
time.sleep(delay)
|
python
|
def type(self, text, delay=0.1):
""" Translates a string into a series of keystrokes.
Respects Sikuli special codes, like "{ENTER}".
"""
in_special_code = False
special_code = ""
modifier_held = False
modifier_stuck = False
modifier_codes = []
for i in range(0, len(text)):
if text[i] == "{":
in_special_code = True
elif in_special_code and (text[i] == "}" or text[i] == " " or i == len(text)-1):
in_special_code = False
if special_code in self._SPECIAL_KEYCODES.keys():
# Found a special code
keyboard.press_and_release(self._SPECIAL_KEYCODES[special_code])
else:
# Wasn't a special code, just treat it as keystrokes
keyboard.press(self._SPECIAL_KEYCODES["SHIFT"])
keyboard.press_and_release(self._UPPERCASE_KEYCODES["{"])
keyboard.release(self._SPECIAL_KEYCODES["SHIFT"])
# Release the rest of the keys normally
self.type(special_code)
self.type(text[i])
special_code = ""
elif in_special_code:
special_code += text[i]
elif text[i] in self._REGULAR_KEYCODES.keys():
keyboard.press(self._REGULAR_KEYCODES[text[i]])
keyboard.release(self._REGULAR_KEYCODES[text[i]])
elif text[i] in self._UPPERCASE_KEYCODES.keys():
keyboard.press(self._SPECIAL_KEYCODES["SHIFT"])
keyboard.press_and_release(self._UPPERCASE_KEYCODES[text[i]])
keyboard.release(self._SPECIAL_KEYCODES["SHIFT"])
if delay and not in_special_code:
time.sleep(delay)
|
[
"def",
"type",
"(",
"self",
",",
"text",
",",
"delay",
"=",
"0.1",
")",
":",
"in_special_code",
"=",
"False",
"special_code",
"=",
"\"\"",
"modifier_held",
"=",
"False",
"modifier_stuck",
"=",
"False",
"modifier_codes",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"text",
")",
")",
":",
"if",
"text",
"[",
"i",
"]",
"==",
"\"{\"",
":",
"in_special_code",
"=",
"True",
"elif",
"in_special_code",
"and",
"(",
"text",
"[",
"i",
"]",
"==",
"\"}\"",
"or",
"text",
"[",
"i",
"]",
"==",
"\" \"",
"or",
"i",
"==",
"len",
"(",
"text",
")",
"-",
"1",
")",
":",
"in_special_code",
"=",
"False",
"if",
"special_code",
"in",
"self",
".",
"_SPECIAL_KEYCODES",
".",
"keys",
"(",
")",
":",
"# Found a special code",
"keyboard",
".",
"press_and_release",
"(",
"self",
".",
"_SPECIAL_KEYCODES",
"[",
"special_code",
"]",
")",
"else",
":",
"# Wasn't a special code, just treat it as keystrokes",
"keyboard",
".",
"press",
"(",
"self",
".",
"_SPECIAL_KEYCODES",
"[",
"\"SHIFT\"",
"]",
")",
"keyboard",
".",
"press_and_release",
"(",
"self",
".",
"_UPPERCASE_KEYCODES",
"[",
"\"{\"",
"]",
")",
"keyboard",
".",
"release",
"(",
"self",
".",
"_SPECIAL_KEYCODES",
"[",
"\"SHIFT\"",
"]",
")",
"# Release the rest of the keys normally",
"self",
".",
"type",
"(",
"special_code",
")",
"self",
".",
"type",
"(",
"text",
"[",
"i",
"]",
")",
"special_code",
"=",
"\"\"",
"elif",
"in_special_code",
":",
"special_code",
"+=",
"text",
"[",
"i",
"]",
"elif",
"text",
"[",
"i",
"]",
"in",
"self",
".",
"_REGULAR_KEYCODES",
".",
"keys",
"(",
")",
":",
"keyboard",
".",
"press",
"(",
"self",
".",
"_REGULAR_KEYCODES",
"[",
"text",
"[",
"i",
"]",
"]",
")",
"keyboard",
".",
"release",
"(",
"self",
".",
"_REGULAR_KEYCODES",
"[",
"text",
"[",
"i",
"]",
"]",
")",
"elif",
"text",
"[",
"i",
"]",
"in",
"self",
".",
"_UPPERCASE_KEYCODES",
".",
"keys",
"(",
")",
":",
"keyboard",
".",
"press",
"(",
"self",
".",
"_SPECIAL_KEYCODES",
"[",
"\"SHIFT\"",
"]",
")",
"keyboard",
".",
"press_and_release",
"(",
"self",
".",
"_UPPERCASE_KEYCODES",
"[",
"text",
"[",
"i",
"]",
"]",
")",
"keyboard",
".",
"release",
"(",
"self",
".",
"_SPECIAL_KEYCODES",
"[",
"\"SHIFT\"",
"]",
")",
"if",
"delay",
"and",
"not",
"in_special_code",
":",
"time",
".",
"sleep",
"(",
"delay",
")"
] |
Translates a string into a series of keystrokes.
Respects Sikuli special codes, like "{ENTER}".
|
[
"Translates",
"a",
"string",
"into",
"a",
"series",
"of",
"keystrokes",
"."
] |
7adadfacd7f45d81186710be992f5668b15399fe
|
https://github.com/glitchassassin/lackey/blob/7adadfacd7f45d81186710be992f5668b15399fe/lackey/InputEmulation.py#L347-L385
|
6,792
|
glitchassassin/lackey
|
lackey/TemplateMatchers.py
|
NaiveTemplateMatcher.findBestMatch
|
def findBestMatch(self, needle, similarity):
""" Find the best match for ``needle`` that has a similarity better than or equal to ``similarity``.
Returns a tuple of ``(position, confidence)`` if a match is found, or ``None`` otherwise.
*Developer's Note - Despite the name, this method actually returns the **first** result
with enough similarity, not the **best** result.*
"""
method = cv2.TM_CCOEFF_NORMED
position = None
match = cv2.matchTemplate(self.haystack, needle, method)
min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(match)
if method == cv2.TM_SQDIFF_NORMED or method == cv2.TM_SQDIFF:
confidence = min_val
if min_val <= 1-similarity:
# Confidence checks out
position = min_loc
else:
confidence = max_val
if max_val >= similarity:
# Confidence checks out
position = max_loc
if not position:
return None
return (position, confidence)
|
python
|
def findBestMatch(self, needle, similarity):
""" Find the best match for ``needle`` that has a similarity better than or equal to ``similarity``.
Returns a tuple of ``(position, confidence)`` if a match is found, or ``None`` otherwise.
*Developer's Note - Despite the name, this method actually returns the **first** result
with enough similarity, not the **best** result.*
"""
method = cv2.TM_CCOEFF_NORMED
position = None
match = cv2.matchTemplate(self.haystack, needle, method)
min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(match)
if method == cv2.TM_SQDIFF_NORMED or method == cv2.TM_SQDIFF:
confidence = min_val
if min_val <= 1-similarity:
# Confidence checks out
position = min_loc
else:
confidence = max_val
if max_val >= similarity:
# Confidence checks out
position = max_loc
if not position:
return None
return (position, confidence)
|
[
"def",
"findBestMatch",
"(",
"self",
",",
"needle",
",",
"similarity",
")",
":",
"method",
"=",
"cv2",
".",
"TM_CCOEFF_NORMED",
"position",
"=",
"None",
"match",
"=",
"cv2",
".",
"matchTemplate",
"(",
"self",
".",
"haystack",
",",
"needle",
",",
"method",
")",
"min_val",
",",
"max_val",
",",
"min_loc",
",",
"max_loc",
"=",
"cv2",
".",
"minMaxLoc",
"(",
"match",
")",
"if",
"method",
"==",
"cv2",
".",
"TM_SQDIFF_NORMED",
"or",
"method",
"==",
"cv2",
".",
"TM_SQDIFF",
":",
"confidence",
"=",
"min_val",
"if",
"min_val",
"<=",
"1",
"-",
"similarity",
":",
"# Confidence checks out",
"position",
"=",
"min_loc",
"else",
":",
"confidence",
"=",
"max_val",
"if",
"max_val",
">=",
"similarity",
":",
"# Confidence checks out",
"position",
"=",
"max_loc",
"if",
"not",
"position",
":",
"return",
"None",
"return",
"(",
"position",
",",
"confidence",
")"
] |
Find the best match for ``needle`` that has a similarity better than or equal to ``similarity``.
Returns a tuple of ``(position, confidence)`` if a match is found, or ``None`` otherwise.
*Developer's Note - Despite the name, this method actually returns the **first** result
with enough similarity, not the **best** result.*
|
[
"Find",
"the",
"best",
"match",
"for",
"needle",
"that",
"has",
"a",
"similarity",
"better",
"than",
"or",
"equal",
"to",
"similarity",
"."
] |
7adadfacd7f45d81186710be992f5668b15399fe
|
https://github.com/glitchassassin/lackey/blob/7adadfacd7f45d81186710be992f5668b15399fe/lackey/TemplateMatchers.py#L16-L43
|
6,793
|
glitchassassin/lackey
|
lackey/TemplateMatchers.py
|
NaiveTemplateMatcher.findAllMatches
|
def findAllMatches(self, needle, similarity):
""" Find all matches for ``needle`` with confidence better than or equal to ``similarity``.
Returns an array of tuples ``(position, confidence)`` if match(es) is/are found,
or an empty array otherwise.
"""
positions = []
method = cv2.TM_CCOEFF_NORMED
match = cv2.matchTemplate(self.haystack, self.needle, method)
indices = (-match).argpartition(100, axis=None)[:100] # Review the 100 top matches
unraveled_indices = numpy.array(numpy.unravel_index(indices, match.shape)).T
for location in unraveled_indices:
y, x = location
confidence = match[y][x]
if method == cv2.TM_SQDIFF_NORMED or method == cv2.TM_SQDIFF:
if confidence <= 1-similarity:
positions.append(((x, y), confidence))
else:
if confidence >= similarity:
positions.append(((x, y), confidence))
positions.sort(key=lambda x: (x[0][1], x[0][0]))
return positions
|
python
|
def findAllMatches(self, needle, similarity):
""" Find all matches for ``needle`` with confidence better than or equal to ``similarity``.
Returns an array of tuples ``(position, confidence)`` if match(es) is/are found,
or an empty array otherwise.
"""
positions = []
method = cv2.TM_CCOEFF_NORMED
match = cv2.matchTemplate(self.haystack, self.needle, method)
indices = (-match).argpartition(100, axis=None)[:100] # Review the 100 top matches
unraveled_indices = numpy.array(numpy.unravel_index(indices, match.shape)).T
for location in unraveled_indices:
y, x = location
confidence = match[y][x]
if method == cv2.TM_SQDIFF_NORMED or method == cv2.TM_SQDIFF:
if confidence <= 1-similarity:
positions.append(((x, y), confidence))
else:
if confidence >= similarity:
positions.append(((x, y), confidence))
positions.sort(key=lambda x: (x[0][1], x[0][0]))
return positions
|
[
"def",
"findAllMatches",
"(",
"self",
",",
"needle",
",",
"similarity",
")",
":",
"positions",
"=",
"[",
"]",
"method",
"=",
"cv2",
".",
"TM_CCOEFF_NORMED",
"match",
"=",
"cv2",
".",
"matchTemplate",
"(",
"self",
".",
"haystack",
",",
"self",
".",
"needle",
",",
"method",
")",
"indices",
"=",
"(",
"-",
"match",
")",
".",
"argpartition",
"(",
"100",
",",
"axis",
"=",
"None",
")",
"[",
":",
"100",
"]",
"# Review the 100 top matches",
"unraveled_indices",
"=",
"numpy",
".",
"array",
"(",
"numpy",
".",
"unravel_index",
"(",
"indices",
",",
"match",
".",
"shape",
")",
")",
".",
"T",
"for",
"location",
"in",
"unraveled_indices",
":",
"y",
",",
"x",
"=",
"location",
"confidence",
"=",
"match",
"[",
"y",
"]",
"[",
"x",
"]",
"if",
"method",
"==",
"cv2",
".",
"TM_SQDIFF_NORMED",
"or",
"method",
"==",
"cv2",
".",
"TM_SQDIFF",
":",
"if",
"confidence",
"<=",
"1",
"-",
"similarity",
":",
"positions",
".",
"append",
"(",
"(",
"(",
"x",
",",
"y",
")",
",",
"confidence",
")",
")",
"else",
":",
"if",
"confidence",
">=",
"similarity",
":",
"positions",
".",
"append",
"(",
"(",
"(",
"x",
",",
"y",
")",
",",
"confidence",
")",
")",
"positions",
".",
"sort",
"(",
"key",
"=",
"lambda",
"x",
":",
"(",
"x",
"[",
"0",
"]",
"[",
"1",
"]",
",",
"x",
"[",
"0",
"]",
"[",
"0",
"]",
")",
")",
"return",
"positions"
] |
Find all matches for ``needle`` with confidence better than or equal to ``similarity``.
Returns an array of tuples ``(position, confidence)`` if match(es) is/are found,
or an empty array otherwise.
|
[
"Find",
"all",
"matches",
"for",
"needle",
"with",
"confidence",
"better",
"than",
"or",
"equal",
"to",
"similarity",
"."
] |
7adadfacd7f45d81186710be992f5668b15399fe
|
https://github.com/glitchassassin/lackey/blob/7adadfacd7f45d81186710be992f5668b15399fe/lackey/TemplateMatchers.py#L45-L69
|
6,794
|
glitchassassin/lackey
|
lackey/TemplateMatchers.py
|
PyramidTemplateMatcher.findAllMatches
|
def findAllMatches(self, needle, similarity):
""" Finds all matches above ``similarity`` using a search pyramid to improve efficiency
Pyramid implementation unashamedly stolen from https://github.com/stb-tester/stb-tester
"""
positions = []
# Use findBestMatch to get the best match
while True:
best_match = self.findBestMatch(needle, similarity)
if best_match is None: # No more matches
break
# Found a match. Add it to our list
positions.append(best_match) # (position, confidence)
# Erase the found match from the haystack.
# Repeat this process until no other matches are found
x, y = best_match[0]
w = needle.shape[1]
h = needle.shape[0]
roi = (x, y, w, h)
# numpy 2D slice
roi_slice = (slice(roi[1], roi[1]+roi[3]), slice(roi[0], roi[0]+roi[2]))
self.haystack[roi_slice] = 0
# Whew! Let's see if there's a match after all that.
positions.sort(key=lambda x: (x[0][1], x[0][0]))
return positions
|
python
|
def findAllMatches(self, needle, similarity):
""" Finds all matches above ``similarity`` using a search pyramid to improve efficiency
Pyramid implementation unashamedly stolen from https://github.com/stb-tester/stb-tester
"""
positions = []
# Use findBestMatch to get the best match
while True:
best_match = self.findBestMatch(needle, similarity)
if best_match is None: # No more matches
break
# Found a match. Add it to our list
positions.append(best_match) # (position, confidence)
# Erase the found match from the haystack.
# Repeat this process until no other matches are found
x, y = best_match[0]
w = needle.shape[1]
h = needle.shape[0]
roi = (x, y, w, h)
# numpy 2D slice
roi_slice = (slice(roi[1], roi[1]+roi[3]), slice(roi[0], roi[0]+roi[2]))
self.haystack[roi_slice] = 0
# Whew! Let's see if there's a match after all that.
positions.sort(key=lambda x: (x[0][1], x[0][0]))
return positions
|
[
"def",
"findAllMatches",
"(",
"self",
",",
"needle",
",",
"similarity",
")",
":",
"positions",
"=",
"[",
"]",
"# Use findBestMatch to get the best match",
"while",
"True",
":",
"best_match",
"=",
"self",
".",
"findBestMatch",
"(",
"needle",
",",
"similarity",
")",
"if",
"best_match",
"is",
"None",
":",
"# No more matches",
"break",
"# Found a match. Add it to our list",
"positions",
".",
"append",
"(",
"best_match",
")",
"# (position, confidence)",
"# Erase the found match from the haystack.",
"# Repeat this process until no other matches are found",
"x",
",",
"y",
"=",
"best_match",
"[",
"0",
"]",
"w",
"=",
"needle",
".",
"shape",
"[",
"1",
"]",
"h",
"=",
"needle",
".",
"shape",
"[",
"0",
"]",
"roi",
"=",
"(",
"x",
",",
"y",
",",
"w",
",",
"h",
")",
"# numpy 2D slice",
"roi_slice",
"=",
"(",
"slice",
"(",
"roi",
"[",
"1",
"]",
",",
"roi",
"[",
"1",
"]",
"+",
"roi",
"[",
"3",
"]",
")",
",",
"slice",
"(",
"roi",
"[",
"0",
"]",
",",
"roi",
"[",
"0",
"]",
"+",
"roi",
"[",
"2",
"]",
")",
")",
"self",
".",
"haystack",
"[",
"roi_slice",
"]",
"=",
"0",
"# Whew! Let's see if there's a match after all that.",
"positions",
".",
"sort",
"(",
"key",
"=",
"lambda",
"x",
":",
"(",
"x",
"[",
"0",
"]",
"[",
"1",
"]",
",",
"x",
"[",
"0",
"]",
"[",
"0",
"]",
")",
")",
"return",
"positions"
] |
Finds all matches above ``similarity`` using a search pyramid to improve efficiency
Pyramid implementation unashamedly stolen from https://github.com/stb-tester/stb-tester
|
[
"Finds",
"all",
"matches",
"above",
"similarity",
"using",
"a",
"search",
"pyramid",
"to",
"improve",
"efficiency"
] |
7adadfacd7f45d81186710be992f5668b15399fe
|
https://github.com/glitchassassin/lackey/blob/7adadfacd7f45d81186710be992f5668b15399fe/lackey/TemplateMatchers.py#L218-L244
|
6,795
|
glitchassassin/lackey
|
lackey/TemplateMatchers.py
|
PyramidTemplateMatcher._build_pyramid
|
def _build_pyramid(self, image, levels):
""" Returns a list of reduced-size images, from smallest to original size """
pyramid = [image]
for l in range(levels-1):
if any(x < 20 for x in pyramid[-1].shape[:2]):
break
pyramid.append(cv2.pyrDown(pyramid[-1]))
return list(reversed(pyramid))
|
python
|
def _build_pyramid(self, image, levels):
""" Returns a list of reduced-size images, from smallest to original size """
pyramid = [image]
for l in range(levels-1):
if any(x < 20 for x in pyramid[-1].shape[:2]):
break
pyramid.append(cv2.pyrDown(pyramid[-1]))
return list(reversed(pyramid))
|
[
"def",
"_build_pyramid",
"(",
"self",
",",
"image",
",",
"levels",
")",
":",
"pyramid",
"=",
"[",
"image",
"]",
"for",
"l",
"in",
"range",
"(",
"levels",
"-",
"1",
")",
":",
"if",
"any",
"(",
"x",
"<",
"20",
"for",
"x",
"in",
"pyramid",
"[",
"-",
"1",
"]",
".",
"shape",
"[",
":",
"2",
"]",
")",
":",
"break",
"pyramid",
".",
"append",
"(",
"cv2",
".",
"pyrDown",
"(",
"pyramid",
"[",
"-",
"1",
"]",
")",
")",
"return",
"list",
"(",
"reversed",
"(",
"pyramid",
")",
")"
] |
Returns a list of reduced-size images, from smallest to original size
|
[
"Returns",
"a",
"list",
"of",
"reduced",
"-",
"size",
"images",
"from",
"smallest",
"to",
"original",
"size"
] |
7adadfacd7f45d81186710be992f5668b15399fe
|
https://github.com/glitchassassin/lackey/blob/7adadfacd7f45d81186710be992f5668b15399fe/lackey/TemplateMatchers.py#L246-L253
|
6,796
|
google-research/batch-ppo
|
agents/tools/count_weights.py
|
count_weights
|
def count_weights(scope=None, exclude=None, graph=None):
"""Count learnable parameters.
Args:
scope: Restrict the count to a variable scope.
exclude: Regex to match variable names to exclude.
graph: Operate on a graph other than the current default graph.
Returns:
Number of learnable parameters as integer.
"""
if scope:
scope = scope if scope.endswith('/') else scope + '/'
graph = graph or tf.get_default_graph()
vars_ = graph.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES)
if scope:
vars_ = [var for var in vars_ if var.name.startswith(scope)]
if exclude:
exclude = re.compile(exclude)
vars_ = [var for var in vars_ if not exclude.match(var.name)]
shapes = [var.get_shape().as_list() for var in vars_]
return int(sum(np.prod(shape) for shape in shapes))
|
python
|
def count_weights(scope=None, exclude=None, graph=None):
"""Count learnable parameters.
Args:
scope: Restrict the count to a variable scope.
exclude: Regex to match variable names to exclude.
graph: Operate on a graph other than the current default graph.
Returns:
Number of learnable parameters as integer.
"""
if scope:
scope = scope if scope.endswith('/') else scope + '/'
graph = graph or tf.get_default_graph()
vars_ = graph.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES)
if scope:
vars_ = [var for var in vars_ if var.name.startswith(scope)]
if exclude:
exclude = re.compile(exclude)
vars_ = [var for var in vars_ if not exclude.match(var.name)]
shapes = [var.get_shape().as_list() for var in vars_]
return int(sum(np.prod(shape) for shape in shapes))
|
[
"def",
"count_weights",
"(",
"scope",
"=",
"None",
",",
"exclude",
"=",
"None",
",",
"graph",
"=",
"None",
")",
":",
"if",
"scope",
":",
"scope",
"=",
"scope",
"if",
"scope",
".",
"endswith",
"(",
"'/'",
")",
"else",
"scope",
"+",
"'/'",
"graph",
"=",
"graph",
"or",
"tf",
".",
"get_default_graph",
"(",
")",
"vars_",
"=",
"graph",
".",
"get_collection",
"(",
"tf",
".",
"GraphKeys",
".",
"TRAINABLE_VARIABLES",
")",
"if",
"scope",
":",
"vars_",
"=",
"[",
"var",
"for",
"var",
"in",
"vars_",
"if",
"var",
".",
"name",
".",
"startswith",
"(",
"scope",
")",
"]",
"if",
"exclude",
":",
"exclude",
"=",
"re",
".",
"compile",
"(",
"exclude",
")",
"vars_",
"=",
"[",
"var",
"for",
"var",
"in",
"vars_",
"if",
"not",
"exclude",
".",
"match",
"(",
"var",
".",
"name",
")",
"]",
"shapes",
"=",
"[",
"var",
".",
"get_shape",
"(",
")",
".",
"as_list",
"(",
")",
"for",
"var",
"in",
"vars_",
"]",
"return",
"int",
"(",
"sum",
"(",
"np",
".",
"prod",
"(",
"shape",
")",
"for",
"shape",
"in",
"shapes",
")",
")"
] |
Count learnable parameters.
Args:
scope: Restrict the count to a variable scope.
exclude: Regex to match variable names to exclude.
graph: Operate on a graph other than the current default graph.
Returns:
Number of learnable parameters as integer.
|
[
"Count",
"learnable",
"parameters",
"."
] |
3d09705977bae4e7c3eb20339a3b384d2a5531e4
|
https://github.com/google-research/batch-ppo/blob/3d09705977bae4e7c3eb20339a3b384d2a5531e4/agents/tools/count_weights.py#L27-L48
|
6,797
|
google-research/batch-ppo
|
agents/scripts/networks.py
|
_custom_diag_normal_kl
|
def _custom_diag_normal_kl(lhs, rhs, name=None): # pylint: disable=unused-argument
"""Empirical KL divergence of two normals with diagonal covariance.
Args:
lhs: Diagonal Normal distribution.
rhs: Diagonal Normal distribution.
name: Name scope for the op.
Returns:
KL divergence from lhs to rhs.
"""
with tf.name_scope(name or 'kl_divergence'):
mean0 = lhs.mean()
mean1 = rhs.mean()
logstd0 = tf.log(lhs.stddev())
logstd1 = tf.log(rhs.stddev())
logstd0_2, logstd1_2 = 2 * logstd0, 2 * logstd1
return 0.5 * (
tf.reduce_sum(tf.exp(logstd0_2 - logstd1_2), -1) +
tf.reduce_sum((mean1 - mean0) ** 2 / tf.exp(logstd1_2), -1) +
tf.reduce_sum(logstd1_2, -1) - tf.reduce_sum(logstd0_2, -1) -
mean0.shape[-1].value)
|
python
|
def _custom_diag_normal_kl(lhs, rhs, name=None): # pylint: disable=unused-argument
"""Empirical KL divergence of two normals with diagonal covariance.
Args:
lhs: Diagonal Normal distribution.
rhs: Diagonal Normal distribution.
name: Name scope for the op.
Returns:
KL divergence from lhs to rhs.
"""
with tf.name_scope(name or 'kl_divergence'):
mean0 = lhs.mean()
mean1 = rhs.mean()
logstd0 = tf.log(lhs.stddev())
logstd1 = tf.log(rhs.stddev())
logstd0_2, logstd1_2 = 2 * logstd0, 2 * logstd1
return 0.5 * (
tf.reduce_sum(tf.exp(logstd0_2 - logstd1_2), -1) +
tf.reduce_sum((mean1 - mean0) ** 2 / tf.exp(logstd1_2), -1) +
tf.reduce_sum(logstd1_2, -1) - tf.reduce_sum(logstd0_2, -1) -
mean0.shape[-1].value)
|
[
"def",
"_custom_diag_normal_kl",
"(",
"lhs",
",",
"rhs",
",",
"name",
"=",
"None",
")",
":",
"# pylint: disable=unused-argument",
"with",
"tf",
".",
"name_scope",
"(",
"name",
"or",
"'kl_divergence'",
")",
":",
"mean0",
"=",
"lhs",
".",
"mean",
"(",
")",
"mean1",
"=",
"rhs",
".",
"mean",
"(",
")",
"logstd0",
"=",
"tf",
".",
"log",
"(",
"lhs",
".",
"stddev",
"(",
")",
")",
"logstd1",
"=",
"tf",
".",
"log",
"(",
"rhs",
".",
"stddev",
"(",
")",
")",
"logstd0_2",
",",
"logstd1_2",
"=",
"2",
"*",
"logstd0",
",",
"2",
"*",
"logstd1",
"return",
"0.5",
"*",
"(",
"tf",
".",
"reduce_sum",
"(",
"tf",
".",
"exp",
"(",
"logstd0_2",
"-",
"logstd1_2",
")",
",",
"-",
"1",
")",
"+",
"tf",
".",
"reduce_sum",
"(",
"(",
"mean1",
"-",
"mean0",
")",
"**",
"2",
"/",
"tf",
".",
"exp",
"(",
"logstd1_2",
")",
",",
"-",
"1",
")",
"+",
"tf",
".",
"reduce_sum",
"(",
"logstd1_2",
",",
"-",
"1",
")",
"-",
"tf",
".",
"reduce_sum",
"(",
"logstd0_2",
",",
"-",
"1",
")",
"-",
"mean0",
".",
"shape",
"[",
"-",
"1",
"]",
".",
"value",
")"
] |
Empirical KL divergence of two normals with diagonal covariance.
Args:
lhs: Diagonal Normal distribution.
rhs: Diagonal Normal distribution.
name: Name scope for the op.
Returns:
KL divergence from lhs to rhs.
|
[
"Empirical",
"KL",
"divergence",
"of",
"two",
"normals",
"with",
"diagonal",
"covariance",
"."
] |
3d09705977bae4e7c3eb20339a3b384d2a5531e4
|
https://github.com/google-research/batch-ppo/blob/3d09705977bae4e7c3eb20339a3b384d2a5531e4/agents/scripts/networks.py#L43-L64
|
6,798
|
google-research/batch-ppo
|
agents/scripts/utility.py
|
define_simulation_graph
|
def define_simulation_graph(batch_env, algo_cls, config):
"""Define the algorithm and environment interaction.
Args:
batch_env: In-graph environments object.
algo_cls: Constructor of a batch algorithm.
config: Configuration object for the algorithm.
Returns:
Object providing graph elements via attributes.
"""
# pylint: disable=unused-variable
step = tf.Variable(0, False, dtype=tf.int32, name='global_step')
is_training = tf.placeholder(tf.bool, name='is_training')
should_log = tf.placeholder(tf.bool, name='should_log')
do_report = tf.placeholder(tf.bool, name='do_report')
force_reset = tf.placeholder(tf.bool, name='force_reset')
algo = algo_cls(batch_env, step, is_training, should_log, config)
done, score, summary = tools.simulate(
batch_env, algo, should_log, force_reset)
message = 'Graph contains {} trainable variables.'
tf.logging.info(message.format(tools.count_weights()))
# pylint: enable=unused-variable
return tools.AttrDict(locals())
|
python
|
def define_simulation_graph(batch_env, algo_cls, config):
"""Define the algorithm and environment interaction.
Args:
batch_env: In-graph environments object.
algo_cls: Constructor of a batch algorithm.
config: Configuration object for the algorithm.
Returns:
Object providing graph elements via attributes.
"""
# pylint: disable=unused-variable
step = tf.Variable(0, False, dtype=tf.int32, name='global_step')
is_training = tf.placeholder(tf.bool, name='is_training')
should_log = tf.placeholder(tf.bool, name='should_log')
do_report = tf.placeholder(tf.bool, name='do_report')
force_reset = tf.placeholder(tf.bool, name='force_reset')
algo = algo_cls(batch_env, step, is_training, should_log, config)
done, score, summary = tools.simulate(
batch_env, algo, should_log, force_reset)
message = 'Graph contains {} trainable variables.'
tf.logging.info(message.format(tools.count_weights()))
# pylint: enable=unused-variable
return tools.AttrDict(locals())
|
[
"def",
"define_simulation_graph",
"(",
"batch_env",
",",
"algo_cls",
",",
"config",
")",
":",
"# pylint: disable=unused-variable",
"step",
"=",
"tf",
".",
"Variable",
"(",
"0",
",",
"False",
",",
"dtype",
"=",
"tf",
".",
"int32",
",",
"name",
"=",
"'global_step'",
")",
"is_training",
"=",
"tf",
".",
"placeholder",
"(",
"tf",
".",
"bool",
",",
"name",
"=",
"'is_training'",
")",
"should_log",
"=",
"tf",
".",
"placeholder",
"(",
"tf",
".",
"bool",
",",
"name",
"=",
"'should_log'",
")",
"do_report",
"=",
"tf",
".",
"placeholder",
"(",
"tf",
".",
"bool",
",",
"name",
"=",
"'do_report'",
")",
"force_reset",
"=",
"tf",
".",
"placeholder",
"(",
"tf",
".",
"bool",
",",
"name",
"=",
"'force_reset'",
")",
"algo",
"=",
"algo_cls",
"(",
"batch_env",
",",
"step",
",",
"is_training",
",",
"should_log",
",",
"config",
")",
"done",
",",
"score",
",",
"summary",
"=",
"tools",
".",
"simulate",
"(",
"batch_env",
",",
"algo",
",",
"should_log",
",",
"force_reset",
")",
"message",
"=",
"'Graph contains {} trainable variables.'",
"tf",
".",
"logging",
".",
"info",
"(",
"message",
".",
"format",
"(",
"tools",
".",
"count_weights",
"(",
")",
")",
")",
"# pylint: enable=unused-variable",
"return",
"tools",
".",
"AttrDict",
"(",
"locals",
"(",
")",
")"
] |
Define the algorithm and environment interaction.
Args:
batch_env: In-graph environments object.
algo_cls: Constructor of a batch algorithm.
config: Configuration object for the algorithm.
Returns:
Object providing graph elements via attributes.
|
[
"Define",
"the",
"algorithm",
"and",
"environment",
"interaction",
"."
] |
3d09705977bae4e7c3eb20339a3b384d2a5531e4
|
https://github.com/google-research/batch-ppo/blob/3d09705977bae4e7c3eb20339a3b384d2a5531e4/agents/scripts/utility.py#L31-L54
|
6,799
|
google-research/batch-ppo
|
agents/scripts/utility.py
|
define_batch_env
|
def define_batch_env(constructor, num_agents, env_processes):
"""Create environments and apply all desired wrappers.
Args:
constructor: Constructor of an OpenAI gym environment.
num_agents: Number of environments to combine in the batch.
env_processes: Whether to step environment in external processes.
Returns:
In-graph environments object.
"""
with tf.variable_scope('environments'):
if env_processes:
envs = [
tools.wrappers.ExternalProcess(constructor)
for _ in range(num_agents)]
else:
envs = [constructor() for _ in range(num_agents)]
batch_env = tools.BatchEnv(envs, blocking=not env_processes)
batch_env = tools.InGraphBatchEnv(batch_env)
return batch_env
|
python
|
def define_batch_env(constructor, num_agents, env_processes):
"""Create environments and apply all desired wrappers.
Args:
constructor: Constructor of an OpenAI gym environment.
num_agents: Number of environments to combine in the batch.
env_processes: Whether to step environment in external processes.
Returns:
In-graph environments object.
"""
with tf.variable_scope('environments'):
if env_processes:
envs = [
tools.wrappers.ExternalProcess(constructor)
for _ in range(num_agents)]
else:
envs = [constructor() for _ in range(num_agents)]
batch_env = tools.BatchEnv(envs, blocking=not env_processes)
batch_env = tools.InGraphBatchEnv(batch_env)
return batch_env
|
[
"def",
"define_batch_env",
"(",
"constructor",
",",
"num_agents",
",",
"env_processes",
")",
":",
"with",
"tf",
".",
"variable_scope",
"(",
"'environments'",
")",
":",
"if",
"env_processes",
":",
"envs",
"=",
"[",
"tools",
".",
"wrappers",
".",
"ExternalProcess",
"(",
"constructor",
")",
"for",
"_",
"in",
"range",
"(",
"num_agents",
")",
"]",
"else",
":",
"envs",
"=",
"[",
"constructor",
"(",
")",
"for",
"_",
"in",
"range",
"(",
"num_agents",
")",
"]",
"batch_env",
"=",
"tools",
".",
"BatchEnv",
"(",
"envs",
",",
"blocking",
"=",
"not",
"env_processes",
")",
"batch_env",
"=",
"tools",
".",
"InGraphBatchEnv",
"(",
"batch_env",
")",
"return",
"batch_env"
] |
Create environments and apply all desired wrappers.
Args:
constructor: Constructor of an OpenAI gym environment.
num_agents: Number of environments to combine in the batch.
env_processes: Whether to step environment in external processes.
Returns:
In-graph environments object.
|
[
"Create",
"environments",
"and",
"apply",
"all",
"desired",
"wrappers",
"."
] |
3d09705977bae4e7c3eb20339a3b384d2a5531e4
|
https://github.com/google-research/batch-ppo/blob/3d09705977bae4e7c3eb20339a3b384d2a5531e4/agents/scripts/utility.py#L57-L77
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.