INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Scramble used for mysql_native_password
def scramble_native_password(password, message): """Scramble used for mysql_native_password""" if not password: return b'' stage1 = sha1_new(password).digest() stage2 = sha1_new(stage1).digest() s = sha1_new() s.update(message[:SCRAMBLE_LENGTH]) s.update(stage2) result = s.diges...
Encrypt password with salt and public_key.
def sha2_rsa_encrypt(password, salt, public_key): """Encrypt password with salt and public_key. Used for sha256_password and caching_sha2_password. """ if not _have_cryptography: raise RuntimeError("'cryptography' package is required for sha256_password or caching_sha2_password auth methods") ...
Scramble algorithm used in cached_sha2_password fast path.
def scramble_caching_sha2(password, nonce): # (bytes, bytes) -> bytes """Scramble algorithm used in cached_sha2_password fast path. XOR(SHA256(password), SHA256(SHA256(SHA256(password)), nonce)) """ if not password: return b'' p1 = hashlib.sha256(password).digest() p2 = hashlib.sha...
Model factory for the transitive closure extension.
def ClosureTable(model_class, foreign_key=None, referencing_class=None, referencing_key=None): """Model factory for the transitive closure extension.""" if referencing_class is None: referencing_class = model_class if foreign_key is None: for field_obj in model_class._meta....
Usage:
def bm25(raw_match_info, *args): """ Usage: # Format string *must* be pcnalx # Second parameter to bm25 specifies the index of the column, on # the table being queries. bm25(matchinfo(document_tbl, 'pcnalx'), 1) AS rank """ match_info = _parse_match_info(raw_match_info) ...
Full - text search using selected term.
def search(cls, term, weights=None, with_score=False, score_alias='score', explicit_ordering=False): """Full-text search using selected `term`.""" return cls._search( term, weights, with_score, score_alias, cls.rank, ...
Full - text search for selected term using BM25 algorithm.
def search_bm25(cls, term, weights=None, with_score=False, score_alias='score', explicit_ordering=False): """Full-text search for selected `term` using BM25 algorithm.""" return cls._search( term, weights, with_score, score_alias, ...
Full - text search for selected term using BM25 algorithm.
def search_bm25f(cls, term, weights=None, with_score=False, score_alias='score', explicit_ordering=False): """Full-text search for selected `term` using BM25 algorithm.""" return cls._search( term, weights, with_score, score_alias, ...
Full - text search for selected term using BM25 algorithm.
def search_lucene(cls, term, weights=None, with_score=False, score_alias='score', explicit_ordering=False): """Full-text search for selected `term` using BM25 algorithm.""" return cls._search( term, weights, with_score, score_alias, ...
Simple helper function to indicate whether a search query is a valid FTS5 query. Note: this simply looks at the characters being used and is not guaranteed to catch all problematic queries.
def validate_query(query): """ Simple helper function to indicate whether a search query is a valid FTS5 query. Note: this simply looks at the characters being used, and is not guaranteed to catch all problematic queries. """ tokens = _quote_re.findall(query) for ...
Clean a query of invalid tokens.
def clean_query(query, replace=chr(26)): """ Clean a query of invalid tokens. """ accum = [] any_invalid = False tokens = _quote_re.findall(query) for token in tokens: if token.startswith('"') and token.endswith('"'): accum.append(token...
Full - text search using selected term.
def search(cls, term, weights=None, with_score=False, score_alias='score', explicit_ordering=False): """Full-text search using selected `term`.""" return cls.search_bm25( FTS5Model.clean_query(term), weights, with_score, score_alias, ...
Full - text search using selected term.
def search_bm25(cls, term, weights=None, with_score=False, score_alias='score', explicit_ordering=False): """Full-text search using selected `term`.""" if not weights: rank = SQL('rank') elif isinstance(weights, dict): weight_args = [] for ...
Close the underlying connection without returning it to the pool.
def manual_close(self): """ Close the underlying connection without returning it to the pool. """ if self.is_closed(): return False # Obtain reference to the connection in-use by the calling thread. conn = self.connection() # A connection will only b...
Get a breakdown of top pages per interval i. e.
def top_pages_by_time_period(self, interval='day'): """ Get a breakdown of top pages per interval, i.e. day url count 2014-01-01 /blog/ 11 2014-01-02 /blog/ 14 2014-01-03 /blog/ 9 """ date_trunc = fn.date_trunc(interval, PageView.timesta...
Retrieve the cookies header from all the users who visited.
def cookies(self): """ Retrieve the cookies header from all the users who visited. """ return (self.get_query() .select(PageView.ip, PageView.headers['Cookie']) .where(PageView.headers['Cookie'].is_null(False)) .tuples())
Retrieve user - agents sorted by most common to least common.
def user_agents(self): """ Retrieve user-agents, sorted by most common to least common. """ return (self.get_query() .select( PageView.headers['User-Agent'], fn.Count(PageView.id)) .group_by(PageView.headers['User-Ag...
Retrieve languages sorted by most common to least common. The Accept - Languages header sometimes looks weird i. e. en - US en ; q = 0. 8 is ; q = 0. 6 da ; q = 0. 4 We will split on the first semi - colon.
def languages(self): """ Retrieve languages, sorted by most common to least common. The Accept-Languages header sometimes looks weird, i.e. "en-US,en;q=0.8,is;q=0.6,da;q=0.4" We will split on the first semi- colon. """ language = PageView.headers['Accept-Language'...
Get all visitors by IP and then list the pages they visited in order.
def trail(self): """ Get all visitors by IP and then list the pages they visited in order. """ inner = (self.get_query() .select(PageView.ip, PageView.url) .order_by(PageView.timestamp)) return (PageView .select( ...
What domains send us the most traffic?
def top_referrers(self, domain_only=True): """ What domains send us the most traffic? """ referrer = self._referrer_clause(domain_only) return (self.get_query() .select(referrer, fn.Count(PageView.id)) .group_by(referrer) .order_by(...
Add entry
def add_entry(): """Add entry""" print('Enter your entry. Press ctrl+d when finished.') data = sys.stdin.read().strip() if data and raw_input('Save entry? [Yn] ') != 'n': Entry.create(content=data) print('Saved successfully.')
View previous entries
def view_entries(search_query=None): """View previous entries""" query = Entry.select().order_by(Entry.timestamp.desc()) if search_query: query = query.where(Entry.content.contains(search_query)) for entry in query: timestamp = entry.timestamp.strftime('%A %B %d, %Y %I:%M%p') pr...
Generate HTML representation of the markdown - formatted blog entry and also convert any media URLs into rich media objects such as video players or images.
def html_content(self): """ Generate HTML representation of the markdown-formatted blog entry, and also convert any media URLs into rich media objects such as video players or images. """ hilite = CodeHiliteExtension(linenums=False, css_class='highlight') extras =...
Convert a model instance ( and any related objects ) to a dictionary.
def model_to_dict(model, recurse=True, backrefs=False, only=None, exclude=None, seen=None, extra_attrs=None, fields_from_query=None, max_depth=None, manytomany=False): """ Convert a model instance (and any related objects) to a dictionary. :param bool recurse: Whether fo...
Lightweight factory which returns a method that builds an Expression consisting of the left - hand and right - hand operands using op.
def _e(op, inv=False): """ Lightweight factory which returns a method that builds an Expression consisting of the left-hand and right-hand operands, using `op`. """ def inner(self, rhs): if inv: return Expression(rhs, op, self) return Expre...
Returns the intraday exchange rate for any pair of physical currency ( e. g. EUR ) or physical currency ( e. g. USD ).
def get_currency_exchange_intraday(self, from_symbol, to_symbol, interval='15min', outputsize='compact'): """ Returns the intraday exchange rate for any pair of physical currency (e.g., EUR) or physical currency (e.g., USD). Keyword Arguments: from_symbol: The currency you would lik...
Decorator for forming the api call with the arguments of the function it works by taking the arguments given to the function and building the url to call the api on it
def _call_api_on_func(cls, func): """ Decorator for forming the api call with the arguments of the function, it works by taking the arguments given to the function and building the url to call the api on it Keyword Arguments: func: The function to be decorated """ ...
Decorator in charge of giving the output its right format either json or pandas
def _output_format(cls, func, override=None): """ Decorator in charge of giving the output its right format, either json or pandas Keyword Arguments: func: The function to be decorated override: Override the internal format of the call, default None """ ...
Convert to the alpha vantage math type integer. It returns an integer correspondent to the type of math to apply to a function. It raises ValueError if an integer greater than the supported math types is given.
def map_to_matype(self, matype): """ Convert to the alpha vantage math type integer. It returns an integer correspondent to the type of math to apply to a function. It raises ValueError if an integer greater than the supported math types is given. Keyword Arguments: ...
Handle the return call from the api and return a data and meta_data object. It raises a ValueError on problems
def _handle_api_call(self, url): """ Handle the return call from the api and return a data and meta_data object. It raises a ValueError on problems Keyword Arguments: url: The url of the service data_key: The key for getting the data from the jso object me...
Decorator in charge of giving the output its right format either json or pandas ( replacing the % for usable floats range 0 - 1. 0 )
def _output_format_sector(func, override=None): """ Decorator in charge of giving the output its right format, either json or pandas (replacing the % for usable floats, range 0-1.0) Keyword Arguments: func: The function to be decorated override: Override the internal for...
Return the moving average convergence/ divergence time series in two json objects as data and meta_data. It raises ValueError when problems arise
def get_macd(self, symbol, interval='daily', series_type='close', fastperiod=None, slowperiod=None, signalperiod=None): """ Return the moving average convergence/divergence time series in two json objects as data and meta_data. It raises ValueError when problems arise K...
Return the moving average convergence/ divergence time series in two json objects as data and meta_data. It raises ValueError when problems arise
def get_macdext(self, symbol, interval='daily', series_type='close', fastperiod=None, slowperiod=None, signalperiod=None, fastmatype=None, slowmatype=None, signalmatype=None): """ Return the moving average convergence/divergence time series in two json objects as ...
Return the stochatic oscillator values in two json objects as data and meta_data. It raises ValueError when problems arise
def get_stoch(self, symbol, interval='daily', fastkperiod=None, slowkperiod=None, slowdperiod=None, slowkmatype=None, slowdmatype=None): """ Return the stochatic oscillator values in two json objects as data and meta_data. It raises ValueError when problems arise Keywo...
Return the stochatic relative strength index in two json objects as data and meta_data. It raises ValueError when problems arise
def get_stochrsi(self, symbol, interval='daily', time_period=20, series_type='close', fastkperiod=None, fastdperiod=None, fastdmatype=None): """ Return the stochatic relative strength index in two json objects as data and meta_data. It raises ValueError when problems arise ...
Return the absolute price oscillator values in two json objects as data and meta_data. It raises ValueError when problems arise
def get_apo(self, symbol, interval='daily', series_type='close', fastperiod=None, slowperiod=None, matype=None): """ Return the absolute price oscillator values in two json objects as data and meta_data. It raises ValueError when problems arise Keyword Arguments: ...
Return the bollinger bands values in two json objects as data and meta_data. It raises ValueError when problems arise
def get_bbands(self, symbol, interval='daily', time_period=20, series_type='close', nbdevup=None, nbdevdn=None, matype=None): """ Return the bollinger bands values in two json objects as data and meta_data. It raises ValueError when problems arise Keyword Arguments: ...
Return a three tuple of data code and headers
def unpack(value): """Return a three tuple of data, code, and headers""" if not isinstance(value, tuple): return value, 200, {} try: data, code, headers = value return data, code, headers except ValueError: pass try: data, code = value return data, c...
Makes a Flask response with a XML encoded body
def output_xml(data, code, headers=None): """Makes a Flask response with a XML encoded body""" resp = make_response(dumps({'response' :data}), code) resp.headers.extend(headers or {}) return resp
Makes a Flask response with a JSON encoded body
def output_json(data, code, headers=None): """Makes a Flask response with a JSON encoded body""" settings = current_app.config.get('RESTFUL_JSON', {}) # If we're in debug mode, and the indent is not set, we set it to a # reasonable value here. Note that this won't override any existing value # th...
Raise a HTTPException for the given http_status_code. Attach any keyword arguments to the exception for later processing.
def abort(http_status_code, **kwargs): """Raise a HTTPException for the given http_status_code. Attach any keyword arguments to the exception for later processing. """ #noinspection PyUnresolvedReferences try: original_flask_abort(http_status_code) except HTTPException as e: if l...
Takes raw data ( in the form of a dict list object ) and a dict of fields to output and filters the data based on those fields.
def marshal(data, fields, envelope=None): """Takes raw data (in the form of a dict, list, object) and a dict of fields to output and filters the data based on those fields. :param data: the actual object(s) from which the fields are taken from :param fields: a dict of whose keys will make up the final ...
Initialize this class with the given: class: flask. Flask application or: class: flask. Blueprint object.
def init_app(self, app): """Initialize this class with the given :class:`flask.Flask` application or :class:`flask.Blueprint` object. :param app: the Flask application or blueprint object :type app: flask.Flask :type app: flask.Blueprint Examples:: api = Ap...
This method is used to defer the construction of the final url in the case that the Api is created with a Blueprint.
def _complete_url(self, url_part, registration_prefix): """This method is used to defer the construction of the final url in the case that the Api is created with a Blueprint. :param url_part: The part of the url the endpoint is registered with :param registration_prefix: The part of th...
Perform initialization actions with the given: class: flask. Flask object.
def _init_app(self, app): """Perform initialization actions with the given :class:`flask.Flask` object. :param app: The flask application object :type app: flask.Flask """ app.handle_exception = partial(self.error_router, app.handle_exception) app.handle_user_exc...
Tests if an endpoint name ( not path ) belongs to this Api. Takes in to account the Blueprint name part of the endpoint name.
def owns_endpoint(self, endpoint): """Tests if an endpoint name (not path) belongs to this Api. Takes in to account the Blueprint name part of the endpoint name. :param endpoint: The name of the endpoint being checked :return: bool """ if self.blueprint: if...
Determine if error should be handled with FR or default Flask
def _should_use_fr_error_handler(self): """ Determine if error should be handled with FR or default Flask The goal is to return Flask error handlers for non-FR-related routes, and FR errors (with the correct media type) for FR endpoints. This method currently handles 404 and 405 errors....
Encapsulating the rules for whether the request was to a Flask endpoint
def _has_fr_route(self): """Encapsulating the rules for whether the request was to a Flask endpoint""" # 404's, 405's, which might not have a url_rule if self._should_use_fr_error_handler(): return True # for all other errors, just check if FR dispatched the route if ...
This function decides whether the error occured in a flask - restful endpoint or not. If it happened in a flask - restful endpoint our handler will be dispatched. If it happened in an unrelated view the app s original error handler will be dispatched. In the event that the error occurred in a flask - restful endpoint b...
def error_router(self, original_handler, e): """This function decides whether the error occured in a flask-restful endpoint or not. If it happened in a flask-restful endpoint, our handler will be dispatched. If it happened in an unrelated view, the app's original error handler will be di...
Error handler for the API transforms a raised exception into a Flask response with the appropriate HTTP status code and body.
def handle_error(self, e): """Error handler for the API transforms a raised exception into a Flask response, with the appropriate HTTP status code and body. :param e: the raised Exception object :type e: Exception """ got_request_exception.send(current_app._get_current_...
Adds a resource to the api.
def add_resource(self, resource, *urls, **kwargs): """Adds a resource to the api. :param resource: the class name of your resource :type resource: :class:`Type[Resource]` :param urls: one or more url routes to match for the resource, standard flask routing rules ap...
Wraps a: class: ~flask_restful. Resource class adding it to the api. Parameters are the same as: meth: ~flask_restful. Api. add_resource.
def resource(self, *urls, **kwargs): """Wraps a :class:`~flask_restful.Resource` class, adding it to the api. Parameters are the same as :meth:`~flask_restful.Api.add_resource`. Example:: app = Flask(__name__) api = restful.Api(app) @api.resource('/foo') ...
Wraps a resource ( as a flask view function ) for cases where the resource does not directly return a response object
def output(self, resource): """Wraps a resource (as a flask view function), for cases where the resource does not directly return a response object :param resource: The resource as a flask view function """ @wraps(resource) def wrapper(*args, **kwargs): resp ...
Generates a URL to the given resource.
def url_for(self, resource, **values): """Generates a URL to the given resource. Works like :func:`flask.url_for`.""" endpoint = resource.endpoint if self.blueprint: endpoint = '{0}.{1}'.format(self.blueprint.name, endpoint) return url_for(endpoint, **values)
Looks up the representation transformer for the requested media type invoking the transformer to create a response object. This defaults to default_mediatype if no transformer is found for the requested mediatype. If default_mediatype is None a 406 Not Acceptable response will be sent as per RFC 2616 section 14. 1
def make_response(self, data, *args, **kwargs): """Looks up the representation transformer for the requested media type, invoking the transformer to create a response object. This defaults to default_mediatype if no transformer is found for the requested mediatype. If default_mediatype i...
Returns a list of requested mediatypes sent in the Accept header
def mediatypes(self): """Returns a list of requested mediatypes sent in the Accept header""" return [h for h, q in sorted(request.accept_mimetypes, key=operator.itemgetter(1), reverse=True)]
Allows additional representation transformers to be declared for the api. Transformers are functions that must be decorated with this method passing the mediatype the transformer represents. Three arguments are passed to the transformer:
def representation(self, mediatype): """Allows additional representation transformers to be declared for the api. Transformers are functions that must be decorated with this method, passing the mediatype the transformer represents. Three arguments are passed to the transformer: ...
Pulls values off the request in the provided location: param request: The flask request object to parse arguments from
def source(self, request): """Pulls values off the request in the provided location :param request: The flask request object to parse arguments from """ if isinstance(self.location, six.string_types): value = getattr(request, self.location, MultiDict()) if callabl...
Called when an error is raised while parsing. Aborts the request with a 400 status and an error message
def handle_validation_error(self, error, bundle_errors): """Called when an error is raised while parsing. Aborts the request with a 400 status and an error message :param error: the error that was raised :param bundle_errors: do not abort when first error occurs, return a di...
Parses argument value ( s ) from the request converting according to the argument s type.
def parse(self, request, bundle_errors=False): """Parses argument value(s) from the request, converting according to the argument's type. :param request: The flask request object to parse arguments from :param bundle_errors: Do not abort when first error occurs, return a dic...
Adds an argument to be parsed.
def add_argument(self, *args, **kwargs): """Adds an argument to be parsed. Accepts either a single instance of Argument or arguments to be passed into :class:`Argument`'s constructor. See :class:`Argument`'s constructor for documentation on the available options. """ ...
Parse all arguments from the provided request and return the results as a Namespace
def parse_args(self, req=None, strict=False, http_error_code=400): """Parse all arguments from the provided request and return the results as a Namespace :param req: Can be used to overwrite request from Flask :param strict: if req includes args not in parser, throw 400 BadRequest excep...
Creates a copy of this RequestParser with the same set of arguments
def copy(self): """ Creates a copy of this RequestParser with the same set of arguments """ parser_copy = self.__class__(self.argument_class, self.namespace_class) parser_copy.args = deepcopy(self.args) parser_copy.trim = self.trim parser_copy.bundle_errors = self.bundle_errors ...
Replace the argument matching the given name with a new version.
def replace_argument(self, name, *args, **kwargs): """ Replace the argument matching the given name with a new version. """ new_arg = self.argument_class(name, *args, **kwargs) for index, arg in enumerate(self.args[:]): if new_arg.name == arg.name: del self.args[index...
Remove the argument matching the given name.
def remove_argument(self, name): """ Remove the argument matching the given name. """ for index, arg in enumerate(self.args[:]): if name == arg.name: del self.args[index] break return self
Helper for converting an object to a dictionary only if it is not dictionary already or an indexable object nor a simple type
def to_marshallable_type(obj): """Helper for converting an object to a dictionary only if it is not dictionary already or an indexable object nor a simple type""" if obj is None: return None # make it idempotent for None if hasattr(obj, '__marshallable__'): return obj.__marshallable__(...
Pulls the value for the given key from the object applies the field s formatting and returns the result. If the key is not found in the object returns the default value. Field classes that create values which do not require the existence of the key in the object should override this and return the desired value.
def output(self, key, obj): """Pulls the value for the given key from the object, applies the field's formatting and returns the result. If the key is not found in the object, returns the default value. Field classes that create values which do not require the existence of the key in the...
Validate a URL.
def url(value): """Validate a URL. :param string value: The URL to validate :returns: The URL if valid. :raises: ValueError """ if not url_regex.search(value): message = u"{0} is not a valid URL".format(value) if url_regex.search('http://' + value): message += u". Di...
Normalize datetime intervals.
def _normalize_interval(start, end, value): """Normalize datetime intervals. Given a pair of datetime.date or datetime.datetime objects, returns a 2-tuple of tz-aware UTC datetimes spanning the same interval. For datetime.date objects, the returned interval starts at 00:00:00.0 on the first date a...
Do some nasty try/ except voodoo to get some sort of datetime object ( s ) out of the string.
def _parse_interval(value): """Do some nasty try/except voodoo to get some sort of datetime object(s) out of the string. """ try: return sorted(aniso8601.parse_interval(value)) except ValueError: try: return aniso8601.parse_datetime(value), None except ValueError:...
Parses ISO 8601 - formatted datetime intervals into tuples of datetimes.
def iso8601interval(value, argument='argument'): """Parses ISO 8601-formatted datetime intervals into tuples of datetimes. Accepts both a single date(time) or a full interval using either start/end or start/duration notation, with the following behavior: - Intervals are defined as inclusive start, exc...
Restrict input type to the natural numbers ( 0 1 2 3... )
def natural(value, argument='argument'): """ Restrict input type to the natural numbers (0, 1, 2, 3...) """ value = _get_integer(value) if value < 0: error = ('Invalid {arg}: {value}. {arg} must be a non-negative ' 'integer'.format(arg=argument, value=value)) raise ValueErro...
Restrict input type to the positive integers ( 1 2 3... )
def positive(value, argument='argument'): """ Restrict input type to the positive integers (1, 2, 3...) """ value = _get_integer(value) if value < 1: error = ('Invalid {arg}: {value}. {arg} must be a positive ' 'integer'.format(arg=argument, value=value)) raise ValueError(er...
Parse the string true or false as a boolean ( case insensitive ). Also accepts 1 and 0 as True/ False ( respectively ). If the input is from the request JSON body the type is already a native python boolean and will be passed through without further parsing.
def boolean(value): """Parse the string ``"true"`` or ``"false"`` as a boolean (case insensitive). Also accepts ``"1"`` and ``"0"`` as ``True``/``False`` (respectively). If the input is from the request JSON body, the type is already a native python boolean, and will be passed through without furthe...
Helper method for special keys.
def _specialKeyEvent(key, upDown): """ Helper method for special keys. Source: http://stackoverflow.com/questions/11045814/emulate-media-key-press-on-mac """ assert upDown in ('up', 'down'), "upDown argument must be 'up' or 'down'" key_code = special_key_translate_table[key] ev = AppKit.NSEve...
Performs a keyboard key press without the release. This will put that key in a held down state.
def _keyDown(key): """Performs a keyboard key press without the release. This will put that key in a held down state. NOTE: For some reason, this does not seem to cause key repeats like would happen if a keyboard key was held down on a text field. Args: key (str): The key to be pressed down....
Performs a keyboard key release ( without the press down beforehand ).
def _keyUp(key): """Performs a keyboard key release (without the press down beforehand). Args: key (str): The key to be released up. The valid names are listed in pyautogui.KEY_NAMES. Returns: None """ """ Release a given character key. Also works with character keycodes as ...
Return dict: { window title: window handle } for all visible windows
def getWindows(): #https://sjohannes.wordpress.com/2012/03/23/win32-python-getting-all-window-titles/ """Return dict: {'window title' : window handle} for all visible windows""" titles = {} def foreach_window(hwnd, lparam): if IsWindowVisible(hwnd): length = GetWindowTextLength(hwnd)...
Return Window object if title or its part found in visible windows titles else return None
def getWindow(title, exact=False): """Return Window object if 'title' or its part found in visible windows titles, else return None Return only 1 window found first Args: title: unicode string exact (bool): True if search only exact match """ titles = getWindows() hwnd = titles....
Set window top - left corner position and size
def set_position(self, x, y, width, height): """Set window top-left corner position and size""" SetWindowPos(self._hwnd, None, x, y, width, height, ctypes.c_uint(0))
Move window top - left corner to position
def move(self, x, y): """Move window top-left corner to position""" SetWindowPos(self._hwnd, None, x, y, 0, 0, SWP_NOSIZE)
Change window size
def resize(self, width, height): """Change window size""" SetWindowPos(self._hwnd, None, 0, 0, width, height, SWP_NOMOVE)
Returns tuple of 4 numbers: ( x y ) s of top - left and bottom - right corners
def get_position(self): """Returns tuple of 4 numbers: (x, y)s of top-left and bottom-right corners""" rect = _Rect() GetWindowRect(self._hwnd, ctypes.pointer(rect)) return rect.left, rect.top, rect.right, rect.bottom
Returns the ( x y ) tuple of the point that has progressed a proportion n along the line defined by the two x y coordinates.
def getPointOnLine(x1, y1, x2, y2, n): """Returns the (x, y) tuple of the point that has progressed a proportion n along the line defined by the two x, y coordinates. Copied from pytweening module. """ x = ((x2 - x1) * n) + x1 y = ((y2 - y1) * n) + y1 return (x, y)
If x is a sequence and y is None returns x [ 0 ] y [ 0 ]. Else returns x y.
def _unpackXY(x, y): """If x is a sequence and y is None, returns x[0], y[0]. Else, returns x, y. On functions that receive a pair of x,y coordinates, they can be passed as separate arguments, or as a single two-element sequence. """ if isinstance(x, str): # x parameter is the string of an ...
Returns the current xy coordinates of the mouse cursor as a two - integer tuple.
def position(x=None, y=None): """Returns the current xy coordinates of the mouse cursor as a two-integer tuple. Args: x (int, None, optional) - If not None, this argument overrides the x in the return value. y (int, None, optional) - If not None, this argument overrides the y in ...
Returns whether the given xy coordinates are on the screen or not.
def onScreen(x, y=None): """Returns whether the given xy coordinates are on the screen or not. Args: Either the arguments are two separate values, first arg for x and second for y, or there is a single argument of a sequence with two values, the first x and the second y. Example: ...
Performs releasing a mouse button up ( but not down beforehand ).
def mouseUp(x=None, y=None, button='left', duration=0.0, tween=linear, pause=None, _pause=True): """Performs releasing a mouse button up (but not down beforehand). The x and y parameters detail where the mouse event happens. If None, the current mouse position is used. If a float value, it is rounded down....
Performs pressing a mouse button down and then immediately releasing it.
def click(x=None, y=None, clicks=1, interval=0.0, button='left', duration=0.0, tween=linear, pause=None, _pause=True): """Performs pressing a mouse button down and then immediately releasing it. The x and y parameters detail where the mouse event happens. If None, the current mouse position is used. If a f...
Performs a right mouse button click.
def rightClick(x=None, y=None, duration=0.0, tween=linear, pause=None, _pause=True): """Performs a right mouse button click. This is a wrapper function for click('right', x, y). The x and y parameters detail where the mouse event happens. If None, the current mouse position is used. If a float value, ...
Performs a double click.
def doubleClick(x=None, y=None, interval=0.0, button='left', duration=0.0, tween=linear, pause=None, _pause=True): """Performs a double click. This is a wrapper function for click('left', x, y, 2, interval). The x and y parameters detail where the mouse event happens. If None, the current mouse positi...
Performs a scroll of the mouse scroll wheel.
def scroll(clicks, x=None, y=None, pause=None, _pause=True): """Performs a scroll of the mouse scroll wheel. Whether this is a vertical or horizontal scroll depends on the underlying operating system. The x and y parameters detail where the mouse event happens. If None, the current mouse position ...
Performs an explicitly horizontal scroll of the mouse scroll wheel if this is supported by the operating system. ( Currently just Linux. )
def hscroll(clicks, x=None, y=None, pause=None, _pause=True): """Performs an explicitly horizontal scroll of the mouse scroll wheel, if this is supported by the operating system. (Currently just Linux.) The x and y parameters detail where the mouse event happens. If None, the current mouse position is ...
Performs an explicitly vertical scroll of the mouse scroll wheel if this is supported by the operating system. ( Currently just Linux. )
def vscroll(clicks, x=None, y=None, pause=None, _pause=True): """Performs an explicitly vertical scroll of the mouse scroll wheel, if this is supported by the operating system. (Currently just Linux.) The x and y parameters detail where the mouse event happens. If None, the current mouse position is us...
Moves the mouse cursor to a point on the screen.
def moveTo(x=None, y=None, duration=0.0, tween=linear, pause=None, _pause=True): """Moves the mouse cursor to a point on the screen. The x and y parameters detail where the mouse event happens. If None, the current mouse position is used. If a float value, it is rounded down. If outside the boundaries ...
Moves the mouse cursor to a point on the screen relative to its current position.
def moveRel(xOffset=None, yOffset=None, duration=0.0, tween=linear, pause=None, _pause=True): """Moves the mouse cursor to a point on the screen, relative to its current position. The x and y parameters detail where the mouse event happens. If None, the current mouse position is used. If a float value,...
Performs a mouse drag ( mouse movement while a button is held down ) to a point on the screen.
def dragTo(x=None, y=None, duration=0.0, tween=linear, button='left', pause=None, _pause=True, mouseDownUp=True): """Performs a mouse drag (mouse movement while a button is held down) to a point on the screen. The x and y parameters detail where the mouse event happens. If None, the current mouse posit...
Performs a mouse drag ( mouse movement while a button is held down ) to a point on the screen relative to its current position.
def dragRel(xOffset=0, yOffset=0, duration=0.0, tween=linear, button='left', pause=None, _pause=True, mouseDownUp=True): """Performs a mouse drag (mouse movement while a button is held down) to a point on the screen, relative to its current position. The x and y parameters detail where the mouse event happ...
Handles the actual move or drag event since different platforms implement them differently.
def _mouseMoveDrag(moveOrDrag, x, y, xOffset, yOffset, duration, tween=linear, button=None): """Handles the actual move or drag event, since different platforms implement them differently. On Windows & Linux, a drag is a normal mouse move while a mouse button is held down. On OS X, a distinct "drag" ev...
Performs a keyboard key press without the release. This will put that key in a held down state.
def keyDown(key, pause=None, _pause=True): """Performs a keyboard key press without the release. This will put that key in a held down state. NOTE: For some reason, this does not seem to cause key repeats like would happen if a keyboard key was held down on a text field. Args: key (str): The...