Python get screen

60 Python code examples are found related to " get screen". You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.
Example 1
Source File: TargetManager.py    From Pirates-Online-Rewritten with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def getTargetScreenXY(self, target):
        tNodePath = target.attachNewNode('temp')
        distance = camera.getDistance(target)
        mult = 0.66
        if target.avatarType.isA(AvatarTypes.GiantCrab):
            mult = 0.1
        elif target.avatarType.isA(AvatarTypes.CrusherCrab):
            mult = 0.1
        elif target.avatarType.isA(AvatarTypes.RockCrab):
            mult = 0.2
        elif target.avatarType.isA(AvatarTypes.FireBat):
            mult = 0.8
        tNodePath.setPos(target, 0, 0, target.getHeight() * mult)
        nearVec = self.getNearProjectionPoint(tNodePath)
        nearVec *= base.camLens.getFocalLength() / base.camLens.getNear()
        render2dX = CLAMP(nearVec[0] / (base.camLens.getFilmSize()[0] / 2.0), -0.9, 0.9)
        aspect2dX = render2dX * base.getAspectRatio()
        aspect2dZ = CLAMP(nearVec[2] / (base.camLens.getFilmSize()[1] / 2.0), -0.8, 0.9)
        tNodePath.removeNode()
        return (
         Vec3(aspect2dX, 0, aspect2dZ), distance) 
