INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
Update a document if it exist - insert it otherwise. | def upsert(self, document, cond):
"""
Update a document, if it exist - insert it otherwise.
Note: this will update *all* documents matching the query.
:param document: the document to insert or the fields to update
:param cond: which document to look for
:returns: a lis... |
Search for all documents matching a where cond. | def search(self, cond):
"""
Search for all documents matching a 'where' cond.
:param cond: the condition to check against
:type cond: Query
:returns: list of matching documents
:rtype: list[Element]
"""
if cond in self._query_cache:
return s... |
Get exactly one document specified by a query or and ID. | def get(self, cond=None, doc_id=None, eid=None):
"""
Get exactly one document specified by a query or and ID.
Returns ``None`` if the document doesn't exist
:param cond: the condition to check against
:type cond: Query
:param doc_id: the document's ID
:returns... |
Check wether the database contains a document matching a condition or an ID. | def contains(self, cond=None, doc_ids=None, eids=None):
"""
Check wether the database contains a document matching a condition or
an ID.
If ``eids`` is set, it checks if the db contains a document with one
of the specified.
:param cond: the condition use
:type c... |
Flush all unwritten data to disk. | def flush(self):
"""
Flush all unwritten data to disk.
"""
if self._cache_modified_count > 0:
self.storage.write(self.cache)
self._cache_modified_count = 0 |
Run a regex test against a dict value ( whole string has to match ). | def matches(self, regex, flags=0):
"""
Run a regex test against a dict value (whole string has to match).
>>> Query().f1.matches(r'^\w+$')
:param regex: The regular expression to use for matching
"""
return self._generate_test(
lambda value: re.match(regex, ... |
Run a regex test against a dict value ( only substring string has to match ). | def search(self, regex, flags=0):
"""
Run a regex test against a dict value (only substring string has to
match).
>>> Query().f1.search(r'^\w+$')
:param regex: The regular expression to use for matching
"""
return self._generate_test(
lambda value: r... |
Check if a condition is met by any document in a list where a condition can also be a sequence ( e. g. list ). | def any(self, cond):
"""
Check if a condition is met by any document in a list,
where a condition can also be a sequence (e.g. list).
>>> Query().f1.any(Query().f2 == 1)
Matches::
{'f1': [{'f2': 1}, {'f2': 0}]}
>>> Query().f1.any([1, 2, 3])
Matche... |
Check if the value is contained in a list or generator. | def one_of(self, items):
"""
Check if the value is contained in a list or generator.
>>> Query().f1.one_of(['value 1', 'value 2'])
:param items: The list of items to check with
"""
return self._generate_test(
lambda value: value in items,
('one_o... |
Sets an object attribute with the correct data type. | def setobjattr(obj, key, value):
"""Sets an object attribute with the correct data type."""
try:
setattr(obj, key, int(value))
except ValueError:
try:
setattr(obj, key, float(value))
except ValueError:
# string if not number
try:
se... |
Return the game file for a certain day matching certain criteria. | def get_scoreboard(year, month, day):
"""Return the game file for a certain day matching certain criteria."""
try:
data = urlopen(BASE_URL.format(year, month, day) + 'scoreboard.xml')
except HTTPError:
data = os.path.join(PWD, 'default.xml')
return data |
Return the box score file of a game with matching id. | def get_box_score(game_id):
"""Return the box score file of a game with matching id."""
year, month, day = get_date_from_game_id(game_id)
try:
return urlopen(GAME_URL.format(year, month, day, game_id,
'boxscore.xml'))
except HTTPError:
raise ValueEr... |
Return the innings file of a game with matching id. | def get_innings(game_id):
"""Return the innings file of a game with matching id."""
year, month, day = get_date_from_game_id(game_id)
try:
return urlopen(INNINGS_URL.format(year, month, day, game_id))
except HTTPError:
raise ValueError('Could not find a game with that id.') |
Return the standings file for current standings ( given current date ). | def get_standings(date):
"""Return the standings file for current standings (given current date)."""
try:
return urlopen(STANDINGS_URL.format(date.year,
date.strftime('%Y/%m/%d')))
except HTTPError:
ValueError('Could not find the standings file. '
... |
Return the historical standings file for specified date. | def get_historical_standings(date):
"""Return the historical standings file for specified date."""
try:
url = STANDINGS_HISTORICAL_URL.format(date.year,
date.strftime('%Y/%m/%d'))
return urlopen(url)
except HTTPError:
ValueError('Could no... |
Return the scoreboard information for games matching the parameters as a dictionary. | def scoreboard(year, month, day, home=None, away=None):
"""Return the scoreboard information for games matching the parameters
as a dictionary.
"""
# get data
data = mlbgame.data.get_scoreboard(year, month, day)
# parse data
parsed = etree.parse(data)
root = parsed.getroot()
games = ... |
Gets the box score information for the game with matching id. | def box_score(game_id):
"""Gets the box score information for the game with matching id."""
# get data
data = mlbgame.data.get_box_score(game_id)
# parse data
parsed = etree.parse(data)
root = parsed.getroot()
linescore = root.find('linescore')
result = dict()
result['game_id'] = gam... |
Massage runs in an inning to 0 if an empty string or key not found. Otherwise return the value | def value_to_int(attrib, key):
""" Massage runs in an inning to 0 if an empty string,
or key not found. Otherwise return the value """
val = attrib.get(key, 0)
if isinstance(val, str):
if val.isspace() or val == '':
return 0
return val |
Gets the overview information for the game with matching id. | def overview(game_id):
"""Gets the overview information for the game with matching id."""
output = {}
# get data
overview = mlbgame.data.get_overview(game_id)
# parse data
overview_root = etree.parse(overview).getroot()
try:
output = add_raw_box_score_attributes(output, game_id)
... |
Gets player/ coach/ umpire information for the game with matching id. | def players(game_id):
"""Gets player/coach/umpire information for the game with matching id."""
# get data
data = mlbgame.data.get_players(game_id)
# parse data
parsed = etree.parse(data)
root = parsed.getroot()
output = {}
output['game_id'] = game_id
# get player/coach data
fo... |
Print object as a scoreboard. | def print_scoreboard(self):
"""Print object as a scoreboard."""
output = ''
# parallel dictionaries with innings and scores
innings = []
away = []
home = []
for x in self:
innings.append(x['inning'])
away.append(x['away'])
home.... |
Return a list of games for a certain day. | def day(year, month, day, home=None, away=None):
"""Return a list of games for a certain day.
If the home and away team are the same,
it will return the game(s) for that team.
"""
# get the days per month
daysinmonth = calendar.monthrange(year, month)[1]
# do not even try to get data if day... |
Return a list of lists of games for multiple days. | def games(years, months=None, days=None, home=None, away=None):
"""Return a list of lists of games for multiple days.
If home and away are the same team, it will return all games for that team.
"""
# put in data if months and days are not specified
if months is None:
months = list(range(1, ... |
Return box score for game matching the game id. | def box_score(game_id):
"""Return box score for game matching the game id."""
# get box score data
data = mlbgame.game.box_score(game_id)
# create object with data
obj = mlbgame.game.GameBoxScore(data)
return obj |
Return dictionary of player stats for game matching the game id. | def player_stats(game_id):
"""Return dictionary of player stats for game matching the game id."""
# get information for that game
data = mlbgame.stats.player_stats(game_id)
return mlbgame.stats.Stats(data, game_id, True) |
Return dictionary of team stats for game matching the game id. | def team_stats(game_id):
"""Return dictionary of team stats for game matching the game id."""
# get data
data = mlbgame.stats.team_stats(game_id)
return mlbgame.stats.Stats(data, game_id, False) |
Return list of Inning objects for game matching the game id. | def game_events(game_id, innings_endpoint=False):
"""Return list of Inning objects for game matching the game id.
Using `inning_endpoints=True` will result in objects with
additional, undocumented data properties, but also objects
that may be missing properties expected by the user.
`innings_endpo... |
Return ImportantDates object that contains MLB important dates | def important_dates(year=None):
"""Return ImportantDates object that contains MLB important dates"""
year = datetime.now().year if not year else year
data = mlbgame.info.important_dates(year)
return mlbgame.info.ImportantDates(data) |
Return Roster object that contains roster info for a team | def roster(team_id):
"""Return Roster object that contains roster info for a team"""
data = mlbgame.info.roster(team_id)
return mlbgame.info.Roster(data) |
Return Standings object that contains standings info | def standings(date=datetime.now()):
"""Return Standings object that contains standings info
date should be a datetime object,
leave empty to get current standings
"""
data = mlbgame.info.standings(date)
return mlbgame.info.Standings(data) |
Return BroadcastInfo object that containts information about the television and radio broadcasts for the team_id and year | def broadcast_info(team_id, date=datetime.now()):
"""Return BroadcastInfo object that containts information
about the television and radio broadcasts for the team_id
and year"""
data = mlbgame.info.broadcast_info(team_id, date)
return [mlbgame.info.BroadcastInfo(x) for x in data] |
Return dictionary of individual stats of a game with matching id. | def player_stats(game_id):
"""Return dictionary of individual stats of a game with matching id.
The additional pitching/batting is mostly the same stats, except it
contains some useful stats such as groundouts/flyouts per pitcher
(go/ao). MLB decided to have two box score files, thus we return... |
Return team stats of a game with matching id. | def team_stats(game_id):
"""Return team stats of a game with matching id.
The additional pitching/batting is mostly the same stats. MLB decided
to have two box score files, thus we return the data from both.
"""
# get data from data module
box_score = mlbgame.data.get_box_score(game_id)
raw... |
Returns the xml object corresponding to the league | def __get_league_object():
"""Returns the xml object corresponding to the league
Only designed for internal use"""
# get data
data = mlbgame.data.get_properties()
# return league object
return etree.parse(data).getroot().find('leagues').find('league') |
Returns a dictionary of league information | def league_info():
"""Returns a dictionary of league information"""
league = __get_league_object()
output = {}
for x in league.attrib:
output[x] = league.attrib[x]
return output |
Returns a list of team information dictionaries | def team_info():
"""Returns a list of team information dictionaries"""
teams = __get_league_object().find('teams').findall('team')
output = []
for team in teams:
info = {}
for x in team.attrib:
info[x] = team.attrib[x]
output.append(info)
return output |
Returns a dictionary of important dates | def important_dates(year):
"""Returns a dictionary of important dates"""
output = {}
data = mlbgame.data.get_important_dates(year)
important_dates = etree.parse(data).getroot().\
find('queryResults').find('row')
try:
for x in important_dates.attrib:
output[x] = important_... |
Returns a dictionary of broadcast information for a given team during a given season | def broadcast_info(team_id, date=datetime.now()):
"""Returns a dictionary of broadcast information
for a given team during a given season"""
year = date.year
game_date = date.strftime('%Y-%m-%dT00:00:00')
data = mlbgame.data.get_broadcast_info(team_id, year)
schedule = json.loads(data.read().dec... |
Returns a dictionary of roster information for team id | def roster(team_id):
"""Returns a dictionary of roster information for team id"""
data = mlbgame.data.get_roster(team_id)
parsed = json.loads(data.read().decode('utf-8'))
players = parsed['roster_40']['queryResults']['row']
return {'players': players, 'team_id': team_id} |
Return a string for printing | def nice_output(self):
"""Return a string for printing"""
dates = [
str_format('Opening Day {0}: {1}.',
[self.year, date_format(self.first_date_seas)]),
str_format('Last day of the 1st half: {0}.',
[date_format(self.last_date_1sth)]),... |
Return dictionary of events for a game with matching id. | def game_events(game_id, innings_endpoint=False):
"""Return dictionary of events for a game with matching id."""
# get data from data module
if not innings_endpoint:
data = mlbgame.data.get_game_events(game_id)
endpoint = 'game_events'
else:
data = mlbgame.data.get_innings(game_i... |
Return a DHT platform interface for the currently detected platform. | def get_platform():
"""Return a DHT platform interface for the currently detected platform."""
plat = platform_detect.platform_detect()
if plat == platform_detect.RASPBERRY_PI:
# Check for version 1 or 2 of the pi.
version = platform_detect.pi_version()
if version == 1:
f... |
Read DHT sensor of specified sensor type ( DHT11 DHT22 or AM2302 ) on specified pin and return a tuple of humidity ( as a floating point value in percent ) and temperature ( as a floating point value in Celsius ). Note that because the sensor requires strict timing to read and Linux is not a real time OS a result is no... | def read(sensor, pin, platform=None):
"""Read DHT sensor of specified sensor type (DHT11, DHT22, or AM2302) on
specified pin and return a tuple of humidity (as a floating point value
in percent) and temperature (as a floating point value in Celsius). Note that
because the sensor requires strict timing t... |
Read DHT sensor of specified sensor type ( DHT11 DHT22 or AM2302 ) on specified pin and return a tuple of humidity ( as a floating point value in percent ) and temperature ( as a floating point value in Celsius ). Unlike the read function this read_retry function will attempt to read multiple times ( up to the specifie... | def read_retry(sensor, pin, retries=15, delay_seconds=2, platform=None):
"""Read DHT sensor of specified sensor type (DHT11, DHT22, or AM2302) on
specified pin and return a tuple of humidity (as a floating point value
in percent) and temperature (as a floating point value in Celsius).
Unlike the read fu... |
Connect to Google Docs spreadsheet and return the first worksheet. | def login_open_sheet(oauth_key_file, spreadsheet):
"""Connect to Google Docs spreadsheet and return the first worksheet."""
try:
scope = ['https://spreadsheets.google.com/feeds']
credentials = ServiceAccountCredentials.from_json_keyfile_name(oauth_key_file, scope)
gc = gspread.authorize... |
Detect if running on the Raspberry Pi or Beaglebone Black and return the platform type. Will return RASPBERRY_PI BEAGLEBONE_BLACK or UNKNOWN. | def platform_detect():
"""Detect if running on the Raspberry Pi or Beaglebone Black and return the
platform type. Will return RASPBERRY_PI, BEAGLEBONE_BLACK, or UNKNOWN."""
# Handle Raspberry Pi
pi = pi_version()
if pi is not None:
return RASPBERRY_PI
# Handle Beaglebone Black
# TO... |
Detect the revision number of a Raspberry Pi useful for changing functionality like default I2C bus based on revision. | def pi_revision():
"""Detect the revision number of a Raspberry Pi, useful for changing
functionality like default I2C bus based on revision."""
# Revision list available at: http://elinux.org/RPi_HardwareHistory#Board_Revision_History
with open('/proc/cpuinfo', 'r') as infile:
for line in infil... |
Handles getting the password | def handle_password(user, password): # pragma: no cover
""" Handles getting the password"""
if password is None:
try:
password = keyring.get_password("yagmail", user)
except NameError as e:
print(
"'keyring' cannot be loaded. Try 'pip install keyring' or ... |
Handle the targets addresses adding aliases when defined | def resolve_addresses(user, useralias, to, cc, bcc):
""" Handle the targets addresses, adding aliases when defined """
addresses = {"recipients": []}
if to is not None:
make_addr_alias_target(to, addresses, "To")
elif cc is not None and bcc is not None:
make_addr_alias_target([user, user... |
This is the function that is run from commandline with yagmail | def main():
""" This is the function that is run from commandline with `yagmail` """
import argparse
parser = argparse.ArgumentParser(description='Send a (g)mail with yagmail.')
subparsers = parser.add_subparsers(dest="command")
oauth = subparsers.add_parser('oauth')
oauth.add_argument(
... |
Prepare a MIME message | def prepare_message(user, useralias, addresses, subject, contents, attachments, headers, encoding, newline_to_break=True):
# check if closed!!!!!! XXX
""" Prepare a MIME message """
if isinstance(contents, text_type):
contents = [contents]
if isinstance(attachments, text_type):
attachmen... |
Note that this will only filter out syntax mistakes in emailaddresses. If a human would think it is probably a valid email it will most likely pass. However it could still very well be that the actual emailaddress has simply not be claimed by anyone ( so then this function fails to devalidate ). | def validate_email_with_regex(email_address):
"""
Note that this will only filter out syntax mistakes in emailaddresses.
If a human would think it is probably a valid email, it will most likely pass.
However, it could still very well be that the actual emailaddress has simply
not be claimed by anyon... |
This function allows to change the logging backend either output or file as backend It also allows to set the logging level ( whether to display only critical/ error/ info/ debug. for example:: | def set_logging(self, log_level=logging.ERROR, file_path_name=None):
"""
This function allows to change the logging backend, either output or file as backend
It also allows to set the logging level (whether to display only critical/error/info/debug.
for example::
yag = yagma... |
Use this to send an email with gmail | def send(
self,
to=None,
subject=None,
contents=None,
attachments=None,
cc=None,
bcc=None,
preview_only=False,
headers=None,
newline_to_break=True,
):
""" Use this to send an email with gmail"""
self.login()
reci... |
Emails that were not being able to send will be stored in: attr: self. unsent. Use this function to attempt to send these again | def send_unsent(self):
"""
Emails that were not being able to send will be stored in :attr:`self.unsent`.
Use this function to attempt to send these again
"""
for i in range(len(self.unsent)):
recipients, msg_string = self.unsent.pop(i)
self._attempt_send(... |
Close the connection to the SMTP server | def close(self):
""" Close the connection to the SMTP server """
self.is_closed = True
try:
self.smtp.quit()
except (TypeError, AttributeError, smtplib.SMTPServerDisconnected):
pass |
Login to the SMTP server using password. login only needs to be manually run when the connection to the SMTP server was closed by the user. | def _login(self, password):
"""
Login to the SMTP server using password. `login` only needs to be manually run when the
connection to the SMTP server was closed by the user.
"""
self.smtp = self.connection(self.host, self.port, **self.kwargs)
self.smtp.set_debuglevel(self... |
Start the server. | def start(self):
"""
Start the server.
"""
plugins = voltron.plugin.pm.web_plugins
self.app = DispatcherMiddleware(
RootFlaskApp(),
{
"/api": APIFlaskApp(server=self),
"/view": SharedDataMiddleware(
None,... |
Stop the server. | def stop(self):
"""
Stop the server.
"""
log.debug("Stopping listeners")
self.queue_lock.acquire()
for s in self.listeners:
log.debug("Stopping {}".format(s))
s.shutdown()
s.socket.close()
self.cancel_queue()
for t in se... |
Cancel all requests in the queue so we can exit. | def cancel_queue(self):
"""
Cancel all requests in the queue so we can exit.
"""
q = list(self.queue)
self.queue = []
log.debug("Canceling requests: {}".format(q))
for req in q:
req.response = APIServerNotRunningErrorResponse()
for req in q:
... |
Dispatch any queued requests. | def dispatch_queue(self):
"""
Dispatch any queued requests.
Called by the debugger when it stops.
"""
self.queue_lock.acquire()
q = list(self.queue)
self.queue = []
self.queue_lock.release()
log.debug("Dispatching requests: {}".format(q))
... |
Dispatch a request object. | def dispatch_request(self, req):
"""
Dispatch a request object.
"""
log.debug("Dispatching request: {}".format(str(req)))
# make sure it's valid
res = None
try:
req.validate()
except MissingFieldError as e:
res = APIMissingFieldErr... |
Send a request to the server. | def send_request(self, request):
"""
Send a request to the server.
`request` is an APIRequest subclass.
Returns an APIResponse or subclass instance. If an error occurred, it
will be an APIErrorResponse, if the request was successful it will be
the plugin's specified res... |
Send a set of requests. | def send_requests(self, *args):
"""
Send a set of requests.
Each request is sent over its own connection and the function will
return when all the requests have been fulfilled.
"""
threads = [ClientThread(self, req) for req in args]
for t in threads:
... |
Create and send a request. | def perform_request(self, request_type, *args, **kwargs):
"""
Create and send a request.
`request_type` is the request type (string). This is used to look up a
plugin, whose request class is instantiated and passed the remaining
arguments passed to this function.
"""
... |
Update the display | def update(self):
"""
Update the display
"""
# build requests for this iteration
reqs = self.build_requests()
for r in reqs:
r.block = self.block
results = self.send_requests(*reqs)
# call callback with the results
self.callback(result... |
Run the client in a loop calling the callback each time the debugger stops. | def run(self, build_requests=None, callback=None):
"""
Run the client in a loop, calling the callback each time the debugger
stops.
"""
if callback:
self.callback = callback
if build_requests:
self.build_requests = build_requests
def norma... |
Run the client using a background thread. | def start(self, build_requests=None, callback=None):
"""
Run the client using a background thread.
"""
if callback:
self.callback = callback
if build_requests:
self.build_requests = build_requests
# spin off requester thread
self.sw = thre... |
Decorator to designate an API method applicable only to server - side instances. | def server_side(func):
"""
Decorator to designate an API method applicable only to server-side
instances.
This allows us to use the same APIRequest and APIResponse subclasses on the
client and server sides without too much confusion.
"""
def inner(*args, **kwargs):
if args and hasat... |
Decorator to designate an API method applicable only to client - side instances. | def client_side(func):
"""
Decorator to designate an API method applicable only to client-side
instances.
This allows us to use the same APIRequest and APIResponse subclasses on the
client and server sides without too much confusion.
"""
def inner(*args, **kwargs):
if args and hasat... |
Return a transmission - safe dictionary representation of the API message properties. | def to_dict(self):
"""
Return a transmission-safe dictionary representation of the API message properties.
"""
d = {field: getattr(self, field) for field in self._top_fields if hasattr(self, field)}
# set values of data fields
d['data'] = {}
for field in self._fi... |
Initialise an API message from a transmission - safe dictionary. | def from_dict(self, d):
"""
Initialise an API message from a transmission-safe dictionary.
"""
for key in d:
if key == 'data':
for dkey in d['data']:
if dkey in self._encode_fields:
setattr(self, str(dkey), base64.b6... |
Initialise an API message from a JSON representation. | def from_json(self, data):
"""
Initialise an API message from a JSON representation.
"""
try:
d = json.loads(data)
except ValueError:
raise InvalidMessageException()
self.from_dict(d) |
Validate the message. | def validate(self):
"""
Validate the message.
Ensure all the required fields are present and not None.
"""
required_fields = list(filter(lambda x: self._fields[x], self._fields.keys()))
for field in (self._top_fields + required_fields):
if not hasattr(self, f... |
Wait for the request to be dispatched. | def wait(self):
"""
Wait for the request to be dispatched.
"""
self.wait_event = threading.Event()
timeout = int(self.timeout) if self.timeout else None
self.timed_out = not self.wait_event.wait(timeout) |
A decorator that ensures that the specified target_id exists and is valid. | def validate_target(func, *args, **kwargs):
"""
A decorator that ensures that the specified target_id exists and
is valid.
Expects the target ID to be either the 'target_id' param in kwargs,
or the first positional parameter.
Raises a NoSuchTargetException if the target does not exist.
"""... |
A decorator that raises an exception if the specified target is busy. | def validate_busy(func, *args, **kwargs):
"""
A decorator that raises an exception if the specified target is busy.
Expects the target ID to be either the 'target_id' param in kwargs,
or the first positional parameter.
Raises a TargetBusyException if the target does not exist.
"""
def inne... |
A decorator that acquires a lock before accessing the debugger to avoid API locking related errors with the debugger host. | def lock_host(func, *args, **kwargs):
"""
A decorator that acquires a lock before accessing the debugger to
avoid API locking related errors with the debugger host.
"""
def inner(self, *args, **kwargs):
self.host_lock.acquire()
try:
res = func(self, *args, **kwargs)
... |
Returns True or False indicating whether or not the specified target is present and valid. | def target_exists(self, target_id=0):
"""
Returns True or False indicating whether or not the specified
target is present and valid.
`target_id` is a target ID (or None for the first target)
"""
try:
target = self._target(target_id=target_id)
except E... |
Returns True or False indicating whether or not the specified target is present and valid. | def target_is_valid(self, target_id=0):
"""
Returns True or False indicating whether or not the specified
target is present and valid.
`target_id` is a target ID (or None for the first target)
"""
try:
target = self._target(target_id=target_id)
except... |
Returns True or False indicating whether or not the specified target is busy. | def target_is_busy(self, target_id=0):
"""
Returns True or False indicating whether or not the specified
target is busy.
`target_id` is a target ID (or None for the first target)
"""
try:
target = self._target(target_id=target_id)
except:
... |
Remove a listener. | def remove_listener(self, callback):
"""
Remove a listener.
"""
listeners = filter(lambda x: x['callback'] == callback, self.listeners)
for l in listeners:
self.listeners.remove(l) |
Disassemble with capstone. | def disassemble_capstone(self, target_id=0, address=None, count=None):
"""
Disassemble with capstone.
"""
target = self._target(target_id)
if not address:
pc_name, address = self.pc()
mem = self.memory(address, count * 16, target_id=target_id)
md = c... |
Create an API request. | def api_request(request, *args, **kwargs):
"""
Create an API request.
`request_type` is the request type (string). This is used to look up a
plugin, whose request class is instantiated and passed the remaining
arguments passed to this function.
"""
plugin = pm.api_plugin_for_request(request... |
Register a new plugin with the PluginManager. | def register_plugin(self, plugin):
"""
Register a new plugin with the PluginManager.
`plugin` is a subclass of scruffy's Plugin class.
This is called by __init__(), but may also be called by the debugger
host to load a specific plugin at runtime.
"""
if hasattr(... |
Validate an API plugin ensuring it is an API plugin and has the necessary fields present. | def valid_api_plugin(self, plugin):
"""
Validate an API plugin, ensuring it is an API plugin and has the
necessary fields present.
`plugin` is a subclass of scruffy's Plugin class.
"""
if (issubclass(plugin, APIPlugin) and
hasattr(plugin, 'plugin_type')... |
Validate a debugger plugin ensuring it is a debugger plugin and has the necessary fields present. | def valid_debugger_plugin(self, plugin):
"""
Validate a debugger plugin, ensuring it is a debugger plugin and has
the necessary fields present.
`plugin` is a subclass of scruffy's Plugin class.
"""
if (issubclass(plugin, DebuggerAdaptorPlugin) and
hasattr(plu... |
Validate a view plugin ensuring it is a view plugin and has the necessary fields present. | def valid_view_plugin(self, plugin):
"""
Validate a view plugin, ensuring it is a view plugin and has the
necessary fields present.
`plugin` is a subclass of scruffy's Plugin class.
"""
if (issubclass(plugin, ViewPlugin) and
hasattr(plugin, 'plugin_type'... |
Validate a web plugin ensuring it is a web plugin and has the necessary fields present. | def valid_web_plugin(self, plugin):
"""
Validate a web plugin, ensuring it is a web plugin and has the
necessary fields present.
`plugin` is a subclass of scruffy's Plugin class.
"""
if (issubclass(plugin, WebPlugin) and
hasattr(plugin, 'plugin_type') ... |
Validate a command plugin ensuring it is a command plugin and has the necessary fields present. | def valid_command_plugin(self, plugin):
"""
Validate a command plugin, ensuring it is a command plugin and has the
necessary fields present.
`plugin` is a subclass of scruffy's Plugin class.
"""
if (issubclass(plugin, CommandPlugin) and
hasattr(plugin, 'plu... |
Try to detect the two most common installation errors: | def check_install():
"""
Try to detect the two most common installation errors:
1. Installing on macOS using a Homebrew version of Python
2. Installing on Linux using Python 2 when GDB is linked with Python 3
"""
if platform.system() == 'Darwin' and sys.executable != '/usr/bin/python':
... |
Run the view event loop. | def run(self):
"""
Run the view event loop.
"""
def render(results=[], error=None):
if len(results) and not results[0].timed_out:
self.render(results)
elif error:
self.do_render(error=error)
# start the client
self.... |
Handle a keypress. Concrete subclasses can implement this method if custom keypresses need to be handled other than for exit and scrolling. | def handle_key(self, key):
"""
Handle a keypress. Concrete subclasses can implement this method if
custom keypresses need to be handled other than for exit and scrolling.
"""
try:
func = None
if key.is_sequence:
try:
fun... |
Handle reception of a new CastStatus. | def new_cast_status(self, cast_status):
"""Handle reception of a new CastStatus."""
casts = self._casts
group_members = self._mz.members
for member_uuid in group_members:
if member_uuid not in casts:
continue
for listener in list(casts[member_uuid]... |
Handle reception of a new MediaStatus. | def new_media_status(self, media_status):
"""Handle reception of a new MediaStatus."""
casts = self._casts
group_members = self._mz.members
for member_uuid in group_members:
if member_uuid not in casts:
continue
for listener in list(casts[member_uu... |
Handle reception of a new ConnectionStatus. | def new_connection_status(self, conn_status):
"""Handle reception of a new ConnectionStatus."""
if conn_status.status == CONNECTION_STATUS_CONNECTED:
self._mz.update_members()
if (conn_status.status == CONNECTION_STATUS_DISCONNECTED or
conn_status.status == CONNECTION... |
Handle added audio group member. | def multizone_member_added(self, member_uuid):
"""Handle added audio group member."""
casts = self._casts
if member_uuid not in casts:
casts[member_uuid] = {'listeners': [],
'groups': set()}
casts[member_uuid]['groups'].add(self._group_uuid)
... |
Handle removed audio group member. | def multizone_member_removed(self, member_uuid):
"""Handle removed audio group member."""
casts = self._casts
if member_uuid not in casts:
casts[member_uuid] = {'listeners': [], 'groups': set()}
casts[member_uuid]['groups'].discard(self._group_uuid)
for listener in li... |
Start managing a group | def add_multizone(self, group_cast):
""" Start managing a group """
self._groups[str(group_cast.uuid)] = {
'chromecast': group_cast,
'listener': Listener(group_cast, self._casts),
'members': set()} |
Stop managing a group | def remove_multizone(self, group_uuid):
""" Stop managing a group """
group_uuid = str(group_uuid)
group = self._groups.pop(group_uuid, None)
# Inform all group members that they are no longer members
if group is not None:
group['listener']._mz.reset_members() # noqa... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.