id int32 0 252k | repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1 value | code stringlengths 51 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 |
|---|---|---|---|---|---|---|---|---|---|---|---|
241,500 | NetEaseGame/ATX | atx/adbkit/openstf/service.py | pack | def pack(mtype, request, rid=None):
'''pack request to delimited data'''
envelope = wire.Envelope()
if rid is not None:
envelope.id = rid
envelope.type = mtype
envelope.message = request.SerializeToString()
data = envelope.SerializeToString()
data = encoder._VarintBytes(len(data)) + data
return data | python | def pack(mtype, request, rid=None):
'''pack request to delimited data'''
envelope = wire.Envelope()
if rid is not None:
envelope.id = rid
envelope.type = mtype
envelope.message = request.SerializeToString()
data = envelope.SerializeToString()
data = encoder._VarintBytes(len(data)) + data
return data | [
"def",
"pack",
"(",
"mtype",
",",
"request",
",",
"rid",
"=",
"None",
")",
":",
"envelope",
"=",
"wire",
".",
"Envelope",
"(",
")",
"if",
"rid",
"is",
"not",
"None",
":",
"envelope",
".",
"id",
"=",
"rid",
"envelope",
".",
"type",
"=",
"mtype",
"... | pack request to delimited data | [
"pack",
"request",
"to",
"delimited",
"data"
] | f4415c57b45cb0730e08899cbc92a2af1c047ffb | https://github.com/NetEaseGame/ATX/blob/f4415c57b45cb0730e08899cbc92a2af1c047ffb/atx/adbkit/openstf/service.py#L75-L84 |
241,501 | NetEaseGame/ATX | atx/adbkit/openstf/service.py | unpack | def unpack(data):
'''unpack from delimited data'''
size, position = decoder._DecodeVarint(data, 0)
envelope = wire.Envelope()
envelope.ParseFromString(data[position:position+size])
return envelope | python | def unpack(data):
'''unpack from delimited data'''
size, position = decoder._DecodeVarint(data, 0)
envelope = wire.Envelope()
envelope.ParseFromString(data[position:position+size])
return envelope | [
"def",
"unpack",
"(",
"data",
")",
":",
"size",
",",
"position",
"=",
"decoder",
".",
"_DecodeVarint",
"(",
"data",
",",
"0",
")",
"envelope",
"=",
"wire",
".",
"Envelope",
"(",
")",
"envelope",
".",
"ParseFromString",
"(",
"data",
"[",
"position",
":"... | unpack from delimited data | [
"unpack",
"from",
"delimited",
"data"
] | f4415c57b45cb0730e08899cbc92a2af1c047ffb | https://github.com/NetEaseGame/ATX/blob/f4415c57b45cb0730e08899cbc92a2af1c047ffb/atx/adbkit/openstf/service.py#L86-L91 |
241,502 | NetEaseGame/ATX | atx/adbkit/openstf/service.py | check_stf_agent | def check_stf_agent(adbprefix=None, kill=False):
'''return True if agent is alive.'''
if adbprefix is None:
adbprefix = ['adb']
command = adbprefix + ['shell', 'ps']
out = subprocess.check_output(command).strip()
out = out.splitlines()
if len(out) > 1:
first, out = out[0], out[1:]
idx = first.split().index('PID')
pid = None
for line in out:
if 'stf.agent' in line:
pid = line.split()[idx]
print 'stf.agent is running, pid is', pid
break
if pid is not None:
if kill:
print 'killing', pid
command = adbprefix + ['shell', 'kill', '-9', pid]
subprocess.call(command)
return False
return True
return False | python | def check_stf_agent(adbprefix=None, kill=False):
'''return True if agent is alive.'''
if adbprefix is None:
adbprefix = ['adb']
command = adbprefix + ['shell', 'ps']
out = subprocess.check_output(command).strip()
out = out.splitlines()
if len(out) > 1:
first, out = out[0], out[1:]
idx = first.split().index('PID')
pid = None
for line in out:
if 'stf.agent' in line:
pid = line.split()[idx]
print 'stf.agent is running, pid is', pid
break
if pid is not None:
if kill:
print 'killing', pid
command = adbprefix + ['shell', 'kill', '-9', pid]
subprocess.call(command)
return False
return True
return False | [
"def",
"check_stf_agent",
"(",
"adbprefix",
"=",
"None",
",",
"kill",
"=",
"False",
")",
":",
"if",
"adbprefix",
"is",
"None",
":",
"adbprefix",
"=",
"[",
"'adb'",
"]",
"command",
"=",
"adbprefix",
"+",
"[",
"'shell'",
",",
"'ps'",
"]",
"out",
"=",
"... | return True if agent is alive. | [
"return",
"True",
"if",
"agent",
"is",
"alive",
"."
] | f4415c57b45cb0730e08899cbc92a2af1c047ffb | https://github.com/NetEaseGame/ATX/blob/f4415c57b45cb0730e08899cbc92a2af1c047ffb/atx/adbkit/openstf/service.py#L182-L205 |
241,503 | NetEaseGame/ATX | atx/cmds/tkgui.py | insert_code | def insert_code(filename, code, save=True, marker='# ATX CODE END'):
""" Auto append code """
content = ''
found = False
for line in open(filename, 'rb'):
if not found and line.strip() == marker:
found = True
cnt = line.find(marker)
content += line[:cnt] + code
content += line
if not found:
if not content.endswith('\n'):
content += '\n'
content += code + marker + '\n'
if save:
with open(filename, 'wb') as f:
f.write(content)
return content | python | def insert_code(filename, code, save=True, marker='# ATX CODE END'):
content = ''
found = False
for line in open(filename, 'rb'):
if not found and line.strip() == marker:
found = True
cnt = line.find(marker)
content += line[:cnt] + code
content += line
if not found:
if not content.endswith('\n'):
content += '\n'
content += code + marker + '\n'
if save:
with open(filename, 'wb') as f:
f.write(content)
return content | [
"def",
"insert_code",
"(",
"filename",
",",
"code",
",",
"save",
"=",
"True",
",",
"marker",
"=",
"'# ATX CODE END'",
")",
":",
"content",
"=",
"''",
"found",
"=",
"False",
"for",
"line",
"in",
"open",
"(",
"filename",
",",
"'rb'",
")",
":",
"if",
"n... | Auto append code | [
"Auto",
"append",
"code"
] | f4415c57b45cb0730e08899cbc92a2af1c047ffb | https://github.com/NetEaseGame/ATX/blob/f4415c57b45cb0730e08899cbc92a2af1c047ffb/atx/cmds/tkgui.py#L41-L58 |
241,504 | NetEaseGame/ATX | scripts/image.py | find_image_position | def find_image_position(origin='origin.png', query='query.png', outfile=None):
'''
find all image positions
@return None if not found else a tuple: (origin.shape, query.shape, postions)
might raise Exception
'''
img1 = cv2.imread(query, 0) # query image(small)
img2 = cv2.imread(origin, 0) # train image(big)
# Initiate SIFT detector
sift = cv2.SIFT()
# find the keypoints and descriptors with SIFT
kp1, des1 = sift.detectAndCompute(img1,None)
kp2, des2 = sift.detectAndCompute(img2,None)
print len(kp1), len(kp2)
FLANN_INDEX_KDTREE = 0
index_params = dict(algorithm = FLANN_INDEX_KDTREE, trees = 5)
search_params = dict(checks = 50)
# flann
flann = cv2.FlannBasedMatcher(index_params, search_params)
matches = flann.knnMatch(des1, des2, k=2)
# store all the good matches as per Lowe's ratio test.
good = []
for m,n in matches:
if m.distance < 0.7*n.distance:
good.append(m)
print len(kp1), len(kp2), 'good cnt:', len(good)
if len(good)*1.0/len(kp1) < 0.5:
#if len(good)<MIN_MATCH_COUNT:
print "Not enough matches are found - %d/%d" % (len(good),MIN_MATCH_COUNT)
return img2.shape, img1.shape, []
queryPts = []
trainPts = []
for dm in good:
queryPts.append(kp1[dm.queryIdx])
trainPts.append(kp2[dm.trainIdx])
img3 = cv2.drawKeypoints(img1, queryPts)
cv2.imwrite('image/query.png', img3)
img3 = cv2.drawKeypoints(img2, trainPts)
point = _middlePoint(trainPts)
print 'position in', point
if outfile:
edge = 10
top_left = (point[0]-edge, point[1]-edge)
bottom_right = (point[0]+edge, point[1]+edge)
cv2.rectangle(img3, top_left, bottom_right, 255, 2)
cv2.imwrite(outfile, img3)
return img2.shape, img1.shape, [point] | python | def find_image_position(origin='origin.png', query='query.png', outfile=None):
'''
find all image positions
@return None if not found else a tuple: (origin.shape, query.shape, postions)
might raise Exception
'''
img1 = cv2.imread(query, 0) # query image(small)
img2 = cv2.imread(origin, 0) # train image(big)
# Initiate SIFT detector
sift = cv2.SIFT()
# find the keypoints and descriptors with SIFT
kp1, des1 = sift.detectAndCompute(img1,None)
kp2, des2 = sift.detectAndCompute(img2,None)
print len(kp1), len(kp2)
FLANN_INDEX_KDTREE = 0
index_params = dict(algorithm = FLANN_INDEX_KDTREE, trees = 5)
search_params = dict(checks = 50)
# flann
flann = cv2.FlannBasedMatcher(index_params, search_params)
matches = flann.knnMatch(des1, des2, k=2)
# store all the good matches as per Lowe's ratio test.
good = []
for m,n in matches:
if m.distance < 0.7*n.distance:
good.append(m)
print len(kp1), len(kp2), 'good cnt:', len(good)
if len(good)*1.0/len(kp1) < 0.5:
#if len(good)<MIN_MATCH_COUNT:
print "Not enough matches are found - %d/%d" % (len(good),MIN_MATCH_COUNT)
return img2.shape, img1.shape, []
queryPts = []
trainPts = []
for dm in good:
queryPts.append(kp1[dm.queryIdx])
trainPts.append(kp2[dm.trainIdx])
img3 = cv2.drawKeypoints(img1, queryPts)
cv2.imwrite('image/query.png', img3)
img3 = cv2.drawKeypoints(img2, trainPts)
point = _middlePoint(trainPts)
print 'position in', point
if outfile:
edge = 10
top_left = (point[0]-edge, point[1]-edge)
bottom_right = (point[0]+edge, point[1]+edge)
cv2.rectangle(img3, top_left, bottom_right, 255, 2)
cv2.imwrite(outfile, img3)
return img2.shape, img1.shape, [point] | [
"def",
"find_image_position",
"(",
"origin",
"=",
"'origin.png'",
",",
"query",
"=",
"'query.png'",
",",
"outfile",
"=",
"None",
")",
":",
"img1",
"=",
"cv2",
".",
"imread",
"(",
"query",
",",
"0",
")",
"# query image(small)",
"img2",
"=",
"cv2",
".",
"i... | find all image positions
@return None if not found else a tuple: (origin.shape, query.shape, postions)
might raise Exception | [
"find",
"all",
"image",
"positions"
] | f4415c57b45cb0730e08899cbc92a2af1c047ffb | https://github.com/NetEaseGame/ATX/blob/f4415c57b45cb0730e08899cbc92a2af1c047ffb/scripts/image.py#L46-L102 |
241,505 | NetEaseGame/ATX | atx/taskqueue/__main__.py | TaskQueueHandler.get | def get(self, udid):
''' get new task '''
timeout = self.get_argument('timeout', 20.0)
if timeout is not None:
timeout = float(timeout)
que = self.ques[udid]
try:
item = yield que.get(timeout=time.time()+timeout) # timeout is a timestamp, strange
print 'get from queue:', item
self.write(item)
que.task_done()
except gen.TimeoutError:
print 'timeout'
self.write('')
finally:
self.finish() | python | def get(self, udid):
''' get new task '''
timeout = self.get_argument('timeout', 20.0)
if timeout is not None:
timeout = float(timeout)
que = self.ques[udid]
try:
item = yield que.get(timeout=time.time()+timeout) # timeout is a timestamp, strange
print 'get from queue:', item
self.write(item)
que.task_done()
except gen.TimeoutError:
print 'timeout'
self.write('')
finally:
self.finish() | [
"def",
"get",
"(",
"self",
",",
"udid",
")",
":",
"timeout",
"=",
"self",
".",
"get_argument",
"(",
"'timeout'",
",",
"20.0",
")",
"if",
"timeout",
"is",
"not",
"None",
":",
"timeout",
"=",
"float",
"(",
"timeout",
")",
"que",
"=",
"self",
".",
"qu... | get new task | [
"get",
"new",
"task"
] | f4415c57b45cb0730e08899cbc92a2af1c047ffb | https://github.com/NetEaseGame/ATX/blob/f4415c57b45cb0730e08899cbc92a2af1c047ffb/atx/taskqueue/__main__.py#L42-L57 |
241,506 | NetEaseGame/ATX | atx/taskqueue/__main__.py | TaskQueueHandler.post | def post(self, udid):
''' add new task '''
que = self.ques[udid]
timeout = self.get_argument('timeout', 10.0)
if timeout is not None:
timeout = float(timeout)
data = tornado.escape.json_decode(self.request.body)
data = {'id': str(uuid.uuid1()), 'data': data}
yield que.put(data, timeout=time.time()+timeout)
print 'post, queue size:', que.qsize()
self.write({'id': data['id']})
self.finish() | python | def post(self, udid):
''' add new task '''
que = self.ques[udid]
timeout = self.get_argument('timeout', 10.0)
if timeout is not None:
timeout = float(timeout)
data = tornado.escape.json_decode(self.request.body)
data = {'id': str(uuid.uuid1()), 'data': data}
yield que.put(data, timeout=time.time()+timeout)
print 'post, queue size:', que.qsize()
self.write({'id': data['id']})
self.finish() | [
"def",
"post",
"(",
"self",
",",
"udid",
")",
":",
"que",
"=",
"self",
".",
"ques",
"[",
"udid",
"]",
"timeout",
"=",
"self",
".",
"get_argument",
"(",
"'timeout'",
",",
"10.0",
")",
"if",
"timeout",
"is",
"not",
"None",
":",
"timeout",
"=",
"float... | add new task | [
"add",
"new",
"task"
] | f4415c57b45cb0730e08899cbc92a2af1c047ffb | https://github.com/NetEaseGame/ATX/blob/f4415c57b45cb0730e08899cbc92a2af1c047ffb/atx/taskqueue/__main__.py#L60-L71 |
241,507 | NetEaseGame/ATX | atx/record/android_hooks.py | InputParser._process_touch_batch | def _process_touch_batch(self):
'''a batch syncs in about 0.001 seconds.'''
if not self._touch_batch:
return
_time = self._temp_status_time
changed = False
for (_time, _device, _type, _code, _value) in self._touch_batch:
if _code == 'ABS_MT_TRACKING_ID':
if _value == 0xffffffff:
self._temp_status[self._curr_slot] = -INF
changed = True
else:
pass
elif _code == 'ABS_MT_SLOT':
self._curr_slot = _value
else:
if _code == 'ABS_MT_POSITION_X':
self._temp_status[self._curr_slot,_X] = _value
changed = True
elif _code == 'ABS_MT_POSITION_Y':
self._temp_status[self._curr_slot,_Y] = _value
changed = True
elif _code == 'ABS_MT_PRESSURE':
self._temp_status[self._curr_slot,_PR] = _value
elif _code == 'ABS_MT_TOUCH_MAJOR':
self._temp_status[self._curr_slot,_MJ] = _value
else:
print 'Unknown code', _code
self._temp_status_time = _time
self._touch_batch = []
if not changed:
return
# check differences, if position changes are big enough then emit events
diff = self._temp_status - self._status
dt = self._temp_status_time - self._status_time
emitted = False
for i in range(SLOT_NUM):
arr = self._temp_status[i]
oldarr = self._status[i]
dx, dy = diff[i,_X], diff[i,_Y]
if dx > INF or dy > INF:
# touch begin
event = TouchEvent(_time, HC.TOUCH_DOWN, i, arr[_X], arr[_Y], arr[_PR], arr[_MJ])
self.emit_touch_event(event)
emitted = True
elif dx < -INF or dy < -INF:
# touch end
event = TouchEvent(_time, HC.TOUCH_UP, i, oldarr[_X], oldarr[_Y], oldarr[_PR], oldarr[_MJ])
self.emit_touch_event(event)
emitted = True
else:
r, a = radang(float(dx), float(dy))
if r > self._move_radius:
v = r / dt
event = TouchEvent(_time, HC.TOUCH_MOVE, i, arr[_X], arr[_Y], arr[_PR], arr[_MJ], angle=a, velocity=v)
self.emit_touch_event(event)
emitted = True
if not emitted:
return
self._status = self._temp_status.copy()
self._status_time = self._temp_status_time | python | def _process_touch_batch(self):
'''a batch syncs in about 0.001 seconds.'''
if not self._touch_batch:
return
_time = self._temp_status_time
changed = False
for (_time, _device, _type, _code, _value) in self._touch_batch:
if _code == 'ABS_MT_TRACKING_ID':
if _value == 0xffffffff:
self._temp_status[self._curr_slot] = -INF
changed = True
else:
pass
elif _code == 'ABS_MT_SLOT':
self._curr_slot = _value
else:
if _code == 'ABS_MT_POSITION_X':
self._temp_status[self._curr_slot,_X] = _value
changed = True
elif _code == 'ABS_MT_POSITION_Y':
self._temp_status[self._curr_slot,_Y] = _value
changed = True
elif _code == 'ABS_MT_PRESSURE':
self._temp_status[self._curr_slot,_PR] = _value
elif _code == 'ABS_MT_TOUCH_MAJOR':
self._temp_status[self._curr_slot,_MJ] = _value
else:
print 'Unknown code', _code
self._temp_status_time = _time
self._touch_batch = []
if not changed:
return
# check differences, if position changes are big enough then emit events
diff = self._temp_status - self._status
dt = self._temp_status_time - self._status_time
emitted = False
for i in range(SLOT_NUM):
arr = self._temp_status[i]
oldarr = self._status[i]
dx, dy = diff[i,_X], diff[i,_Y]
if dx > INF or dy > INF:
# touch begin
event = TouchEvent(_time, HC.TOUCH_DOWN, i, arr[_X], arr[_Y], arr[_PR], arr[_MJ])
self.emit_touch_event(event)
emitted = True
elif dx < -INF or dy < -INF:
# touch end
event = TouchEvent(_time, HC.TOUCH_UP, i, oldarr[_X], oldarr[_Y], oldarr[_PR], oldarr[_MJ])
self.emit_touch_event(event)
emitted = True
else:
r, a = radang(float(dx), float(dy))
if r > self._move_radius:
v = r / dt
event = TouchEvent(_time, HC.TOUCH_MOVE, i, arr[_X], arr[_Y], arr[_PR], arr[_MJ], angle=a, velocity=v)
self.emit_touch_event(event)
emitted = True
if not emitted:
return
self._status = self._temp_status.copy()
self._status_time = self._temp_status_time | [
"def",
"_process_touch_batch",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_touch_batch",
":",
"return",
"_time",
"=",
"self",
".",
"_temp_status_time",
"changed",
"=",
"False",
"for",
"(",
"_time",
",",
"_device",
",",
"_type",
",",
"_code",
",",
... | a batch syncs in about 0.001 seconds. | [
"a",
"batch",
"syncs",
"in",
"about",
"0",
".",
"001",
"seconds",
"."
] | f4415c57b45cb0730e08899cbc92a2af1c047ffb | https://github.com/NetEaseGame/ATX/blob/f4415c57b45cb0730e08899cbc92a2af1c047ffb/atx/record/android_hooks.py#L218-L283 |
241,508 | NetEaseGame/ATX | atx/record/android_hooks.py | GestureRecognizer.process | def process(self):
'''handle events and trigger time-related events'''
timediff = 0
while True:
try:
time.sleep(0.001)
event = self.queue.get_nowait()
self.handle_event(event)
if event.msg & HC.KEY_ANY:
continue
if timediff == 0:
timediff = time.time() - event.time
self.touches[event.slotid] = event
except Queue.Empty:
if not self.running:
break
now = time.time() - timediff
for i in range(SLOT_NUM):
e = self.touches[i]
if e is None:
continue
if e.msg == HC.TOUCH_DOWN and now - e.time > self.long_press_delay:
self.analyze_tracks(TouchTimeoutEvent(now, HC.TOUCH_PRESS_TIMEOUT, i))
self.touches[i] = None
elif e.msg == HC.TOUCH_UP and now - e.time > self.double_tap_delay:
self.analyze_tracks(TouchTimeoutEvent(now, HC.TOUCH_FOLLOW_TIMEOUT, i))
self.touches[i] = None
elif e.msg == HC.TOUCH_MOVE and now - e.time > self.move_stop_delay:
self.analyze_tracks(TouchTimeoutEvent(now, HC.TOUCH_MOVESTOP_TIMEOUT, i))
self.touches[i] = None
except:
traceback.print_exc()
print 'process done.' | python | def process(self):
'''handle events and trigger time-related events'''
timediff = 0
while True:
try:
time.sleep(0.001)
event = self.queue.get_nowait()
self.handle_event(event)
if event.msg & HC.KEY_ANY:
continue
if timediff == 0:
timediff = time.time() - event.time
self.touches[event.slotid] = event
except Queue.Empty:
if not self.running:
break
now = time.time() - timediff
for i in range(SLOT_NUM):
e = self.touches[i]
if e is None:
continue
if e.msg == HC.TOUCH_DOWN and now - e.time > self.long_press_delay:
self.analyze_tracks(TouchTimeoutEvent(now, HC.TOUCH_PRESS_TIMEOUT, i))
self.touches[i] = None
elif e.msg == HC.TOUCH_UP and now - e.time > self.double_tap_delay:
self.analyze_tracks(TouchTimeoutEvent(now, HC.TOUCH_FOLLOW_TIMEOUT, i))
self.touches[i] = None
elif e.msg == HC.TOUCH_MOVE and now - e.time > self.move_stop_delay:
self.analyze_tracks(TouchTimeoutEvent(now, HC.TOUCH_MOVESTOP_TIMEOUT, i))
self.touches[i] = None
except:
traceback.print_exc()
print 'process done.' | [
"def",
"process",
"(",
"self",
")",
":",
"timediff",
"=",
"0",
"while",
"True",
":",
"try",
":",
"time",
".",
"sleep",
"(",
"0.001",
")",
"event",
"=",
"self",
".",
"queue",
".",
"get_nowait",
"(",
")",
"self",
".",
"handle_event",
"(",
"event",
")... | handle events and trigger time-related events | [
"handle",
"events",
"and",
"trigger",
"time",
"-",
"related",
"events"
] | f4415c57b45cb0730e08899cbc92a2af1c047ffb | https://github.com/NetEaseGame/ATX/blob/f4415c57b45cb0730e08899cbc92a2af1c047ffb/atx/record/android_hooks.py#L334-L367 |
241,509 | NetEaseGame/ATX | atx/drivers/mixin.py | DeviceMixin.exists | def exists(self, pattern, **match_kwargs):
"""Check if image exists in screen
Returns:
If exists, return FindPoint, or
return None if result.confidence < self.image_match_threshold
"""
ret = self.match(pattern, **match_kwargs)
if ret is None:
return None
if not ret.matched:
return None
return ret | python | def exists(self, pattern, **match_kwargs):
ret = self.match(pattern, **match_kwargs)
if ret is None:
return None
if not ret.matched:
return None
return ret | [
"def",
"exists",
"(",
"self",
",",
"pattern",
",",
"*",
"*",
"match_kwargs",
")",
":",
"ret",
"=",
"self",
".",
"match",
"(",
"pattern",
",",
"*",
"*",
"match_kwargs",
")",
"if",
"ret",
"is",
"None",
":",
"return",
"None",
"if",
"not",
"ret",
".",
... | Check if image exists in screen
Returns:
If exists, return FindPoint, or
return None if result.confidence < self.image_match_threshold | [
"Check",
"if",
"image",
"exists",
"in",
"screen"
] | f4415c57b45cb0730e08899cbc92a2af1c047ffb | https://github.com/NetEaseGame/ATX/blob/f4415c57b45cb0730e08899cbc92a2af1c047ffb/atx/drivers/mixin.py#L143-L155 |
241,510 | NetEaseGame/ATX | atx/drivers/mixin.py | DeviceMixin._match_auto | def _match_auto(self, screen, search_img, threshold):
"""Maybe not a good idea
"""
# 1. try template first
ret = ac.find_template(screen, search_img)
if ret and ret['confidence'] > threshold:
return FindPoint(ret['result'], ret['confidence'], consts.IMAGE_MATCH_METHOD_TMPL, matched=True)
# 2. try sift
ret = ac.find_sift(screen, search_img, min_match_count=10)
if ret is None:
return None
matches, total = ret['confidence']
if 1.0*matches/total > 0.5: # FIXME(ssx): sift just write here
return FindPoint(ret['result'], ret['confidence'], consts.IMAGE_MATCH_METHOD_SIFT, matched=True)
return None | python | def _match_auto(self, screen, search_img, threshold):
# 1. try template first
ret = ac.find_template(screen, search_img)
if ret and ret['confidence'] > threshold:
return FindPoint(ret['result'], ret['confidence'], consts.IMAGE_MATCH_METHOD_TMPL, matched=True)
# 2. try sift
ret = ac.find_sift(screen, search_img, min_match_count=10)
if ret is None:
return None
matches, total = ret['confidence']
if 1.0*matches/total > 0.5: # FIXME(ssx): sift just write here
return FindPoint(ret['result'], ret['confidence'], consts.IMAGE_MATCH_METHOD_SIFT, matched=True)
return None | [
"def",
"_match_auto",
"(",
"self",
",",
"screen",
",",
"search_img",
",",
"threshold",
")",
":",
"# 1. try template first",
"ret",
"=",
"ac",
".",
"find_template",
"(",
"screen",
",",
"search_img",
")",
"if",
"ret",
"and",
"ret",
"[",
"'confidence'",
"]",
... | Maybe not a good idea | [
"Maybe",
"not",
"a",
"good",
"idea"
] | f4415c57b45cb0730e08899cbc92a2af1c047ffb | https://github.com/NetEaseGame/ATX/blob/f4415c57b45cb0730e08899cbc92a2af1c047ffb/atx/drivers/mixin.py#L217-L233 |
241,511 | NetEaseGame/ATX | atx/drivers/mixin.py | DeviceMixin.match_all | def match_all(self, pattern):
"""
Test method, not suggested to use
"""
pattern = self.pattern_open(pattern)
search_img = pattern.image
screen = self.region_screenshot()
screen = imutils.from_pillow(screen)
points = ac.find_all_template(screen, search_img, maxcnt=10)
return points | python | def match_all(self, pattern):
pattern = self.pattern_open(pattern)
search_img = pattern.image
screen = self.region_screenshot()
screen = imutils.from_pillow(screen)
points = ac.find_all_template(screen, search_img, maxcnt=10)
return points | [
"def",
"match_all",
"(",
"self",
",",
"pattern",
")",
":",
"pattern",
"=",
"self",
".",
"pattern_open",
"(",
"pattern",
")",
"search_img",
"=",
"pattern",
".",
"image",
"screen",
"=",
"self",
".",
"region_screenshot",
"(",
")",
"screen",
"=",
"imutils",
... | Test method, not suggested to use | [
"Test",
"method",
"not",
"suggested",
"to",
"use"
] | f4415c57b45cb0730e08899cbc92a2af1c047ffb | https://github.com/NetEaseGame/ATX/blob/f4415c57b45cb0730e08899cbc92a2af1c047ffb/atx/drivers/mixin.py#L235-L244 |
241,512 | NetEaseGame/ATX | atx/drivers/mixin.py | DeviceMixin.region_screenshot | def region_screenshot(self, filename=None):
"""Deprecated
Take part of the screenshot
"""
# warnings.warn("deprecated, use screenshot().crop(bounds) instead", DeprecationWarning)
screen = self.__last_screen if self.__keep_screen else self.screenshot()
if self.bounds:
screen = screen.crop(self.bounds)
if filename:
screen.save(filename)
return screen | python | def region_screenshot(self, filename=None):
# warnings.warn("deprecated, use screenshot().crop(bounds) instead", DeprecationWarning)
screen = self.__last_screen if self.__keep_screen else self.screenshot()
if self.bounds:
screen = screen.crop(self.bounds)
if filename:
screen.save(filename)
return screen | [
"def",
"region_screenshot",
"(",
"self",
",",
"filename",
"=",
"None",
")",
":",
"# warnings.warn(\"deprecated, use screenshot().crop(bounds) instead\", DeprecationWarning)",
"screen",
"=",
"self",
".",
"__last_screen",
"if",
"self",
".",
"__keep_screen",
"else",
"self",
... | Deprecated
Take part of the screenshot | [
"Deprecated",
"Take",
"part",
"of",
"the",
"screenshot"
] | f4415c57b45cb0730e08899cbc92a2af1c047ffb | https://github.com/NetEaseGame/ATX/blob/f4415c57b45cb0730e08899cbc92a2af1c047ffb/atx/drivers/mixin.py#L375-L385 |
241,513 | NetEaseGame/ATX | atx/drivers/mixin.py | DeviceMixin.screenshot | def screenshot(self, filename=None):
"""
Take screen snapshot
Args:
- filename: filename where save to, optional
Returns:
PIL.Image object
Raises:
TypeError, IOError
"""
if self.__keep_screen:
return self.__last_screen
try:
screen = self._take_screenshot()
except IOError:
# try taks screenshot again
log.warn("warning, screenshot failed [2/1], retry again")
screen = self._take_screenshot()
self.__last_screen = screen
if filename:
save_dir = os.path.dirname(filename) or '.'
if not os.path.exists(save_dir):
os.makedirs(save_dir)
screen.save(filename)
return screen | python | def screenshot(self, filename=None):
if self.__keep_screen:
return self.__last_screen
try:
screen = self._take_screenshot()
except IOError:
# try taks screenshot again
log.warn("warning, screenshot failed [2/1], retry again")
screen = self._take_screenshot()
self.__last_screen = screen
if filename:
save_dir = os.path.dirname(filename) or '.'
if not os.path.exists(save_dir):
os.makedirs(save_dir)
screen.save(filename)
return screen | [
"def",
"screenshot",
"(",
"self",
",",
"filename",
"=",
"None",
")",
":",
"if",
"self",
".",
"__keep_screen",
":",
"return",
"self",
".",
"__last_screen",
"try",
":",
"screen",
"=",
"self",
".",
"_take_screenshot",
"(",
")",
"except",
"IOError",
":",
"# ... | Take screen snapshot
Args:
- filename: filename where save to, optional
Returns:
PIL.Image object
Raises:
TypeError, IOError | [
"Take",
"screen",
"snapshot"
] | f4415c57b45cb0730e08899cbc92a2af1c047ffb | https://github.com/NetEaseGame/ATX/blob/f4415c57b45cb0730e08899cbc92a2af1c047ffb/atx/drivers/mixin.py#L388-L415 |
241,514 | NetEaseGame/ATX | atx/drivers/mixin.py | DeviceMixin.click_nowait | def click_nowait(self, pattern, action='click', desc=None, **match_kwargs):
""" Return immediately if no image found
Args:
- pattern (str or Pattern): filename or an opencv image object.
- action (str): click or long_click
Returns:
Click point or None
"""
point = self.match(pattern, **match_kwargs)
if not point or not point.matched:
return None
func = getattr(self, action)
func(*point.pos)
return point | python | def click_nowait(self, pattern, action='click', desc=None, **match_kwargs):
point = self.match(pattern, **match_kwargs)
if not point or not point.matched:
return None
func = getattr(self, action)
func(*point.pos)
return point | [
"def",
"click_nowait",
"(",
"self",
",",
"pattern",
",",
"action",
"=",
"'click'",
",",
"desc",
"=",
"None",
",",
"*",
"*",
"match_kwargs",
")",
":",
"point",
"=",
"self",
".",
"match",
"(",
"pattern",
",",
"*",
"*",
"match_kwargs",
")",
"if",
"not",... | Return immediately if no image found
Args:
- pattern (str or Pattern): filename or an opencv image object.
- action (str): click or long_click
Returns:
Click point or None | [
"Return",
"immediately",
"if",
"no",
"image",
"found"
] | f4415c57b45cb0730e08899cbc92a2af1c047ffb | https://github.com/NetEaseGame/ATX/blob/f4415c57b45cb0730e08899cbc92a2af1c047ffb/atx/drivers/mixin.py#L471-L487 |
241,515 | NetEaseGame/ATX | atx/drivers/mixin.py | DeviceMixin.click_image | def click_image(self, pattern, timeout=20.0, action='click', safe=False, desc=None, delay=None, **match_kwargs):
"""Simulate click according image position
Args:
- pattern (str or Pattern): filename or an opencv image object.
- timeout (float): if image not found during this time, ImageNotFoundError will raise.
- action (str): click or long_click
- safe (bool): if safe is True, Exception will not raise and return None instead.
- method (str): image match method, choice of <template|sift>
- delay (float): wait for a moment then perform click
Returns:
None
Raises:
ImageNotFoundError: An error occured when img not found in current screen.
"""
pattern = self.pattern_open(pattern)
log.info('click image:%s %s', desc or '', pattern)
start_time = time.time()
found = False
point = None
while time.time() - start_time < timeout:
point = self.match(pattern, **match_kwargs)
if point is None:
sys.stdout.write('.')
sys.stdout.flush()
continue
log.debug('confidence: %s', point.confidence)
if not point.matched:
log.info('Ignore confidence: %s', point.confidence)
continue
# wait for program ready
if delay and delay > 0:
self.delay(delay)
func = getattr(self, action)
func(*point.pos)
found = True
break
sys.stdout.write('\n')
if not found:
if safe:
log.info("Image(%s) not found, safe=True, skip", pattern)
return None
raise errors.ImageNotFoundError('Not found image %s' % pattern, point)
# FIXME(ssx): maybe this function is too complex
return point | python | def click_image(self, pattern, timeout=20.0, action='click', safe=False, desc=None, delay=None, **match_kwargs):
pattern = self.pattern_open(pattern)
log.info('click image:%s %s', desc or '', pattern)
start_time = time.time()
found = False
point = None
while time.time() - start_time < timeout:
point = self.match(pattern, **match_kwargs)
if point is None:
sys.stdout.write('.')
sys.stdout.flush()
continue
log.debug('confidence: %s', point.confidence)
if not point.matched:
log.info('Ignore confidence: %s', point.confidence)
continue
# wait for program ready
if delay and delay > 0:
self.delay(delay)
func = getattr(self, action)
func(*point.pos)
found = True
break
sys.stdout.write('\n')
if not found:
if safe:
log.info("Image(%s) not found, safe=True, skip", pattern)
return None
raise errors.ImageNotFoundError('Not found image %s' % pattern, point)
# FIXME(ssx): maybe this function is too complex
return point | [
"def",
"click_image",
"(",
"self",
",",
"pattern",
",",
"timeout",
"=",
"20.0",
",",
"action",
"=",
"'click'",
",",
"safe",
"=",
"False",
",",
"desc",
"=",
"None",
",",
"delay",
"=",
"None",
",",
"*",
"*",
"match_kwargs",
")",
":",
"pattern",
"=",
... | Simulate click according image position
Args:
- pattern (str or Pattern): filename or an opencv image object.
- timeout (float): if image not found during this time, ImageNotFoundError will raise.
- action (str): click or long_click
- safe (bool): if safe is True, Exception will not raise and return None instead.
- method (str): image match method, choice of <template|sift>
- delay (float): wait for a moment then perform click
Returns:
None
Raises:
ImageNotFoundError: An error occured when img not found in current screen. | [
"Simulate",
"click",
"according",
"image",
"position"
] | f4415c57b45cb0730e08899cbc92a2af1c047ffb | https://github.com/NetEaseGame/ATX/blob/f4415c57b45cb0730e08899cbc92a2af1c047ffb/atx/drivers/mixin.py#L503-L555 |
241,516 | NetEaseGame/ATX | atx/base.py | list_images | def list_images(path=['.']):
""" Return list of image files """
for image_dir in set(path):
if not os.path.isdir(image_dir):
continue
for filename in os.listdir(image_dir):
bname, ext = os.path.splitext(filename)
if ext.lower() not in VALID_IMAGE_EXTS:
continue
filepath = os.path.join(image_dir, filename)
yield strutils.decode(filepath) | python | def list_images(path=['.']):
for image_dir in set(path):
if not os.path.isdir(image_dir):
continue
for filename in os.listdir(image_dir):
bname, ext = os.path.splitext(filename)
if ext.lower() not in VALID_IMAGE_EXTS:
continue
filepath = os.path.join(image_dir, filename)
yield strutils.decode(filepath) | [
"def",
"list_images",
"(",
"path",
"=",
"[",
"'.'",
"]",
")",
":",
"for",
"image_dir",
"in",
"set",
"(",
"path",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"image_dir",
")",
":",
"continue",
"for",
"filename",
"in",
"os",
".",
"... | Return list of image files | [
"Return",
"list",
"of",
"image",
"files"
] | f4415c57b45cb0730e08899cbc92a2af1c047ffb | https://github.com/NetEaseGame/ATX/blob/f4415c57b45cb0730e08899cbc92a2af1c047ffb/atx/base.py#L94-L105 |
241,517 | NetEaseGame/ATX | atx/base.py | list_all_image | def list_all_image(path, valid_exts=VALID_IMAGE_EXTS):
"""List all images under path
@return unicode list
"""
for filename in os.listdir(path):
bname, ext = os.path.splitext(filename)
if ext.lower() not in VALID_IMAGE_EXTS:
continue
filepath = os.path.join(path, filename)
yield strutils.decode(filepath) | python | def list_all_image(path, valid_exts=VALID_IMAGE_EXTS):
for filename in os.listdir(path):
bname, ext = os.path.splitext(filename)
if ext.lower() not in VALID_IMAGE_EXTS:
continue
filepath = os.path.join(path, filename)
yield strutils.decode(filepath) | [
"def",
"list_all_image",
"(",
"path",
",",
"valid_exts",
"=",
"VALID_IMAGE_EXTS",
")",
":",
"for",
"filename",
"in",
"os",
".",
"listdir",
"(",
"path",
")",
":",
"bname",
",",
"ext",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"filename",
")",
"if",
... | List all images under path
@return unicode list | [
"List",
"all",
"images",
"under",
"path"
] | f4415c57b45cb0730e08899cbc92a2af1c047ffb | https://github.com/NetEaseGame/ATX/blob/f4415c57b45cb0730e08899cbc92a2af1c047ffb/atx/base.py#L108-L118 |
241,518 | NetEaseGame/ATX | atx/base.py | search_image | def search_image(name=None, path=['.']):
"""
look for the image real path, if name is None, then return all images under path.
@return system encoded path string
FIXME(ssx): this code is just looking wired.
"""
name = strutils.decode(name)
for image_dir in path:
if not os.path.isdir(image_dir):
continue
image_dir = strutils.decode(image_dir)
image_path = os.path.join(image_dir, name)
if os.path.isfile(image_path):
return strutils.encode(image_path)
for image_path in list_all_image(image_dir):
if not image_name_match(name, image_path):
continue
return strutils.encode(image_path)
return None | python | def search_image(name=None, path=['.']):
name = strutils.decode(name)
for image_dir in path:
if not os.path.isdir(image_dir):
continue
image_dir = strutils.decode(image_dir)
image_path = os.path.join(image_dir, name)
if os.path.isfile(image_path):
return strutils.encode(image_path)
for image_path in list_all_image(image_dir):
if not image_name_match(name, image_path):
continue
return strutils.encode(image_path)
return None | [
"def",
"search_image",
"(",
"name",
"=",
"None",
",",
"path",
"=",
"[",
"'.'",
"]",
")",
":",
"name",
"=",
"strutils",
".",
"decode",
"(",
"name",
")",
"for",
"image_dir",
"in",
"path",
":",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"ima... | look for the image real path, if name is None, then return all images under path.
@return system encoded path string
FIXME(ssx): this code is just looking wired. | [
"look",
"for",
"the",
"image",
"real",
"path",
"if",
"name",
"is",
"None",
"then",
"return",
"all",
"images",
"under",
"path",
"."
] | f4415c57b45cb0730e08899cbc92a2af1c047ffb | https://github.com/NetEaseGame/ATX/blob/f4415c57b45cb0730e08899cbc92a2af1c047ffb/atx/base.py#L145-L165 |
241,519 | NetEaseGame/ATX | atx/adbkit/device.py | Device.run_cmd | def run_cmd(self, *args, **kwargs):
"""
Unix style output, already replace \r\n to \n
Args:
- timeout (float): timeout for a command exec
"""
timeout = kwargs.pop('timeout', None)
p = self.raw_cmd(*args, **kwargs)
return p.communicate(timeout=timeout)[0].decode('utf-8').replace('\r\n', '\n') | python | def run_cmd(self, *args, **kwargs):
timeout = kwargs.pop('timeout', None)
p = self.raw_cmd(*args, **kwargs)
return p.communicate(timeout=timeout)[0].decode('utf-8').replace('\r\n', '\n') | [
"def",
"run_cmd",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"timeout",
"=",
"kwargs",
".",
"pop",
"(",
"'timeout'",
",",
"None",
")",
"p",
"=",
"self",
".",
"raw_cmd",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"ret... | Unix style output, already replace \r\n to \n
Args:
- timeout (float): timeout for a command exec | [
"Unix",
"style",
"output",
"already",
"replace",
"\\",
"r",
"\\",
"n",
"to",
"\\",
"n"
] | f4415c57b45cb0730e08899cbc92a2af1c047ffb | https://github.com/NetEaseGame/ATX/blob/f4415c57b45cb0730e08899cbc92a2af1c047ffb/atx/adbkit/device.py#L47-L56 |
241,520 | NetEaseGame/ATX | atx/adbkit/device.py | Device.shell | def shell(self, *args, **kwargs):
"""
Run command `adb shell`
"""
args = ['shell'] + list(args)
return self.run_cmd(*args, **kwargs) | python | def shell(self, *args, **kwargs):
args = ['shell'] + list(args)
return self.run_cmd(*args, **kwargs) | [
"def",
"shell",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"args",
"=",
"[",
"'shell'",
"]",
"+",
"list",
"(",
"args",
")",
"return",
"self",
".",
"run_cmd",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | Run command `adb shell` | [
"Run",
"command",
"adb",
"shell"
] | f4415c57b45cb0730e08899cbc92a2af1c047ffb | https://github.com/NetEaseGame/ATX/blob/f4415c57b45cb0730e08899cbc92a2af1c047ffb/atx/adbkit/device.py#L58-L63 |
241,521 | NetEaseGame/ATX | atx/adbkit/device.py | Device.remove | def remove(self, filename):
"""
Remove file from device
"""
output = self.shell('rm', filename)
# any output means rm failed.
return False if output else True | python | def remove(self, filename):
output = self.shell('rm', filename)
# any output means rm failed.
return False if output else True | [
"def",
"remove",
"(",
"self",
",",
"filename",
")",
":",
"output",
"=",
"self",
".",
"shell",
"(",
"'rm'",
",",
"filename",
")",
"# any output means rm failed.",
"return",
"False",
"if",
"output",
"else",
"True"
] | Remove file from device | [
"Remove",
"file",
"from",
"device"
] | f4415c57b45cb0730e08899cbc92a2af1c047ffb | https://github.com/NetEaseGame/ATX/blob/f4415c57b45cb0730e08899cbc92a2af1c047ffb/atx/adbkit/device.py#L69-L75 |
241,522 | NetEaseGame/ATX | atx/adbkit/device.py | Device.display | def display(self):
'''
Return device width, height, rotation
'''
w, h = (0, 0)
for line in self.shell('dumpsys', 'display').splitlines():
m = _DISPLAY_RE.search(line, 0)
if not m:
continue
w = int(m.group('width'))
h = int(m.group('height'))
o = int(m.group('orientation'))
w, h = min(w, h), max(w, h)
return self.Display(w, h, o)
output = self.shell('LD_LIBRARY_PATH=/data/local/tmp', self.__minicap, '-i')
try:
data = json.loads(output)
(w, h, o) = (data['width'], data['height'], data['rotation']/90)
return self.Display(w, h, o)
except ValueError:
pass | python | def display(self):
'''
Return device width, height, rotation
'''
w, h = (0, 0)
for line in self.shell('dumpsys', 'display').splitlines():
m = _DISPLAY_RE.search(line, 0)
if not m:
continue
w = int(m.group('width'))
h = int(m.group('height'))
o = int(m.group('orientation'))
w, h = min(w, h), max(w, h)
return self.Display(w, h, o)
output = self.shell('LD_LIBRARY_PATH=/data/local/tmp', self.__minicap, '-i')
try:
data = json.loads(output)
(w, h, o) = (data['width'], data['height'], data['rotation']/90)
return self.Display(w, h, o)
except ValueError:
pass | [
"def",
"display",
"(",
"self",
")",
":",
"w",
",",
"h",
"=",
"(",
"0",
",",
"0",
")",
"for",
"line",
"in",
"self",
".",
"shell",
"(",
"'dumpsys'",
",",
"'display'",
")",
".",
"splitlines",
"(",
")",
":",
"m",
"=",
"_DISPLAY_RE",
".",
"search",
... | Return device width, height, rotation | [
"Return",
"device",
"width",
"height",
"rotation"
] | f4415c57b45cb0730e08899cbc92a2af1c047ffb | https://github.com/NetEaseGame/ATX/blob/f4415c57b45cb0730e08899cbc92a2af1c047ffb/atx/adbkit/device.py#L105-L126 |
241,523 | NetEaseGame/ATX | atx/adbkit/device.py | Device.packages | def packages(self):
"""
Show all packages
"""
pattern = re.compile(r'package:(/[^=]+\.apk)=([^\s]+)')
packages = []
for line in self.shell('pm', 'list', 'packages', '-f').splitlines():
m = pattern.match(line)
if not m:
continue
path, name = m.group(1), m.group(2)
packages.append(self.Package(name, path))
return packages | python | def packages(self):
pattern = re.compile(r'package:(/[^=]+\.apk)=([^\s]+)')
packages = []
for line in self.shell('pm', 'list', 'packages', '-f').splitlines():
m = pattern.match(line)
if not m:
continue
path, name = m.group(1), m.group(2)
packages.append(self.Package(name, path))
return packages | [
"def",
"packages",
"(",
"self",
")",
":",
"pattern",
"=",
"re",
".",
"compile",
"(",
"r'package:(/[^=]+\\.apk)=([^\\s]+)'",
")",
"packages",
"=",
"[",
"]",
"for",
"line",
"in",
"self",
".",
"shell",
"(",
"'pm'",
",",
"'list'",
",",
"'packages'",
",",
"'-... | Show all packages | [
"Show",
"all",
"packages"
] | f4415c57b45cb0730e08899cbc92a2af1c047ffb | https://github.com/NetEaseGame/ATX/blob/f4415c57b45cb0730e08899cbc92a2af1c047ffb/atx/adbkit/device.py#L153-L165 |
241,524 | NetEaseGame/ATX | atx/adbkit/device.py | Device._adb_screencap | def _adb_screencap(self, scale=1.0):
"""
capture screen with adb shell screencap
"""
remote_file = tempfile.mktemp(dir='/data/local/tmp/', prefix='screencap-', suffix='.png')
local_file = tempfile.mktemp(prefix='atx-screencap-', suffix='.png')
self.shell('screencap', '-p', remote_file)
try:
self.pull(remote_file, local_file)
image = imutils.open_as_pillow(local_file)
if scale is not None and scale != 1.0:
image = image.resize([int(scale * s) for s in image.size], Image.BICUBIC)
rotation = self.rotation()
if rotation:
method = getattr(Image, 'ROTATE_{}'.format(rotation*90))
image = image.transpose(method)
return image
finally:
self.remove(remote_file)
os.unlink(local_file) | python | def _adb_screencap(self, scale=1.0):
remote_file = tempfile.mktemp(dir='/data/local/tmp/', prefix='screencap-', suffix='.png')
local_file = tempfile.mktemp(prefix='atx-screencap-', suffix='.png')
self.shell('screencap', '-p', remote_file)
try:
self.pull(remote_file, local_file)
image = imutils.open_as_pillow(local_file)
if scale is not None and scale != 1.0:
image = image.resize([int(scale * s) for s in image.size], Image.BICUBIC)
rotation = self.rotation()
if rotation:
method = getattr(Image, 'ROTATE_{}'.format(rotation*90))
image = image.transpose(method)
return image
finally:
self.remove(remote_file)
os.unlink(local_file) | [
"def",
"_adb_screencap",
"(",
"self",
",",
"scale",
"=",
"1.0",
")",
":",
"remote_file",
"=",
"tempfile",
".",
"mktemp",
"(",
"dir",
"=",
"'/data/local/tmp/'",
",",
"prefix",
"=",
"'screencap-'",
",",
"suffix",
"=",
"'.png'",
")",
"local_file",
"=",
"tempf... | capture screen with adb shell screencap | [
"capture",
"screen",
"with",
"adb",
"shell",
"screencap"
] | f4415c57b45cb0730e08899cbc92a2af1c047ffb | https://github.com/NetEaseGame/ATX/blob/f4415c57b45cb0730e08899cbc92a2af1c047ffb/atx/adbkit/device.py#L167-L186 |
241,525 | NetEaseGame/ATX | atx/adbkit/device.py | Device._adb_minicap | def _adb_minicap(self, scale=1.0):
"""
capture screen with minicap
https://github.com/openstf/minicap
"""
remote_file = tempfile.mktemp(dir='/data/local/tmp/', prefix='minicap-', suffix='.jpg')
local_file = tempfile.mktemp(prefix='atx-minicap-', suffix='.jpg')
(w, h, r) = self.display
params = '{x}x{y}@{rx}x{ry}/{r}'.format(x=w, y=h, rx=int(w*scale), ry=int(h*scale), r=r*90)
try:
self.shell('LD_LIBRARY_PATH=/data/local/tmp', self.__minicap, '-s', '-P', params, '>', remote_file)
self.pull(remote_file, local_file)
image = imutils.open_as_pillow(local_file)
return image
finally:
self.remove(remote_file)
os.unlink(local_file) | python | def _adb_minicap(self, scale=1.0):
remote_file = tempfile.mktemp(dir='/data/local/tmp/', prefix='minicap-', suffix='.jpg')
local_file = tempfile.mktemp(prefix='atx-minicap-', suffix='.jpg')
(w, h, r) = self.display
params = '{x}x{y}@{rx}x{ry}/{r}'.format(x=w, y=h, rx=int(w*scale), ry=int(h*scale), r=r*90)
try:
self.shell('LD_LIBRARY_PATH=/data/local/tmp', self.__minicap, '-s', '-P', params, '>', remote_file)
self.pull(remote_file, local_file)
image = imutils.open_as_pillow(local_file)
return image
finally:
self.remove(remote_file)
os.unlink(local_file) | [
"def",
"_adb_minicap",
"(",
"self",
",",
"scale",
"=",
"1.0",
")",
":",
"remote_file",
"=",
"tempfile",
".",
"mktemp",
"(",
"dir",
"=",
"'/data/local/tmp/'",
",",
"prefix",
"=",
"'minicap-'",
",",
"suffix",
"=",
"'.jpg'",
")",
"local_file",
"=",
"tempfile"... | capture screen with minicap
https://github.com/openstf/minicap | [
"capture",
"screen",
"with",
"minicap"
] | f4415c57b45cb0730e08899cbc92a2af1c047ffb | https://github.com/NetEaseGame/ATX/blob/f4415c57b45cb0730e08899cbc92a2af1c047ffb/atx/adbkit/device.py#L188-L205 |
241,526 | NetEaseGame/ATX | atx/adbkit/device.py | Device.screenshot | def screenshot(self, filename=None, scale=1.0, method=None):
"""
Take device screenshot
Args:
- filename(string): optional, save int filename
- scale(float): scale size
- method(string): one of minicap,screencap
Return:
PIL.Image
"""
image = None
method = method or self._screenshot_method
if method == 'minicap':
try:
image = self._adb_minicap(scale)
except Exception as e:
logger.warn("use minicap failed, fallback to screencap. error detail: %s", e)
self._screenshot_method = 'screencap'
return self.screenshot(filename=filename, scale=scale)
elif method == 'screencap':
image = self._adb_screencap(scale)
else:
raise RuntimeError("No such method(%s)" % method)
if filename:
image.save(filename)
return image | python | def screenshot(self, filename=None, scale=1.0, method=None):
image = None
method = method or self._screenshot_method
if method == 'minicap':
try:
image = self._adb_minicap(scale)
except Exception as e:
logger.warn("use minicap failed, fallback to screencap. error detail: %s", e)
self._screenshot_method = 'screencap'
return self.screenshot(filename=filename, scale=scale)
elif method == 'screencap':
image = self._adb_screencap(scale)
else:
raise RuntimeError("No such method(%s)" % method)
if filename:
image.save(filename)
return image | [
"def",
"screenshot",
"(",
"self",
",",
"filename",
"=",
"None",
",",
"scale",
"=",
"1.0",
",",
"method",
"=",
"None",
")",
":",
"image",
"=",
"None",
"method",
"=",
"method",
"or",
"self",
".",
"_screenshot_method",
"if",
"method",
"==",
"'minicap'",
"... | Take device screenshot
Args:
- filename(string): optional, save int filename
- scale(float): scale size
- method(string): one of minicap,screencap
Return:
PIL.Image | [
"Take",
"device",
"screenshot"
] | f4415c57b45cb0730e08899cbc92a2af1c047ffb | https://github.com/NetEaseGame/ATX/blob/f4415c57b45cb0730e08899cbc92a2af1c047ffb/atx/adbkit/device.py#L207-L235 |
241,527 | NetEaseGame/ATX | atx/record/android_layout.py | AndroidLayout.get_index_node | def get_index_node(self, idx):
'''get node with iterindex `idx`'''
idx = self.node_index.index(idx)
return self.nodes[idx] | python | def get_index_node(self, idx):
'''get node with iterindex `idx`'''
idx = self.node_index.index(idx)
return self.nodes[idx] | [
"def",
"get_index_node",
"(",
"self",
",",
"idx",
")",
":",
"idx",
"=",
"self",
".",
"node_index",
".",
"index",
"(",
"idx",
")",
"return",
"self",
".",
"nodes",
"[",
"idx",
"]"
] | get node with iterindex `idx` | [
"get",
"node",
"with",
"iterindex",
"idx"
] | f4415c57b45cb0730e08899cbc92a2af1c047ffb | https://github.com/NetEaseGame/ATX/blob/f4415c57b45cb0730e08899cbc92a2af1c047ffb/atx/record/android_layout.py#L178-L181 |
241,528 | NetEaseGame/ATX | atx/record/base.py | BaseRecorder.start | def start(self):
'''start running in background.'''
self.update_device_info()
self.get_device_status(0) # start addons.
self.hook()
self.thread = threading.Thread(target=self._run)
self.thread.start()
self.running = True | python | def start(self):
'''start running in background.'''
self.update_device_info()
self.get_device_status(0) # start addons.
self.hook()
self.thread = threading.Thread(target=self._run)
self.thread.start()
self.running = True | [
"def",
"start",
"(",
"self",
")",
":",
"self",
".",
"update_device_info",
"(",
")",
"self",
".",
"get_device_status",
"(",
"0",
")",
"# start addons.\r",
"self",
".",
"hook",
"(",
")",
"self",
".",
"thread",
"=",
"threading",
".",
"Thread",
"(",
"target"... | start running in background. | [
"start",
"running",
"in",
"background",
"."
] | f4415c57b45cb0730e08899cbc92a2af1c047ffb | https://github.com/NetEaseGame/ATX/blob/f4415c57b45cb0730e08899cbc92a2af1c047ffb/atx/record/base.py#L66-L73 |
241,529 | NetEaseGame/ATX | atx/record/base.py | BaseRecorder.analyze_frames | def analyze_frames(cls, workdir):
'''generate draft from recorded frames'''
record = cls(None, workdir)
obj = {}
with open(os.path.join(workdir, 'frames', 'frames.json')) as f:
obj = json.load(f)
record.device_info = obj['device']
record.frames = obj['frames']
record.analyze_all()
record.save() | python | def analyze_frames(cls, workdir):
'''generate draft from recorded frames'''
record = cls(None, workdir)
obj = {}
with open(os.path.join(workdir, 'frames', 'frames.json')) as f:
obj = json.load(f)
record.device_info = obj['device']
record.frames = obj['frames']
record.analyze_all()
record.save() | [
"def",
"analyze_frames",
"(",
"cls",
",",
"workdir",
")",
":",
"record",
"=",
"cls",
"(",
"None",
",",
"workdir",
")",
"obj",
"=",
"{",
"}",
"with",
"open",
"(",
"os",
".",
"path",
".",
"join",
"(",
"workdir",
",",
"'frames'",
",",
"'frames.json'",
... | generate draft from recorded frames | [
"generate",
"draft",
"from",
"recorded",
"frames"
] | f4415c57b45cb0730e08899cbc92a2af1c047ffb | https://github.com/NetEaseGame/ATX/blob/f4415c57b45cb0730e08899cbc92a2af1c047ffb/atx/record/base.py#L180-L189 |
241,530 | NetEaseGame/ATX | atx/record/base.py | BaseRecorder.process_casefile | def process_casefile(cls, workdir):
'''generate code from case.json'''
record = cls(None, workdir)
obj = {}
with open(os.path.join(workdir, 'frames', 'frames.json')) as f:
obj = json.load(f)
record.device_info = obj['device']
record.frames = obj['frames']
casedir = os.path.join(workdir, 'case')
with open(os.path.join(casedir, 'case.json')) as f:
record.case_draft = json.load(f)
# remove old files
for f in os.listdir(casedir):
if f != 'case.json':
os.remove(os.path.join(casedir, f))
record.generate_script() | python | def process_casefile(cls, workdir):
'''generate code from case.json'''
record = cls(None, workdir)
obj = {}
with open(os.path.join(workdir, 'frames', 'frames.json')) as f:
obj = json.load(f)
record.device_info = obj['device']
record.frames = obj['frames']
casedir = os.path.join(workdir, 'case')
with open(os.path.join(casedir, 'case.json')) as f:
record.case_draft = json.load(f)
# remove old files
for f in os.listdir(casedir):
if f != 'case.json':
os.remove(os.path.join(casedir, f))
record.generate_script() | [
"def",
"process_casefile",
"(",
"cls",
",",
"workdir",
")",
":",
"record",
"=",
"cls",
"(",
"None",
",",
"workdir",
")",
"obj",
"=",
"{",
"}",
"with",
"open",
"(",
"os",
".",
"path",
".",
"join",
"(",
"workdir",
",",
"'frames'",
",",
"'frames.json'",... | generate code from case.json | [
"generate",
"code",
"from",
"case",
".",
"json"
] | f4415c57b45cb0730e08899cbc92a2af1c047ffb | https://github.com/NetEaseGame/ATX/blob/f4415c57b45cb0730e08899cbc92a2af1c047ffb/atx/record/base.py#L192-L210 |
241,531 | NetEaseGame/ATX | atx/adbkit/client.py | Client.adb_path | def adb_path(cls):
"""return adb binary full path"""
if cls.__adb_cmd is None:
if "ANDROID_HOME" in os.environ:
filename = "adb.exe" if os.name == 'nt' else "adb"
adb_dir = os.path.join(os.environ["ANDROID_HOME"], "platform-tools")
adb_cmd = os.path.join(adb_dir, filename)
if not os.path.exists(adb_cmd):
raise EnvironmentError(
"Adb not found in $ANDROID_HOME/platform-tools path: %s." % adb_dir)
else:
import distutils
if "spawn" not in dir(distutils):
import distutils.spawn
adb_cmd = distutils.spawn.find_executable("adb")
if adb_cmd:
adb_cmd = os.path.realpath(adb_cmd)
else:
raise EnvironmentError("$ANDROID_HOME environment not set.")
cls.__adb_cmd = adb_cmd
return cls.__adb_cmd | python | def adb_path(cls):
if cls.__adb_cmd is None:
if "ANDROID_HOME" in os.environ:
filename = "adb.exe" if os.name == 'nt' else "adb"
adb_dir = os.path.join(os.environ["ANDROID_HOME"], "platform-tools")
adb_cmd = os.path.join(adb_dir, filename)
if not os.path.exists(adb_cmd):
raise EnvironmentError(
"Adb not found in $ANDROID_HOME/platform-tools path: %s." % adb_dir)
else:
import distutils
if "spawn" not in dir(distutils):
import distutils.spawn
adb_cmd = distutils.spawn.find_executable("adb")
if adb_cmd:
adb_cmd = os.path.realpath(adb_cmd)
else:
raise EnvironmentError("$ANDROID_HOME environment not set.")
cls.__adb_cmd = adb_cmd
return cls.__adb_cmd | [
"def",
"adb_path",
"(",
"cls",
")",
":",
"if",
"cls",
".",
"__adb_cmd",
"is",
"None",
":",
"if",
"\"ANDROID_HOME\"",
"in",
"os",
".",
"environ",
":",
"filename",
"=",
"\"adb.exe\"",
"if",
"os",
".",
"name",
"==",
"'nt'",
"else",
"\"adb\"",
"adb_dir",
"... | return adb binary full path | [
"return",
"adb",
"binary",
"full",
"path"
] | f4415c57b45cb0730e08899cbc92a2af1c047ffb | https://github.com/NetEaseGame/ATX/blob/f4415c57b45cb0730e08899cbc92a2af1c047ffb/atx/adbkit/client.py#L52-L72 |
241,532 | NetEaseGame/ATX | atx/adbkit/client.py | Client.connect | def connect(self, addr):
'''
Call adb connect
Return true when connect success
'''
if addr.find(':') == -1:
addr += ':5555'
output = self.run_cmd('connect', addr)
return 'unable to connect' not in output | python | def connect(self, addr):
'''
Call adb connect
Return true when connect success
'''
if addr.find(':') == -1:
addr += ':5555'
output = self.run_cmd('connect', addr)
return 'unable to connect' not in output | [
"def",
"connect",
"(",
"self",
",",
"addr",
")",
":",
"if",
"addr",
".",
"find",
"(",
"':'",
")",
"==",
"-",
"1",
":",
"addr",
"+=",
"':5555'",
"output",
"=",
"self",
".",
"run_cmd",
"(",
"'connect'",
",",
"addr",
")",
"return",
"'unable to connect'"... | Call adb connect
Return true when connect success | [
"Call",
"adb",
"connect",
"Return",
"true",
"when",
"connect",
"success"
] | f4415c57b45cb0730e08899cbc92a2af1c047ffb | https://github.com/NetEaseGame/ATX/blob/f4415c57b45cb0730e08899cbc92a2af1c047ffb/atx/adbkit/client.py#L137-L145 |
241,533 | NetEaseGame/ATX | atx/cmds/screencap.py | main | def main(host=None, port=None, serial=None, scale=1.0, out='screenshot.png', method='minicap'):
"""
If minicap not avaliable then use uiautomator instead
Disable scale for now.
Because -s scale is conflict of -s serial
"""
print('Started screencap')
start = time.time()
client = adbkit.Client(host=host, port=port)
device = client.device(serial)
im = device.screenshot(scale=scale)
im.save(out)
print('Time spend: %.2fs' % (time.time() - start))
print('File saved to "%s"' % out)
try:
import win32clipboard
output = StringIO()
im.convert("RGB").save(output, "BMP")
data = output.getvalue()[14:]
output.close()
win32clipboard.OpenClipboard()
win32clipboard.EmptyClipboard()
win32clipboard.SetClipboardData(win32clipboard.CF_DIB, data)
win32clipboard.CloseClipboard()
print('Copied to clipboard')
except:
pass | python | def main(host=None, port=None, serial=None, scale=1.0, out='screenshot.png', method='minicap'):
print('Started screencap')
start = time.time()
client = adbkit.Client(host=host, port=port)
device = client.device(serial)
im = device.screenshot(scale=scale)
im.save(out)
print('Time spend: %.2fs' % (time.time() - start))
print('File saved to "%s"' % out)
try:
import win32clipboard
output = StringIO()
im.convert("RGB").save(output, "BMP")
data = output.getvalue()[14:]
output.close()
win32clipboard.OpenClipboard()
win32clipboard.EmptyClipboard()
win32clipboard.SetClipboardData(win32clipboard.CF_DIB, data)
win32clipboard.CloseClipboard()
print('Copied to clipboard')
except:
pass | [
"def",
"main",
"(",
"host",
"=",
"None",
",",
"port",
"=",
"None",
",",
"serial",
"=",
"None",
",",
"scale",
"=",
"1.0",
",",
"out",
"=",
"'screenshot.png'",
",",
"method",
"=",
"'minicap'",
")",
":",
"print",
"(",
"'Started screencap'",
")",
"start",
... | If minicap not avaliable then use uiautomator instead
Disable scale for now.
Because -s scale is conflict of -s serial | [
"If",
"minicap",
"not",
"avaliable",
"then",
"use",
"uiautomator",
"instead",
"Disable",
"scale",
"for",
"now",
".",
"Because",
"-",
"s",
"scale",
"is",
"conflict",
"of",
"-",
"s",
"serial"
] | f4415c57b45cb0730e08899cbc92a2af1c047ffb | https://github.com/NetEaseGame/ATX/blob/f4415c57b45cb0730e08899cbc92a2af1c047ffb/atx/cmds/screencap.py#L14-L45 |
241,534 | NetEaseGame/ATX | atx/drivers/android.py | AndroidDevice.rotation | def rotation(self):
"""
Rotaion of the phone
0: normal
1: home key on the right
2: home key on the top
3: home key on the left
"""
if self.screen_rotation in range(4):
return self.screen_rotation
return self.adb_device.rotation() or self.info['displayRotation'] | python | def rotation(self):
if self.screen_rotation in range(4):
return self.screen_rotation
return self.adb_device.rotation() or self.info['displayRotation'] | [
"def",
"rotation",
"(",
"self",
")",
":",
"if",
"self",
".",
"screen_rotation",
"in",
"range",
"(",
"4",
")",
":",
"return",
"self",
".",
"screen_rotation",
"return",
"self",
".",
"adb_device",
".",
"rotation",
"(",
")",
"or",
"self",
".",
"info",
"[",... | Rotaion of the phone
0: normal
1: home key on the right
2: home key on the top
3: home key on the left | [
"Rotaion",
"of",
"the",
"phone"
] | f4415c57b45cb0730e08899cbc92a2af1c047ffb | https://github.com/NetEaseGame/ATX/blob/f4415c57b45cb0730e08899cbc92a2af1c047ffb/atx/drivers/android.py#L192-L203 |
241,535 | NetEaseGame/ATX | atx/drivers/android.py | AndroidDevice.properties | def properties(self):
'''
Android Properties, extracted from `adb shell getprop`
Returns:
dict of props, for
example:
{'ro.bluetooth.dun': 'true'}
'''
props = {}
for line in self.adb_shell(['getprop']).splitlines():
m = _PROP_PATTERN.match(line)
if m:
props[m.group('key')] = m.group('value')
return props | python | def properties(self):
'''
Android Properties, extracted from `adb shell getprop`
Returns:
dict of props, for
example:
{'ro.bluetooth.dun': 'true'}
'''
props = {}
for line in self.adb_shell(['getprop']).splitlines():
m = _PROP_PATTERN.match(line)
if m:
props[m.group('key')] = m.group('value')
return props | [
"def",
"properties",
"(",
"self",
")",
":",
"props",
"=",
"{",
"}",
"for",
"line",
"in",
"self",
".",
"adb_shell",
"(",
"[",
"'getprop'",
"]",
")",
".",
"splitlines",
"(",
")",
":",
"m",
"=",
"_PROP_PATTERN",
".",
"match",
"(",
"line",
")",
"if",
... | Android Properties, extracted from `adb shell getprop`
Returns:
dict of props, for
example:
{'ro.bluetooth.dun': 'true'} | [
"Android",
"Properties",
"extracted",
"from",
"adb",
"shell",
"getprop"
] | f4415c57b45cb0730e08899cbc92a2af1c047ffb | https://github.com/NetEaseGame/ATX/blob/f4415c57b45cb0730e08899cbc92a2af1c047ffb/atx/drivers/android.py#L265-L280 |
241,536 | NetEaseGame/ATX | atx/drivers/android.py | AndroidDevice.type | def type(self, s, enter=False, clear=False):
"""Input some text, this method has been tested not very stable on some device.
"Hi world" maybe spell into "H iworld"
Args:
- s: string (text to input), better to be unicode
- enter(bool): input enter at last
- next(bool): perform editor action Next
- clear(bool): clear text before type
- ui_select_kwargs(**): tap then type
The android source code show that
space need to change to %s
insteresting thing is that if want to input %s, it is really unconvinent.
android source code can be found here.
https://android.googlesource.com/platform/frameworks/base/+/android-4.4.2_r1/cmds/input/src/com/android/commands/input/Input.java#159
app source see here: https://github.com/openatx/android-unicode
"""
if clear:
self.clear_text()
self._uiauto.send_keys(s)
if enter:
self.keyevent('KEYCODE_ENTER') | python | def type(self, s, enter=False, clear=False):
if clear:
self.clear_text()
self._uiauto.send_keys(s)
if enter:
self.keyevent('KEYCODE_ENTER') | [
"def",
"type",
"(",
"self",
",",
"s",
",",
"enter",
"=",
"False",
",",
"clear",
"=",
"False",
")",
":",
"if",
"clear",
":",
"self",
".",
"clear_text",
"(",
")",
"self",
".",
"_uiauto",
".",
"send_keys",
"(",
"s",
")",
"if",
"enter",
":",
"self",
... | Input some text, this method has been tested not very stable on some device.
"Hi world" maybe spell into "H iworld"
Args:
- s: string (text to input), better to be unicode
- enter(bool): input enter at last
- next(bool): perform editor action Next
- clear(bool): clear text before type
- ui_select_kwargs(**): tap then type
The android source code show that
space need to change to %s
insteresting thing is that if want to input %s, it is really unconvinent.
android source code can be found here.
https://android.googlesource.com/platform/frameworks/base/+/android-4.4.2_r1/cmds/input/src/com/android/commands/input/Input.java#159
app source see here: https://github.com/openatx/android-unicode | [
"Input",
"some",
"text",
"this",
"method",
"has",
"been",
"tested",
"not",
"very",
"stable",
"on",
"some",
"device",
".",
"Hi",
"world",
"maybe",
"spell",
"into",
"H",
"iworld"
] | f4415c57b45cb0730e08899cbc92a2af1c047ffb | https://github.com/NetEaseGame/ATX/blob/f4415c57b45cb0730e08899cbc92a2af1c047ffb/atx/drivers/android.py#L436-L461 |
241,537 | NetEaseGame/ATX | atx/drivers/android.py | AndroidDevice.input_methods | def input_methods(self):
"""
Get all input methods
Return example: ['com.sohu.inputmethod.sogou/.SogouIME', 'android.unicode.ime/.Utf7ImeService']
"""
imes = []
for line in self.adb_shell(['ime', 'list', '-s', '-a']).splitlines():
line = line.strip()
if re.match('^.+/.+$', line):
imes.append(line)
return imes | python | def input_methods(self):
imes = []
for line in self.adb_shell(['ime', 'list', '-s', '-a']).splitlines():
line = line.strip()
if re.match('^.+/.+$', line):
imes.append(line)
return imes | [
"def",
"input_methods",
"(",
"self",
")",
":",
"imes",
"=",
"[",
"]",
"for",
"line",
"in",
"self",
".",
"adb_shell",
"(",
"[",
"'ime'",
",",
"'list'",
",",
"'-s'",
",",
"'-a'",
"]",
")",
".",
"splitlines",
"(",
")",
":",
"line",
"=",
"line",
".",... | Get all input methods
Return example: ['com.sohu.inputmethod.sogou/.SogouIME', 'android.unicode.ime/.Utf7ImeService'] | [
"Get",
"all",
"input",
"methods"
] | f4415c57b45cb0730e08899cbc92a2af1c047ffb | https://github.com/NetEaseGame/ATX/blob/f4415c57b45cb0730e08899cbc92a2af1c047ffb/atx/drivers/android.py#L473-L484 |
241,538 | NetEaseGame/ATX | atx/drivers/android.py | AndroidDevice.current_ime | def current_ime(self):
''' Get current input method '''
dumpout = self.adb_shell(['dumpsys', 'input_method'])
m = _INPUT_METHOD_RE.search(dumpout)
if m:
return m.group(1) | python | def current_ime(self):
''' Get current input method '''
dumpout = self.adb_shell(['dumpsys', 'input_method'])
m = _INPUT_METHOD_RE.search(dumpout)
if m:
return m.group(1) | [
"def",
"current_ime",
"(",
"self",
")",
":",
"dumpout",
"=",
"self",
".",
"adb_shell",
"(",
"[",
"'dumpsys'",
",",
"'input_method'",
"]",
")",
"m",
"=",
"_INPUT_METHOD_RE",
".",
"search",
"(",
"dumpout",
")",
"if",
"m",
":",
"return",
"m",
".",
"group"... | Get current input method | [
"Get",
"current",
"input",
"method"
] | f4415c57b45cb0730e08899cbc92a2af1c047ffb | https://github.com/NetEaseGame/ATX/blob/f4415c57b45cb0730e08899cbc92a2af1c047ffb/atx/drivers/android.py#L486-L491 |
241,539 | NetEaseGame/ATX | atx/imutils.py | open_as_pillow | def open_as_pillow(filename):
""" This way can delete file immediately """
with __sys_open(filename, 'rb') as f:
data = BytesIO(f.read())
return Image.open(data) | python | def open_as_pillow(filename):
with __sys_open(filename, 'rb') as f:
data = BytesIO(f.read())
return Image.open(data) | [
"def",
"open_as_pillow",
"(",
"filename",
")",
":",
"with",
"__sys_open",
"(",
"filename",
",",
"'rb'",
")",
"as",
"f",
":",
"data",
"=",
"BytesIO",
"(",
"f",
".",
"read",
"(",
")",
")",
"return",
"Image",
".",
"open",
"(",
"data",
")"
] | This way can delete file immediately | [
"This",
"way",
"can",
"delete",
"file",
"immediately"
] | f4415c57b45cb0730e08899cbc92a2af1c047ffb | https://github.com/NetEaseGame/ATX/blob/f4415c57b45cb0730e08899cbc92a2af1c047ffb/atx/imutils.py#L71-L75 |
241,540 | NetEaseGame/ATX | atx/imutils.py | from_pillow | def from_pillow(pil_image):
""" Convert from pillow image to opencv """
# convert PIL to OpenCV
pil_image = pil_image.convert('RGB')
cv2_image = np.array(pil_image)
# Convert RGB to BGR
cv2_image = cv2_image[:, :, ::-1].copy()
return cv2_image | python | def from_pillow(pil_image):
# convert PIL to OpenCV
pil_image = pil_image.convert('RGB')
cv2_image = np.array(pil_image)
# Convert RGB to BGR
cv2_image = cv2_image[:, :, ::-1].copy()
return cv2_image | [
"def",
"from_pillow",
"(",
"pil_image",
")",
":",
"# convert PIL to OpenCV",
"pil_image",
"=",
"pil_image",
".",
"convert",
"(",
"'RGB'",
")",
"cv2_image",
"=",
"np",
".",
"array",
"(",
"pil_image",
")",
"# Convert RGB to BGR ",
"cv2_image",
"=",
"cv2_image",
"[... | Convert from pillow image to opencv | [
"Convert",
"from",
"pillow",
"image",
"to",
"opencv"
] | f4415c57b45cb0730e08899cbc92a2af1c047ffb | https://github.com/NetEaseGame/ATX/blob/f4415c57b45cb0730e08899cbc92a2af1c047ffb/atx/imutils.py#L81-L88 |
241,541 | NetEaseGame/ATX | atx/imutils.py | url_to_image | def url_to_image(url, flag=cv2.IMREAD_COLOR):
""" download the image, convert it to a NumPy array, and then read
it into OpenCV format """
resp = urlopen(url)
image = np.asarray(bytearray(resp.read()), dtype="uint8")
image = cv2.imdecode(image, flag)
return image | python | def url_to_image(url, flag=cv2.IMREAD_COLOR):
resp = urlopen(url)
image = np.asarray(bytearray(resp.read()), dtype="uint8")
image = cv2.imdecode(image, flag)
return image | [
"def",
"url_to_image",
"(",
"url",
",",
"flag",
"=",
"cv2",
".",
"IMREAD_COLOR",
")",
":",
"resp",
"=",
"urlopen",
"(",
"url",
")",
"image",
"=",
"np",
".",
"asarray",
"(",
"bytearray",
"(",
"resp",
".",
"read",
"(",
")",
")",
",",
"dtype",
"=",
... | download the image, convert it to a NumPy array, and then read
it into OpenCV format | [
"download",
"the",
"image",
"convert",
"it",
"to",
"a",
"NumPy",
"array",
"and",
"then",
"read",
"it",
"into",
"OpenCV",
"format"
] | f4415c57b45cb0730e08899cbc92a2af1c047ffb | https://github.com/NetEaseGame/ATX/blob/f4415c57b45cb0730e08899cbc92a2af1c047ffb/atx/imutils.py#L97-L103 |
241,542 | NetEaseGame/ATX | atx/imutils.py | mark_point | def mark_point(img, x, y):
"""
Mark a point
Args:
- img(numpy): the source image
- x, y(int): position
"""
overlay = img.copy()
output = img.copy()
alpha = 0.5
radius = max(5, min(img.shape[:2])//15)
center = int(x), int(y)
color = (0, 0, 255)
cv2.circle(overlay, center, radius, color, -1)
cv2.addWeighted(overlay, alpha, output, 1-alpha, 0, output)
return output | python | def mark_point(img, x, y):
overlay = img.copy()
output = img.copy()
alpha = 0.5
radius = max(5, min(img.shape[:2])//15)
center = int(x), int(y)
color = (0, 0, 255)
cv2.circle(overlay, center, radius, color, -1)
cv2.addWeighted(overlay, alpha, output, 1-alpha, 0, output)
return output | [
"def",
"mark_point",
"(",
"img",
",",
"x",
",",
"y",
")",
":",
"overlay",
"=",
"img",
".",
"copy",
"(",
")",
"output",
"=",
"img",
".",
"copy",
"(",
")",
"alpha",
"=",
"0.5",
"radius",
"=",
"max",
"(",
"5",
",",
"min",
"(",
"img",
".",
"shape... | Mark a point
Args:
- img(numpy): the source image
- x, y(int): position | [
"Mark",
"a",
"point"
] | f4415c57b45cb0730e08899cbc92a2af1c047ffb | https://github.com/NetEaseGame/ATX/blob/f4415c57b45cb0730e08899cbc92a2af1c047ffb/atx/imutils.py#L139-L157 |
241,543 | NetEaseGame/ATX | atx/drivers/ios_webdriveragent.py | IOSDevice.display | def display(self):
""" Get screen width and height """
w, h = self.session.window_size()
return Display(w*self.scale, h*self.scale) | python | def display(self):
w, h = self.session.window_size()
return Display(w*self.scale, h*self.scale) | [
"def",
"display",
"(",
"self",
")",
":",
"w",
",",
"h",
"=",
"self",
".",
"session",
".",
"window_size",
"(",
")",
"return",
"Display",
"(",
"w",
"*",
"self",
".",
"scale",
",",
"h",
"*",
"self",
".",
"scale",
")"
] | Get screen width and height | [
"Get",
"screen",
"width",
"and",
"height"
] | f4415c57b45cb0730e08899cbc92a2af1c047ffb | https://github.com/NetEaseGame/ATX/blob/f4415c57b45cb0730e08899cbc92a2af1c047ffb/atx/drivers/ios_webdriveragent.py#L99-L102 |
241,544 | NetEaseGame/ATX | scripts/adb_old.py | Adb.forward | def forward(self, device_port, local_port=None):
'''adb port forward. return local_port'''
if local_port is None:
for s, lp, rp in self.forward_list():
if s == self.device_serial() and rp == 'tcp:%d' % device_port:
return int(lp[4:])
return self.forward(device_port, next_local_port(self.server_host))
else:
self.cmd("forward", "tcp:%d" % local_port, "tcp:%d" % device_port).wait()
return local_port | python | def forward(self, device_port, local_port=None):
'''adb port forward. return local_port'''
if local_port is None:
for s, lp, rp in self.forward_list():
if s == self.device_serial() and rp == 'tcp:%d' % device_port:
return int(lp[4:])
return self.forward(device_port, next_local_port(self.server_host))
else:
self.cmd("forward", "tcp:%d" % local_port, "tcp:%d" % device_port).wait()
return local_port | [
"def",
"forward",
"(",
"self",
",",
"device_port",
",",
"local_port",
"=",
"None",
")",
":",
"if",
"local_port",
"is",
"None",
":",
"for",
"s",
",",
"lp",
",",
"rp",
"in",
"self",
".",
"forward_list",
"(",
")",
":",
"if",
"s",
"==",
"self",
".",
... | adb port forward. return local_port | [
"adb",
"port",
"forward",
".",
"return",
"local_port"
] | f4415c57b45cb0730e08899cbc92a2af1c047ffb | https://github.com/NetEaseGame/ATX/blob/f4415c57b45cb0730e08899cbc92a2af1c047ffb/scripts/adb_old.py#L178-L187 |
241,545 | NetEaseGame/ATX | atx/record/android.py | touch2screen | def touch2screen(w, h, o, x, y):
'''convert touch position'''
if o == 0:
return x, y
elif o == 1: # landscape-right
return y, w-x
elif o == 2: # upsidedown
return w-x, h-y
elif o == 3: # landscape-left
return h-y, x
return x, y | python | def touch2screen(w, h, o, x, y):
'''convert touch position'''
if o == 0:
return x, y
elif o == 1: # landscape-right
return y, w-x
elif o == 2: # upsidedown
return w-x, h-y
elif o == 3: # landscape-left
return h-y, x
return x, y | [
"def",
"touch2screen",
"(",
"w",
",",
"h",
",",
"o",
",",
"x",
",",
"y",
")",
":",
"if",
"o",
"==",
"0",
":",
"return",
"x",
",",
"y",
"elif",
"o",
"==",
"1",
":",
"# landscape-right\r",
"return",
"y",
",",
"w",
"-",
"x",
"elif",
"o",
"==",
... | convert touch position | [
"convert",
"touch",
"position"
] | f4415c57b45cb0730e08899cbc92a2af1c047ffb | https://github.com/NetEaseGame/ATX/blob/f4415c57b45cb0730e08899cbc92a2af1c047ffb/atx/record/android.py#L342-L352 |
241,546 | NetEaseGame/ATX | atx/ext/report/__init__.py | Report.patch_wda | def patch_wda(self):
"""
Record steps of WebDriverAgent
"""
import wda
def _click(that):
rawx, rawy = that.bounds.center
x, y = self.d.scale*rawx, self.d.scale*rawy
screen_before = self._save_screenshot()
orig_click = pt.get_original(wda.Selector, 'click')
screen_after = self._save_screenshot()
self.add_step('click',
screen_before=screen_before,
screen_after=screen_after,
position={'x': x, 'y': y})
return orig_click(that)
pt.patch_item(wda.Selector, 'click', _click) | python | def patch_wda(self):
import wda
def _click(that):
rawx, rawy = that.bounds.center
x, y = self.d.scale*rawx, self.d.scale*rawy
screen_before = self._save_screenshot()
orig_click = pt.get_original(wda.Selector, 'click')
screen_after = self._save_screenshot()
self.add_step('click',
screen_before=screen_before,
screen_after=screen_after,
position={'x': x, 'y': y})
return orig_click(that)
pt.patch_item(wda.Selector, 'click', _click) | [
"def",
"patch_wda",
"(",
"self",
")",
":",
"import",
"wda",
"def",
"_click",
"(",
"that",
")",
":",
"rawx",
",",
"rawy",
"=",
"that",
".",
"bounds",
".",
"center",
"x",
",",
"y",
"=",
"self",
".",
"d",
".",
"scale",
"*",
"rawx",
",",
"self",
".... | Record steps of WebDriverAgent | [
"Record",
"steps",
"of",
"WebDriverAgent"
] | f4415c57b45cb0730e08899cbc92a2af1c047ffb | https://github.com/NetEaseGame/ATX/blob/f4415c57b45cb0730e08899cbc92a2af1c047ffb/atx/ext/report/__init__.py#L109-L127 |
241,547 | NetEaseGame/ATX | atx/ext/report/__init__.py | Report._take_screenshot | def _take_screenshot(self, screenshot=False, name_prefix='unknown'):
"""
This is different from _save_screenshot.
The return value maybe None or the screenshot path
Args:
screenshot: bool or PIL image
"""
if isinstance(screenshot, bool):
if not screenshot:
return
return self._save_screenshot(name_prefix=name_prefix)
if isinstance(screenshot, Image.Image):
return self._save_screenshot(screen=screenshot, name_prefix=name_prefix)
raise TypeError("invalid type for func _take_screenshot: "+ type(screenshot)) | python | def _take_screenshot(self, screenshot=False, name_prefix='unknown'):
if isinstance(screenshot, bool):
if not screenshot:
return
return self._save_screenshot(name_prefix=name_prefix)
if isinstance(screenshot, Image.Image):
return self._save_screenshot(screen=screenshot, name_prefix=name_prefix)
raise TypeError("invalid type for func _take_screenshot: "+ type(screenshot)) | [
"def",
"_take_screenshot",
"(",
"self",
",",
"screenshot",
"=",
"False",
",",
"name_prefix",
"=",
"'unknown'",
")",
":",
"if",
"isinstance",
"(",
"screenshot",
",",
"bool",
")",
":",
"if",
"not",
"screenshot",
":",
"return",
"return",
"self",
".",
"_save_s... | This is different from _save_screenshot.
The return value maybe None or the screenshot path
Args:
screenshot: bool or PIL image | [
"This",
"is",
"different",
"from",
"_save_screenshot",
".",
"The",
"return",
"value",
"maybe",
"None",
"or",
"the",
"screenshot",
"path"
] | f4415c57b45cb0730e08899cbc92a2af1c047ffb | https://github.com/NetEaseGame/ATX/blob/f4415c57b45cb0730e08899cbc92a2af1c047ffb/atx/ext/report/__init__.py#L223-L238 |
241,548 | NetEaseGame/ATX | atx/ext/report/__init__.py | Report._add_assert | def _add_assert(self, **kwargs):
"""
if screenshot is None, only failed case will take screenshot
"""
# convert screenshot to relative path from <None|True|False|PIL.Image>
screenshot = kwargs.get('screenshot')
is_success = kwargs.get('success')
screenshot = (not is_success) if screenshot is None else screenshot
kwargs['screenshot'] = self._take_screenshot(screenshot=screenshot, name_prefix='assert')
action = kwargs.pop('action', 'assert')
self.add_step(action, **kwargs)
if not is_success:
message = kwargs.get('message')
frame, filename, line_number, function_name, lines, index = inspect.stack()[2]
print('Assert [%s: %d] WARN: %s' % (filename, line_number, message))
if not kwargs.get('safe', False):
raise AssertionError(message) | python | def _add_assert(self, **kwargs):
# convert screenshot to relative path from <None|True|False|PIL.Image>
screenshot = kwargs.get('screenshot')
is_success = kwargs.get('success')
screenshot = (not is_success) if screenshot is None else screenshot
kwargs['screenshot'] = self._take_screenshot(screenshot=screenshot, name_prefix='assert')
action = kwargs.pop('action', 'assert')
self.add_step(action, **kwargs)
if not is_success:
message = kwargs.get('message')
frame, filename, line_number, function_name, lines, index = inspect.stack()[2]
print('Assert [%s: %d] WARN: %s' % (filename, line_number, message))
if not kwargs.get('safe', False):
raise AssertionError(message) | [
"def",
"_add_assert",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"# convert screenshot to relative path from <None|True|False|PIL.Image>",
"screenshot",
"=",
"kwargs",
".",
"get",
"(",
"'screenshot'",
")",
"is_success",
"=",
"kwargs",
".",
"get",
"(",
"'success... | if screenshot is None, only failed case will take screenshot | [
"if",
"screenshot",
"is",
"None",
"only",
"failed",
"case",
"will",
"take",
"screenshot"
] | f4415c57b45cb0730e08899cbc92a2af1c047ffb | https://github.com/NetEaseGame/ATX/blob/f4415c57b45cb0730e08899cbc92a2af1c047ffb/atx/ext/report/__init__.py#L251-L267 |
241,549 | Phylliade/ikpy | src/ikpy/plot_utils.py | plot_chain | def plot_chain(chain, joints, ax, target=None, show=False):
"""Plots the chain"""
# LIst of nodes and orientations
nodes = []
axes = []
transformation_matrixes = chain.forward_kinematics(joints, full_kinematics=True)
# Get the nodes and the orientation from the tranformation matrix
for (index, link) in enumerate(chain.links):
(node, rotation) = geometry_utils.from_transformation_matrix(transformation_matrixes[index])
nodes.append(node)
rotation_axis = link._get_rotation_axis()
if index == 0:
axes.append(rotation_axis)
else:
axes.append(geometry_utils.homogeneous_to_cartesian_vectors(np.dot(transformation_matrixes[index - 1], rotation_axis)))
# Plot the chain
ax.plot([x[0] for x in nodes], [x[1] for x in nodes], [x[2] for x in nodes])
# Plot of the nodes of the chain
ax.scatter([x[0] for x in nodes], [x[1] for x in nodes], [x[2] for x in nodes])
# Plot rotation axes
for index, axe in enumerate(axes):
ax.plot([nodes[index][0], axe[0]], [nodes[index][1], axe[1]], [nodes[index][2], axe[2]]) | python | def plot_chain(chain, joints, ax, target=None, show=False):
# LIst of nodes and orientations
nodes = []
axes = []
transformation_matrixes = chain.forward_kinematics(joints, full_kinematics=True)
# Get the nodes and the orientation from the tranformation matrix
for (index, link) in enumerate(chain.links):
(node, rotation) = geometry_utils.from_transformation_matrix(transformation_matrixes[index])
nodes.append(node)
rotation_axis = link._get_rotation_axis()
if index == 0:
axes.append(rotation_axis)
else:
axes.append(geometry_utils.homogeneous_to_cartesian_vectors(np.dot(transformation_matrixes[index - 1], rotation_axis)))
# Plot the chain
ax.plot([x[0] for x in nodes], [x[1] for x in nodes], [x[2] for x in nodes])
# Plot of the nodes of the chain
ax.scatter([x[0] for x in nodes], [x[1] for x in nodes], [x[2] for x in nodes])
# Plot rotation axes
for index, axe in enumerate(axes):
ax.plot([nodes[index][0], axe[0]], [nodes[index][1], axe[1]], [nodes[index][2], axe[2]]) | [
"def",
"plot_chain",
"(",
"chain",
",",
"joints",
",",
"ax",
",",
"target",
"=",
"None",
",",
"show",
"=",
"False",
")",
":",
"# LIst of nodes and orientations",
"nodes",
"=",
"[",
"]",
"axes",
"=",
"[",
"]",
"transformation_matrixes",
"=",
"chain",
".",
... | Plots the chain | [
"Plots",
"the",
"chain"
] | 60e36d6163136942bf520d952db17123c658d0b6 | https://github.com/Phylliade/ikpy/blob/60e36d6163136942bf520d952db17123c658d0b6/src/ikpy/plot_utils.py#L29-L54 |
241,550 | Phylliade/ikpy | src/ikpy/plot_utils.py | plot_target | def plot_target(target, ax):
"""Ajoute la target au plot"""
ax.scatter(target[0], target[1], target[2], c="red", s=80) | python | def plot_target(target, ax):
ax.scatter(target[0], target[1], target[2], c="red", s=80) | [
"def",
"plot_target",
"(",
"target",
",",
"ax",
")",
":",
"ax",
".",
"scatter",
"(",
"target",
"[",
"0",
"]",
",",
"target",
"[",
"1",
"]",
",",
"target",
"[",
"2",
"]",
",",
"c",
"=",
"\"red\"",
",",
"s",
"=",
"80",
")"
] | Ajoute la target au plot | [
"Ajoute",
"la",
"target",
"au",
"plot"
] | 60e36d6163136942bf520d952db17123c658d0b6 | https://github.com/Phylliade/ikpy/blob/60e36d6163136942bf520d952db17123c658d0b6/src/ikpy/plot_utils.py#L57-L59 |
241,551 | Phylliade/ikpy | src/ikpy/geometry_utils.py | Rx_matrix | def Rx_matrix(theta):
"""Rotation matrix around the X axis"""
return np.array([
[1, 0, 0],
[0, np.cos(theta), -np.sin(theta)],
[0, np.sin(theta), np.cos(theta)]
]) | python | def Rx_matrix(theta):
return np.array([
[1, 0, 0],
[0, np.cos(theta), -np.sin(theta)],
[0, np.sin(theta), np.cos(theta)]
]) | [
"def",
"Rx_matrix",
"(",
"theta",
")",
":",
"return",
"np",
".",
"array",
"(",
"[",
"[",
"1",
",",
"0",
",",
"0",
"]",
",",
"[",
"0",
",",
"np",
".",
"cos",
"(",
"theta",
")",
",",
"-",
"np",
".",
"sin",
"(",
"theta",
")",
"]",
",",
"[",
... | Rotation matrix around the X axis | [
"Rotation",
"matrix",
"around",
"the",
"X",
"axis"
] | 60e36d6163136942bf520d952db17123c658d0b6 | https://github.com/Phylliade/ikpy/blob/60e36d6163136942bf520d952db17123c658d0b6/src/ikpy/geometry_utils.py#L10-L16 |
241,552 | Phylliade/ikpy | src/ikpy/geometry_utils.py | Rz_matrix | def Rz_matrix(theta):
"""Rotation matrix around the Z axis"""
return np.array([
[np.cos(theta), -np.sin(theta), 0],
[np.sin(theta), np.cos(theta), 0],
[0, 0, 1]
]) | python | def Rz_matrix(theta):
return np.array([
[np.cos(theta), -np.sin(theta), 0],
[np.sin(theta), np.cos(theta), 0],
[0, 0, 1]
]) | [
"def",
"Rz_matrix",
"(",
"theta",
")",
":",
"return",
"np",
".",
"array",
"(",
"[",
"[",
"np",
".",
"cos",
"(",
"theta",
")",
",",
"-",
"np",
".",
"sin",
"(",
"theta",
")",
",",
"0",
"]",
",",
"[",
"np",
".",
"sin",
"(",
"theta",
")",
",",
... | Rotation matrix around the Z axis | [
"Rotation",
"matrix",
"around",
"the",
"Z",
"axis"
] | 60e36d6163136942bf520d952db17123c658d0b6 | https://github.com/Phylliade/ikpy/blob/60e36d6163136942bf520d952db17123c658d0b6/src/ikpy/geometry_utils.py#L19-L25 |
241,553 | Phylliade/ikpy | src/ikpy/geometry_utils.py | symbolic_Rz_matrix | def symbolic_Rz_matrix(symbolic_theta):
"""Matrice symbolique de rotation autour de l'axe Z"""
return sympy.Matrix([
[sympy.cos(symbolic_theta), -sympy.sin(symbolic_theta), 0],
[sympy.sin(symbolic_theta), sympy.cos(symbolic_theta), 0],
[0, 0, 1]
]) | python | def symbolic_Rz_matrix(symbolic_theta):
return sympy.Matrix([
[sympy.cos(symbolic_theta), -sympy.sin(symbolic_theta), 0],
[sympy.sin(symbolic_theta), sympy.cos(symbolic_theta), 0],
[0, 0, 1]
]) | [
"def",
"symbolic_Rz_matrix",
"(",
"symbolic_theta",
")",
":",
"return",
"sympy",
".",
"Matrix",
"(",
"[",
"[",
"sympy",
".",
"cos",
"(",
"symbolic_theta",
")",
",",
"-",
"sympy",
".",
"sin",
"(",
"symbolic_theta",
")",
",",
"0",
"]",
",",
"[",
"sympy",... | Matrice symbolique de rotation autour de l'axe Z | [
"Matrice",
"symbolique",
"de",
"rotation",
"autour",
"de",
"l",
"axe",
"Z"
] | 60e36d6163136942bf520d952db17123c658d0b6 | https://github.com/Phylliade/ikpy/blob/60e36d6163136942bf520d952db17123c658d0b6/src/ikpy/geometry_utils.py#L28-L34 |
241,554 | Phylliade/ikpy | src/ikpy/geometry_utils.py | Ry_matrix | def Ry_matrix(theta):
"""Rotation matrix around the Y axis"""
return np.array([
[np.cos(theta), 0, np.sin(theta)],
[0, 1, 0],
[-np.sin(theta), 0, np.cos(theta)]
]) | python | def Ry_matrix(theta):
return np.array([
[np.cos(theta), 0, np.sin(theta)],
[0, 1, 0],
[-np.sin(theta), 0, np.cos(theta)]
]) | [
"def",
"Ry_matrix",
"(",
"theta",
")",
":",
"return",
"np",
".",
"array",
"(",
"[",
"[",
"np",
".",
"cos",
"(",
"theta",
")",
",",
"0",
",",
"np",
".",
"sin",
"(",
"theta",
")",
"]",
",",
"[",
"0",
",",
"1",
",",
"0",
"]",
",",
"[",
"-",
... | Rotation matrix around the Y axis | [
"Rotation",
"matrix",
"around",
"the",
"Y",
"axis"
] | 60e36d6163136942bf520d952db17123c658d0b6 | https://github.com/Phylliade/ikpy/blob/60e36d6163136942bf520d952db17123c658d0b6/src/ikpy/geometry_utils.py#L37-L43 |
241,555 | Phylliade/ikpy | src/ikpy/geometry_utils.py | rpy_matrix | def rpy_matrix(roll, pitch, yaw):
"""Returns a rotation matrix described by the extrinsinc roll, pitch, yaw coordinates"""
return np.dot(Rz_matrix(yaw), np.dot(Ry_matrix(pitch), Rx_matrix(roll))) | python | def rpy_matrix(roll, pitch, yaw):
return np.dot(Rz_matrix(yaw), np.dot(Ry_matrix(pitch), Rx_matrix(roll))) | [
"def",
"rpy_matrix",
"(",
"roll",
",",
"pitch",
",",
"yaw",
")",
":",
"return",
"np",
".",
"dot",
"(",
"Rz_matrix",
"(",
"yaw",
")",
",",
"np",
".",
"dot",
"(",
"Ry_matrix",
"(",
"pitch",
")",
",",
"Rx_matrix",
"(",
"roll",
")",
")",
")"
] | Returns a rotation matrix described by the extrinsinc roll, pitch, yaw coordinates | [
"Returns",
"a",
"rotation",
"matrix",
"described",
"by",
"the",
"extrinsinc",
"roll",
"pitch",
"yaw",
"coordinates"
] | 60e36d6163136942bf520d952db17123c658d0b6 | https://github.com/Phylliade/ikpy/blob/60e36d6163136942bf520d952db17123c658d0b6/src/ikpy/geometry_utils.py#L56-L58 |
241,556 | Phylliade/ikpy | src/ikpy/geometry_utils.py | cartesian_to_homogeneous | def cartesian_to_homogeneous(cartesian_matrix, matrix_type="numpy"):
"""Converts a cartesian matrix to an homogenous matrix"""
dimension_x, dimension_y = cartesian_matrix.shape
# Square matrix
# Manage different types fo input matrixes
if matrix_type == "numpy":
homogeneous_matrix = np.eye(dimension_x + 1)
elif matrix_type == "sympy":
homogeneous_matrix = sympy.eye(dimension_x + 1)
# Add a column filled with 0 and finishing with 1 to the cartesian matrix to transform it into an homogeneous one
homogeneous_matrix[:-1, :-1] = cartesian_matrix
return homogeneous_matrix | python | def cartesian_to_homogeneous(cartesian_matrix, matrix_type="numpy"):
dimension_x, dimension_y = cartesian_matrix.shape
# Square matrix
# Manage different types fo input matrixes
if matrix_type == "numpy":
homogeneous_matrix = np.eye(dimension_x + 1)
elif matrix_type == "sympy":
homogeneous_matrix = sympy.eye(dimension_x + 1)
# Add a column filled with 0 and finishing with 1 to the cartesian matrix to transform it into an homogeneous one
homogeneous_matrix[:-1, :-1] = cartesian_matrix
return homogeneous_matrix | [
"def",
"cartesian_to_homogeneous",
"(",
"cartesian_matrix",
",",
"matrix_type",
"=",
"\"numpy\"",
")",
":",
"dimension_x",
",",
"dimension_y",
"=",
"cartesian_matrix",
".",
"shape",
"# Square matrix",
"# Manage different types fo input matrixes",
"if",
"matrix_type",
"==",
... | Converts a cartesian matrix to an homogenous matrix | [
"Converts",
"a",
"cartesian",
"matrix",
"to",
"an",
"homogenous",
"matrix"
] | 60e36d6163136942bf520d952db17123c658d0b6 | https://github.com/Phylliade/ikpy/blob/60e36d6163136942bf520d952db17123c658d0b6/src/ikpy/geometry_utils.py#L112-L124 |
241,557 | Phylliade/ikpy | src/ikpy/geometry_utils.py | cartesian_to_homogeneous_vectors | def cartesian_to_homogeneous_vectors(cartesian_vector, matrix_type="numpy"):
"""Converts a cartesian vector to an homogenous vector"""
dimension_x = cartesian_vector.shape[0]
# Vector
if matrix_type == "numpy":
homogeneous_vector = np.zeros(dimension_x + 1)
# Last item is a 1
homogeneous_vector[-1] = 1
homogeneous_vector[:-1] = cartesian_vector
return homogeneous_vector | python | def cartesian_to_homogeneous_vectors(cartesian_vector, matrix_type="numpy"):
dimension_x = cartesian_vector.shape[0]
# Vector
if matrix_type == "numpy":
homogeneous_vector = np.zeros(dimension_x + 1)
# Last item is a 1
homogeneous_vector[-1] = 1
homogeneous_vector[:-1] = cartesian_vector
return homogeneous_vector | [
"def",
"cartesian_to_homogeneous_vectors",
"(",
"cartesian_vector",
",",
"matrix_type",
"=",
"\"numpy\"",
")",
":",
"dimension_x",
"=",
"cartesian_vector",
".",
"shape",
"[",
"0",
"]",
"# Vector",
"if",
"matrix_type",
"==",
"\"numpy\"",
":",
"homogeneous_vector",
"=... | Converts a cartesian vector to an homogenous vector | [
"Converts",
"a",
"cartesian",
"vector",
"to",
"an",
"homogenous",
"vector"
] | 60e36d6163136942bf520d952db17123c658d0b6 | https://github.com/Phylliade/ikpy/blob/60e36d6163136942bf520d952db17123c658d0b6/src/ikpy/geometry_utils.py#L127-L136 |
241,558 | Phylliade/ikpy | src/ikpy/URDF_utils.py | find_next_joint | def find_next_joint(root, current_link, next_joint_name):
"""
Find the next joint in the URDF tree
Parameters
----------
root
current_link: xml.etree.ElementTree
The current URDF link
next_joint_name: str
Optional : The name of the next joint. If not provided, find it automatically as the first child of the link.
"""
# Find the joint attached to the link
has_next = False
next_joint = None
search_by_name = True
current_link_name = None
if next_joint_name is None:
# If no next joint is provided, find it automatically
search_by_name = False
current_link_name = current_link.attrib["name"]
for joint in root.iter("joint"):
# Iterate through all joints to find the good one
if search_by_name:
# Find the joint given its name
if joint.attrib["name"] == next_joint_name:
has_next = True
next_joint = joint
else:
# Find the first joint whose parent is the current_link
# FIXME: We are not sending a warning when we have two children for the same link
# Even if this is not possible, we should ensure something coherent
if joint.find("parent").attrib["link"] == current_link_name:
has_next = True
next_joint = joint
break
return has_next, next_joint | python | def find_next_joint(root, current_link, next_joint_name):
# Find the joint attached to the link
has_next = False
next_joint = None
search_by_name = True
current_link_name = None
if next_joint_name is None:
# If no next joint is provided, find it automatically
search_by_name = False
current_link_name = current_link.attrib["name"]
for joint in root.iter("joint"):
# Iterate through all joints to find the good one
if search_by_name:
# Find the joint given its name
if joint.attrib["name"] == next_joint_name:
has_next = True
next_joint = joint
else:
# Find the first joint whose parent is the current_link
# FIXME: We are not sending a warning when we have two children for the same link
# Even if this is not possible, we should ensure something coherent
if joint.find("parent").attrib["link"] == current_link_name:
has_next = True
next_joint = joint
break
return has_next, next_joint | [
"def",
"find_next_joint",
"(",
"root",
",",
"current_link",
",",
"next_joint_name",
")",
":",
"# Find the joint attached to the link",
"has_next",
"=",
"False",
"next_joint",
"=",
"None",
"search_by_name",
"=",
"True",
"current_link_name",
"=",
"None",
"if",
"next_joi... | Find the next joint in the URDF tree
Parameters
----------
root
current_link: xml.etree.ElementTree
The current URDF link
next_joint_name: str
Optional : The name of the next joint. If not provided, find it automatically as the first child of the link. | [
"Find",
"the",
"next",
"joint",
"in",
"the",
"URDF",
"tree"
] | 60e36d6163136942bf520d952db17123c658d0b6 | https://github.com/Phylliade/ikpy/blob/60e36d6163136942bf520d952db17123c658d0b6/src/ikpy/URDF_utils.py#L16-L55 |
241,559 | Phylliade/ikpy | src/ikpy/URDF_utils.py | find_next_link | def find_next_link(root, current_joint, next_link_name):
"""
Find the next link in the URDF tree
Parameters
----------
root
current_joint: xml.etree.ElementTree
The current URDF joint
next_link_name: str
Optional : The name of the next link. If not provided, find it automatically as the first child of the joint.
"""
has_next = False
next_link = None
# If no next link, find it automatically
if next_link_name is None:
# If the name of the next link is not provided, find it
next_link_name = current_joint.find("child").attrib["link"]
for urdf_link in root.iter("link"):
if urdf_link.attrib["name"] == next_link_name:
next_link = urdf_link
has_next = True
return has_next, next_link | python | def find_next_link(root, current_joint, next_link_name):
has_next = False
next_link = None
# If no next link, find it automatically
if next_link_name is None:
# If the name of the next link is not provided, find it
next_link_name = current_joint.find("child").attrib["link"]
for urdf_link in root.iter("link"):
if urdf_link.attrib["name"] == next_link_name:
next_link = urdf_link
has_next = True
return has_next, next_link | [
"def",
"find_next_link",
"(",
"root",
",",
"current_joint",
",",
"next_link_name",
")",
":",
"has_next",
"=",
"False",
"next_link",
"=",
"None",
"# If no next link, find it automatically",
"if",
"next_link_name",
"is",
"None",
":",
"# If the name of the next link is not p... | Find the next link in the URDF tree
Parameters
----------
root
current_joint: xml.etree.ElementTree
The current URDF joint
next_link_name: str
Optional : The name of the next link. If not provided, find it automatically as the first child of the joint. | [
"Find",
"the",
"next",
"link",
"in",
"the",
"URDF",
"tree"
] | 60e36d6163136942bf520d952db17123c658d0b6 | https://github.com/Phylliade/ikpy/blob/60e36d6163136942bf520d952db17123c658d0b6/src/ikpy/URDF_utils.py#L58-L82 |
241,560 | Phylliade/ikpy | src/ikpy/URDF_utils.py | get_urdf_parameters | def get_urdf_parameters(urdf_file, base_elements=None, last_link_vector=None, base_element_type="link"):
"""
Returns translated parameters from the given URDF file
Parameters
----------
urdf_file: str
The path of the URDF file
base_elements: list of strings
List of the links beginning the chain
last_link_vector: numpy.array
Optional : The translation vector of the tip.
base_element_type: str
Returns
-------
list[ikpy.link.URDFLink]
"""
tree = ET.parse(urdf_file)
root = tree.getroot()
base_elements = list(base_elements)
if base_elements is None:
base_elements = ["base_link"]
elif base_elements is []:
raise ValueError("base_elements can't be the empty list []")
joints = []
links = []
has_next = True
current_joint = None
current_link = None
# Initialize the tree traversal
if base_element_type == "link":
# The first element is a link, so its (virtual) parent should be a joint
node_type = "joint"
elif base_element_type == "joint":
# The same as before, but swap link and joint
node_type = "link"
else:
raise ValueError("Unknown type: {}".format(base_element_type))
# Parcours récursif de la structure de la chain
while has_next:
if len(base_elements) != 0:
next_element = base_elements.pop(0)
else:
next_element = None
if node_type == "link":
# Current element is a link, find child joint
(has_next, current_joint) = find_next_joint(root, current_link, next_element)
node_type = "joint"
if has_next:
joints.append(current_joint)
elif node_type == "joint":
# Current element is a joint, find child link
(has_next, current_link) = find_next_link(root, current_joint, next_element)
node_type = "link"
if has_next:
links.append(current_link)
parameters = []
# Save the joints in the good format
for joint in joints:
translation = [0, 0, 0]
orientation = [0, 0, 0]
rotation = [1, 0, 0]
bounds = [None, None]
origin = joint.find("origin")
if origin is not None:
if origin.attrib["xyz"]:
translation = [float(x) for x in origin.attrib["xyz"].split()]
if origin.attrib["rpy"]:
orientation = [float(x) for x in origin.attrib["rpy"].split()]
axis = joint.find("axis")
if axis is not None:
rotation = [float(x) for x in axis.attrib["xyz"].split()]
limit = joint.find("limit")
if limit is not None:
if limit.attrib["lower"]:
bounds[0] = float(limit.attrib["lower"])
if limit.attrib["upper"]:
bounds[1] = float(limit.attrib["upper"])
parameters.append(lib_link.URDFLink(
name=joint.attrib["name"],
bounds=tuple(bounds),
translation_vector=translation,
orientation=orientation,
rotation=rotation,
))
# Add last_link_vector to parameters
if last_link_vector is not None:
parameters.append(lib_link.URDFLink(
translation_vector=last_link_vector,
orientation=[0, 0, 0],
rotation=[1, 0, 0],
name="last_joint"
))
return parameters | python | def get_urdf_parameters(urdf_file, base_elements=None, last_link_vector=None, base_element_type="link"):
tree = ET.parse(urdf_file)
root = tree.getroot()
base_elements = list(base_elements)
if base_elements is None:
base_elements = ["base_link"]
elif base_elements is []:
raise ValueError("base_elements can't be the empty list []")
joints = []
links = []
has_next = True
current_joint = None
current_link = None
# Initialize the tree traversal
if base_element_type == "link":
# The first element is a link, so its (virtual) parent should be a joint
node_type = "joint"
elif base_element_type == "joint":
# The same as before, but swap link and joint
node_type = "link"
else:
raise ValueError("Unknown type: {}".format(base_element_type))
# Parcours récursif de la structure de la chain
while has_next:
if len(base_elements) != 0:
next_element = base_elements.pop(0)
else:
next_element = None
if node_type == "link":
# Current element is a link, find child joint
(has_next, current_joint) = find_next_joint(root, current_link, next_element)
node_type = "joint"
if has_next:
joints.append(current_joint)
elif node_type == "joint":
# Current element is a joint, find child link
(has_next, current_link) = find_next_link(root, current_joint, next_element)
node_type = "link"
if has_next:
links.append(current_link)
parameters = []
# Save the joints in the good format
for joint in joints:
translation = [0, 0, 0]
orientation = [0, 0, 0]
rotation = [1, 0, 0]
bounds = [None, None]
origin = joint.find("origin")
if origin is not None:
if origin.attrib["xyz"]:
translation = [float(x) for x in origin.attrib["xyz"].split()]
if origin.attrib["rpy"]:
orientation = [float(x) for x in origin.attrib["rpy"].split()]
axis = joint.find("axis")
if axis is not None:
rotation = [float(x) for x in axis.attrib["xyz"].split()]
limit = joint.find("limit")
if limit is not None:
if limit.attrib["lower"]:
bounds[0] = float(limit.attrib["lower"])
if limit.attrib["upper"]:
bounds[1] = float(limit.attrib["upper"])
parameters.append(lib_link.URDFLink(
name=joint.attrib["name"],
bounds=tuple(bounds),
translation_vector=translation,
orientation=orientation,
rotation=rotation,
))
# Add last_link_vector to parameters
if last_link_vector is not None:
parameters.append(lib_link.URDFLink(
translation_vector=last_link_vector,
orientation=[0, 0, 0],
rotation=[1, 0, 0],
name="last_joint"
))
return parameters | [
"def",
"get_urdf_parameters",
"(",
"urdf_file",
",",
"base_elements",
"=",
"None",
",",
"last_link_vector",
"=",
"None",
",",
"base_element_type",
"=",
"\"link\"",
")",
":",
"tree",
"=",
"ET",
".",
"parse",
"(",
"urdf_file",
")",
"root",
"=",
"tree",
".",
... | Returns translated parameters from the given URDF file
Parameters
----------
urdf_file: str
The path of the URDF file
base_elements: list of strings
List of the links beginning the chain
last_link_vector: numpy.array
Optional : The translation vector of the tip.
base_element_type: str
Returns
-------
list[ikpy.link.URDFLink] | [
"Returns",
"translated",
"parameters",
"from",
"the",
"given",
"URDF",
"file"
] | 60e36d6163136942bf520d952db17123c658d0b6 | https://github.com/Phylliade/ikpy/blob/60e36d6163136942bf520d952db17123c658d0b6/src/ikpy/URDF_utils.py#L103-L210 |
241,561 | Phylliade/ikpy | src/ikpy/URDF_utils.py | _convert_angle_limit | def _convert_angle_limit(angle, joint, **kwargs):
"""Converts the limit angle of the PyPot JSON file to the internal format"""
angle_pypot = angle
# No need to take care of orientation
if joint["orientation"] == "indirect":
angle_pypot = 1 * angle_pypot
# angle_pypot = angle_pypot + offset
return angle_pypot * np.pi / 180 | python | def _convert_angle_limit(angle, joint, **kwargs):
angle_pypot = angle
# No need to take care of orientation
if joint["orientation"] == "indirect":
angle_pypot = 1 * angle_pypot
# angle_pypot = angle_pypot + offset
return angle_pypot * np.pi / 180 | [
"def",
"_convert_angle_limit",
"(",
"angle",
",",
"joint",
",",
"*",
"*",
"kwargs",
")",
":",
"angle_pypot",
"=",
"angle",
"# No need to take care of orientation",
"if",
"joint",
"[",
"\"orientation\"",
"]",
"==",
"\"indirect\"",
":",
"angle_pypot",
"=",
"1",
"*... | Converts the limit angle of the PyPot JSON file to the internal format | [
"Converts",
"the",
"limit",
"angle",
"of",
"the",
"PyPot",
"JSON",
"file",
"to",
"the",
"internal",
"format"
] | 60e36d6163136942bf520d952db17123c658d0b6 | https://github.com/Phylliade/ikpy/blob/60e36d6163136942bf520d952db17123c658d0b6/src/ikpy/URDF_utils.py#L261-L271 |
241,562 | Phylliade/ikpy | scripts/hand_follow.py | follow_hand | def follow_hand(poppy, delta):
"""Tell the right hand to follow the left hand"""
right_arm_position = poppy.l_arm_chain.end_effector + delta
poppy.r_arm_chain.goto(right_arm_position, 0.5, wait=True) | python | def follow_hand(poppy, delta):
right_arm_position = poppy.l_arm_chain.end_effector + delta
poppy.r_arm_chain.goto(right_arm_position, 0.5, wait=True) | [
"def",
"follow_hand",
"(",
"poppy",
",",
"delta",
")",
":",
"right_arm_position",
"=",
"poppy",
".",
"l_arm_chain",
".",
"end_effector",
"+",
"delta",
"poppy",
".",
"r_arm_chain",
".",
"goto",
"(",
"right_arm_position",
",",
"0.5",
",",
"wait",
"=",
"True",
... | Tell the right hand to follow the left hand | [
"Tell",
"the",
"right",
"hand",
"to",
"follow",
"the",
"left",
"hand"
] | 60e36d6163136942bf520d952db17123c658d0b6 | https://github.com/Phylliade/ikpy/blob/60e36d6163136942bf520d952db17123c658d0b6/scripts/hand_follow.py#L27-L30 |
241,563 | Phylliade/ikpy | src/ikpy/inverse_kinematics.py | inverse_kinematic_optimization | def inverse_kinematic_optimization(chain, target_frame, starting_nodes_angles, regularization_parameter=None, max_iter=None):
"""
Computes the inverse kinematic on the specified target with an optimization method
Parameters
----------
chain: ikpy.chain.Chain
The chain used for the Inverse kinematics.
target_frame: numpy.array
The desired target.
starting_nodes_angles: numpy.array
The initial pose of your chain.
regularization_parameter: float
The coefficient of the regularization.
max_iter: int
Maximum number of iterations for the optimisation algorithm.
"""
# Only get the position
target = target_frame[:3, 3]
if starting_nodes_angles is None:
raise ValueError("starting_nodes_angles must be specified")
# Compute squared distance to target
def optimize_target(x):
# y = np.append(starting_nodes_angles[:chain.first_active_joint], x)
y = chain.active_to_full(x, starting_nodes_angles)
squared_distance = np.linalg.norm(chain.forward_kinematics(y)[:3, -1] - target)
return squared_distance
# If a regularization is selected
if regularization_parameter is not None:
def optimize_total(x):
regularization = np.linalg.norm(x - starting_nodes_angles[chain.first_active_joint:])
return optimize_target(x) + regularization_parameter * regularization
else:
def optimize_total(x):
return optimize_target(x)
# Compute bounds
real_bounds = [link.bounds for link in chain.links]
# real_bounds = real_bounds[chain.first_active_joint:]
real_bounds = chain.active_from_full(real_bounds)
options = {}
# Manage iterations maximum
if max_iter is not None:
options["maxiter"] = max_iter
# Utilisation d'une optimisation L-BFGS-B
res = scipy.optimize.minimize(optimize_total, chain.active_from_full(starting_nodes_angles), method='L-BFGS-B', bounds=real_bounds, options=options)
logs.manager.info("Inverse kinematic optimisation OK, done in {} iterations".format(res.nit))
return chain.active_to_full(res.x, starting_nodes_angles) | python | def inverse_kinematic_optimization(chain, target_frame, starting_nodes_angles, regularization_parameter=None, max_iter=None):
# Only get the position
target = target_frame[:3, 3]
if starting_nodes_angles is None:
raise ValueError("starting_nodes_angles must be specified")
# Compute squared distance to target
def optimize_target(x):
# y = np.append(starting_nodes_angles[:chain.first_active_joint], x)
y = chain.active_to_full(x, starting_nodes_angles)
squared_distance = np.linalg.norm(chain.forward_kinematics(y)[:3, -1] - target)
return squared_distance
# If a regularization is selected
if regularization_parameter is not None:
def optimize_total(x):
regularization = np.linalg.norm(x - starting_nodes_angles[chain.first_active_joint:])
return optimize_target(x) + regularization_parameter * regularization
else:
def optimize_total(x):
return optimize_target(x)
# Compute bounds
real_bounds = [link.bounds for link in chain.links]
# real_bounds = real_bounds[chain.first_active_joint:]
real_bounds = chain.active_from_full(real_bounds)
options = {}
# Manage iterations maximum
if max_iter is not None:
options["maxiter"] = max_iter
# Utilisation d'une optimisation L-BFGS-B
res = scipy.optimize.minimize(optimize_total, chain.active_from_full(starting_nodes_angles), method='L-BFGS-B', bounds=real_bounds, options=options)
logs.manager.info("Inverse kinematic optimisation OK, done in {} iterations".format(res.nit))
return chain.active_to_full(res.x, starting_nodes_angles) | [
"def",
"inverse_kinematic_optimization",
"(",
"chain",
",",
"target_frame",
",",
"starting_nodes_angles",
",",
"regularization_parameter",
"=",
"None",
",",
"max_iter",
"=",
"None",
")",
":",
"# Only get the position",
"target",
"=",
"target_frame",
"[",
":",
"3",
"... | Computes the inverse kinematic on the specified target with an optimization method
Parameters
----------
chain: ikpy.chain.Chain
The chain used for the Inverse kinematics.
target_frame: numpy.array
The desired target.
starting_nodes_angles: numpy.array
The initial pose of your chain.
regularization_parameter: float
The coefficient of the regularization.
max_iter: int
Maximum number of iterations for the optimisation algorithm. | [
"Computes",
"the",
"inverse",
"kinematic",
"on",
"the",
"specified",
"target",
"with",
"an",
"optimization",
"method"
] | 60e36d6163136942bf520d952db17123c658d0b6 | https://github.com/Phylliade/ikpy/blob/60e36d6163136942bf520d952db17123c658d0b6/src/ikpy/inverse_kinematics.py#L7-L61 |
241,564 | Phylliade/ikpy | src/ikpy/chain.py | Chain.forward_kinematics | def forward_kinematics(self, joints, full_kinematics=False):
"""Returns the transformation matrix of the forward kinematics
Parameters
----------
joints: list
The list of the positions of each joint. Note : Inactive joints must be in the list.
full_kinematics: bool
Return the transformation matrices of each joint
Returns
-------
frame_matrix:
The transformation matrix
"""
frame_matrix = np.eye(4)
if full_kinematics:
frame_matrixes = []
if len(self.links) != len(joints):
raise ValueError("Your joints vector length is {} but you have {} links".format(len(joints), len(self.links)))
for index, (link, joint_angle) in enumerate(zip(self.links, joints)):
# Compute iteratively the position
# NB : Use asarray to avoid old sympy problems
frame_matrix = np.dot(frame_matrix, np.asarray(link.get_transformation_matrix(joint_angle)))
if full_kinematics:
# rotation_axe = np.dot(frame_matrix, link.rotation)
frame_matrixes.append(frame_matrix)
# Return the matrix, or matrixes
if full_kinematics:
return frame_matrixes
else:
return frame_matrix | python | def forward_kinematics(self, joints, full_kinematics=False):
frame_matrix = np.eye(4)
if full_kinematics:
frame_matrixes = []
if len(self.links) != len(joints):
raise ValueError("Your joints vector length is {} but you have {} links".format(len(joints), len(self.links)))
for index, (link, joint_angle) in enumerate(zip(self.links, joints)):
# Compute iteratively the position
# NB : Use asarray to avoid old sympy problems
frame_matrix = np.dot(frame_matrix, np.asarray(link.get_transformation_matrix(joint_angle)))
if full_kinematics:
# rotation_axe = np.dot(frame_matrix, link.rotation)
frame_matrixes.append(frame_matrix)
# Return the matrix, or matrixes
if full_kinematics:
return frame_matrixes
else:
return frame_matrix | [
"def",
"forward_kinematics",
"(",
"self",
",",
"joints",
",",
"full_kinematics",
"=",
"False",
")",
":",
"frame_matrix",
"=",
"np",
".",
"eye",
"(",
"4",
")",
"if",
"full_kinematics",
":",
"frame_matrixes",
"=",
"[",
"]",
"if",
"len",
"(",
"self",
".",
... | Returns the transformation matrix of the forward kinematics
Parameters
----------
joints: list
The list of the positions of each joint. Note : Inactive joints must be in the list.
full_kinematics: bool
Return the transformation matrices of each joint
Returns
-------
frame_matrix:
The transformation matrix | [
"Returns",
"the",
"transformation",
"matrix",
"of",
"the",
"forward",
"kinematics"
] | 60e36d6163136942bf520d952db17123c658d0b6 | https://github.com/Phylliade/ikpy/blob/60e36d6163136942bf520d952db17123c658d0b6/src/ikpy/chain.py#L48-L83 |
241,565 | Phylliade/ikpy | src/ikpy/chain.py | Chain.inverse_kinematics | def inverse_kinematics(self, target, initial_position=None, **kwargs):
"""Computes the inverse kinematic on the specified target
Parameters
----------
target: numpy.array
The frame target of the inverse kinematic, in meters. It must be 4x4 transformation matrix
initial_position: numpy.array
Optional : the initial position of each joint of the chain. Defaults to 0 for each joint
Returns
-------
The list of the positions of each joint according to the target. Note : Inactive joints are in the list.
"""
# Checks on input
target = np.array(target)
if target.shape != (4, 4):
raise ValueError("Your target must be a 4x4 transformation matrix")
if initial_position is None:
initial_position = [0] * len(self.links)
return ik.inverse_kinematic_optimization(self, target, starting_nodes_angles=initial_position, **kwargs) | python | def inverse_kinematics(self, target, initial_position=None, **kwargs):
# Checks on input
target = np.array(target)
if target.shape != (4, 4):
raise ValueError("Your target must be a 4x4 transformation matrix")
if initial_position is None:
initial_position = [0] * len(self.links)
return ik.inverse_kinematic_optimization(self, target, starting_nodes_angles=initial_position, **kwargs) | [
"def",
"inverse_kinematics",
"(",
"self",
",",
"target",
",",
"initial_position",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"# Checks on input",
"target",
"=",
"np",
".",
"array",
"(",
"target",
")",
"if",
"target",
".",
"shape",
"!=",
"(",
"4",
... | Computes the inverse kinematic on the specified target
Parameters
----------
target: numpy.array
The frame target of the inverse kinematic, in meters. It must be 4x4 transformation matrix
initial_position: numpy.array
Optional : the initial position of each joint of the chain. Defaults to 0 for each joint
Returns
-------
The list of the positions of each joint according to the target. Note : Inactive joints are in the list. | [
"Computes",
"the",
"inverse",
"kinematic",
"on",
"the",
"specified",
"target"
] | 60e36d6163136942bf520d952db17123c658d0b6 | https://github.com/Phylliade/ikpy/blob/60e36d6163136942bf520d952db17123c658d0b6/src/ikpy/chain.py#L85-L107 |
241,566 | Phylliade/ikpy | src/ikpy/chain.py | Chain.plot | def plot(self, joints, ax, target=None, show=False):
"""Plots the Chain using Matplotlib
Parameters
----------
joints: list
The list of the positions of each joint
ax: matplotlib.axes.Axes
A matplotlib axes
target: numpy.array
An optional target
show: bool
Display the axe. Defaults to False
"""
from . import plot_utils
if ax is None:
# If ax is not given, create one
ax = plot_utils.init_3d_figure()
plot_utils.plot_chain(self, joints, ax)
plot_utils.plot_basis(ax, self._length)
# Plot the goal position
if target is not None:
plot_utils.plot_target(target, ax)
if show:
plot_utils.show_figure() | python | def plot(self, joints, ax, target=None, show=False):
from . import plot_utils
if ax is None:
# If ax is not given, create one
ax = plot_utils.init_3d_figure()
plot_utils.plot_chain(self, joints, ax)
plot_utils.plot_basis(ax, self._length)
# Plot the goal position
if target is not None:
plot_utils.plot_target(target, ax)
if show:
plot_utils.show_figure() | [
"def",
"plot",
"(",
"self",
",",
"joints",
",",
"ax",
",",
"target",
"=",
"None",
",",
"show",
"=",
"False",
")",
":",
"from",
".",
"import",
"plot_utils",
"if",
"ax",
"is",
"None",
":",
"# If ax is not given, create one",
"ax",
"=",
"plot_utils",
".",
... | Plots the Chain using Matplotlib
Parameters
----------
joints: list
The list of the positions of each joint
ax: matplotlib.axes.Axes
A matplotlib axes
target: numpy.array
An optional target
show: bool
Display the axe. Defaults to False | [
"Plots",
"the",
"Chain",
"using",
"Matplotlib"
] | 60e36d6163136942bf520d952db17123c658d0b6 | https://github.com/Phylliade/ikpy/blob/60e36d6163136942bf520d952db17123c658d0b6/src/ikpy/chain.py#L109-L135 |
241,567 | Phylliade/ikpy | src/ikpy/chain.py | Chain.from_urdf_file | def from_urdf_file(cls, urdf_file, base_elements=None, last_link_vector=None, base_element_type="link", active_links_mask=None, name="chain"):
"""Creates a chain from an URDF file
Parameters
----------
urdf_file: str
The path of the URDF file
base_elements: list of strings
List of the links beginning the chain
last_link_vector: numpy.array
Optional : The translation vector of the tip.
name: str
The name of the Chain
base_element_type: str
active_links_mask: list[bool]
"""
if base_elements is None:
base_elements = ["base_link"]
links = URDF_utils.get_urdf_parameters(urdf_file, base_elements=base_elements, last_link_vector=last_link_vector, base_element_type=base_element_type)
# Add an origin link at the beginning
return cls([link_lib.OriginLink()] + links, active_links_mask=active_links_mask, name=name) | python | def from_urdf_file(cls, urdf_file, base_elements=None, last_link_vector=None, base_element_type="link", active_links_mask=None, name="chain"):
if base_elements is None:
base_elements = ["base_link"]
links = URDF_utils.get_urdf_parameters(urdf_file, base_elements=base_elements, last_link_vector=last_link_vector, base_element_type=base_element_type)
# Add an origin link at the beginning
return cls([link_lib.OriginLink()] + links, active_links_mask=active_links_mask, name=name) | [
"def",
"from_urdf_file",
"(",
"cls",
",",
"urdf_file",
",",
"base_elements",
"=",
"None",
",",
"last_link_vector",
"=",
"None",
",",
"base_element_type",
"=",
"\"link\"",
",",
"active_links_mask",
"=",
"None",
",",
"name",
"=",
"\"chain\"",
")",
":",
"if",
"... | Creates a chain from an URDF file
Parameters
----------
urdf_file: str
The path of the URDF file
base_elements: list of strings
List of the links beginning the chain
last_link_vector: numpy.array
Optional : The translation vector of the tip.
name: str
The name of the Chain
base_element_type: str
active_links_mask: list[bool] | [
"Creates",
"a",
"chain",
"from",
"an",
"URDF",
"file"
] | 60e36d6163136942bf520d952db17123c658d0b6 | https://github.com/Phylliade/ikpy/blob/60e36d6163136942bf520d952db17123c658d0b6/src/ikpy/chain.py#L138-L159 |
241,568 | blockchain-certificates/cert-issuer | cert_issuer/signer.py | check_internet_off | def check_internet_off(secrets_file_path):
"""If internet off and USB plugged in, returns true. Else, continues to wait..."""
while True:
if internet_on() is False and os.path.exists(secrets_file_path):
break
else:
print("Turn off your internet and plug in your USB to continue...")
time.sleep(10)
return True | python | def check_internet_off(secrets_file_path):
while True:
if internet_on() is False and os.path.exists(secrets_file_path):
break
else:
print("Turn off your internet and plug in your USB to continue...")
time.sleep(10)
return True | [
"def",
"check_internet_off",
"(",
"secrets_file_path",
")",
":",
"while",
"True",
":",
"if",
"internet_on",
"(",
")",
"is",
"False",
"and",
"os",
".",
"path",
".",
"exists",
"(",
"secrets_file_path",
")",
":",
"break",
"else",
":",
"print",
"(",
"\"Turn of... | If internet off and USB plugged in, returns true. Else, continues to wait... | [
"If",
"internet",
"off",
"and",
"USB",
"plugged",
"in",
"returns",
"true",
".",
"Else",
"continues",
"to",
"wait",
"..."
] | e8a48e25472473b149bd411a9fd5f2ff0f8f100a | https://github.com/blockchain-certificates/cert-issuer/blob/e8a48e25472473b149bd411a9fd5f2ff0f8f100a/cert_issuer/signer.py#L66-L74 |
241,569 | blockchain-certificates/cert-issuer | cert_issuer/signer.py | check_internet_on | def check_internet_on(secrets_file_path):
"""If internet on and USB unplugged, returns true. Else, continues to wait..."""
while True:
if internet_on() is True and not os.path.exists(secrets_file_path):
break
else:
print("Turn on your internet and unplug your USB to continue...")
time.sleep(10)
return True | python | def check_internet_on(secrets_file_path):
while True:
if internet_on() is True and not os.path.exists(secrets_file_path):
break
else:
print("Turn on your internet and unplug your USB to continue...")
time.sleep(10)
return True | [
"def",
"check_internet_on",
"(",
"secrets_file_path",
")",
":",
"while",
"True",
":",
"if",
"internet_on",
"(",
")",
"is",
"True",
"and",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"secrets_file_path",
")",
":",
"break",
"else",
":",
"print",
"(",
"\"... | If internet on and USB unplugged, returns true. Else, continues to wait... | [
"If",
"internet",
"on",
"and",
"USB",
"unplugged",
"returns",
"true",
".",
"Else",
"continues",
"to",
"wait",
"..."
] | e8a48e25472473b149bd411a9fd5f2ff0f8f100a | https://github.com/blockchain-certificates/cert-issuer/blob/e8a48e25472473b149bd411a9fd5f2ff0f8f100a/cert_issuer/signer.py#L77-L85 |
241,570 | blockchain-certificates/cert-issuer | cert_issuer/blockchain_handlers/bitcoin/signer.py | verify_signature | def verify_signature(uid, signed_cert_file_name, issuing_address):
"""
Verify the certificate signature matches the expected. Double-check the uid field in the certificate and use
VerifyMessage to confirm that the signature in the certificate matches the issuing_address.
Raises error is verification fails.
Raises UnverifiedSignatureError if signature is invalid
:param uid:
:param signed_cert_file_name:
:param issuing_address:
:return:
"""
logging.info('verifying signature for certificate with uid=%s:', uid)
with open(signed_cert_file_name) as in_file:
signed_cert = in_file.read()
signed_cert_json = json.loads(signed_cert)
to_verify = uid
signature = signed_cert_json['signature']
verified = verify_message(issuing_address, to_verify, signature)
if not verified:
error_message = 'There was a problem with the signature for certificate uid={}'.format(uid)
raise UnverifiedSignatureError(error_message)
logging.info('verified signature') | python | def verify_signature(uid, signed_cert_file_name, issuing_address):
logging.info('verifying signature for certificate with uid=%s:', uid)
with open(signed_cert_file_name) as in_file:
signed_cert = in_file.read()
signed_cert_json = json.loads(signed_cert)
to_verify = uid
signature = signed_cert_json['signature']
verified = verify_message(issuing_address, to_verify, signature)
if not verified:
error_message = 'There was a problem with the signature for certificate uid={}'.format(uid)
raise UnverifiedSignatureError(error_message)
logging.info('verified signature') | [
"def",
"verify_signature",
"(",
"uid",
",",
"signed_cert_file_name",
",",
"issuing_address",
")",
":",
"logging",
".",
"info",
"(",
"'verifying signature for certificate with uid=%s:'",
",",
"uid",
")",
"with",
"open",
"(",
"signed_cert_file_name",
")",
"as",
"in_file... | Verify the certificate signature matches the expected. Double-check the uid field in the certificate and use
VerifyMessage to confirm that the signature in the certificate matches the issuing_address.
Raises error is verification fails.
Raises UnverifiedSignatureError if signature is invalid
:param uid:
:param signed_cert_file_name:
:param issuing_address:
:return: | [
"Verify",
"the",
"certificate",
"signature",
"matches",
"the",
"expected",
".",
"Double",
"-",
"check",
"the",
"uid",
"field",
"in",
"the",
"certificate",
"and",
"use",
"VerifyMessage",
"to",
"confirm",
"that",
"the",
"signature",
"in",
"the",
"certificate",
"... | e8a48e25472473b149bd411a9fd5f2ff0f8f100a | https://github.com/blockchain-certificates/cert-issuer/blob/e8a48e25472473b149bd411a9fd5f2ff0f8f100a/cert_issuer/blockchain_handlers/bitcoin/signer.py#L52-L78 |
241,571 | blockchain-certificates/cert-issuer | cert_issuer/blockchain_handlers/ethereum/connectors.py | EtherscanBroadcaster.get_balance | def get_balance(self, address, api_token):
"""
returns the balance in wei
with some inspiration from PyWallet
"""
broadcast_url = self.base_url + '?module=account&action=balance'
broadcast_url += '&address=%s' % address
broadcast_url += '&tag=latest'
if api_token:
'&apikey=%s' % api_token
response = requests.get(broadcast_url)
if int(response.status_code) == 200:
balance = int(response.json().get('result', None))
logging.info('Balance check succeeded: %s', response.json())
return balance
raise BroadcastError(response.text) | python | def get_balance(self, address, api_token):
broadcast_url = self.base_url + '?module=account&action=balance'
broadcast_url += '&address=%s' % address
broadcast_url += '&tag=latest'
if api_token:
'&apikey=%s' % api_token
response = requests.get(broadcast_url)
if int(response.status_code) == 200:
balance = int(response.json().get('result', None))
logging.info('Balance check succeeded: %s', response.json())
return balance
raise BroadcastError(response.text) | [
"def",
"get_balance",
"(",
"self",
",",
"address",
",",
"api_token",
")",
":",
"broadcast_url",
"=",
"self",
".",
"base_url",
"+",
"'?module=account&action=balance'",
"broadcast_url",
"+=",
"'&address=%s'",
"%",
"address",
"broadcast_url",
"+=",
"'&tag=latest'",
"if... | returns the balance in wei
with some inspiration from PyWallet | [
"returns",
"the",
"balance",
"in",
"wei",
"with",
"some",
"inspiration",
"from",
"PyWallet"
] | e8a48e25472473b149bd411a9fd5f2ff0f8f100a | https://github.com/blockchain-certificates/cert-issuer/blob/e8a48e25472473b149bd411a9fd5f2ff0f8f100a/cert_issuer/blockchain_handlers/ethereum/connectors.py#L80-L95 |
241,572 | blockchain-certificates/cert-issuer | cert_issuer/blockchain_handlers/ethereum/connectors.py | EtherscanBroadcaster.get_address_nonce | def get_address_nonce(self, address, api_token):
"""
Looks up the address nonce of this address
Neccesary for the transaction creation
"""
broadcast_url = self.base_url + '?module=proxy&action=eth_getTransactionCount'
broadcast_url += '&address=%s' % address
broadcast_url += '&tag=latest'
if api_token:
'&apikey=%s' % api_token
response = requests.get(broadcast_url, )
if int(response.status_code) == 200:
# the int(res, 0) transforms the hex nonce to int
nonce = int(response.json().get('result', None), 0)
logging.info('Nonce check went correct: %s', response.json())
return nonce
else:
logging.info('response error checking nonce')
raise BroadcastError('Error checking the nonce through the Etherscan API. Error msg: %s', response.text) | python | def get_address_nonce(self, address, api_token):
broadcast_url = self.base_url + '?module=proxy&action=eth_getTransactionCount'
broadcast_url += '&address=%s' % address
broadcast_url += '&tag=latest'
if api_token:
'&apikey=%s' % api_token
response = requests.get(broadcast_url, )
if int(response.status_code) == 200:
# the int(res, 0) transforms the hex nonce to int
nonce = int(response.json().get('result', None), 0)
logging.info('Nonce check went correct: %s', response.json())
return nonce
else:
logging.info('response error checking nonce')
raise BroadcastError('Error checking the nonce through the Etherscan API. Error msg: %s', response.text) | [
"def",
"get_address_nonce",
"(",
"self",
",",
"address",
",",
"api_token",
")",
":",
"broadcast_url",
"=",
"self",
".",
"base_url",
"+",
"'?module=proxy&action=eth_getTransactionCount'",
"broadcast_url",
"+=",
"'&address=%s'",
"%",
"address",
"broadcast_url",
"+=",
"'... | Looks up the address nonce of this address
Neccesary for the transaction creation | [
"Looks",
"up",
"the",
"address",
"nonce",
"of",
"this",
"address",
"Neccesary",
"for",
"the",
"transaction",
"creation"
] | e8a48e25472473b149bd411a9fd5f2ff0f8f100a | https://github.com/blockchain-certificates/cert-issuer/blob/e8a48e25472473b149bd411a9fd5f2ff0f8f100a/cert_issuer/blockchain_handlers/ethereum/connectors.py#L97-L115 |
241,573 | tensorflow/mesh | mesh_tensorflow/tpu_variables.py | ReplicatedVariable._dense_var_to_tensor | def _dense_var_to_tensor(self, dtype=None, name=None, as_ref=False):
"""Converts a variable to a tensor."""
# pylint: disable=protected-access
if _enclosing_tpu_context() is None:
if hasattr(self._primary_var, '_dense_var_to_tensor'):
return self._primary_var._dense_var_to_tensor(dtype, name, as_ref)
else:
return ops.convert_to_tensor(self._primary_var)
# pylint: enable=protected-access
if dtype is not None and dtype != self.dtype:
return NotImplemented
if as_ref:
return self.handle
else:
return self.read_value() | python | def _dense_var_to_tensor(self, dtype=None, name=None, as_ref=False):
# pylint: disable=protected-access
if _enclosing_tpu_context() is None:
if hasattr(self._primary_var, '_dense_var_to_tensor'):
return self._primary_var._dense_var_to_tensor(dtype, name, as_ref)
else:
return ops.convert_to_tensor(self._primary_var)
# pylint: enable=protected-access
if dtype is not None and dtype != self.dtype:
return NotImplemented
if as_ref:
return self.handle
else:
return self.read_value() | [
"def",
"_dense_var_to_tensor",
"(",
"self",
",",
"dtype",
"=",
"None",
",",
"name",
"=",
"None",
",",
"as_ref",
"=",
"False",
")",
":",
"# pylint: disable=protected-access",
"if",
"_enclosing_tpu_context",
"(",
")",
"is",
"None",
":",
"if",
"hasattr",
"(",
"... | Converts a variable to a tensor. | [
"Converts",
"a",
"variable",
"to",
"a",
"tensor",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/tpu_variables.py#L183-L197 |
241,574 | tensorflow/mesh | mesh_tensorflow/auto_mtf/memory_estimator.py | MemoryEstimator._compute_layout_validator | def _compute_layout_validator(self):
"""Computes self._layout_validator."""
self._layout_validator = valid_layouts.LayoutValidator(self.mtf_graph,
self.mesh_shape) | python | def _compute_layout_validator(self):
self._layout_validator = valid_layouts.LayoutValidator(self.mtf_graph,
self.mesh_shape) | [
"def",
"_compute_layout_validator",
"(",
"self",
")",
":",
"self",
".",
"_layout_validator",
"=",
"valid_layouts",
".",
"LayoutValidator",
"(",
"self",
".",
"mtf_graph",
",",
"self",
".",
"mesh_shape",
")"
] | Computes self._layout_validator. | [
"Computes",
"self",
".",
"_layout_validator",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/auto_mtf/memory_estimator.py#L87-L90 |
241,575 | tensorflow/mesh | mesh_tensorflow/auto_mtf/memory_estimator.py | MemoryEstimator._compute_graph_interface | def _compute_graph_interface(self):
"""Computes self._graph_interface."""
self._graph_interface = graph_interface.GraphInterface(self.mtf_graph)
for mtf_output in self.mtf_outputs:
self._graph_interface.set_tensor_final(mtf_output.name) | python | def _compute_graph_interface(self):
self._graph_interface = graph_interface.GraphInterface(self.mtf_graph)
for mtf_output in self.mtf_outputs:
self._graph_interface.set_tensor_final(mtf_output.name) | [
"def",
"_compute_graph_interface",
"(",
"self",
")",
":",
"self",
".",
"_graph_interface",
"=",
"graph_interface",
".",
"GraphInterface",
"(",
"self",
".",
"mtf_graph",
")",
"for",
"mtf_output",
"in",
"self",
".",
"mtf_outputs",
":",
"self",
".",
"_graph_interfa... | Computes self._graph_interface. | [
"Computes",
"self",
".",
"_graph_interface",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/auto_mtf/memory_estimator.py#L92-L96 |
241,576 | tensorflow/mesh | mesh_tensorflow/transformer/transformer.py | make_layer_stack | def make_layer_stack(layers=gin.REQUIRED, num_layers=6):
"""Configurable layer stack.
Args:
layers: a list of subclasses of TransformerLayer
num_layers: an integer
Returns:
a LayerStack
"""
return LayerStack([cls() for cls in layers] * num_layers) | python | def make_layer_stack(layers=gin.REQUIRED, num_layers=6):
return LayerStack([cls() for cls in layers] * num_layers) | [
"def",
"make_layer_stack",
"(",
"layers",
"=",
"gin",
".",
"REQUIRED",
",",
"num_layers",
"=",
"6",
")",
":",
"return",
"LayerStack",
"(",
"[",
"cls",
"(",
")",
"for",
"cls",
"in",
"layers",
"]",
"*",
"num_layers",
")"
] | Configurable layer stack.
Args:
layers: a list of subclasses of TransformerLayer
num_layers: an integer
Returns:
a LayerStack | [
"Configurable",
"layer",
"stack",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/transformer/transformer.py#L946-L955 |
241,577 | tensorflow/mesh | mesh_tensorflow/transformer/transformer.py | make_bitransformer | def make_bitransformer(
input_vocab_size=gin.REQUIRED,
output_vocab_size=gin.REQUIRED,
layout=None,
mesh_shape=None):
"""Gin-configurable bitransformer constructor.
In your config file you need to set the encoder and decoder layers like this:
encoder/make_layer_stack.layers = [
@transformer_layers.SelfAttention,
@transformer_layers.DenseReluDense,
]
decoder/make_layer_stack.layers = [
@transformer_layers.SelfAttention,
@transformer_layers.EncDecAttention,
@transformer_layers.DenseReluDense,
]
Args:
input_vocab_size: a integer
output_vocab_size: an integer
layout: optional - an input to mtf.convert_to_layout_rules
Some layers (e.g. MoE layers) cheat by looking at layout and mesh_shape
mesh_shape: optional - an input to mtf.convert_to_shape
Some layers (e.g. MoE layers) cheat by looking at layout and mesh_shape
Returns:
a Bitransformer
"""
with gin.config_scope("encoder"):
encoder = Unitransformer(
layer_stack=make_layer_stack(),
input_vocab_size=input_vocab_size,
output_vocab_size=None,
autoregressive=False,
name="encoder",
layout=layout,
mesh_shape=mesh_shape)
with gin.config_scope("decoder"):
decoder = Unitransformer(
layer_stack=make_layer_stack(),
input_vocab_size=output_vocab_size,
output_vocab_size=output_vocab_size,
autoregressive=True,
name="decoder",
layout=layout,
mesh_shape=mesh_shape)
return Bitransformer(encoder, decoder) | python | def make_bitransformer(
input_vocab_size=gin.REQUIRED,
output_vocab_size=gin.REQUIRED,
layout=None,
mesh_shape=None):
with gin.config_scope("encoder"):
encoder = Unitransformer(
layer_stack=make_layer_stack(),
input_vocab_size=input_vocab_size,
output_vocab_size=None,
autoregressive=False,
name="encoder",
layout=layout,
mesh_shape=mesh_shape)
with gin.config_scope("decoder"):
decoder = Unitransformer(
layer_stack=make_layer_stack(),
input_vocab_size=output_vocab_size,
output_vocab_size=output_vocab_size,
autoregressive=True,
name="decoder",
layout=layout,
mesh_shape=mesh_shape)
return Bitransformer(encoder, decoder) | [
"def",
"make_bitransformer",
"(",
"input_vocab_size",
"=",
"gin",
".",
"REQUIRED",
",",
"output_vocab_size",
"=",
"gin",
".",
"REQUIRED",
",",
"layout",
"=",
"None",
",",
"mesh_shape",
"=",
"None",
")",
":",
"with",
"gin",
".",
"config_scope",
"(",
"\"encode... | Gin-configurable bitransformer constructor.
In your config file you need to set the encoder and decoder layers like this:
encoder/make_layer_stack.layers = [
@transformer_layers.SelfAttention,
@transformer_layers.DenseReluDense,
]
decoder/make_layer_stack.layers = [
@transformer_layers.SelfAttention,
@transformer_layers.EncDecAttention,
@transformer_layers.DenseReluDense,
]
Args:
input_vocab_size: a integer
output_vocab_size: an integer
layout: optional - an input to mtf.convert_to_layout_rules
Some layers (e.g. MoE layers) cheat by looking at layout and mesh_shape
mesh_shape: optional - an input to mtf.convert_to_shape
Some layers (e.g. MoE layers) cheat by looking at layout and mesh_shape
Returns:
a Bitransformer | [
"Gin",
"-",
"configurable",
"bitransformer",
"constructor",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/transformer/transformer.py#L959-L1005 |
241,578 | tensorflow/mesh | mesh_tensorflow/transformer/transformer.py | Context.get_states | def get_states(self, n):
"""Get the next n recurrent states.
Called by layers in "incremental" mode.
Args:
n: an integer
Returns:
a list of n Tensors
"""
return self.states[len(self.new_states):len(self.new_states) + n] | python | def get_states(self, n):
return self.states[len(self.new_states):len(self.new_states) + n] | [
"def",
"get_states",
"(",
"self",
",",
"n",
")",
":",
"return",
"self",
".",
"states",
"[",
"len",
"(",
"self",
".",
"new_states",
")",
":",
"len",
"(",
"self",
".",
"new_states",
")",
"+",
"n",
"]"
] | Get the next n recurrent states.
Called by layers in "incremental" mode.
Args:
n: an integer
Returns:
a list of n Tensors | [
"Get",
"the",
"next",
"n",
"recurrent",
"states",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/transformer/transformer.py#L219-L229 |
241,579 | tensorflow/mesh | mesh_tensorflow/transformer/transformer.py | Context.get_constant_state | def get_constant_state(self):
"""Read state that was written in "first_part" mode.
Returns:
a structure
"""
ret = self.constant_states[self.next_constant_state]
self.next_constant_state += 1
return ret | python | def get_constant_state(self):
ret = self.constant_states[self.next_constant_state]
self.next_constant_state += 1
return ret | [
"def",
"get_constant_state",
"(",
"self",
")",
":",
"ret",
"=",
"self",
".",
"constant_states",
"[",
"self",
".",
"next_constant_state",
"]",
"self",
".",
"next_constant_state",
"+=",
"1",
"return",
"ret"
] | Read state that was written in "first_part" mode.
Returns:
a structure | [
"Read",
"state",
"that",
"was",
"written",
"in",
"first_part",
"mode",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/transformer/transformer.py#L252-L260 |
241,580 | tensorflow/mesh | mesh_tensorflow/transformer/transformer.py | Context.nonpadding | def nonpadding(self):
"""Tensor with zeros in padding positions and ones elsewhere."""
if self.sequence_id is None:
return None
if self.sequence_id == 1:
return 1
else:
return mtf.cast(
mtf.not_equal(self.sequence_id, 0), self.activation_dtype) | python | def nonpadding(self):
if self.sequence_id is None:
return None
if self.sequence_id == 1:
return 1
else:
return mtf.cast(
mtf.not_equal(self.sequence_id, 0), self.activation_dtype) | [
"def",
"nonpadding",
"(",
"self",
")",
":",
"if",
"self",
".",
"sequence_id",
"is",
"None",
":",
"return",
"None",
"if",
"self",
".",
"sequence_id",
"==",
"1",
":",
"return",
"1",
"else",
":",
"return",
"mtf",
".",
"cast",
"(",
"mtf",
".",
"not_equal... | Tensor with zeros in padding positions and ones elsewhere. | [
"Tensor",
"with",
"zeros",
"in",
"padding",
"positions",
"and",
"ones",
"elsewhere",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/transformer/transformer.py#L263-L271 |
241,581 | tensorflow/mesh | mesh_tensorflow/transformer/metrics.py | sequence_accuracy | def sequence_accuracy(labels, outputs):
"""Compute the sequence-level accuracy.
A sequence is only considered correct if all of its entries were predicted
correctly.
Args:
labels: ground-truth labels, shape=(batch, packed_seq_length)
outputs: predicted tokens, shape=(batch, seq_length)
Returns:
Two ops, one for getting the current average accuracy and another for
updating the running average estimate.
"""
# A sequence is correct if all of the non-padded entries are correct
all_correct = tf.reduce_all(
tf.logical_or(tf.equal(labels, outputs), tf.equal(labels, 0)), axis=-1
)
return tf.metrics.mean(all_correct) | python | def sequence_accuracy(labels, outputs):
# A sequence is correct if all of the non-padded entries are correct
all_correct = tf.reduce_all(
tf.logical_or(tf.equal(labels, outputs), tf.equal(labels, 0)), axis=-1
)
return tf.metrics.mean(all_correct) | [
"def",
"sequence_accuracy",
"(",
"labels",
",",
"outputs",
")",
":",
"# A sequence is correct if all of the non-padded entries are correct",
"all_correct",
"=",
"tf",
".",
"reduce_all",
"(",
"tf",
".",
"logical_or",
"(",
"tf",
".",
"equal",
"(",
"labels",
",",
"outp... | Compute the sequence-level accuracy.
A sequence is only considered correct if all of its entries were predicted
correctly.
Args:
labels: ground-truth labels, shape=(batch, packed_seq_length)
outputs: predicted tokens, shape=(batch, seq_length)
Returns:
Two ops, one for getting the current average accuracy and another for
updating the running average estimate. | [
"Compute",
"the",
"sequence",
"-",
"level",
"accuracy",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/transformer/metrics.py#L46-L63 |
241,582 | tensorflow/mesh | mesh_tensorflow/auto_mtf/graph_interface.py | GraphInterface.get_operation_input_names | def get_operation_input_names(self, operation_name):
"""Generates the names of all input tensors of an operation.
Args:
operation_name: a string, the name of an operation in the graph.
Yields:
a string, the name of an input tensor.
"""
for input_tensor in self._name_to_operation(operation_name).inputs:
yield input_tensor.name | python | def get_operation_input_names(self, operation_name):
for input_tensor in self._name_to_operation(operation_name).inputs:
yield input_tensor.name | [
"def",
"get_operation_input_names",
"(",
"self",
",",
"operation_name",
")",
":",
"for",
"input_tensor",
"in",
"self",
".",
"_name_to_operation",
"(",
"operation_name",
")",
".",
"inputs",
":",
"yield",
"input_tensor",
".",
"name"
] | Generates the names of all input tensors of an operation.
Args:
operation_name: a string, the name of an operation in the graph.
Yields:
a string, the name of an input tensor. | [
"Generates",
"the",
"names",
"of",
"all",
"input",
"tensors",
"of",
"an",
"operation",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/auto_mtf/graph_interface.py#L93-L103 |
241,583 | tensorflow/mesh | mesh_tensorflow/auto_mtf/graph_interface.py | GraphInterface.get_operation_output_names | def get_operation_output_names(self, operation_name):
"""Generates the names of all output tensors of an operation.
Args:
operation_name: a string, the name of an operation in the graph.
Yields:
a string, the name of an output tensor.
"""
for output_tensor in self._name_to_operation(operation_name).outputs:
yield output_tensor.name | python | def get_operation_output_names(self, operation_name):
for output_tensor in self._name_to_operation(operation_name).outputs:
yield output_tensor.name | [
"def",
"get_operation_output_names",
"(",
"self",
",",
"operation_name",
")",
":",
"for",
"output_tensor",
"in",
"self",
".",
"_name_to_operation",
"(",
"operation_name",
")",
".",
"outputs",
":",
"yield",
"output_tensor",
".",
"name"
] | Generates the names of all output tensors of an operation.
Args:
operation_name: a string, the name of an operation in the graph.
Yields:
a string, the name of an output tensor. | [
"Generates",
"the",
"names",
"of",
"all",
"output",
"tensors",
"of",
"an",
"operation",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/auto_mtf/graph_interface.py#L105-L115 |
241,584 | tensorflow/mesh | mesh_tensorflow/auto_mtf/graph_interface.py | GraphInterface.get_tensor_shape | def get_tensor_shape(self, tensor_name):
"""The tf.TensorShape of a tensor.
Args:
tensor_name: string, the name of a tensor in the graph.
Returns:
a tf.TensorShape
"""
tensor = self._name_to_tensor(tensor_name)
if isinstance(tensor, mtf.Tensor):
return tf.TensorShape(tensor.shape.to_integer_list)
else: # tf.Tensor
return tensor.shape | python | def get_tensor_shape(self, tensor_name):
tensor = self._name_to_tensor(tensor_name)
if isinstance(tensor, mtf.Tensor):
return tf.TensorShape(tensor.shape.to_integer_list)
else: # tf.Tensor
return tensor.shape | [
"def",
"get_tensor_shape",
"(",
"self",
",",
"tensor_name",
")",
":",
"tensor",
"=",
"self",
".",
"_name_to_tensor",
"(",
"tensor_name",
")",
"if",
"isinstance",
"(",
"tensor",
",",
"mtf",
".",
"Tensor",
")",
":",
"return",
"tf",
".",
"TensorShape",
"(",
... | The tf.TensorShape of a tensor.
Args:
tensor_name: string, the name of a tensor in the graph.
Returns:
a tf.TensorShape | [
"The",
"tf",
".",
"TensorShape",
"of",
"a",
"tensor",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/auto_mtf/graph_interface.py#L137-L151 |
241,585 | tensorflow/mesh | mesh_tensorflow/auto_mtf/graph_interface.py | GraphInterface.get_tensor_num_entries | def get_tensor_num_entries(self, tensor_name, partial_layout=None,
mesh_dimension_to_size=None):
"""The number of entries in a tensor.
If partial_layout is specified, then mesh_dimension_to_size must also be. In
this case, the number of entries on a single device is returned.
Args:
tensor_name: a string, name of a tensor in the graph.
partial_layout: an optional {string: string}, from MTF dimension name to
mesh dimension name.
mesh_dimension_to_size: an optional {string: int}, from mesh dimension
name to size.
Returns:
an integer
"""
shape = self.get_tensor_shape(tensor_name)
# We don't have to worry about divisiblity issues because Mesh TensorFlow
# only allows evenly divisible assignments.
num_entries = 1
for dim in shape.dims:
num_entries = num_entries * dim.value
if not partial_layout:
return num_entries
for mtf_dimension_name in self.get_tensor_mtf_dimension_names(tensor_name):
if mtf_dimension_name not in partial_layout:
continue
mesh_dimension_name = partial_layout[mtf_dimension_name]
mesh_dimension_size = mesh_dimension_to_size[mesh_dimension_name]
num_entries = int(math.ceil(num_entries / mesh_dimension_size))
return num_entries | python | def get_tensor_num_entries(self, tensor_name, partial_layout=None,
mesh_dimension_to_size=None):
shape = self.get_tensor_shape(tensor_name)
# We don't have to worry about divisiblity issues because Mesh TensorFlow
# only allows evenly divisible assignments.
num_entries = 1
for dim in shape.dims:
num_entries = num_entries * dim.value
if not partial_layout:
return num_entries
for mtf_dimension_name in self.get_tensor_mtf_dimension_names(tensor_name):
if mtf_dimension_name not in partial_layout:
continue
mesh_dimension_name = partial_layout[mtf_dimension_name]
mesh_dimension_size = mesh_dimension_to_size[mesh_dimension_name]
num_entries = int(math.ceil(num_entries / mesh_dimension_size))
return num_entries | [
"def",
"get_tensor_num_entries",
"(",
"self",
",",
"tensor_name",
",",
"partial_layout",
"=",
"None",
",",
"mesh_dimension_to_size",
"=",
"None",
")",
":",
"shape",
"=",
"self",
".",
"get_tensor_shape",
"(",
"tensor_name",
")",
"# We don't have to worry about divisibl... | The number of entries in a tensor.
If partial_layout is specified, then mesh_dimension_to_size must also be. In
this case, the number of entries on a single device is returned.
Args:
tensor_name: a string, name of a tensor in the graph.
partial_layout: an optional {string: string}, from MTF dimension name to
mesh dimension name.
mesh_dimension_to_size: an optional {string: int}, from mesh dimension
name to size.
Returns:
an integer | [
"The",
"number",
"of",
"entries",
"in",
"a",
"tensor",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/auto_mtf/graph_interface.py#L153-L187 |
241,586 | tensorflow/mesh | mesh_tensorflow/auto_mtf/graph_interface.py | GraphInterface.get_tensor_size | def get_tensor_size(self, tensor_name, partial_layout=None,
mesh_dimension_to_size=None):
"""The size of a tensor in bytes.
If partial_layout is specified, then mesh_dimension_to_size must also be. In
this case, the size on a single device is returned.
Args:
tensor_name: a string, name of a tensor in the graph.
partial_layout: an optional {string: string}, from MTF dimension name to
mesh dimension name.
mesh_dimension_to_size: an optional {string: int}, from mesh dimension
name to size.
Returns:
an integer
"""
return (self.get_tensor_dtype(tensor_name).size *
self.get_tensor_num_entries(tensor_name, partial_layout,
mesh_dimension_to_size)) | python | def get_tensor_size(self, tensor_name, partial_layout=None,
mesh_dimension_to_size=None):
return (self.get_tensor_dtype(tensor_name).size *
self.get_tensor_num_entries(tensor_name, partial_layout,
mesh_dimension_to_size)) | [
"def",
"get_tensor_size",
"(",
"self",
",",
"tensor_name",
",",
"partial_layout",
"=",
"None",
",",
"mesh_dimension_to_size",
"=",
"None",
")",
":",
"return",
"(",
"self",
".",
"get_tensor_dtype",
"(",
"tensor_name",
")",
".",
"size",
"*",
"self",
".",
"get_... | The size of a tensor in bytes.
If partial_layout is specified, then mesh_dimension_to_size must also be. In
this case, the size on a single device is returned.
Args:
tensor_name: a string, name of a tensor in the graph.
partial_layout: an optional {string: string}, from MTF dimension name to
mesh dimension name.
mesh_dimension_to_size: an optional {string: int}, from mesh dimension
name to size.
Returns:
an integer | [
"The",
"size",
"of",
"a",
"tensor",
"in",
"bytes",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/auto_mtf/graph_interface.py#L189-L208 |
241,587 | tensorflow/mesh | mesh_tensorflow/auto_mtf/graph_interface.py | GraphInterface.get_tensor_device | def get_tensor_device(self, tensor_name):
"""The device of a tensor.
Note that only tf tensors have device assignments.
Args:
tensor_name: a string, name of a tensor in the graph.
Returns:
a string or None, representing the device name.
"""
tensor = self._name_to_tensor(tensor_name)
if isinstance(tensor, tf.Tensor):
return tensor.device
else: # mtf.Tensor
return None | python | def get_tensor_device(self, tensor_name):
tensor = self._name_to_tensor(tensor_name)
if isinstance(tensor, tf.Tensor):
return tensor.device
else: # mtf.Tensor
return None | [
"def",
"get_tensor_device",
"(",
"self",
",",
"tensor_name",
")",
":",
"tensor",
"=",
"self",
".",
"_name_to_tensor",
"(",
"tensor_name",
")",
"if",
"isinstance",
"(",
"tensor",
",",
"tf",
".",
"Tensor",
")",
":",
"return",
"tensor",
".",
"device",
"else",... | The device of a tensor.
Note that only tf tensors have device assignments.
Args:
tensor_name: a string, name of a tensor in the graph.
Returns:
a string or None, representing the device name. | [
"The",
"device",
"of",
"a",
"tensor",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/auto_mtf/graph_interface.py#L210-L225 |
241,588 | tensorflow/mesh | mesh_tensorflow/auto_mtf/graph_interface.py | GraphInterface.get_operation_device | def get_operation_device(self, operation_name):
"""The device of an operation.
Note that only tf operations have device assignments.
Args:
operation_name: a string, name of an operation in the graph.
Returns:
a string or None, representing the device name.
"""
operation = self._name_to_operation(operation_name)
if isinstance(operation, tf.Operation):
return operation.device
else: # mtf.Operation
return None | python | def get_operation_device(self, operation_name):
operation = self._name_to_operation(operation_name)
if isinstance(operation, tf.Operation):
return operation.device
else: # mtf.Operation
return None | [
"def",
"get_operation_device",
"(",
"self",
",",
"operation_name",
")",
":",
"operation",
"=",
"self",
".",
"_name_to_operation",
"(",
"operation_name",
")",
"if",
"isinstance",
"(",
"operation",
",",
"tf",
".",
"Operation",
")",
":",
"return",
"operation",
".... | The device of an operation.
Note that only tf operations have device assignments.
Args:
operation_name: a string, name of an operation in the graph.
Returns:
a string or None, representing the device name. | [
"The",
"device",
"of",
"an",
"operation",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/auto_mtf/graph_interface.py#L242-L257 |
241,589 | tensorflow/mesh | mesh_tensorflow/auto_mtf/graph_interface.py | GraphInterface.get_tensor_mtf_dimension_names | def get_tensor_mtf_dimension_names(self, tensor_name):
"""The Mesh TensorFlow dimensions associated with a tensor.
Args:
tensor_name: a string, name of a tensor in the graph.
Returns:
a [string], the names of Mesh TensorFlow dimensions.
"""
tensor = self._name_to_tensor(tensor_name)
if isinstance(tensor, mtf.Tensor):
return tensor.shape.dimension_names
else: # tf.Tensor
return [] | python | def get_tensor_mtf_dimension_names(self, tensor_name):
tensor = self._name_to_tensor(tensor_name)
if isinstance(tensor, mtf.Tensor):
return tensor.shape.dimension_names
else: # tf.Tensor
return [] | [
"def",
"get_tensor_mtf_dimension_names",
"(",
"self",
",",
"tensor_name",
")",
":",
"tensor",
"=",
"self",
".",
"_name_to_tensor",
"(",
"tensor_name",
")",
"if",
"isinstance",
"(",
"tensor",
",",
"mtf",
".",
"Tensor",
")",
":",
"return",
"tensor",
".",
"shap... | The Mesh TensorFlow dimensions associated with a tensor.
Args:
tensor_name: a string, name of a tensor in the graph.
Returns:
a [string], the names of Mesh TensorFlow dimensions. | [
"The",
"Mesh",
"TensorFlow",
"dimensions",
"associated",
"with",
"a",
"tensor",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/auto_mtf/graph_interface.py#L259-L272 |
241,590 | tensorflow/mesh | mesh_tensorflow/auto_mtf/graph_interface.py | GraphInterface.get_operation_mtf_dimension_names | def get_operation_mtf_dimension_names(self, operation_name):
"""The Mesh TensorFlow dimensions associated with an operation.
Args:
operation_name: a string, name of an operation in the graph.
Returns:
a set(string), the names of Mesh TensorFlow dimensions.
"""
mtf_dimension_names = set()
for tensor_name in self.get_operation_input_names(operation_name):
mtf_dimension_names.update(self.get_tensor_mtf_dimension_names(
tensor_name))
for tensor_name in self.get_operation_output_names(operation_name):
mtf_dimension_names.update(self.get_tensor_mtf_dimension_names(
tensor_name))
return mtf_dimension_names | python | def get_operation_mtf_dimension_names(self, operation_name):
mtf_dimension_names = set()
for tensor_name in self.get_operation_input_names(operation_name):
mtf_dimension_names.update(self.get_tensor_mtf_dimension_names(
tensor_name))
for tensor_name in self.get_operation_output_names(operation_name):
mtf_dimension_names.update(self.get_tensor_mtf_dimension_names(
tensor_name))
return mtf_dimension_names | [
"def",
"get_operation_mtf_dimension_names",
"(",
"self",
",",
"operation_name",
")",
":",
"mtf_dimension_names",
"=",
"set",
"(",
")",
"for",
"tensor_name",
"in",
"self",
".",
"get_operation_input_names",
"(",
"operation_name",
")",
":",
"mtf_dimension_names",
".",
... | The Mesh TensorFlow dimensions associated with an operation.
Args:
operation_name: a string, name of an operation in the graph.
Returns:
a set(string), the names of Mesh TensorFlow dimensions. | [
"The",
"Mesh",
"TensorFlow",
"dimensions",
"associated",
"with",
"an",
"operation",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/auto_mtf/graph_interface.py#L274-L290 |
241,591 | tensorflow/mesh | mesh_tensorflow/auto_mtf/graph_interface.py | GraphInterface.set_tensor_final | def set_tensor_final(self, tensor_name):
"""Denotes a tensor as a final output of the computation.
Args:
tensor_name: a string, name of a tensor in the graph.
"""
tensor = self._name_to_tensor(tensor_name)
self._final_tensors.add(tensor) | python | def set_tensor_final(self, tensor_name):
tensor = self._name_to_tensor(tensor_name)
self._final_tensors.add(tensor) | [
"def",
"set_tensor_final",
"(",
"self",
",",
"tensor_name",
")",
":",
"tensor",
"=",
"self",
".",
"_name_to_tensor",
"(",
"tensor_name",
")",
"self",
".",
"_final_tensors",
".",
"add",
"(",
"tensor",
")"
] | Denotes a tensor as a final output of the computation.
Args:
tensor_name: a string, name of a tensor in the graph. | [
"Denotes",
"a",
"tensor",
"as",
"a",
"final",
"output",
"of",
"the",
"computation",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/auto_mtf/graph_interface.py#L292-L299 |
241,592 | tensorflow/mesh | mesh_tensorflow/auto_mtf/graph_interface.py | GraphInterface.is_tensor_final | def is_tensor_final(self, tensor_name):
"""Whether a tensor is a final output of the computation.
Args:
tensor_name: a string, name of a tensor in the graph.
Returns:
a boolean indicating whether the tensor was a final output.
"""
tensor = self._name_to_tensor(tensor_name)
return tensor in self._final_tensors | python | def is_tensor_final(self, tensor_name):
tensor = self._name_to_tensor(tensor_name)
return tensor in self._final_tensors | [
"def",
"is_tensor_final",
"(",
"self",
",",
"tensor_name",
")",
":",
"tensor",
"=",
"self",
".",
"_name_to_tensor",
"(",
"tensor_name",
")",
"return",
"tensor",
"in",
"self",
".",
"_final_tensors"
] | Whether a tensor is a final output of the computation.
Args:
tensor_name: a string, name of a tensor in the graph.
Returns:
a boolean indicating whether the tensor was a final output. | [
"Whether",
"a",
"tensor",
"is",
"a",
"final",
"output",
"of",
"the",
"computation",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/auto_mtf/graph_interface.py#L301-L311 |
241,593 | tensorflow/mesh | mesh_tensorflow/auto_mtf/graph_interface.py | GraphInterface.compute_cost_graph | def compute_cost_graph(self, devices=None):
"""Computes a CostGraphDef protobuf based on this graph.
Defined in tensorflow/core/framework/cost_graph.proto.
Args:
devices: optional [string], the names of devices to consider. If
specified, any tensor on a device not listed is given a size of zero.
Any device-less tensor (e.g. Mesh TensorFlow tensor) is not affected.
Returns:
a CostGraphDef protobuf with a Node for every operation in the graph, each
of which is populated with size/dtype information for its inputs and
outputs (which match the input/output order of the operation).
"""
cost_graph_def = cost_graph_pb2.CostGraphDef()
for i, operation_name in enumerate(self.get_all_operation_names()):
node = cost_graph_def.node.add(
name=operation_name,
device=self.get_operation_device(operation_name),
id=i)
for input_name in self.get_operation_input_names(operation_name):
id1, id2 = self._tensor_name_to_ids[input_name]
node.input_info.add(preceding_node=id1, preceding_port=id2)
for output_name in self.get_operation_output_names(operation_name):
tensor_device = self.get_tensor_device(output_name)
# devices = [] is not the same as None, and tensor_device = '' is also
# not the same as None.
if devices is None or tensor_device is None or tensor_device in devices:
node.output_info.add(
size=self.get_tensor_num_entries(output_name),
alias_input_port=-1,
dtype=self.get_tensor_dtype(output_name).as_datatype_enum,
shape=self.get_tensor_shape(output_name).as_proto(),
)
else:
node.output_info.add(
size=0,
alias_input_port=-1,
dtype=self.get_tensor_dtype(output_name).as_datatype_enum,
)
# NOTE(joshuawang): Unfortunately, the CostGraphDef protobuf has final
# operations, not tensors. As a result, we have to declare any operation
# that outputs a final tensor as final, which may expand the final set
# of tensors to keep in memory. This issue also arises in the scheduler
# code we will interface with.
if self.is_tensor_final(output_name):
node.is_final = True
return cost_graph_def | python | def compute_cost_graph(self, devices=None):
cost_graph_def = cost_graph_pb2.CostGraphDef()
for i, operation_name in enumerate(self.get_all_operation_names()):
node = cost_graph_def.node.add(
name=operation_name,
device=self.get_operation_device(operation_name),
id=i)
for input_name in self.get_operation_input_names(operation_name):
id1, id2 = self._tensor_name_to_ids[input_name]
node.input_info.add(preceding_node=id1, preceding_port=id2)
for output_name in self.get_operation_output_names(operation_name):
tensor_device = self.get_tensor_device(output_name)
# devices = [] is not the same as None, and tensor_device = '' is also
# not the same as None.
if devices is None or tensor_device is None or tensor_device in devices:
node.output_info.add(
size=self.get_tensor_num_entries(output_name),
alias_input_port=-1,
dtype=self.get_tensor_dtype(output_name).as_datatype_enum,
shape=self.get_tensor_shape(output_name).as_proto(),
)
else:
node.output_info.add(
size=0,
alias_input_port=-1,
dtype=self.get_tensor_dtype(output_name).as_datatype_enum,
)
# NOTE(joshuawang): Unfortunately, the CostGraphDef protobuf has final
# operations, not tensors. As a result, we have to declare any operation
# that outputs a final tensor as final, which may expand the final set
# of tensors to keep in memory. This issue also arises in the scheduler
# code we will interface with.
if self.is_tensor_final(output_name):
node.is_final = True
return cost_graph_def | [
"def",
"compute_cost_graph",
"(",
"self",
",",
"devices",
"=",
"None",
")",
":",
"cost_graph_def",
"=",
"cost_graph_pb2",
".",
"CostGraphDef",
"(",
")",
"for",
"i",
",",
"operation_name",
"in",
"enumerate",
"(",
"self",
".",
"get_all_operation_names",
"(",
")"... | Computes a CostGraphDef protobuf based on this graph.
Defined in tensorflow/core/framework/cost_graph.proto.
Args:
devices: optional [string], the names of devices to consider. If
specified, any tensor on a device not listed is given a size of zero.
Any device-less tensor (e.g. Mesh TensorFlow tensor) is not affected.
Returns:
a CostGraphDef protobuf with a Node for every operation in the graph, each
of which is populated with size/dtype information for its inputs and
outputs (which match the input/output order of the operation). | [
"Computes",
"a",
"CostGraphDef",
"protobuf",
"based",
"on",
"this",
"graph",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/auto_mtf/graph_interface.py#L313-L365 |
241,594 | tensorflow/mesh | mesh_tensorflow/auto_mtf/graph_interface.py | GraphInterface.compute_memory_contents_under_schedule | def compute_memory_contents_under_schedule(self, schedule):
"""The in-memory tensors present when executing each operation in schedule.
Simulates running operations in the order given by a schedule. Keeps track
of the tensors in memory at every point in time, and outputs a list (one
entry for each point in time) of all sets of all memory contents (i.e. a
frozenset of strings) ever seen in this execution.
It is assumed (but not checked) that schedule is a valid topological sort of
the operations in this graph.
Args:
schedule: A list of integer ids; the order to run operations in.
Returns:
a list of frozenset of strings, where the ith entry describes the tensors
in memory when executing operation i (where schedule[i] is an index into
get_all_operation_names()).
"""
out_degree = self._compute_initial_out_degree()
curr_memory_contents = set()
memory_contents_for_each_operation = []
for operation_id in schedule:
operation_name = self._operations[operation_id].name
# Allocate new memory to perform the computation at this node.
for output_name in self.get_operation_output_names(operation_name):
curr_memory_contents.add(output_name)
memory_contents_for_each_operation.append(frozenset(curr_memory_contents))
# Free any tensors which are no longer needed.
for output_name in self.get_operation_output_names(operation_name):
if out_degree[output_name] == 0:
curr_memory_contents.remove(output_name)
for input_name in self.get_operation_input_names(operation_name):
out_degree[input_name] -= 1
if out_degree[input_name] == 0:
curr_memory_contents.remove(input_name)
return memory_contents_for_each_operation | python | def compute_memory_contents_under_schedule(self, schedule):
out_degree = self._compute_initial_out_degree()
curr_memory_contents = set()
memory_contents_for_each_operation = []
for operation_id in schedule:
operation_name = self._operations[operation_id].name
# Allocate new memory to perform the computation at this node.
for output_name in self.get_operation_output_names(operation_name):
curr_memory_contents.add(output_name)
memory_contents_for_each_operation.append(frozenset(curr_memory_contents))
# Free any tensors which are no longer needed.
for output_name in self.get_operation_output_names(operation_name):
if out_degree[output_name] == 0:
curr_memory_contents.remove(output_name)
for input_name in self.get_operation_input_names(operation_name):
out_degree[input_name] -= 1
if out_degree[input_name] == 0:
curr_memory_contents.remove(input_name)
return memory_contents_for_each_operation | [
"def",
"compute_memory_contents_under_schedule",
"(",
"self",
",",
"schedule",
")",
":",
"out_degree",
"=",
"self",
".",
"_compute_initial_out_degree",
"(",
")",
"curr_memory_contents",
"=",
"set",
"(",
")",
"memory_contents_for_each_operation",
"=",
"[",
"]",
"for",
... | The in-memory tensors present when executing each operation in schedule.
Simulates running operations in the order given by a schedule. Keeps track
of the tensors in memory at every point in time, and outputs a list (one
entry for each point in time) of all sets of all memory contents (i.e. a
frozenset of strings) ever seen in this execution.
It is assumed (but not checked) that schedule is a valid topological sort of
the operations in this graph.
Args:
schedule: A list of integer ids; the order to run operations in.
Returns:
a list of frozenset of strings, where the ith entry describes the tensors
in memory when executing operation i (where schedule[i] is an index into
get_all_operation_names()). | [
"The",
"in",
"-",
"memory",
"tensors",
"present",
"when",
"executing",
"each",
"operation",
"in",
"schedule",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/auto_mtf/graph_interface.py#L367-L407 |
241,595 | tensorflow/mesh | mesh_tensorflow/auto_mtf/graph_interface.py | GraphInterface._initialize_operations | def _initialize_operations(self):
"""Initializer for _operations.
Raises:
TypeError: _graph is not a tf.Graph or mtf.Graph.
Returns:
a list of (tf.Operation or mtf.Operation)
"""
if isinstance(self._graph, tf.Graph):
return self._graph.get_operations()
elif isinstance(self._graph, mtf.Graph):
return self._graph.operations
else:
raise TypeError('Graph is not tf.Graph or mtf.Graph: {}'
.format(type(self._graph))) | python | def _initialize_operations(self):
if isinstance(self._graph, tf.Graph):
return self._graph.get_operations()
elif isinstance(self._graph, mtf.Graph):
return self._graph.operations
else:
raise TypeError('Graph is not tf.Graph or mtf.Graph: {}'
.format(type(self._graph))) | [
"def",
"_initialize_operations",
"(",
"self",
")",
":",
"if",
"isinstance",
"(",
"self",
".",
"_graph",
",",
"tf",
".",
"Graph",
")",
":",
"return",
"self",
".",
"_graph",
".",
"get_operations",
"(",
")",
"elif",
"isinstance",
"(",
"self",
".",
"_graph",... | Initializer for _operations.
Raises:
TypeError: _graph is not a tf.Graph or mtf.Graph.
Returns:
a list of (tf.Operation or mtf.Operation) | [
"Initializer",
"for",
"_operations",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/auto_mtf/graph_interface.py#L409-L424 |
241,596 | tensorflow/mesh | mesh_tensorflow/auto_mtf/graph_interface.py | GraphInterface._initialize_operation_name_to_id | def _initialize_operation_name_to_id(self):
"""Initializer for _operation_name_to_id.
Returns:
a {string: int}, mapping operation names to their index in _operations.
"""
operation_name_to_id = {}
for i, operation in enumerate(self._operations):
operation_name_to_id[operation.name] = i
return operation_name_to_id | python | def _initialize_operation_name_to_id(self):
operation_name_to_id = {}
for i, operation in enumerate(self._operations):
operation_name_to_id[operation.name] = i
return operation_name_to_id | [
"def",
"_initialize_operation_name_to_id",
"(",
"self",
")",
":",
"operation_name_to_id",
"=",
"{",
"}",
"for",
"i",
",",
"operation",
"in",
"enumerate",
"(",
"self",
".",
"_operations",
")",
":",
"operation_name_to_id",
"[",
"operation",
".",
"name",
"]",
"="... | Initializer for _operation_name_to_id.
Returns:
a {string: int}, mapping operation names to their index in _operations. | [
"Initializer",
"for",
"_operation_name_to_id",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/auto_mtf/graph_interface.py#L426-L435 |
241,597 | tensorflow/mesh | mesh_tensorflow/auto_mtf/graph_interface.py | GraphInterface._initialize_tensor_name_to_ids | def _initialize_tensor_name_to_ids(self):
"""Initializer for _tensor_name_to_ids.
Returns:
a {string: (int, int)}, mapping the name of tensor T to the index of T's
operation in _operations and T's index in T's operation's outputs.
"""
tensor_name_to_ids = {}
for i, operation in enumerate(self._operations):
for j, tensor in enumerate(operation.outputs):
tensor_name_to_ids[tensor.name] = (i, j)
return tensor_name_to_ids | python | def _initialize_tensor_name_to_ids(self):
tensor_name_to_ids = {}
for i, operation in enumerate(self._operations):
for j, tensor in enumerate(operation.outputs):
tensor_name_to_ids[tensor.name] = (i, j)
return tensor_name_to_ids | [
"def",
"_initialize_tensor_name_to_ids",
"(",
"self",
")",
":",
"tensor_name_to_ids",
"=",
"{",
"}",
"for",
"i",
",",
"operation",
"in",
"enumerate",
"(",
"self",
".",
"_operations",
")",
":",
"for",
"j",
",",
"tensor",
"in",
"enumerate",
"(",
"operation",
... | Initializer for _tensor_name_to_ids.
Returns:
a {string: (int, int)}, mapping the name of tensor T to the index of T's
operation in _operations and T's index in T's operation's outputs. | [
"Initializer",
"for",
"_tensor_name_to_ids",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/auto_mtf/graph_interface.py#L437-L448 |
241,598 | tensorflow/mesh | mesh_tensorflow/auto_mtf/graph_interface.py | GraphInterface._name_to_tensor | def _name_to_tensor(self, tensor_name):
"""The tensor with the given name.
Args:
tensor_name: a string, name of a tensor in the graph.
Returns:
a tf.Tensor or mtf.Tensor
"""
id1, id2 = self._tensor_name_to_ids[tensor_name]
return self._operations[id1].outputs[id2] | python | def _name_to_tensor(self, tensor_name):
id1, id2 = self._tensor_name_to_ids[tensor_name]
return self._operations[id1].outputs[id2] | [
"def",
"_name_to_tensor",
"(",
"self",
",",
"tensor_name",
")",
":",
"id1",
",",
"id2",
"=",
"self",
".",
"_tensor_name_to_ids",
"[",
"tensor_name",
"]",
"return",
"self",
".",
"_operations",
"[",
"id1",
"]",
".",
"outputs",
"[",
"id2",
"]"
] | The tensor with the given name.
Args:
tensor_name: a string, name of a tensor in the graph.
Returns:
a tf.Tensor or mtf.Tensor | [
"The",
"tensor",
"with",
"the",
"given",
"name",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/auto_mtf/graph_interface.py#L471-L481 |
241,599 | tensorflow/mesh | mesh_tensorflow/auto_mtf/graph_interface.py | GraphInterface._compute_initial_out_degree | def _compute_initial_out_degree(self):
"""The number of operations which use each tensor as input.
Returns:
a {string, int} mapping tensor name to the number of operations which use
it as input, or one plus that quantity if the tensor is final.
"""
out_degree = collections.defaultdict(int)
# Pretend that final tensors have an additional degree so they are not
# freed.
for tensor_name in self.get_all_tensor_names():
if self.is_tensor_final(tensor_name):
out_degree[tensor_name] = 1
for operation_name in self.get_all_operation_names():
for input_name in self.get_operation_input_names(operation_name):
out_degree[input_name] += 1
return out_degree | python | def _compute_initial_out_degree(self):
out_degree = collections.defaultdict(int)
# Pretend that final tensors have an additional degree so they are not
# freed.
for tensor_name in self.get_all_tensor_names():
if self.is_tensor_final(tensor_name):
out_degree[tensor_name] = 1
for operation_name in self.get_all_operation_names():
for input_name in self.get_operation_input_names(operation_name):
out_degree[input_name] += 1
return out_degree | [
"def",
"_compute_initial_out_degree",
"(",
"self",
")",
":",
"out_degree",
"=",
"collections",
".",
"defaultdict",
"(",
"int",
")",
"# Pretend that final tensors have an additional degree so they are not",
"# freed.",
"for",
"tensor_name",
"in",
"self",
".",
"get_all_tensor... | The number of operations which use each tensor as input.
Returns:
a {string, int} mapping tensor name to the number of operations which use
it as input, or one plus that quantity if the tensor is final. | [
"The",
"number",
"of",
"operations",
"which",
"use",
"each",
"tensor",
"as",
"input",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/auto_mtf/graph_interface.py#L483-L502 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.