Example 2
Source File: env_utils.py    From Pytorch-Project-Template with MIT License 6 votes vote down vote up
def get_screen(self, env):
        screen = env.render(mode='rgb_array').transpose((2, 0, 1))  # transpose into torch order (CHW)
        # Strip off the top and bottom of the screen
        screen = screen[:, 160:320]
        view_width = 320
        cart_location = self.get_cart_location(env)
        if cart_location < view_width // 2:
            slice_range = slice(view_width)
        elif cart_location > (self.screen_width - view_width // 2):
            slice_range = slice(-view_width, None)
        else:
            slice_range = slice(cart_location - view_width // 2,
                                cart_location + view_width // 2)
        # Strip off the edges, so that we have a square image centered on a cart
        screen = screen[:, :, slice_range]
        # Convert to float, rescale, convert to torch tensor
        screen = np.ascontiguousarray(screen, dtype=np.float32) / 255
        screen = torch.from_numpy(screen)
        # Resize, and add a batch dimension (BCHW)
        return resize(screen).unsqueeze(0) 
Example 3
Source File: ple.py    From humanRL_prior_games with MIT License 6 votes vote down vote up
def getScreenGrayscale(self):
        """
        Gets the current game screen in Grayscale format. Converts from RGB using relative lumiance.

        Returns
        --------
        numpy uint8 array
                Returns a numpy array with the shape (width, height).


        """
        frame = self.getScreenRGB()
        frame = 0.21 * frame[:, :, 0] + 0.72 * \
            frame[:, :, 1] + 0.07 * frame[:, :, 2]
        frame = np.round(frame).astype(np.uint8)

        return frame 
Example 4
Source File: datastar.py    From jdcloud-cli with Apache License 2.0 6 votes vote down vote up
def get_large_screen_data(self):
        client_factory = ClientFactory('datastar')
        client = client_factory.get(self.app)
        if client is None:
            return

        try:
            from jdcloud_sdk.services.datastar.apis.GetLargeScreenDataRequest import GetLargeScreenDataRequest
            params_dict = collect_user_args(self.app)
            headers = collect_user_headers(self.app)
            req = GetLargeScreenDataRequest(params_dict, headers)
            resp = client.send(req)
            Printer.print_result(resp)
        except ImportError:
            print('{"error":"This api is not supported, please use the newer version"}')
        except Exception as e:
            print(e) 
Example 5
Source File: game_position.py    From AutonomousCarAI with MIT License 6 votes vote down vote up
def get_screen(region,win32gui, win32ui, win32con, win32api):
    left,top,width,height = region
    hwin = win32gui.GetDesktopWindow()
    hwindc = win32gui.GetWindowDC(hwin)
    srcdc = win32ui.CreateDCFromHandle(hwindc)
    
    memdc = srcdc.CreateCompatibleDC()
    bmp = win32ui.CreateBitmap()
    bmp.CreateCompatibleBitmap(srcdc, width, height)
    memdc.SelectObject(bmp)
    memdc.BitBlt((0, 0), (width, height), srcdc, (left, top), win32con.SRCCOPY)
    
    intsarray = bmp.GetBitmapBits(True)
    srcdc.DeleteDC()
    memdc.DeleteDC()
    win32gui.ReleaseDC(hwin, hwindc)
    win32gui.DeleteObject(bmp.GetHandle())

    return intsarray,height,width 
Example 6
Source File: grid.py    From panda3dstudio with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def get_point_at_screen_pos(self, screen_pos, point_in_plane=None):

        cam = GD.cam()
        near_point = Point3()
        far_point = Point3()
        GD.cam.lens.extrude(screen_pos, near_point, far_point)
        rel_pt = lambda point: self.origin.get_relative_point(cam, point)

        point = Point3()
        plane = self._planes[self._active_plane_id].node().get_plane()

        if point_in_plane:
            plane = Plane(plane.get_normal(), point_in_plane)

        if plane.intersects_line(point, rel_pt(near_point), rel_pt(far_point)):
            return point 
Example 7
Source File: image_search.py    From ultra_secret_scripts with GNU General Public License v3.0 6 votes vote down vote up
def get_screen_area_as_image(area=(0, 0, GetSystemMetrics(0), GetSystemMetrics(1))):
    screen_width = GetSystemMetrics(0)
    screen_height = GetSystemMetrics(1)

    # h, w = image.shape[:-1]  # height and width of searched image

    x1 = min(int(area[0]), screen_width)
    y1 = min(int(area[1]), screen_height)
    x2 = min(int(area[2]), screen_width)
    y2 = min(int(area[3]), screen_height)

    search_area = (x1, y1, x2, y2)

    img_rgb = ImageGrab.grab().crop(search_area).convert("RGB")
    img_rgb = np.array(img_rgb)  # convert to cv2 readable format (and to BGR)
    img_rgb = img_rgb[:, :, ::-1].copy()  # convert back to RGB

    return img_rgb 
Example 8
Source File: LogViewer.py    From OpenPLC_Editor with GNU General Public License v3.0 6 votes vote down vote up
def GetMessageByScreenPos(self, posx, posy):
        if self.CurrentMessage is not None:
            _width, height = self.MessagePanel.GetClientSize()
            message_idx = self.CurrentMessage
            message = self.LogMessages[message_idx]
            draw_date = True
            offset = 5

            while offset < height and message is not None:
                if draw_date:
                    offset += DATE_INFO_SIZE

                if offset <= posy < offset + MESSAGE_INFO_SIZE:
                    return message

                offset += MESSAGE_INFO_SIZE

                previous_message, message_idx = self.GetPreviousMessage(message_idx)
                if previous_message is not None:
                    draw_date = message.Date != previous_message.Date
                message = previous_message
        return None 
Example 9
Source File: kernel32.py    From OpenXMolar with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def GetConsoleScreenBufferInfo(hConsoleOutput = None):
    _GetConsoleScreenBufferInfo = windll.kernel32.GetConsoleScreenBufferInfo
    _GetConsoleScreenBufferInfo.argytpes = [HANDLE, PCONSOLE_SCREEN_BUFFER_INFO]
    _GetConsoleScreenBufferInfo.restype  = bool
    _GetConsoleScreenBufferInfo.errcheck = RaiseIfZero

    if hConsoleOutput is None:
        hConsoleOutput = GetStdHandle(STD_OUTPUT_HANDLE)
    ConsoleScreenBufferInfo = CONSOLE_SCREEN_BUFFER_INFO()
    _GetConsoleScreenBufferInfo(hConsoleOutput, byref(ConsoleScreenBufferInfo))
    return ConsoleScreenBufferInfo

# BOOL WINAPI GetConsoleScreenBufferInfoEx(
#   _In_   HANDLE hConsoleOutput,
#   _Out_  PCONSOLE_SCREEN_BUFFER_INFOEX lpConsoleScreenBufferInfoEx
# );

# TODO

# BOOL WINAPI SetConsoleWindowInfo(
#   _In_  HANDLE hConsoleOutput,
#   _In_  BOOL bAbsolute,
#   _In_  const SMALL_RECT *lpConsoleWindow
# ); 
Example 10
Source File: brush_state.py    From spore with MIT License 6 votes vote down vote up
def get_screen_position(self, invert_y=True):
        """ get the current brush position in screen space coordinates
        :param invert_y: inverts the y to convert maya coords to qt coords
                         qt = True, maya = False
        :return: x, y position if draw is True else: None"""

        if self.draw:
            view = window_utils.active_view()
            point = om.MPoint(self.position[0], self.position[1], self.position[2])

            x_util = om.MScriptUtil()
            x_ptr = x_util.asShortPtr()
            y_util = om.MScriptUtil()
            y_ptr = y_util.asShortPtr()
            view.worldToView(point, x_ptr, y_ptr)
            x_pos = x_util.getShort(x_ptr)
            y_pos = y_util.getShort(y_ptr)

            if invert_y:
                y_pos = view.portHeight() - y_pos

            return x_pos, y_pos

        else:
            return None 
Example 11
Source File: di_utils.py    From CLAtoolkit with GNU General Public License v3.0 6 votes vote down vote up
def get_user_from_screen_name(screen_name, platform):
    platform_name = platform.lower()
    platform_param_name = None
    if platform_name == 'youtube':
        platform_param_name = "google_account_name__iexact"
    elif platform_name == 'github':
        platform_param_name = "github_account_name__iexact"
    elif platform_name == 'trello':
        platform_param_name = "trello_account_name__iexact"
    elif platform_name == 'facebook':
        platform_param_name = "fb_id__iexact"
    else:
        platform_param_name = "%s_id__iexact" % platform_name

    kwargs = {platform_param_name: screen_name}

    user = None
    try:
        user = UserProfile.objects.get(**kwargs).user
    except UserProfile.DoesNotExist:
        # print 'screen_name %s does not exist. Platform: %s' % (screen_name, platform)
        pass
        
    return user 
Example 12
Source File: apis.py    From lyrebird-ios with MIT License 6 votes vote down vote up
def get_screen_shot(message):
    if message.get('cmd') != 'screenshot':
        return
    screen_shots = []
    device_list = message.get('device_id')
    for device_id in device_list:
        device = device_service.devices.get(device_id)
        if not device:
            continue
        screen_shot_info = device.take_screen_shot()
        screen_shots.append(
            {
                'id': device_id,
                'screenshot': {
                    'name': os.path.basename(screen_shot_info.get('screen_shot_file')),
                    'path': screen_shot_info.get('screen_shot_file')
                }
            }
        )
    lyrebird.publish('ios.screenshot', screen_shots, state=True) 
Example 13
Source File: notifications.py    From mac_apt with MIT License 6 votes vote down vote up
def  GetScreenTimeStrings(mac_info):
    strings = {}
    path_1 = '/System/Library/UserNotifications/Bundles/com.apple.ScreenTimeNotifications.bundle/Contents/Resources/en.lproj/Localizable.strings'
    path_2 = '/System/Library/UserNotifications/Bundles/com.apple.ScreenTimeNotifications.bundle/Contents/Resources/en.lproj/InfoPlist.strings'
    if mac_info.IsValidFilePath(path_1):
        success, plist, error = mac_info.ReadPlist(path_1)
        if success:
            strings.update(plist)
        else:
            log.error(f"Failed to read plist {path_1}")
    else:
        log.debug('Did not find path - ' + path_1)

    if mac_info.IsValidFilePath(path_2):
        success, plist, error = mac_info.ReadPlist(path_2)
        if success:
            strings.update(plist)
        else:
            log.error(f"Failed to read plist {path_2}")
    else:
        log.debug('Did not find path - ' + path_2)

    return strings 
Example 14
Source File: PlatformManagerDarwin.py    From lackey with MIT License 6 votes vote down vote up
def getScreenDetails(self):
        """ Return list of attached monitors

        For each monitor (as dict), ``monitor["rect"]`` represents the screen as positioned
        in virtual screen. List is returned in device order, with the first element (0)
        representing the primary monitor.
        """
        primary_screen = None
        screens = []
        for monitor in AppKit.NSScreen.screens():
            # Convert screen rect to Lackey-style rect (x,y,w,h) as position in virtual screen
            screen = {
                "rect": (
                    int(monitor.frame().origin.x),
                    int(monitor.frame().origin.y),
                    int(monitor.frame().size.width),
                    int(monitor.frame().size.height)
                )
            }
            screens.append(screen)
        return screens 
Example 15
Source File: jirahandler.py    From attack2jira with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def get_screen_tabs(self):

        headers = {'Content-Type': 'application/json'}
        screen_ids = self.get_attack_screens()
        screen_tab_ids=[]
        try:
            for screen_id in screen_ids:

                r = requests.get(self.url + '/rest/api/3/screens/'+str(screen_id)+'/tabs', headers=headers, auth=(self.username, self.apitoken), verify=False)
                if r.status_code == 200:
                    for result in r.json():
                        screen_tab_ids.append([screen_id, result['id']])
                else:
                    print("[!] Error obtaining screen tabs")
                    sys.exit(1)

            return screen_tab_ids

        except Exception as ex:
            traceback.print_exc(file=sys.stdout)
            sys.exit() 
Example 16
Source File: KnMoney.py    From KnowledgeMoney with MIT License 6 votes vote down vote up
def getImgFromScreenCapture(ques, ans_one, ans_two, ans_thr):
    question = os.system("screencapture -R {} ./question_screenshot.png".format(ques))
    answer_one = os.system("screencapture -R {} ./answers_one.png".format(ans_one))
    answer_two = os.system("screencapture -R {} ./answers_two.png".format(ans_two))
    answer_thr = os.system("screencapture -R {} ./answers_thr.png".format(ans_thr))

    question_img = Image.open("./question_screenshot.png")
    answer_one_img = Image.open("./answers_one.png")
    answer_two_img = Image.open("./answers_two.png")
    answer_thr_img = Image.open("./answers_thr.png")

    question_enh = getImageFromImageEnhanceForQuestion(question_img)
    ans_one_enh  = getImageFromImageEnhance(answer_one_img)
    ans_two_enh  = getImageFromImageEnhance(answer_two_img)
    ans_thr_enh  = getImageFromImageEnhance(answer_thr_img)

    #使用简体中文解析图片
    print('OCR  ' + datetime.datetime.now().strftime('%H:%M:%S'))
    question_text = pytesseract.image_to_string(question_enh, lang='chi_sim')
    question = question_text
    answers = ['','','']
    return question, answers 
Example 17
Source File: adb.py    From Airtest with Apache License 2.0 6 votes vote down vote up
def getRestrictedScreen(self):
        """
        Get value for mRestrictedScreen (without black border / virtual keyboard)`

        Returns:
            screen resolution mRestrictedScreen value as tuple (x, y)

        """
        # get the effective screen resolution of the device
        result = None
        # get the corresponding mRestrictedScreen parameters according to the device serial number
        dumpsys_info = self.shell("dumpsys window")
        match = re.search(r'mRestrictedScreen=.+', dumpsys_info)
        if match:
            infoline = match.group(0).strip()  # like 'mRestrictedScreen=(0,0) 720x1184'
            resolution = infoline.split(" ")[1].split("x")
            if isinstance(resolution, list) and len(resolution) == 2:
                result = int(str(resolution[0])), int(str(resolution[1]))

        return result 
Example 18
Source File: tl_tweets.py    From evtools with MIT License 6 votes vote down vote up
def get_screen_name(log):
    global MYSELF
    if not MYSELF or MYSELF == "Unknown":
        log.debug("   Getting current user screen name")
        check_twitter_config()
        logging.captureWarnings(True)
        old_level = log.getEffectiveLevel()
        log.setLevel(logging.ERROR)
        twitter = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET)
        try:
            details = twitter.verify_credentials()
        except TwythonAuthError as e:
            log.setLevel(old_level)
            log.exception("   Problem trying to get screen name")
            twitter_auth_issue(e)
            raise
        except:
            log.exception("   Problem trying to get screen name")
            details = None
        log.setLevel(old_level)
        name = "Unknown"
        if details:
            name = details["screen_name"]
        MYSELF = name
    return MYSELF 
Example 19
Source File: tw_hunter.py    From exist with MIT License 6 votes vote down vote up
def getScreenName(tw, screen_name):
    params = {
        'screen_name': screen_name
    }
    url = conf.get('twitter', 'showuser')
    try:
        res = tw.get(url, params = params)
    except Exception as e:
        logger.error(e)
        return

    if res.status_code == 200:
        return json.loads(res.text)['id']
    else:
        logger.error("Error: %d" % res.status_code)
        return 
Example 20
Source File: plugin_manager.py    From SafeEyes with GNU General Public License v3.0 6 votes vote down vote up
def get_break_screen_widgets(self, break_obj):
        """
        Return the HTML widget generated by the plugins.
        The widget is generated by calling the get_widget_title and get_widget_content functions of plugins.
        """
        widget = ''
        for plugin in self.__widget_plugins:
            if break_obj.plugin_enabled(plugin['id'], plugin['enabled']):
                try:
                    title = plugin['module'].get_widget_title(break_obj).upper().strip()
                    if title == '':
                        continue
                    content = plugin['module'].get_widget_content(break_obj)
                    if content == '':
                        continue
                    widget += '<b>{}</b>\n{}\n{}\n\n\n'.format(title, self.horizontal_line, content)
                except BaseException:
                    continue
        return widget.strip() 
Example 21
Source File: environment.py    From Mobile-Security-Framework-MobSF with GNU General Public License v3.0 6 votes vote down vote up
def get_screen_res(self):
        """Get Screen Resolution of Android Instance."""
        logger.info('Getting screen resolution')
        try:
            resp = self.adb_command(['dumpsys', 'window'], True)
            scn_rgx = re.compile(r'mUnrestrictedScreen=\(0,0\) .*')
            scn_rgx2 = re.compile(r'mUnrestricted=\[0,0\]\[.*\]')
            match = scn_rgx.search(resp.decode('utf-8'))
            if match:
                screen_res = match.group().split(' ')[1]
                width, height = screen_res.split('x', 1)
                return width, height
            match = scn_rgx2.search(resp.decode('utf-8'))
            if match:
                res = match.group().split('][')[1].replace(']', '')
                width, height = res.split(',', 1)
                return width, height
            else:
                logger.error('Error getting screen resolution')
        except Exception:
            logger.exception('Getting screen resolution')
        return '1440', '2560' 
Example 22
Source File: Interface.py    From NSC_BUILDER with MIT License 6 votes vote down vote up
def get_screen_gallery(banner,screenlist):
	try:	
		ret='<div class="grid"><div class="row"><div class="img-container thumbnail" style="width: auto;max-height:auto; margin-left: auto; margin-right: auto; display: block;" onclick="showimg()"><img src="{}" id="mainpicture" style="width: auto;max-height:63vh;"></div></div></div><div class="row">'.format(banner)
		banner1="'{}'".format(banner)
		ret+='<div class="cell" style="width: auto;max-height:5vh;"><div class="img-container thumbnail" onclick="setmainimage({})"><img src="{}"></div></div>'.format(banner1,banner)
		screenlist=ast.literal_eval(str(screenlist))
		if isinstance(screenlist, list):
			i=0
			for x in screenlist:
				x1="'{}'".format(x)
				ret+='<div class="cell"><div class="img-container thumbnail"  onclick="setmainimage({})"><img src="{}" id="gallerypicture{}"></div></div>'.format(x1,x,i)
				i+=1
		if 	len(screenlist)<5:
			number=5-len(screenlist)
			for x in range(number):
				x="img/placeholder3.jpg"
				ret+='<div class="cell"><div class="img-container thumbnail"><img src="{}"></div></div>'.format(x)				
			
		ret+='</div>'
		return ret
	except:
		return "Not available"
# @eel.expose	
# def show_picture(img):	
	# eel.show(img) 
Example 23
Source File: x11vnc_desktop.py    From x11vnc-desktop with Apache License 2.0 6 votes vote down vote up
def get_screen_resolution():
    """Obtain the local screen resolution."""

    try:
        if sys.version_info.major > 2:
            import tkinter as tk
        else:
            import Tkinter as tk

        root = tk.Tk()
        root.withdraw()
        width, height = root.winfo_screenwidth(), root.winfo_screenheight()

        return str(width) + 'x' + str(height)
    except:
        return "" 
Example 24
Source File: win32.py    From stegator with MIT License 5 votes vote down vote up
def GetConsoleScreenBufferInfo(stream_id=STDOUT):
        handle = handles[stream_id]
        csbi = CONSOLE_SCREEN_BUFFER_INFO()
        success = windll.kernel32.GetConsoleScreenBufferInfo(
            handle, byref(csbi))
        return csbi 
Example 25
Source File: medical.py    From rl-medical with Apache License 2.0 5 votes vote down vote up
def getScreenDims(self):
        """
        return screen dimensions
        """
        return (self.width, self.height, self.depth) 
Example 26
Source File: win32.py    From syntheticmass with Apache License 2.0 5 votes vote down vote up
def GetConsoleScreenBufferInfo(stream_id=STDOUT):
        handle = handles[stream_id]
        csbi = CONSOLE_SCREEN_BUFFER_INFO()
        success = _GetConsoleScreenBufferInfo(
            handle, byref(csbi))
        return csbi 
Example 27
Source File: win32.py    From Cloudmare with GNU General Public License v3.0 5 votes vote down vote up
def GetConsoleScreenBufferInfo(stream_id=STDOUT):
        handle = _GetStdHandle(stream_id)
        csbi = CONSOLE_SCREEN_BUFFER_INFO()
        success = _GetConsoleScreenBufferInfo(
            handle, byref(csbi))
        return csbi 
Example 28
Source File: win32.py    From POC-EXP with GNU General Public License v3.0 5 votes vote down vote up
def GetConsoleScreenBufferInfo(stream_id=STDOUT):
        handle = handles[stream_id]
        csbi = CONSOLE_SCREEN_BUFFER_INFO()
        success = windll.kernel32.GetConsoleScreenBufferInfo(
            handle, byref(csbi))
        return csbi 
Example 29
Source File: renderer.py    From strike-with-a-pose with GNU General Public License v3.0 5 votes vote down vote up
def get_vertex_screen_coordinates(self):
        world = np.eye(4)
        world[:3, :3] = np.array(self.prog["R_obj"].value).reshape((3, 3)).T
        world[:3, 3] = (
            self.prog["x"].value,
            self.prog["y"].value,
            self.prog["z"].value,
        )
        PV = np.array(self.prog["VP"].value).reshape((4, 4)).T
        pre_screen_coords = PV @ world @ self.hom_vertices.T

        (window_width, window_height) = self.window_size
        screen_xs = (
            window_width
            * (np.array(pre_screen_coords[0]) / np.array(pre_screen_coords[3]) + 1)
            / 2
        )
        screen_ys = (
            window_height
            * (np.array(pre_screen_coords[1]) / np.array(pre_screen_coords[3]) + 1)
            / 2
        )
        screen_coords = np.hstack((screen_xs, screen_ys))

        screen = np.zeros((window_height, window_width))
        for i in range(len(screen_xs)):
            col = x = int(screen_xs[i])
            row = y = int(screen_ys[i])
            if x < window_width and y < window_height:
                screen[window_height - row - 1, col] = 1

        screen_mat = np.uint8(255 * screen)
        screen_img = Image.fromarray(screen_mat, mode="L")
        return (screen_coords, screen_img) 
Example 30
Source File: pocofw.py    From Poco with Apache License 2.0 5 votes vote down vote up
def get_screen_size(self):
        """
        Get the real physical resolution of the screen of target device.

        Returns:
            tuple: float number indicating the screen physical resolution in pixels
        """

        return self.agent.screen.getPortSize() 
Example 31
Source File: screen.py    From Poco with Apache License 2.0 5 votes vote down vote up
def getScreen(self, width):
        b64, fmt = self._getScreen(width)
        if fmt.endswith('.deflate'):
            fmt = fmt[:-len('.deflate')]
            imgdata = base64.b64decode(b64)
            imgdata = zlib.decompress(imgdata)
            b64 = base64.b64encode(imgdata)
        return b64, fmt 
Example 32
Source File: Request.py    From bot-sdk-python with Apache License 2.0 5 votes vote down vote up
def get_screen_card_from_context(self):
        """
        获取屏幕card信息
        :return:
        """
        return Utils.get_dict_data_by_keys(self.data, ['context', 'Screen', 'card']) 
Example 33
Source File: Request.py    From bot-sdk-python with Apache License 2.0 5 votes vote down vote up
def get_screen_context(self):
        """
        获取设备的屏幕信息
        :return:
        """

        return Utils.get_dict_data_by_keys(self.data, ['context', 'Screen']) 
Example 34
Source File: Request.py    From bot-sdk-python with Apache License 2.0 5 votes vote down vote up
def get_screen_token_from_context(self):
        """
        获取屏幕数据中的token
        :return:
        """

        return Utils.get_dict_data_by_keys(self.data, ['context', 'Screen', 'token']) 
Example 35
Source File: twitter.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def GetRecipientScreenName(self):
    '''Get the unique recipient screen name of this direct message.

    Returns:
      The unique recipient screen name of this direct message
    '''
    return self._recipient_screen_name 
Example 36
Source File: androidhelper.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def getScreenBrightness(self):
		'''
		getScreenBrightness(self)
		Returns the screen backlight brightness.
		returns: (Integer) the current screen brightness between 0 and 255
		'''
		return self._rpc("getScreenBrightness") 
Example 37
Source File: androidhelper.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def getScreenTimeout(self):
		'''
		getScreenTimeout(self)
		Returns the current screen timeout in seconds.
		returns: (Integer) the current screen timeout in seconds.
		'''
		return self._rpc("getScreenTimeout") 
Example 38
Source File: twitter.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def GetSenderScreenName(self):
    '''Get the unique sender screen name of this direct message.

    Returns:
      The unique sender screen name of this direct message
    '''
    return self._sender_screen_name 
Example 39
Source File: twitter.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def GetScreenName(self):
    '''Get the short username of this user.

    Returns:
      The short username of this user
    '''
    return self._screen_name 
Example 40
Source File: emulator.py    From tensorflow-rl with Apache License 2.0 5 votes vote down vote up
def get_screen_image(self):
        """ Add screen (luminance) to frame pool """
        # [screen_image, screen_image_rgb] = [self.ale.getScreenGrayscale(), 
        #     self.ale.getScreenRGB()]
        self.ale.getScreenGrayscale(self.gray_screen)
        self.ale.getScreenRGB(self.rgb_screen)
        self.frame_pool[self.current] = np.squeeze(self.gray_screen)
        self.current = (self.current + 1) % FRAMES_IN_POOL
        return self.rgb_screen 
Example 41
Source File: qt_occ_viewer.py    From declaracad with GNU General Public License v3.0 5 votes vote down vote up
def get_screen_coordinate(self, point):
        """ Convert a 3d coordinate to a 2d screen coordinate

        Parameters
        ----------
        (x, y, z): Tuple
            A 3d coordinate
        """
        return self.v3d_view.Convert(point[0], point[1], point[2], 0, 0) 
Example 42
Source File: Util.py    From variety with GNU General Public License v3.0 5 votes vote down vote up
def get_scale_to_screen_ratio(image):
        """Computes the ratio by which the image is scaled to fit the screen: original_size * scale_ratio = scaled_size"""
        iw, ih = Util.get_size(image)
        screen_w, screen_h = (
            Gdk.Screen.get_default().get_width(),
            Gdk.Screen.get_default().get_height(),
        )
        screen_ratio = float(screen_w) / screen_h
        if (
            screen_ratio > float(iw) / ih
        ):  # image is "taller" than the screen ratio - need to offset vertically
            return int(float(screen_w) / iw)
        else:  # image is "wider" than the screen ratio - need to offset horizontally
            return int(float(screen_h) / ih) 
Example 43
Source File: randr.py    From python-xlib with GNU Lesser General Public License v2.1 5 votes vote down vote up
def get_screen_resources_current(self):
    return GetScreenResourcesCurrent(
        display=self.display,
        opcode=self.display.get_extension_major(extname),
        window=self,
        ) 
Example 44
Source File: display.py    From python-xlib with GNU Lesser General Public License v2.1 5 votes vote down vote up
def get_default_screen(self):
        """Return the number of the default screen, extracted from the
        display name."""
        return self.display.get_default_screen()

    ###
    ### Extension module interface
    ### 
Example 45
Source File: randr.py    From python-xlib with GNU Lesser General Public License v2.1 5 votes vote down vote up
def get_screen_resources(self):
    return GetScreenResources(
        display=self.display,
        opcode=self.display.get_extension_major(extname),
        window=self,
        ) 
Example 46
Source File: display.py    From python-xlib with GNU Lesser General Public License v2.1 5 votes vote down vote up
def get_screen_saver(self):
        """Return an object with the attributes timeout, interval,
        prefer_blanking, allow_exposures. See XGetScreenSaver(3X11) for
        details."""
        return request.GetScreenSaver(display = self.display) 
Example 47
Source File: randr.py    From python-xlib with GNU Lesser General Public License v2.1 5 votes vote down vote up
def get_screen_size_range(self):
    """Retrieve the range of possible screen sizes. The screen may be set to
	any size within this range.

    """
    return GetScreenSizeRange(
        display=self.display,
        opcode=self.display.get_extension_major(extname),
        window=self,
        ) 
Example 48
Source File: randr.py    From python-xlib with GNU Lesser General Public License v2.1 5 votes vote down vote up
def get_screen_info(self):
    """Retrieve information about the current and available configurations for
    the screen associated with this window.

    """
    return GetScreenInfo(
        display=self.display,
        opcode=self.display.get_extension_major(extname),
        window=self,
        )


# version 1.2 
Example 49
Source File: xinerama.py    From python-xlib with GNU Lesser General Public License v2.1 5 votes vote down vote up
def get_screen_count(self):
    return GetScreenCount(display=self.display,
                          opcode=self.display.get_extension_major(extname),
                          window=self.id,
                          ) 
Example 50
Source File: xinerama.py    From python-xlib with GNU Lesser General Public License v2.1 5 votes vote down vote up
def get_screen_size(self, screen_no):
    """Returns the size of the given screen number"""
    return GetScreenSize(display=self.display,
                         opcode=self.display.get_extension_major(extname),
                         window=self.id,
                         screen=screen_no,
                         )


# IsActive is only available from Xinerama 1.1 and later.
# It should be used in preference to GetState. 
Example 51
Source File: base.py    From ATX with Apache License 2.0 5 votes vote down vote up
def get_screen(self, t):
        if self.__capture_thread is None:
            self.__start()
        with self.__capture_lock:
            idx = bisect.bisect(self.__capture_cache, (t, None))
            if idx != 0:
                return self.__capture_cache[idx-1][1] 
Example 52
Source File: YuHunModule.py    From yysScript with Apache License 2.0 5 votes vote down vote up
def GetScreenShot():
    """
    获取屏幕截图
    :return:
    """
    screen = ImageGrab.grab()
    # screen.save('screen.jpg')
    # screen = cv2.imread('screen.jpg')
    screen = cv2.cvtColor(numpy.asarray(screen), cv2.COLOR_RGB2BGR)
    logging.info('截屏成功')
    return screen