repository_name
stringlengths 5
67
| func_path_in_repository
stringlengths 4
234
| func_name
stringlengths 0
314
| whole_func_string
stringlengths 52
3.87M
| language
stringclasses 6
values | func_code_string
stringlengths 52
3.87M
| func_documentation_string
stringlengths 1
47.2k
| func_code_url
stringlengths 85
339
|
---|---|---|---|---|---|---|---|
yougov/pmxbot | pmxbot/commands.py | urbandict | def urbandict(rest):
"Define a word with Urban Dictionary"
word = rest.strip()
definition = util.urban_lookup(word)
if not definition:
return "Arg! I didn't find a definition for that."
return 'Urban Dictionary says {word}: {definition}'.format(**locals()) | python | def urbandict(rest):
"Define a word with Urban Dictionary"
word = rest.strip()
definition = util.urban_lookup(word)
if not definition:
return "Arg! I didn't find a definition for that."
return 'Urban Dictionary says {word}: {definition}'.format(**locals()) | Define a word with Urban Dictionary | https://github.com/yougov/pmxbot/blob/5da84a3258a0fd73cb35b60e39769a5d7bfb2ba7/pmxbot/commands.py#L732-L738 |
yougov/pmxbot | pmxbot/commands.py | acit | def acit(rest):
"Look up an acronym"
word = rest.strip()
res = util.lookup_acronym(word)
if res is None:
return "Arg! I couldn't expand that..."
else:
return ' | '.join(res) | python | def acit(rest):
"Look up an acronym"
word = rest.strip()
res = util.lookup_acronym(word)
if res is None:
return "Arg! I couldn't expand that..."
else:
return ' | '.join(res) | Look up an acronym | https://github.com/yougov/pmxbot/blob/5da84a3258a0fd73cb35b60e39769a5d7bfb2ba7/pmxbot/commands.py#L742-L749 |
yougov/pmxbot | pmxbot/commands.py | fight | def fight(nick, rest):
"Pit two sworn enemies against each other (separate with 'vs.')"
if rest:
vtype = random.choice(phrases.fight_victories)
fdesc = random.choice(phrases.fight_descriptions)
# valid separators are vs., v., and vs
pattern = re.compile('(.*) (?:vs[.]?|v[.]) (.*)')
matcher = pattern.match(rest)
if not matcher:
karma.Karma.store.change(nick.lower(), -1)
args = (vtype, nick, fdesc)
return "/me %s %s in %s for bad protocol." % args
contenders = [c.strip() for c in matcher.groups()]
random.shuffle(contenders)
winner, loser = contenders
karma.Karma.store.change(winner, 1)
karma.Karma.store.change(loser, -1)
return "%s %s %s in %s." % (winner, vtype, loser, fdesc) | python | def fight(nick, rest):
"Pit two sworn enemies against each other (separate with 'vs.')"
if rest:
vtype = random.choice(phrases.fight_victories)
fdesc = random.choice(phrases.fight_descriptions)
# valid separators are vs., v., and vs
pattern = re.compile('(.*) (?:vs[.]?|v[.]) (.*)')
matcher = pattern.match(rest)
if not matcher:
karma.Karma.store.change(nick.lower(), -1)
args = (vtype, nick, fdesc)
return "/me %s %s in %s for bad protocol." % args
contenders = [c.strip() for c in matcher.groups()]
random.shuffle(contenders)
winner, loser = contenders
karma.Karma.store.change(winner, 1)
karma.Karma.store.change(loser, -1)
return "%s %s %s in %s." % (winner, vtype, loser, fdesc) | Pit two sworn enemies against each other (separate with 'vs.') | https://github.com/yougov/pmxbot/blob/5da84a3258a0fd73cb35b60e39769a5d7bfb2ba7/pmxbot/commands.py#L753-L770 |
yougov/pmxbot | pmxbot/commands.py | progress | def progress(rest):
"Display the progress of something: start|end|percent"
if rest:
left, right, amount = [piece.strip() for piece in rest.split('|')]
ticks = min(int(round(float(amount) / 10)), 10)
bar = "=" * ticks
return "%s [%-10s] %s" % (left, bar, right) | python | def progress(rest):
"Display the progress of something: start|end|percent"
if rest:
left, right, amount = [piece.strip() for piece in rest.split('|')]
ticks = min(int(round(float(amount) / 10)), 10)
bar = "=" * ticks
return "%s [%-10s] %s" % (left, bar, right) | Display the progress of something: start|end|percent | https://github.com/yougov/pmxbot/blob/5da84a3258a0fd73cb35b60e39769a5d7bfb2ba7/pmxbot/commands.py#L774-L780 |
yougov/pmxbot | pmxbot/commands.py | nastygram | def nastygram(nick, rest):
"""
A random passive-agressive comment, optionally directed toward
some(one|thing).
"""
recipient = ""
if rest:
recipient = rest.strip()
karma.Karma.store.change(recipient, -1)
return util.passagg(recipient, nick.lower()) | python | def nastygram(nick, rest):
"""
A random passive-agressive comment, optionally directed toward
some(one|thing).
"""
recipient = ""
if rest:
recipient = rest.strip()
karma.Karma.store.change(recipient, -1)
return util.passagg(recipient, nick.lower()) | A random passive-agressive comment, optionally directed toward
some(one|thing). | https://github.com/yougov/pmxbot/blob/5da84a3258a0fd73cb35b60e39769a5d7bfb2ba7/pmxbot/commands.py#L784-L793 |
yougov/pmxbot | pmxbot/commands.py | meaculpa | def meaculpa(nick, rest):
"Sincerely apologize"
if rest:
rest = rest.strip()
if rest:
return random.choice(phrases.direct_apologies) % dict(a=nick, b=rest)
else:
return random.choice(phrases.apologies) % dict(a=nick) | python | def meaculpa(nick, rest):
"Sincerely apologize"
if rest:
rest = rest.strip()
if rest:
return random.choice(phrases.direct_apologies) % dict(a=nick, b=rest)
else:
return random.choice(phrases.apologies) % dict(a=nick) | Sincerely apologize | https://github.com/yougov/pmxbot/blob/5da84a3258a0fd73cb35b60e39769a5d7bfb2ba7/pmxbot/commands.py#L835-L843 |
yougov/pmxbot | pmxbot/commands.py | version | def version(rest):
"Get the version of pmxbot or one of its plugins"
pkg = rest.strip() or 'pmxbot'
if pkg.lower() == 'python':
return sys.version.split()[0]
return importlib_metadata.version(pkg) | python | def version(rest):
"Get the version of pmxbot or one of its plugins"
pkg = rest.strip() or 'pmxbot'
if pkg.lower() == 'python':
return sys.version.split()[0]
return importlib_metadata.version(pkg) | Get the version of pmxbot or one of its plugins | https://github.com/yougov/pmxbot/blob/5da84a3258a0fd73cb35b60e39769a5d7bfb2ba7/pmxbot/commands.py#L847-L852 |
yougov/pmxbot | pmxbot/commands.py | timezone | def timezone(rest):
"""Convert date between timezones.
Example:
> !tz 11:00am UTC in PDT
11:00 UTC -> 4:00 PDT
UTC is implicit
> !tz 11:00am in PDT
11:00 UTC -> 4:00 PDT
> !tz 11:00am PDT
11:00 PDT -> 18:00 UTC
"""
if ' in ' in rest:
dstr, tzname = rest.split(' in ', 1)
else:
dstr, tzname = rest, 'UTC'
tzobj = TZINFOS[tzname.strip()]
dt = dateutil.parser.parse(dstr, tzinfos=TZINFOS)
if dt.tzinfo is None:
dt = pytz.UTC.localize(dt)
res = dt.astimezone(tzobj)
return '{} {} -> {} {}'.format(
dt.strftime('%H:%M'), dt.tzname() or dt.strftime('%z'),
res.strftime('%H:%M'), tzname) | python | def timezone(rest):
"""Convert date between timezones.
Example:
> !tz 11:00am UTC in PDT
11:00 UTC -> 4:00 PDT
UTC is implicit
> !tz 11:00am in PDT
11:00 UTC -> 4:00 PDT
> !tz 11:00am PDT
11:00 PDT -> 18:00 UTC
"""
if ' in ' in rest:
dstr, tzname = rest.split(' in ', 1)
else:
dstr, tzname = rest, 'UTC'
tzobj = TZINFOS[tzname.strip()]
dt = dateutil.parser.parse(dstr, tzinfos=TZINFOS)
if dt.tzinfo is None:
dt = pytz.UTC.localize(dt)
res = dt.astimezone(tzobj)
return '{} {} -> {} {}'.format(
dt.strftime('%H:%M'), dt.tzname() or dt.strftime('%z'),
res.strftime('%H:%M'), tzname) | Convert date between timezones.
Example:
> !tz 11:00am UTC in PDT
11:00 UTC -> 4:00 PDT
UTC is implicit
> !tz 11:00am in PDT
11:00 UTC -> 4:00 PDT
> !tz 11:00am PDT
11:00 PDT -> 18:00 UTC | https://github.com/yougov/pmxbot/blob/5da84a3258a0fd73cb35b60e39769a5d7bfb2ba7/pmxbot/commands.py#L898-L927 |
yougov/pmxbot | pmxbot/storage.py | SelectableStorage.finalize | def finalize(cls):
"Delete the various persistence objects"
for finalizer in cls._finalizers:
try:
finalizer()
except Exception:
log.exception("Error in finalizer %s", finalizer) | python | def finalize(cls):
"Delete the various persistence objects"
for finalizer in cls._finalizers:
try:
finalizer()
except Exception:
log.exception("Error in finalizer %s", finalizer) | Delete the various persistence objects | https://github.com/yougov/pmxbot/blob/5da84a3258a0fd73cb35b60e39769a5d7bfb2ba7/pmxbot/storage.py#L51-L57 |
yougov/pmxbot | pmxbot/system.py | help | def help(rest):
"""Help (this command)"""
rs = rest.strip()
if rs:
# give help for matching commands
for handler in Handler._registry:
if handler.name == rs.lower():
yield '!%s: %s' % (handler.name, handler.doc)
break
else:
yield "command not found"
return
# give help for all commands
def mk_entries():
handlers = (
handler
for handler in Handler._registry
if type(handler) is pmxbot.core.CommandHandler
)
handlers = sorted(handlers, key=operator.attrgetter('name'))
for handler in handlers:
res = "!" + handler.name
if handler.aliases:
alias_names = (alias.name for alias in handler.aliases)
res += " (%s)" % ', '.join(alias_names)
yield res
o = io.StringIO(" ".join(mk_entries()))
more = o.read(160)
while more:
yield more
time.sleep(0.3)
more = o.read(160) | python | def help(rest):
"""Help (this command)"""
rs = rest.strip()
if rs:
# give help for matching commands
for handler in Handler._registry:
if handler.name == rs.lower():
yield '!%s: %s' % (handler.name, handler.doc)
break
else:
yield "command not found"
return
# give help for all commands
def mk_entries():
handlers = (
handler
for handler in Handler._registry
if type(handler) is pmxbot.core.CommandHandler
)
handlers = sorted(handlers, key=operator.attrgetter('name'))
for handler in handlers:
res = "!" + handler.name
if handler.aliases:
alias_names = (alias.name for alias in handler.aliases)
res += " (%s)" % ', '.join(alias_names)
yield res
o = io.StringIO(" ".join(mk_entries()))
more = o.read(160)
while more:
yield more
time.sleep(0.3)
more = o.read(160) | Help (this command) | https://github.com/yougov/pmxbot/blob/5da84a3258a0fd73cb35b60e39769a5d7bfb2ba7/pmxbot/system.py#L17-L49 |
yougov/pmxbot | pmxbot/web/viewer.py | pmon | def pmon(month):
"""
P the month
>>> print(pmon('2012-08'))
August, 2012
"""
year, month = month.split('-')
return '{month_name}, {year}'.format(
month_name=calendar.month_name[int(month)],
year=year,
) | python | def pmon(month):
"""
P the month
>>> print(pmon('2012-08'))
August, 2012
"""
year, month = month.split('-')
return '{month_name}, {year}'.format(
month_name=calendar.month_name[int(month)],
year=year,
) | P the month
>>> print(pmon('2012-08'))
August, 2012 | https://github.com/yougov/pmxbot/blob/5da84a3258a0fd73cb35b60e39769a5d7bfb2ba7/pmxbot/web/viewer.py#L54-L65 |
yougov/pmxbot | pmxbot/web/viewer.py | pday | def pday(dayfmt):
"""
P the day
>>> print(pday('2012-08-24'))
Friday the 24th
"""
year, month, day = map(int, dayfmt.split('-'))
return '{day} the {number}'.format(
day=calendar.day_name[calendar.weekday(year, month, day)],
number=inflect.engine().ordinal(day),
) | python | def pday(dayfmt):
"""
P the day
>>> print(pday('2012-08-24'))
Friday the 24th
"""
year, month, day = map(int, dayfmt.split('-'))
return '{day} the {number}'.format(
day=calendar.day_name[calendar.weekday(year, month, day)],
number=inflect.engine().ordinal(day),
) | P the day
>>> print(pday('2012-08-24'))
Friday the 24th | https://github.com/yougov/pmxbot/blob/5da84a3258a0fd73cb35b60e39769a5d7bfb2ba7/pmxbot/web/viewer.py#L68-L80 |
yougov/pmxbot | pmxbot/web/viewer.py | patch_compat | def patch_compat(config):
"""
Support older config values.
"""
if 'web_host' in config:
config['host'] = config.pop('web_host')
if 'web_port' in config:
config['port'] = config.pop('web_port') | python | def patch_compat(config):
"""
Support older config values.
"""
if 'web_host' in config:
config['host'] = config.pop('web_host')
if 'web_port' in config:
config['port'] = config.pop('web_port') | Support older config values. | https://github.com/yougov/pmxbot/blob/5da84a3258a0fd73cb35b60e39769a5d7bfb2ba7/pmxbot/web/viewer.py#L305-L312 |
yougov/pmxbot | pmxbot/web/viewer.py | resolve_file | def resolve_file(mgr, filename):
"""
Given a file manager (ExitStack), load the filename
and set the exit stack to clean up. See
https://importlib-resources.readthedocs.io/en/latest/migration.html#pkg-resources-resource-filename
for more details.
"""
path = importlib_resources.path('pmxbot.web.templates', filename)
return str(mgr.enter_context(path)) | python | def resolve_file(mgr, filename):
"""
Given a file manager (ExitStack), load the filename
and set the exit stack to clean up. See
https://importlib-resources.readthedocs.io/en/latest/migration.html#pkg-resources-resource-filename
for more details.
"""
path = importlib_resources.path('pmxbot.web.templates', filename)
return str(mgr.enter_context(path)) | Given a file manager (ExitStack), load the filename
and set the exit stack to clean up. See
https://importlib-resources.readthedocs.io/en/latest/migration.html#pkg-resources-resource-filename
for more details. | https://github.com/yougov/pmxbot/blob/5da84a3258a0fd73cb35b60e39769a5d7bfb2ba7/pmxbot/web/viewer.py#L339-L347 |
yougov/pmxbot | pmxbot/web/viewer.py | ChannelPage.date_key | def date_key(cls, month_string):
"""
Return a key suitable for sorting by month.
>>> k1 = ChannelPage.date_key('September, 2012')
>>> k2 = ChannelPage.date_key('August, 2013')
>>> k2 > k1
True
"""
month, year = month_string.split(',')
month_ord = cls.month_ordinal[month]
return year, month_ord | python | def date_key(cls, month_string):
"""
Return a key suitable for sorting by month.
>>> k1 = ChannelPage.date_key('September, 2012')
>>> k2 = ChannelPage.date_key('August, 2013')
>>> k2 > k1
True
"""
month, year = month_string.split(',')
month_ord = cls.month_ordinal[month]
return year, month_ord | Return a key suitable for sorting by month.
>>> k1 = ChannelPage.date_key('September, 2012')
>>> k2 = ChannelPage.date_key('August, 2013')
>>> k2 > k1
True | https://github.com/yougov/pmxbot/blob/5da84a3258a0fd73cb35b60e39769a5d7bfb2ba7/pmxbot/web/viewer.py#L110-L121 |
yougov/pmxbot | pmxbot/web/viewer.py | LegacyPage.forward | def forward(self, channel, date_s, fragment):
"""
Given an HREF in the legacy timezone, redirect to an href for UTC.
"""
time_s, sep, nick = fragment.rpartition('.')
time = datetime.datetime.strptime(time_s, '%H.%M.%S')
date = datetime.datetime.strptime(date_s, '%Y-%m-%d')
dt = datetime.datetime.combine(date, time.time())
loc_dt = self.timezone.localize(dt)
utc_dt = loc_dt.astimezone(pytz.utc)
url_tmpl = '/day/{channel}/{target_date}#{target_time}.{nick}'
url = url_tmpl.format(
target_date=utc_dt.date().isoformat(),
target_time=utc_dt.time().strftime('%H.%M.%S'),
**locals()
)
raise cherrypy.HTTPRedirect(url, 301) | python | def forward(self, channel, date_s, fragment):
"""
Given an HREF in the legacy timezone, redirect to an href for UTC.
"""
time_s, sep, nick = fragment.rpartition('.')
time = datetime.datetime.strptime(time_s, '%H.%M.%S')
date = datetime.datetime.strptime(date_s, '%Y-%m-%d')
dt = datetime.datetime.combine(date, time.time())
loc_dt = self.timezone.localize(dt)
utc_dt = loc_dt.astimezone(pytz.utc)
url_tmpl = '/day/{channel}/{target_date}#{target_time}.{nick}'
url = url_tmpl.format(
target_date=utc_dt.date().isoformat(),
target_time=utc_dt.time().strftime('%H.%M.%S'),
**locals()
)
raise cherrypy.HTTPRedirect(url, 301) | Given an HREF in the legacy timezone, redirect to an href for UTC. | https://github.com/yougov/pmxbot/blob/5da84a3258a0fd73cb35b60e39769a5d7bfb2ba7/pmxbot/web/viewer.py#L256-L272 |
yougov/pmxbot | pmxbot/logging.py | parse_date | def parse_date(record):
"Parse a date from sqlite. Assumes the date is in US/Pacific time zone."
dt = record.pop('datetime')
fmts = [
'%Y-%m-%d %H:%M:%S.%f',
'%Y-%m-%d %H:%M:%S',
]
for fmt in fmts:
try:
dt = datetime.datetime.strptime(dt, fmt)
break
except ValueError:
pass
else:
raise
tz = pytz.timezone('US/Pacific')
loc_dt = tz.localize(dt)
record['datetime'] = loc_dt
return record | python | def parse_date(record):
"Parse a date from sqlite. Assumes the date is in US/Pacific time zone."
dt = record.pop('datetime')
fmts = [
'%Y-%m-%d %H:%M:%S.%f',
'%Y-%m-%d %H:%M:%S',
]
for fmt in fmts:
try:
dt = datetime.datetime.strptime(dt, fmt)
break
except ValueError:
pass
else:
raise
tz = pytz.timezone('US/Pacific')
loc_dt = tz.localize(dt)
record['datetime'] = loc_dt
return record | Parse a date from sqlite. Assumes the date is in US/Pacific time zone. | https://github.com/yougov/pmxbot/blob/5da84a3258a0fd73cb35b60e39769a5d7bfb2ba7/pmxbot/logging.py#L219-L237 |
yougov/pmxbot | pmxbot/logging.py | strike | def strike(channel, nick, rest):
"Strike last <n> statements from the record"
yield NoLog
rest = rest.strip()
if not rest:
count = 1
else:
if not rest.isdigit():
yield "Strike how many? Argument must be a positive integer."
raise StopIteration
count = int(rest)
try:
struck = Logger.store.strike(channel, nick, count)
tmpl = (
"Isn't undo great? Last %d statement%s "
"by %s were stricken from the record."
)
yield tmpl % (struck, 's' if struck > 1 else '', nick)
except Exception:
traceback.print_exc()
yield "Hmm.. I didn't find anything of yours to strike!" | python | def strike(channel, nick, rest):
"Strike last <n> statements from the record"
yield NoLog
rest = rest.strip()
if not rest:
count = 1
else:
if not rest.isdigit():
yield "Strike how many? Argument must be a positive integer."
raise StopIteration
count = int(rest)
try:
struck = Logger.store.strike(channel, nick, count)
tmpl = (
"Isn't undo great? Last %d statement%s "
"by %s were stricken from the record."
)
yield tmpl % (struck, 's' if struck > 1 else '', nick)
except Exception:
traceback.print_exc()
yield "Hmm.. I didn't find anything of yours to strike!" | Strike last <n> statements from the record | https://github.com/yougov/pmxbot/blob/5da84a3258a0fd73cb35b60e39769a5d7bfb2ba7/pmxbot/logging.py#L468-L488 |
yougov/pmxbot | pmxbot/logging.py | where | def where(channel, nick, rest):
"When did pmxbot last see <nick> speak?"
onick = rest.strip()
last = Logger.store.last_seen(onick)
if last:
tm, chan = last
tmpl = "I last saw {onick} speak at {tm} in channel #{chan}"
return tmpl.format(tm=tm, chan=chan, onick=onick)
else:
return "Sorry! I don't have any record of %s speaking" % onick | python | def where(channel, nick, rest):
"When did pmxbot last see <nick> speak?"
onick = rest.strip()
last = Logger.store.last_seen(onick)
if last:
tm, chan = last
tmpl = "I last saw {onick} speak at {tm} in channel #{chan}"
return tmpl.format(tm=tm, chan=chan, onick=onick)
else:
return "Sorry! I don't have any record of %s speaking" % onick | When did pmxbot last see <nick> speak? | https://github.com/yougov/pmxbot/blob/5da84a3258a0fd73cb35b60e39769a5d7bfb2ba7/pmxbot/logging.py#L492-L501 |
yougov/pmxbot | pmxbot/logging.py | logs | def logs(channel):
"Where can one find the logs?"
default_url = 'http://' + socket.getfqdn()
base = pmxbot.config.get('logs URL', default_url)
logged_channel = channel in pmxbot.config.log_channels
path = '/channel/' + channel.lstrip('#') if logged_channel else '/'
return urllib.parse.urljoin(base, path) | python | def logs(channel):
"Where can one find the logs?"
default_url = 'http://' + socket.getfqdn()
base = pmxbot.config.get('logs URL', default_url)
logged_channel = channel in pmxbot.config.log_channels
path = '/channel/' + channel.lstrip('#') if logged_channel else '/'
return urllib.parse.urljoin(base, path) | Where can one find the logs? | https://github.com/yougov/pmxbot/blob/5da84a3258a0fd73cb35b60e39769a5d7bfb2ba7/pmxbot/logging.py#L524-L530 |
yougov/pmxbot | pmxbot/logging.py | log | def log(channel, rest):
"""
Enable or disable logging for a channel;
use 'please' to start logging and 'stop please' to stop.
"""
words = [s.lower() for s in rest.split()]
if 'please' not in words:
return
include = 'stop' not in rest
existing = set(pmxbot.config.log_channels)
# add the channel if include, otherwise remove the channel
op = existing.union if include else existing.difference
pmxbot.config.log_channels = list(op([channel])) | python | def log(channel, rest):
"""
Enable or disable logging for a channel;
use 'please' to start logging and 'stop please' to stop.
"""
words = [s.lower() for s in rest.split()]
if 'please' not in words:
return
include = 'stop' not in rest
existing = set(pmxbot.config.log_channels)
# add the channel if include, otherwise remove the channel
op = existing.union if include else existing.difference
pmxbot.config.log_channels = list(op([channel])) | Enable or disable logging for a channel;
use 'please' to start logging and 'stop please' to stop. | https://github.com/yougov/pmxbot/blob/5da84a3258a0fd73cb35b60e39769a5d7bfb2ba7/pmxbot/logging.py#L534-L546 |
yougov/pmxbot | pmxbot/logging.py | MongoDBLogger._add_recent | def _add_recent(self, doc, logged_id):
"Keep a tab on the most recent message for each channel"
spec = dict(channel=doc['channel'])
doc['ref'] = logged_id
doc.pop('_id')
self._recent.replace_one(spec, doc, upsert=True) | python | def _add_recent(self, doc, logged_id):
"Keep a tab on the most recent message for each channel"
spec = dict(channel=doc['channel'])
doc['ref'] = logged_id
doc.pop('_id')
self._recent.replace_one(spec, doc, upsert=True) | Keep a tab on the most recent message for each channel | https://github.com/yougov/pmxbot/blob/5da84a3258a0fd73cb35b60e39769a5d7bfb2ba7/pmxbot/logging.py#L256-L261 |
yougov/pmxbot | pmxbot/logging.py | FullTextMongoDBLogger._has_fulltext | def _has_fulltext(cls, uri):
"""
Enable full text search on the messages if possible and return True.
If the full text search cannot be enabled, then return False.
"""
coll = cls._get_collection(uri)
with ExceptionTrap(storage.pymongo.errors.OperationFailure) as trap:
coll.create_index([('message', 'text')], background=True)
return not trap | python | def _has_fulltext(cls, uri):
"""
Enable full text search on the messages if possible and return True.
If the full text search cannot be enabled, then return False.
"""
coll = cls._get_collection(uri)
with ExceptionTrap(storage.pymongo.errors.OperationFailure) as trap:
coll.create_index([('message', 'text')], background=True)
return not trap | Enable full text search on the messages if possible and return True.
If the full text search cannot be enabled, then return False. | https://github.com/yougov/pmxbot/blob/5da84a3258a0fd73cb35b60e39769a5d7bfb2ba7/pmxbot/logging.py#L422-L430 |
yougov/pmxbot | pmxbot/slack.py | Bot._find_user_channel | def _find_user_channel(self, username):
"""
Use slacker to resolve the username to an opened IM channel
"""
user_id = self.slacker.users.get_user_id(username)
im = user_id and self.slacker.im.open(user_id).body['channel']['id']
return im and self.slack.server.channels.find(im) | python | def _find_user_channel(self, username):
"""
Use slacker to resolve the username to an opened IM channel
"""
user_id = self.slacker.users.get_user_id(username)
im = user_id and self.slacker.im.open(user_id).body['channel']['id']
return im and self.slack.server.channels.find(im) | Use slacker to resolve the username to an opened IM channel | https://github.com/yougov/pmxbot/blob/5da84a3258a0fd73cb35b60e39769a5d7bfb2ba7/pmxbot/slack.py#L65-L71 |
yougov/pmxbot | pmxbot/slack.py | Bot.transmit | def transmit(self, channel, message):
"""
Send the message to Slack.
:param channel: channel or user to whom the message should be sent.
If a ``thread`` attribute is present, that thread ID is used.
:param str message: message to send.
"""
target = (
self.slack.server.channels.find(channel)
or self._find_user_channel(username=channel)
)
message = self._expand_references(message)
target.send_message(message, thread=getattr(channel, 'thread', None)) | python | def transmit(self, channel, message):
"""
Send the message to Slack.
:param channel: channel or user to whom the message should be sent.
If a ``thread`` attribute is present, that thread ID is used.
:param str message: message to send.
"""
target = (
self.slack.server.channels.find(channel)
or self._find_user_channel(username=channel)
)
message = self._expand_references(message)
target.send_message(message, thread=getattr(channel, 'thread', None)) | Send the message to Slack.
:param channel: channel or user to whom the message should be sent.
If a ``thread`` attribute is present, that thread ID is used.
:param str message: message to send. | https://github.com/yougov/pmxbot/blob/5da84a3258a0fd73cb35b60e39769a5d7bfb2ba7/pmxbot/slack.py#L73-L87 |
yougov/pmxbot | pmxbot/util.py | wchoice | def wchoice(d):
"""
Given a dictionary of word: proportion, return a word randomly selected
from the keys weighted by proportion.
>>> wchoice({'a': 0, 'b': 1})
'b'
>>> choices = [wchoice({'a': 1, 'b': 2}) for x in range(1000)]
Statistically speaking, choices should be .5 a:b
>>> ratio = choices.count('a') / choices.count('b')
>>> .4 < ratio < .6
True
"""
total = sum(d.values())
target = random.random() * total
# elect the first item which pushes the count over target
count = 0
for word, proportion in d.items():
count += proportion
if count > target:
return word | python | def wchoice(d):
"""
Given a dictionary of word: proportion, return a word randomly selected
from the keys weighted by proportion.
>>> wchoice({'a': 0, 'b': 1})
'b'
>>> choices = [wchoice({'a': 1, 'b': 2}) for x in range(1000)]
Statistically speaking, choices should be .5 a:b
>>> ratio = choices.count('a') / choices.count('b')
>>> .4 < ratio < .6
True
"""
total = sum(d.values())
target = random.random() * total
# elect the first item which pushes the count over target
count = 0
for word, proportion in d.items():
count += proportion
if count > target:
return word | Given a dictionary of word: proportion, return a word randomly selected
from the keys weighted by proportion.
>>> wchoice({'a': 0, 'b': 1})
'b'
>>> choices = [wchoice({'a': 1, 'b': 2}) for x in range(1000)]
Statistically speaking, choices should be .5 a:b
>>> ratio = choices.count('a') / choices.count('b')
>>> .4 < ratio < .6
True | https://github.com/yougov/pmxbot/blob/5da84a3258a0fd73cb35b60e39769a5d7bfb2ba7/pmxbot/util.py#L20-L41 |
yougov/pmxbot | pmxbot/util.py | splitem | def splitem(query):
"""
Split a query into choices
>>> splitem('dog, cat')
['dog', 'cat']
Disregards trailing punctuation.
>>> splitem('dogs, cats???')
['dogs', 'cats']
>>> splitem('cats!!!')
['cats']
Allow or
>>> splitem('dogs, cats or prarie dogs?')
['dogs', 'cats', 'prarie dogs']
Honors serial commas
>>> splitem('dogs, cats, or prarie dogs?')
['dogs', 'cats', 'prarie dogs']
Allow choices to be prefixed by some ignored prompt.
>>> splitem('stuff: a, b, c')
['a', 'b', 'c']
"""
prompt, sep, query = query.rstrip('?.!').rpartition(':')
choices = query.split(',')
choices[-1:] = choices[-1].split(' or ')
return [choice.strip() for choice in choices if choice.strip()] | python | def splitem(query):
"""
Split a query into choices
>>> splitem('dog, cat')
['dog', 'cat']
Disregards trailing punctuation.
>>> splitem('dogs, cats???')
['dogs', 'cats']
>>> splitem('cats!!!')
['cats']
Allow or
>>> splitem('dogs, cats or prarie dogs?')
['dogs', 'cats', 'prarie dogs']
Honors serial commas
>>> splitem('dogs, cats, or prarie dogs?')
['dogs', 'cats', 'prarie dogs']
Allow choices to be prefixed by some ignored prompt.
>>> splitem('stuff: a, b, c')
['a', 'b', 'c']
"""
prompt, sep, query = query.rstrip('?.!').rpartition(':')
choices = query.split(',')
choices[-1:] = choices[-1].split(' or ')
return [choice.strip() for choice in choices if choice.strip()] | Split a query into choices
>>> splitem('dog, cat')
['dog', 'cat']
Disregards trailing punctuation.
>>> splitem('dogs, cats???')
['dogs', 'cats']
>>> splitem('cats!!!')
['cats']
Allow or
>>> splitem('dogs, cats or prarie dogs?')
['dogs', 'cats', 'prarie dogs']
Honors serial commas
>>> splitem('dogs, cats, or prarie dogs?')
['dogs', 'cats', 'prarie dogs']
Allow choices to be prefixed by some ignored prompt.
>>> splitem('stuff: a, b, c')
['a', 'b', 'c'] | https://github.com/yougov/pmxbot/blob/5da84a3258a0fd73cb35b60e39769a5d7bfb2ba7/pmxbot/util.py#L44-L75 |
yougov/pmxbot | pmxbot/util.py | lookup | def lookup(word):
'''
Get a definition for a word (uses Wordnik)
'''
_patch_wordnik()
# Jason's key - do not abuse
key = 'edc4b9b94b341eeae350e087c2e05d2f5a2a9e0478cefc6dc'
client = wordnik.swagger.ApiClient(key, 'http://api.wordnik.com/v4')
words = wordnik.WordApi.WordApi(client)
definitions = words.getDefinitions(word, limit=1)
if not definitions:
return
definition = definitions[0]
return str(definition.text) | python | def lookup(word):
'''
Get a definition for a word (uses Wordnik)
'''
_patch_wordnik()
# Jason's key - do not abuse
key = 'edc4b9b94b341eeae350e087c2e05d2f5a2a9e0478cefc6dc'
client = wordnik.swagger.ApiClient(key, 'http://api.wordnik.com/v4')
words = wordnik.WordApi.WordApi(client)
definitions = words.getDefinitions(word, limit=1)
if not definitions:
return
definition = definitions[0]
return str(definition.text) | Get a definition for a word (uses Wordnik) | https://github.com/yougov/pmxbot/blob/5da84a3258a0fd73cb35b60e39769a5d7bfb2ba7/pmxbot/util.py#L107-L120 |
yougov/pmxbot | pmxbot/util.py | urban_lookup | def urban_lookup(word):
'''
Return a Urban Dictionary definition for a word or None if no result was
found.
'''
url = "http://api.urbandictionary.com/v0/define"
params = dict(term=word)
resp = requests.get(url, params=params)
resp.raise_for_status()
res = resp.json()
if not res['list']:
return
return res['list'][0]['definition'] | python | def urban_lookup(word):
'''
Return a Urban Dictionary definition for a word or None if no result was
found.
'''
url = "http://api.urbandictionary.com/v0/define"
params = dict(term=word)
resp = requests.get(url, params=params)
resp.raise_for_status()
res = resp.json()
if not res['list']:
return
return res['list'][0]['definition'] | Return a Urban Dictionary definition for a word or None if no result was
found. | https://github.com/yougov/pmxbot/blob/5da84a3258a0fd73cb35b60e39769a5d7bfb2ba7/pmxbot/util.py#L126-L138 |
yougov/pmxbot | pmxbot/util.py | passagg | def passagg(recipient, sender):
"""
Generate a passive-aggressive statement to recipient from sender.
"""
adj = random.choice(pmxbot.phrases.adjs)
if random.choice([False, True]):
# address the recipient last
lead = ""
trail = recipient if not recipient else ", %s" % recipient
else:
# address the recipient first
lead = recipient if not recipient else "%s, " % recipient
trail = ""
body = random.choice(pmxbot.phrases.adj_intros) % adj
if not lead:
body = body.capitalize()
msg = "{lead}{body}{trail}.".format(**locals())
fw = random.choice(pmxbot.phrases.farewells)
return "{msg} {fw}, {sender}.".format(**locals()) | python | def passagg(recipient, sender):
"""
Generate a passive-aggressive statement to recipient from sender.
"""
adj = random.choice(pmxbot.phrases.adjs)
if random.choice([False, True]):
# address the recipient last
lead = ""
trail = recipient if not recipient else ", %s" % recipient
else:
# address the recipient first
lead = recipient if not recipient else "%s, " % recipient
trail = ""
body = random.choice(pmxbot.phrases.adj_intros) % adj
if not lead:
body = body.capitalize()
msg = "{lead}{body}{trail}.".format(**locals())
fw = random.choice(pmxbot.phrases.farewells)
return "{msg} {fw}, {sender}.".format(**locals()) | Generate a passive-aggressive statement to recipient from sender. | https://github.com/yougov/pmxbot/blob/5da84a3258a0fd73cb35b60e39769a5d7bfb2ba7/pmxbot/util.py#L165-L183 |
yougov/pmxbot | pmxbot/config_.py | config | def config(client, event, channel, nick, rest):
"Change the running config, something like a=b or a+=b or a-=b"
pattern = re.compile(r'(?P<key>\w+)\s*(?P<op>[+-]?=)\s*(?P<value>.*)$')
match = pattern.match(rest)
if not match:
return "Command not recognized"
res = match.groupdict()
key = res['key']
op = res['op']
value = yaml.safe_load(res['value'])
if op in ('+=', '-='):
# list operation
op_name = {'+=': 'append', '-=': 'remove'}[op]
op_name
if key not in pmxbot.config:
msg = "{key} not found in config. Can't {op_name}."
return msg.format(**locals())
if not isinstance(pmxbot.config[key], (list, tuple)):
msg = "{key} is not list or tuple. Can't {op_name}."
return msg.format(**locals())
op = getattr(pmxbot.config[key], op_name)
op(value)
else: # op is '='
pmxbot.config[key] = value | python | def config(client, event, channel, nick, rest):
"Change the running config, something like a=b or a+=b or a-=b"
pattern = re.compile(r'(?P<key>\w+)\s*(?P<op>[+-]?=)\s*(?P<value>.*)$')
match = pattern.match(rest)
if not match:
return "Command not recognized"
res = match.groupdict()
key = res['key']
op = res['op']
value = yaml.safe_load(res['value'])
if op in ('+=', '-='):
# list operation
op_name = {'+=': 'append', '-=': 'remove'}[op]
op_name
if key not in pmxbot.config:
msg = "{key} not found in config. Can't {op_name}."
return msg.format(**locals())
if not isinstance(pmxbot.config[key], (list, tuple)):
msg = "{key} is not list or tuple. Can't {op_name}."
return msg.format(**locals())
op = getattr(pmxbot.config[key], op_name)
op(value)
else: # op is '='
pmxbot.config[key] = value | Change the running config, something like a=b or a+=b or a-=b | https://github.com/yougov/pmxbot/blob/5da84a3258a0fd73cb35b60e39769a5d7bfb2ba7/pmxbot/config_.py#L10-L33 |
yougov/pmxbot | pmxbot/itertools.py | trap_exceptions | def trap_exceptions(results, handler, exceptions=Exception):
"""
Iterate through the results, but if an exception occurs, stop
processing the results and instead replace
the results with the output from the exception handler.
"""
try:
for result in results:
yield result
except exceptions as exc:
for result in always_iterable(handler(exc)):
yield result | python | def trap_exceptions(results, handler, exceptions=Exception):
"""
Iterate through the results, but if an exception occurs, stop
processing the results and instead replace
the results with the output from the exception handler.
"""
try:
for result in results:
yield result
except exceptions as exc:
for result in always_iterable(handler(exc)):
yield result | Iterate through the results, but if an exception occurs, stop
processing the results and instead replace
the results with the output from the exception handler. | https://github.com/yougov/pmxbot/blob/5da84a3258a0fd73cb35b60e39769a5d7bfb2ba7/pmxbot/itertools.py#L13-L24 |
yougov/pmxbot | pmxbot/quotes.py | quote | def quote(rest):
"""
If passed with nothing then get a random quote. If passed with some
string then search for that. If prepended with "add:" then add it to the
db, eg "!quote add: drivers: I only work here because of pmxbot!".
Delete an individual quote by prepending "del:" and passing a search
matching exactly one query.
"""
rest = rest.strip()
if rest.startswith('add: ') or rest.startswith('add '):
quote_to_add = rest.split(' ', 1)[1]
Quotes.store.add(quote_to_add)
qt = False
return 'Quote added!'
if rest.startswith('del: ') or rest.startswith('del '):
cmd, sep, lookup = rest.partition(' ')
Quotes.store.delete(lookup)
return 'Deleted the sole quote that matched'
qt, i, n = Quotes.store.lookup(rest)
if not qt:
return
return '(%s/%s): %s' % (i, n, qt) | python | def quote(rest):
"""
If passed with nothing then get a random quote. If passed with some
string then search for that. If prepended with "add:" then add it to the
db, eg "!quote add: drivers: I only work here because of pmxbot!".
Delete an individual quote by prepending "del:" and passing a search
matching exactly one query.
"""
rest = rest.strip()
if rest.startswith('add: ') or rest.startswith('add '):
quote_to_add = rest.split(' ', 1)[1]
Quotes.store.add(quote_to_add)
qt = False
return 'Quote added!'
if rest.startswith('del: ') or rest.startswith('del '):
cmd, sep, lookup = rest.partition(' ')
Quotes.store.delete(lookup)
return 'Deleted the sole quote that matched'
qt, i, n = Quotes.store.lookup(rest)
if not qt:
return
return '(%s/%s): %s' % (i, n, qt) | If passed with nothing then get a random quote. If passed with some
string then search for that. If prepended with "add:" then add it to the
db, eg "!quote add: drivers: I only work here because of pmxbot!".
Delete an individual quote by prepending "del:" and passing a search
matching exactly one query. | https://github.com/yougov/pmxbot/blob/5da84a3258a0fd73cb35b60e39769a5d7bfb2ba7/pmxbot/quotes.py#L199-L220 |
yougov/pmxbot | pmxbot/quotes.py | MongoDBQuotes.delete | def delete(self, lookup):
"""
If exactly one quote matches, delete it. Otherwise,
raise a ValueError.
"""
lookup, num = self.split_num(lookup)
if num:
result = self.find_matches(lookup)[num - 1]
else:
result, = self.find_matches(lookup)
self.db.delete_one(result) | python | def delete(self, lookup):
"""
If exactly one quote matches, delete it. Otherwise,
raise a ValueError.
"""
lookup, num = self.split_num(lookup)
if num:
result = self.find_matches(lookup)[num - 1]
else:
result, = self.find_matches(lookup)
self.db.delete_one(result) | If exactly one quote matches, delete it. Otherwise,
raise a ValueError. | https://github.com/yougov/pmxbot/blob/5da84a3258a0fd73cb35b60e39769a5d7bfb2ba7/pmxbot/quotes.py#L153-L163 |
yougov/pmxbot | pmxbot/stack.py | parse_index | def parse_index(index, items):
"""Return a list of 0-based index numbers from a (1-based) `index` str.
* A single item index, like `[3]`. Negative indices count backward from
the bottom; that is, the bottom-most item in a 3-item stack can be
identified by `[3]` or `[-1]`.
* A slice, shorthand for the entire inclusive range between two numbers,
like `[3:5]`. Either number may be negative, or omitted to mean 1 or -1,
respectively. If both are omitted as `[:]` then all items match.
* Any "text" surrounded by single or double-quotes, which matches any
item containing the text (case-insensitive).
* Any /text/ surrounded by forward-slashes, a regular expression
to match item content.
* The values "first" or "last" (without quotes).
* Any combination of the above, separated by commas; for example,
given a stack of items "1: red | 2: orange | 3: yellow | 4: green |
5: blue | 6: indigo | 7: violet", the index `[6, :2, "i"]` identifies
"6: indigo | 1: red | 2: orange | 7: violet". Note that "indigo"
matches both `[6]` and `["i"]`, but is only included once. However,
if the stack had another "8: indigo" entry, it would have been included.
"""
indices = []
if index is None:
return indices
for atom in index.split(","):
atom = atom.strip()
if not atom:
continue
if (
(atom.startswith("'") and atom.endswith("'")) or
(atom.startswith('"') and atom.endswith('"'))
):
atom = atom[1:-1].lower()
for i, item in enumerate(items):
if atom in item.lower():
indices.append(i)
elif atom.startswith('/') and atom.endswith('/'):
atom = atom[1:-1]
for i, item in enumerate(items):
if re.search(atom, item):
indices.append(i)
elif ":" in atom:
start, end = [x.strip() for x in atom.split(":", 1)]
start = int(start) if start else 1
if start < 0:
start += len(items) + 1
end = int(end) if end else len(items)
if end < 0:
end += len(items) + 1
start -= 1 # Shift to Python 0-based indices
end -= 1 # Shift to Python 0-based indices
for i in range(start, end + 1):
indices.append(i)
elif atom == "first":
indices.append(0)
elif atom == "last":
indices.append(len(items) - 1)
else:
index = int(atom)
if index < 0:
index += len(items) + 1
index -= 1 # Shift to Python 0-based indices
indices.append(index)
return indices | python | def parse_index(index, items):
"""Return a list of 0-based index numbers from a (1-based) `index` str.
* A single item index, like `[3]`. Negative indices count backward from
the bottom; that is, the bottom-most item in a 3-item stack can be
identified by `[3]` or `[-1]`.
* A slice, shorthand for the entire inclusive range between two numbers,
like `[3:5]`. Either number may be negative, or omitted to mean 1 or -1,
respectively. If both are omitted as `[:]` then all items match.
* Any "text" surrounded by single or double-quotes, which matches any
item containing the text (case-insensitive).
* Any /text/ surrounded by forward-slashes, a regular expression
to match item content.
* The values "first" or "last" (without quotes).
* Any combination of the above, separated by commas; for example,
given a stack of items "1: red | 2: orange | 3: yellow | 4: green |
5: blue | 6: indigo | 7: violet", the index `[6, :2, "i"]` identifies
"6: indigo | 1: red | 2: orange | 7: violet". Note that "indigo"
matches both `[6]` and `["i"]`, but is only included once. However,
if the stack had another "8: indigo" entry, it would have been included.
"""
indices = []
if index is None:
return indices
for atom in index.split(","):
atom = atom.strip()
if not atom:
continue
if (
(atom.startswith("'") and atom.endswith("'")) or
(atom.startswith('"') and atom.endswith('"'))
):
atom = atom[1:-1].lower()
for i, item in enumerate(items):
if atom in item.lower():
indices.append(i)
elif atom.startswith('/') and atom.endswith('/'):
atom = atom[1:-1]
for i, item in enumerate(items):
if re.search(atom, item):
indices.append(i)
elif ":" in atom:
start, end = [x.strip() for x in atom.split(":", 1)]
start = int(start) if start else 1
if start < 0:
start += len(items) + 1
end = int(end) if end else len(items)
if end < 0:
end += len(items) + 1
start -= 1 # Shift to Python 0-based indices
end -= 1 # Shift to Python 0-based indices
for i in range(start, end + 1):
indices.append(i)
elif atom == "first":
indices.append(0)
elif atom == "last":
indices.append(len(items) - 1)
else:
index = int(atom)
if index < 0:
index += len(items) + 1
index -= 1 # Shift to Python 0-based indices
indices.append(index)
return indices | Return a list of 0-based index numbers from a (1-based) `index` str.
* A single item index, like `[3]`. Negative indices count backward from
the bottom; that is, the bottom-most item in a 3-item stack can be
identified by `[3]` or `[-1]`.
* A slice, shorthand for the entire inclusive range between two numbers,
like `[3:5]`. Either number may be negative, or omitted to mean 1 or -1,
respectively. If both are omitted as `[:]` then all items match.
* Any "text" surrounded by single or double-quotes, which matches any
item containing the text (case-insensitive).
* Any /text/ surrounded by forward-slashes, a regular expression
to match item content.
* The values "first" or "last" (without quotes).
* Any combination of the above, separated by commas; for example,
given a stack of items "1: red | 2: orange | 3: yellow | 4: green |
5: blue | 6: indigo | 7: violet", the index `[6, :2, "i"]` identifies
"6: indigo | 1: red | 2: orange | 7: violet". Note that "indigo"
matches both `[6]` and `["i"]`, but is only included once. However,
if the stack had another "8: indigo" entry, it would have been included. | https://github.com/yougov/pmxbot/blob/5da84a3258a0fd73cb35b60e39769a5d7bfb2ba7/pmxbot/stack.py#L214-L281 |
yougov/pmxbot | pmxbot/stack.py | stack | def stack(nick, rest):
'Manage short lists in pmxbot. See !stack help for more info'
atoms = [atom.strip() for atom in rest.split(' ', 1) if atom.strip()]
if len(atoms) == 0:
subcommand = "show"
rest = ""
elif len(atoms) == 1:
subcommand = atoms[0]
rest = ""
else:
subcommand, rest = atoms
start = rest.find("[")
finish = rest.rfind("]")
sp = rest.find(" ")
if (
start != -1 and finish != -1 and start < finish and
(sp == -1 or start < sp)
):
topic, index = [atom.strip() for atom in rest[:finish].split("[", 1)]
if not topic:
topic = nick
new_item = rest[finish + 1:].strip()
else:
topic = nick
index = None
new_item = rest.strip()
if subcommand == "topics" or subcommand == "list":
items = Stack.store.get_topics()
items.sort()
else:
items = Stack.store.get_items(topic)
try:
indices = parse_index(index, items)
except ValueError:
return helpdoc["index"]
if debug:
print("SUBCOMMAND", subcommand.ljust(8), "TOPIC", topic.ljust(8),
"INDICES", str(indices).ljust(12), "ITEM", new_item)
if subcommand == "add":
if not new_item:
return ('!stack add <topic[index]> item: '
'You must provide an item to add.')
if not indices:
items.insert(0, new_item)
else:
for i in reversed(sorted(set(indices))):
if i >= len(items):
items.append(new_item)
else:
items.insert(i + 1, new_item)
Stack.store.save_items(topic, items)
elif subcommand == "pop":
if not indices:
indices = [0]
popped_items = [items.pop(i) for i in reversed(sorted(set(indices)))
if len(items) > i >= 0]
Stack.store.save_items(topic, items)
return output([("-", item) for item in reversed(popped_items)],
"(none popped)", pop=True)
elif subcommand == "show":
if new_item:
return helpdoc["show"]
if not indices:
indices = range(len(items))
return output(
[(i + 1, items[i]) for i in indices if len(items) > i >= 0]
)
elif subcommand == "shuffle":
if not indices:
random.shuffle(items)
else:
items = [items[i] for i in indices if len(items) > i >= 0]
Stack.store.save_items(topic, items)
return output(enumerate(items, 1))
elif subcommand == "topics" or subcommand == "list":
if new_item:
return helpdoc["topics"]
if not indices:
indices = range(len(items))
return output(
[(i + 1, items[i]) for i in indices if len(items) > i >= 0]
)
elif subcommand == "help":
return helpdoc.get(new_item, helpdoc["help"])
else:
return helpdoc["stack"] | python | def stack(nick, rest):
'Manage short lists in pmxbot. See !stack help for more info'
atoms = [atom.strip() for atom in rest.split(' ', 1) if atom.strip()]
if len(atoms) == 0:
subcommand = "show"
rest = ""
elif len(atoms) == 1:
subcommand = atoms[0]
rest = ""
else:
subcommand, rest = atoms
start = rest.find("[")
finish = rest.rfind("]")
sp = rest.find(" ")
if (
start != -1 and finish != -1 and start < finish and
(sp == -1 or start < sp)
):
topic, index = [atom.strip() for atom in rest[:finish].split("[", 1)]
if not topic:
topic = nick
new_item = rest[finish + 1:].strip()
else:
topic = nick
index = None
new_item = rest.strip()
if subcommand == "topics" or subcommand == "list":
items = Stack.store.get_topics()
items.sort()
else:
items = Stack.store.get_items(topic)
try:
indices = parse_index(index, items)
except ValueError:
return helpdoc["index"]
if debug:
print("SUBCOMMAND", subcommand.ljust(8), "TOPIC", topic.ljust(8),
"INDICES", str(indices).ljust(12), "ITEM", new_item)
if subcommand == "add":
if not new_item:
return ('!stack add <topic[index]> item: '
'You must provide an item to add.')
if not indices:
items.insert(0, new_item)
else:
for i in reversed(sorted(set(indices))):
if i >= len(items):
items.append(new_item)
else:
items.insert(i + 1, new_item)
Stack.store.save_items(topic, items)
elif subcommand == "pop":
if not indices:
indices = [0]
popped_items = [items.pop(i) for i in reversed(sorted(set(indices)))
if len(items) > i >= 0]
Stack.store.save_items(topic, items)
return output([("-", item) for item in reversed(popped_items)],
"(none popped)", pop=True)
elif subcommand == "show":
if new_item:
return helpdoc["show"]
if not indices:
indices = range(len(items))
return output(
[(i + 1, items[i]) for i in indices if len(items) > i >= 0]
)
elif subcommand == "shuffle":
if not indices:
random.shuffle(items)
else:
items = [items[i] for i in indices if len(items) > i >= 0]
Stack.store.save_items(topic, items)
return output(enumerate(items, 1))
elif subcommand == "topics" or subcommand == "list":
if new_item:
return helpdoc["topics"]
if not indices:
indices = range(len(items))
return output(
[(i + 1, items[i]) for i in indices if len(items) > i >= 0]
)
elif subcommand == "help":
return helpdoc.get(new_item, helpdoc["help"])
else:
return helpdoc["stack"] | Manage short lists in pmxbot. See !stack help for more info | https://github.com/yougov/pmxbot/blob/5da84a3258a0fd73cb35b60e39769a5d7bfb2ba7/pmxbot/stack.py#L293-L393 |
yougov/pmxbot | pmxbot/irc.py | LoggingCommandBot._get_wrapper | def _get_wrapper():
"""
Get a socket wrapper based on SSL config.
"""
if not pmxbot.config.get('use_ssl', False):
return lambda x: x
return importlib.import_module('ssl').wrap_socket | python | def _get_wrapper():
"""
Get a socket wrapper based on SSL config.
"""
if not pmxbot.config.get('use_ssl', False):
return lambda x: x
return importlib.import_module('ssl').wrap_socket | Get a socket wrapper based on SSL config. | https://github.com/yougov/pmxbot/blob/5da84a3258a0fd73cb35b60e39769a5d7bfb2ba7/pmxbot/irc.py#L79-L85 |
yougov/pmxbot | pmxbot/irc.py | LoggingCommandBot.transmit | def transmit(self, channel, msg):
r"""
Transmit the message (or action) and return what was transmitted.
>>> ap = LoggingCommandBot.action_pattern
>>> ap.match('foo').groups()
(None, 'foo')
>>> ap.match('foo\nbar\n').group(2)
'foo\nbar\n'
>>> is_action, msg = ap.match('/me is feeling fine today').groups()
>>> bool(is_action)
True
>>> msg
'is feeling fine today'
"""
is_action, msg = self.action_pattern.match(msg).groups()
func = self._conn.action if is_action else self._conn.privmsg
try:
func(channel, msg)
return msg
except irc.client.MessageTooLong:
# some msgs will fail because they're too long
log.warning("Long message could not be transmitted: %s", msg)
except irc.client.InvalidCharacters:
tmpl = (
"Message contains carriage returns, "
"which aren't allowed in IRC messages: %r"
)
log.warning(tmpl, msg) | python | def transmit(self, channel, msg):
r"""
Transmit the message (or action) and return what was transmitted.
>>> ap = LoggingCommandBot.action_pattern
>>> ap.match('foo').groups()
(None, 'foo')
>>> ap.match('foo\nbar\n').group(2)
'foo\nbar\n'
>>> is_action, msg = ap.match('/me is feeling fine today').groups()
>>> bool(is_action)
True
>>> msg
'is feeling fine today'
"""
is_action, msg = self.action_pattern.match(msg).groups()
func = self._conn.action if is_action else self._conn.privmsg
try:
func(channel, msg)
return msg
except irc.client.MessageTooLong:
# some msgs will fail because they're too long
log.warning("Long message could not be transmitted: %s", msg)
except irc.client.InvalidCharacters:
tmpl = (
"Message contains carriage returns, "
"which aren't allowed in IRC messages: %r"
)
log.warning(tmpl, msg) | r"""
Transmit the message (or action) and return what was transmitted.
>>> ap = LoggingCommandBot.action_pattern
>>> ap.match('foo').groups()
(None, 'foo')
>>> ap.match('foo\nbar\n').group(2)
'foo\nbar\n'
>>> is_action, msg = ap.match('/me is feeling fine today').groups()
>>> bool(is_action)
True
>>> msg
'is feeling fine today' | https://github.com/yougov/pmxbot/blob/5da84a3258a0fd73cb35b60e39769a5d7bfb2ba7/pmxbot/irc.py#L89-L117 |
MeaningCloud/meaningcloud-python | meaningcloud/Response.py | Response.getStatusCode | def getStatusCode(self):
"""
Returns the code of the status or None if it does not exist
:return:
Status code of the response
"""
if 'status' in self._response.keys():
if (self._response['status'] is not None) and ('code' in self._response['status'].keys()) and (self._response['status']['code'] is not None):
return self._response['status']['code']
else:
return None
else:
return None | python | def getStatusCode(self):
"""
Returns the code of the status or None if it does not exist
:return:
Status code of the response
"""
if 'status' in self._response.keys():
if (self._response['status'] is not None) and ('code' in self._response['status'].keys()) and (self._response['status']['code'] is not None):
return self._response['status']['code']
else:
return None
else:
return None | Returns the code of the status or None if it does not exist
:return:
Status code of the response | https://github.com/MeaningCloud/meaningcloud-python/blob/1dd76ecabeedd80c9bb14a1716d39657d645775f/meaningcloud/Response.py#L37-L52 |
MeaningCloud/meaningcloud-python | meaningcloud/Response.py | Response.getStatusMsg | def getStatusMsg(self):
"""
Returns the message of the status or an empty string if it does not exist
:return:
Status message of the response
"""
if 'status' in self._response.keys():
if (self._response['status'] is not None) and ('msg' in self._response['status'].keys()) and (self._response['status']['msg'] is not None):
return self._response['status']['msg']
else:
return '' | python | def getStatusMsg(self):
"""
Returns the message of the status or an empty string if it does not exist
:return:
Status message of the response
"""
if 'status' in self._response.keys():
if (self._response['status'] is not None) and ('msg' in self._response['status'].keys()) and (self._response['status']['msg'] is not None):
return self._response['status']['msg']
else:
return '' | Returns the message of the status or an empty string if it does not exist
:return:
Status message of the response | https://github.com/MeaningCloud/meaningcloud-python/blob/1dd76ecabeedd80c9bb14a1716d39657d645775f/meaningcloud/Response.py#L54-L66 |
MeaningCloud/meaningcloud-python | meaningcloud/Response.py | Response.getConsumedCredits | def getConsumedCredits(self):
"""
Returns the credit consumed by the request made
:return:
String with the number of credits consumed
"""
if 'status' in self._response.keys():
if (self._response['status'] is not None) and ('credits' in self._response['status'].keys()):
if self._response['status']['credits'] is not None:
return self._response['status']['credits']
else:
return '0'
else:
print("Not credits field\n")
else:
return None | python | def getConsumedCredits(self):
"""
Returns the credit consumed by the request made
:return:
String with the number of credits consumed
"""
if 'status' in self._response.keys():
if (self._response['status'] is not None) and ('credits' in self._response['status'].keys()):
if self._response['status']['credits'] is not None:
return self._response['status']['credits']
else:
return '0'
else:
print("Not credits field\n")
else:
return None | Returns the credit consumed by the request made
:return:
String with the number of credits consumed | https://github.com/MeaningCloud/meaningcloud-python/blob/1dd76ecabeedd80c9bb14a1716d39657d645775f/meaningcloud/Response.py#L68-L85 |
MeaningCloud/meaningcloud-python | meaningcloud/Response.py | Response.getRemainingCredits | def getRemainingCredits(self):
"""
Returns the remaining credits for the license key used after the request was made
:return:
String with remaining credits
"""
if 'status' in self._response.keys():
if (self._response['status'] is not None) and ('remaining_credits' in self._response['status'].keys()):
if self._response['status']['remaining_credits'] is not None:
return self._response['status']['remaining_credits']
else:
return ''
else:
print("Not remaining credits field\n")
else:
return None | python | def getRemainingCredits(self):
"""
Returns the remaining credits for the license key used after the request was made
:return:
String with remaining credits
"""
if 'status' in self._response.keys():
if (self._response['status'] is not None) and ('remaining_credits' in self._response['status'].keys()):
if self._response['status']['remaining_credits'] is not None:
return self._response['status']['remaining_credits']
else:
return ''
else:
print("Not remaining credits field\n")
else:
return None | Returns the remaining credits for the license key used after the request was made
:return:
String with remaining credits | https://github.com/MeaningCloud/meaningcloud-python/blob/1dd76ecabeedd80c9bb14a1716d39657d645775f/meaningcloud/Response.py#L87-L104 |
MeaningCloud/meaningcloud-python | meaningcloud/Response.py | Response.getResults | def getResults(self):
"""
Returns the results from the API without the status of the request
:return:
Dictionary with the results
"""
results = self._response.copy()
if 'status' in self._response.keys():
if results['status'] is not None:
del results['status']
return results
else:
return None | python | def getResults(self):
"""
Returns the results from the API without the status of the request
:return:
Dictionary with the results
"""
results = self._response.copy()
if 'status' in self._response.keys():
if results['status'] is not None:
del results['status']
return results
else:
return None | Returns the results from the API without the status of the request
:return:
Dictionary with the results | https://github.com/MeaningCloud/meaningcloud-python/blob/1dd76ecabeedd80c9bb14a1716d39657d645775f/meaningcloud/Response.py#L106-L120 |
rkhleics/police-api-client-python | police_api/__init__.py | PoliceAPI.get_forces | def get_forces(self):
"""
Get a list of all police forces. Uses the forces_ API call.
.. _forces: https://data.police.uk/docs/method/forces/
:rtype: list
:return: A list of :class:`forces.Force` objects (one for each police
force represented in the API)
"""
forces = []
for f in self.service.request('GET', 'forces'):
forces.append(Force(self, id=f['id'], name=f['name']))
return forces | python | def get_forces(self):
"""
Get a list of all police forces. Uses the forces_ API call.
.. _forces: https://data.police.uk/docs/method/forces/
:rtype: list
:return: A list of :class:`forces.Force` objects (one for each police
force represented in the API)
"""
forces = []
for f in self.service.request('GET', 'forces'):
forces.append(Force(self, id=f['id'], name=f['name']))
return forces | Get a list of all police forces. Uses the forces_ API call.
.. _forces: https://data.police.uk/docs/method/forces/
:rtype: list
:return: A list of :class:`forces.Force` objects (one for each police
force represented in the API) | https://github.com/rkhleics/police-api-client-python/blob/b5c1e493487eb2409e2c04ed9fbd304f73d89fdc/police_api/__init__.py#L31-L45 |
rkhleics/police-api-client-python | police_api/__init__.py | PoliceAPI.get_neighbourhoods | def get_neighbourhoods(self, force):
"""
Get a list of all neighbourhoods for a force. Uses the neighbourhoods_
API call.
.. _neighbourhoods: https://data.police.uk/docs/method/neighbourhoods/
:param force: The force to get neighbourhoods for (either by ID or
:class:`forces.Force` object)
:type force: str or :class:`forces.Force`
:rtype: list
:return: A ``list`` of :class:`neighbourhoods.Neighbourhood` objects
(one for each Neighbourhood Policing Team in the given force).
"""
if not isinstance(force, Force):
force = Force(self, id=force)
neighbourhoods = []
for n in self.service.request('GET', '%s/neighbourhoods' % force.id):
neighbourhoods.append(
Neighbourhood(self, force=force, id=n['id'], name=n['name']))
return sorted(neighbourhoods, key=lambda n: n.name) | python | def get_neighbourhoods(self, force):
"""
Get a list of all neighbourhoods for a force. Uses the neighbourhoods_
API call.
.. _neighbourhoods: https://data.police.uk/docs/method/neighbourhoods/
:param force: The force to get neighbourhoods for (either by ID or
:class:`forces.Force` object)
:type force: str or :class:`forces.Force`
:rtype: list
:return: A ``list`` of :class:`neighbourhoods.Neighbourhood` objects
(one for each Neighbourhood Policing Team in the given force).
"""
if not isinstance(force, Force):
force = Force(self, id=force)
neighbourhoods = []
for n in self.service.request('GET', '%s/neighbourhoods' % force.id):
neighbourhoods.append(
Neighbourhood(self, force=force, id=n['id'], name=n['name']))
return sorted(neighbourhoods, key=lambda n: n.name) | Get a list of all neighbourhoods for a force. Uses the neighbourhoods_
API call.
.. _neighbourhoods: https://data.police.uk/docs/method/neighbourhoods/
:param force: The force to get neighbourhoods for (either by ID or
:class:`forces.Force` object)
:type force: str or :class:`forces.Force`
:rtype: list
:return: A ``list`` of :class:`neighbourhoods.Neighbourhood` objects
(one for each Neighbourhood Policing Team in the given force). | https://github.com/rkhleics/police-api-client-python/blob/b5c1e493487eb2409e2c04ed9fbd304f73d89fdc/police_api/__init__.py#L60-L82 |
rkhleics/police-api-client-python | police_api/__init__.py | PoliceAPI.get_neighbourhood | def get_neighbourhood(self, force, id, **attrs):
"""
Get a specific neighbourhood. Uses the neighbourhood_ API call.
.. _neighbourhood: https://data.police.uk/docs/method/neighbourhood/
:param force: The force within which the neighbourhood resides (either
by ID or :class:`forces.Force` object)
:type force: str or Force
:param str neighbourhood: The ID of the neighbourhood to fetch.
:rtype: Neighbourhood
:return: The Neighbourhood object for the given force/ID.
"""
if not isinstance(force, Force):
force = Force(self, id=force, **attrs)
return Neighbourhood(self, force=force, id=id, **attrs) | python | def get_neighbourhood(self, force, id, **attrs):
"""
Get a specific neighbourhood. Uses the neighbourhood_ API call.
.. _neighbourhood: https://data.police.uk/docs/method/neighbourhood/
:param force: The force within which the neighbourhood resides (either
by ID or :class:`forces.Force` object)
:type force: str or Force
:param str neighbourhood: The ID of the neighbourhood to fetch.
:rtype: Neighbourhood
:return: The Neighbourhood object for the given force/ID.
"""
if not isinstance(force, Force):
force = Force(self, id=force, **attrs)
return Neighbourhood(self, force=force, id=id, **attrs) | Get a specific neighbourhood. Uses the neighbourhood_ API call.
.. _neighbourhood: https://data.police.uk/docs/method/neighbourhood/
:param force: The force within which the neighbourhood resides (either
by ID or :class:`forces.Force` object)
:type force: str or Force
:param str neighbourhood: The ID of the neighbourhood to fetch.
:rtype: Neighbourhood
:return: The Neighbourhood object for the given force/ID. | https://github.com/rkhleics/police-api-client-python/blob/b5c1e493487eb2409e2c04ed9fbd304f73d89fdc/police_api/__init__.py#L84-L101 |
rkhleics/police-api-client-python | police_api/__init__.py | PoliceAPI.locate_neighbourhood | def locate_neighbourhood(self, lat, lng):
"""
Find a neighbourhood by location. Uses the locate-neighbourhood_ API
call.
.. _locate-neighbourhood:
https://data.police.uk/docs/method/neighbourhood-locate/
:param lat: The latitude of the location.
:type lat: float or str
:param lng: The longitude of the location.
:type lng: float or str
:rtype: Neighbourhood or None
:return: The Neighbourhood object representing the Neighbourhood
Policing Team responsible for the given location.
"""
method = 'locate-neighbourhood'
q = '%s,%s' % (lat, lng)
try:
result = self.service.request('GET', method, q=q)
return self.get_neighbourhood(result['force'],
result['neighbourhood'])
except APIError:
pass | python | def locate_neighbourhood(self, lat, lng):
"""
Find a neighbourhood by location. Uses the locate-neighbourhood_ API
call.
.. _locate-neighbourhood:
https://data.police.uk/docs/method/neighbourhood-locate/
:param lat: The latitude of the location.
:type lat: float or str
:param lng: The longitude of the location.
:type lng: float or str
:rtype: Neighbourhood or None
:return: The Neighbourhood object representing the Neighbourhood
Policing Team responsible for the given location.
"""
method = 'locate-neighbourhood'
q = '%s,%s' % (lat, lng)
try:
result = self.service.request('GET', method, q=q)
return self.get_neighbourhood(result['force'],
result['neighbourhood'])
except APIError:
pass | Find a neighbourhood by location. Uses the locate-neighbourhood_ API
call.
.. _locate-neighbourhood:
https://data.police.uk/docs/method/neighbourhood-locate/
:param lat: The latitude of the location.
:type lat: float or str
:param lng: The longitude of the location.
:type lng: float or str
:rtype: Neighbourhood or None
:return: The Neighbourhood object representing the Neighbourhood
Policing Team responsible for the given location. | https://github.com/rkhleics/police-api-client-python/blob/b5c1e493487eb2409e2c04ed9fbd304f73d89fdc/police_api/__init__.py#L103-L127 |
rkhleics/police-api-client-python | police_api/__init__.py | PoliceAPI.get_crime_categories | def get_crime_categories(self, date=None):
"""
Get a list of crime categories, valid for a particular date. Uses the
crime-categories_ API call.
.. _crime-categories:
https://data.police.uk/docs/method/crime-categories/
:rtype: list
:param date: The date of the crime categories to get.
:type date: str or None
:return: A ``list`` of crime categories which are valid at the
specified date (or at the latest date, if ``None``).
"""
return sorted(self._get_crime_categories(date=date).values(),
key=lambda c: c.name) | python | def get_crime_categories(self, date=None):
"""
Get a list of crime categories, valid for a particular date. Uses the
crime-categories_ API call.
.. _crime-categories:
https://data.police.uk/docs/method/crime-categories/
:rtype: list
:param date: The date of the crime categories to get.
:type date: str or None
:return: A ``list`` of crime categories which are valid at the
specified date (or at the latest date, if ``None``).
"""
return sorted(self._get_crime_categories(date=date).values(),
key=lambda c: c.name) | Get a list of crime categories, valid for a particular date. Uses the
crime-categories_ API call.
.. _crime-categories:
https://data.police.uk/docs/method/crime-categories/
:rtype: list
:param date: The date of the crime categories to get.
:type date: str or None
:return: A ``list`` of crime categories which are valid at the
specified date (or at the latest date, if ``None``). | https://github.com/rkhleics/police-api-client-python/blob/b5c1e493487eb2409e2c04ed9fbd304f73d89fdc/police_api/__init__.py#L171-L187 |
rkhleics/police-api-client-python | police_api/__init__.py | PoliceAPI.get_crime_category | def get_crime_category(self, id, date=None):
"""
Get a particular crime category by ID, valid at a particular date. Uses
the crime-categories_ API call.
:rtype: CrimeCategory
:param str id: The ID of the crime category to get.
:param date: The date that the given crime category is valid for (the
latest date is used if ``None``).
:type date: str or None
:return: A crime category with the given ID which is valid for the
specified date (or at the latest date, if ``None``).
"""
try:
return self._get_crime_categories(date=date)[id]
except KeyError:
raise InvalidCategoryException(
'Category %s not found for %s' % (id, date)) | python | def get_crime_category(self, id, date=None):
"""
Get a particular crime category by ID, valid at a particular date. Uses
the crime-categories_ API call.
:rtype: CrimeCategory
:param str id: The ID of the crime category to get.
:param date: The date that the given crime category is valid for (the
latest date is used if ``None``).
:type date: str or None
:return: A crime category with the given ID which is valid for the
specified date (or at the latest date, if ``None``).
"""
try:
return self._get_crime_categories(date=date)[id]
except KeyError:
raise InvalidCategoryException(
'Category %s not found for %s' % (id, date)) | Get a particular crime category by ID, valid at a particular date. Uses
the crime-categories_ API call.
:rtype: CrimeCategory
:param str id: The ID of the crime category to get.
:param date: The date that the given crime category is valid for (the
latest date is used if ``None``).
:type date: str or None
:return: A crime category with the given ID which is valid for the
specified date (or at the latest date, if ``None``). | https://github.com/rkhleics/police-api-client-python/blob/b5c1e493487eb2409e2c04ed9fbd304f73d89fdc/police_api/__init__.py#L189-L207 |
rkhleics/police-api-client-python | police_api/__init__.py | PoliceAPI.get_crime | def get_crime(self, persistent_id):
"""
Get a particular crime by persistent ID. Uses the outcomes-for-crime_
API call.
.. _outcomes-for-crime:
https://data.police.uk/docs/method/outcomes-for-crime/
:rtype: Crime
:param str persistent_id: The persistent ID of the crime to get.
:return: The ``Crime`` with the given persistent ID.
"""
method = 'outcomes-for-crime/%s' % persistent_id
response = self.service.request('GET', method)
crime = Crime(self, data=response['crime'])
crime._outcomes = []
outcomes = response['outcomes']
if outcomes is not None:
for o in outcomes:
o.update({
'crime': crime,
})
crime._outcomes.append(crime.Outcome(self, o))
return crime | python | def get_crime(self, persistent_id):
"""
Get a particular crime by persistent ID. Uses the outcomes-for-crime_
API call.
.. _outcomes-for-crime:
https://data.police.uk/docs/method/outcomes-for-crime/
:rtype: Crime
:param str persistent_id: The persistent ID of the crime to get.
:return: The ``Crime`` with the given persistent ID.
"""
method = 'outcomes-for-crime/%s' % persistent_id
response = self.service.request('GET', method)
crime = Crime(self, data=response['crime'])
crime._outcomes = []
outcomes = response['outcomes']
if outcomes is not None:
for o in outcomes:
o.update({
'crime': crime,
})
crime._outcomes.append(crime.Outcome(self, o))
return crime | Get a particular crime by persistent ID. Uses the outcomes-for-crime_
API call.
.. _outcomes-for-crime:
https://data.police.uk/docs/method/outcomes-for-crime/
:rtype: Crime
:param str persistent_id: The persistent ID of the crime to get.
:return: The ``Crime`` with the given persistent ID. | https://github.com/rkhleics/police-api-client-python/blob/b5c1e493487eb2409e2c04ed9fbd304f73d89fdc/police_api/__init__.py#L209-L233 |
rkhleics/police-api-client-python | police_api/__init__.py | PoliceAPI.get_crimes_point | def get_crimes_point(self, lat, lng, date=None, category=None):
"""
Get crimes within a 1-mile radius of a location. Uses the crime-street_
API call.
.. _crime-street: https//data.police.uk/docs/method/crime-street/
:rtype: list
:param lat: The latitude of the location.
:type lat: float or str
:param lng: The longitude of the location.
:type lng: float or str
:param date: The month in which the crimes were reported in the format
``YYYY-MM`` (the latest date is used if ``None``).
:type date: str or None
:param category: The category of the crimes to filter by (either by ID
or CrimeCategory object)
:type category: str or CrimeCategory
:return: A ``list`` of crimes which were reported within 1 mile of the
specified location, in the given month (optionally filtered by
category).
"""
if isinstance(category, CrimeCategory):
category = category.id
method = 'crimes-street/%s' % (category or 'all-crime')
kwargs = {
'lat': lat,
'lng': lng,
}
crimes = []
if date is not None:
kwargs['date'] = date
for c in self.service.request('GET', method, **kwargs):
crimes.append(Crime(self, data=c))
return crimes | python | def get_crimes_point(self, lat, lng, date=None, category=None):
"""
Get crimes within a 1-mile radius of a location. Uses the crime-street_
API call.
.. _crime-street: https//data.police.uk/docs/method/crime-street/
:rtype: list
:param lat: The latitude of the location.
:type lat: float or str
:param lng: The longitude of the location.
:type lng: float or str
:param date: The month in which the crimes were reported in the format
``YYYY-MM`` (the latest date is used if ``None``).
:type date: str or None
:param category: The category of the crimes to filter by (either by ID
or CrimeCategory object)
:type category: str or CrimeCategory
:return: A ``list`` of crimes which were reported within 1 mile of the
specified location, in the given month (optionally filtered by
category).
"""
if isinstance(category, CrimeCategory):
category = category.id
method = 'crimes-street/%s' % (category or 'all-crime')
kwargs = {
'lat': lat,
'lng': lng,
}
crimes = []
if date is not None:
kwargs['date'] = date
for c in self.service.request('GET', method, **kwargs):
crimes.append(Crime(self, data=c))
return crimes | Get crimes within a 1-mile radius of a location. Uses the crime-street_
API call.
.. _crime-street: https//data.police.uk/docs/method/crime-street/
:rtype: list
:param lat: The latitude of the location.
:type lat: float or str
:param lng: The longitude of the location.
:type lng: float or str
:param date: The month in which the crimes were reported in the format
``YYYY-MM`` (the latest date is used if ``None``).
:type date: str or None
:param category: The category of the crimes to filter by (either by ID
or CrimeCategory object)
:type category: str or CrimeCategory
:return: A ``list`` of crimes which were reported within 1 mile of the
specified location, in the given month (optionally filtered by
category). | https://github.com/rkhleics/police-api-client-python/blob/b5c1e493487eb2409e2c04ed9fbd304f73d89fdc/police_api/__init__.py#L235-L270 |
rkhleics/police-api-client-python | police_api/__init__.py | PoliceAPI.get_crimes_area | def get_crimes_area(self, points, date=None, category=None):
"""
Get crimes within a custom area. Uses the crime-street_ API call.
.. _crime-street: https//data.police.uk/docs/method/crime-street/
:rtype: list
:param list points: A ``list`` of ``(lat, lng)`` tuples.
:param date: The month in which the crimes were reported in the format
``YYYY-MM`` (the latest date is used if ``None``).
:type date: str or None
:param category: The category of the crimes to filter by (either by ID
or CrimeCategory object)
:type category: str or CrimeCategory
:return: A ``list`` of crimes which were reported within the specified
boundary, in the given month (optionally filtered by
category).
"""
if isinstance(category, CrimeCategory):
category = category.id
method = 'crimes-street/%s' % (category or 'all-crime')
kwargs = {
'poly': encode_polygon(points),
}
crimes = []
if date is not None:
kwargs['date'] = date
for c in self.service.request('POST', method, **kwargs):
crimes.append(Crime(self, data=c))
return crimes | python | def get_crimes_area(self, points, date=None, category=None):
"""
Get crimes within a custom area. Uses the crime-street_ API call.
.. _crime-street: https//data.police.uk/docs/method/crime-street/
:rtype: list
:param list points: A ``list`` of ``(lat, lng)`` tuples.
:param date: The month in which the crimes were reported in the format
``YYYY-MM`` (the latest date is used if ``None``).
:type date: str or None
:param category: The category of the crimes to filter by (either by ID
or CrimeCategory object)
:type category: str or CrimeCategory
:return: A ``list`` of crimes which were reported within the specified
boundary, in the given month (optionally filtered by
category).
"""
if isinstance(category, CrimeCategory):
category = category.id
method = 'crimes-street/%s' % (category or 'all-crime')
kwargs = {
'poly': encode_polygon(points),
}
crimes = []
if date is not None:
kwargs['date'] = date
for c in self.service.request('POST', method, **kwargs):
crimes.append(Crime(self, data=c))
return crimes | Get crimes within a custom area. Uses the crime-street_ API call.
.. _crime-street: https//data.police.uk/docs/method/crime-street/
:rtype: list
:param list points: A ``list`` of ``(lat, lng)`` tuples.
:param date: The month in which the crimes were reported in the format
``YYYY-MM`` (the latest date is used if ``None``).
:type date: str or None
:param category: The category of the crimes to filter by (either by ID
or CrimeCategory object)
:type category: str or CrimeCategory
:return: A ``list`` of crimes which were reported within the specified
boundary, in the given month (optionally filtered by
category). | https://github.com/rkhleics/police-api-client-python/blob/b5c1e493487eb2409e2c04ed9fbd304f73d89fdc/police_api/__init__.py#L272-L302 |
rkhleics/police-api-client-python | police_api/__init__.py | PoliceAPI.get_crimes_location | def get_crimes_location(self, location_id, date=None):
"""
Get crimes at a particular snap-point location. Uses the
crimes-at-location_ API call.
.. _crimes-at-location:
https://data.police.uk/docs/method/crimes-at-location/
:rtype: list
:param int location_id: The ID of the location to get crimes for.
:param date: The month in which the crimes were reported in the format
``YYYY-MM`` (the latest date is used if ``None``).
:type date: str or None
:return: A ``list`` of :class:`Crime` objects which were snapped to the
:class:`Location` with the specified ID in the given month.
"""
kwargs = {
'location_id': location_id,
}
crimes = []
if date is not None:
kwargs['date'] = date
for c in self.service.request('GET', 'crimes-at-location', **kwargs):
crimes.append(Crime(self, data=c))
return crimes | python | def get_crimes_location(self, location_id, date=None):
"""
Get crimes at a particular snap-point location. Uses the
crimes-at-location_ API call.
.. _crimes-at-location:
https://data.police.uk/docs/method/crimes-at-location/
:rtype: list
:param int location_id: The ID of the location to get crimes for.
:param date: The month in which the crimes were reported in the format
``YYYY-MM`` (the latest date is used if ``None``).
:type date: str or None
:return: A ``list`` of :class:`Crime` objects which were snapped to the
:class:`Location` with the specified ID in the given month.
"""
kwargs = {
'location_id': location_id,
}
crimes = []
if date is not None:
kwargs['date'] = date
for c in self.service.request('GET', 'crimes-at-location', **kwargs):
crimes.append(Crime(self, data=c))
return crimes | Get crimes at a particular snap-point location. Uses the
crimes-at-location_ API call.
.. _crimes-at-location:
https://data.police.uk/docs/method/crimes-at-location/
:rtype: list
:param int location_id: The ID of the location to get crimes for.
:param date: The month in which the crimes were reported in the format
``YYYY-MM`` (the latest date is used if ``None``).
:type date: str or None
:return: A ``list`` of :class:`Crime` objects which were snapped to the
:class:`Location` with the specified ID in the given month. | https://github.com/rkhleics/police-api-client-python/blob/b5c1e493487eb2409e2c04ed9fbd304f73d89fdc/police_api/__init__.py#L304-L329 |
rkhleics/police-api-client-python | police_api/__init__.py | PoliceAPI.get_crimes_no_location | def get_crimes_no_location(self, force, date=None, category=None):
"""
Get crimes with no location for a force. Uses the crimes-no-location_
API call.
.. _crimes-no-location:
https://data.police.uk/docs/method/crimes-no-location/
:rtype: list
:param force: The force to get no-location crimes for.
:type force: str or Force
:param date: The month in which the crimes were reported in the format
``YYYY-MM`` (the latest date is used if ``None``).
:type date: str or None
:param category: The category of the crimes to filter by (either by ID
or CrimeCategory object)
:type category: str or CrimeCategory
:return: A ``list`` of :class:`crime.NoLocationCrime` objects which
were reported in the given month, by the specified force, but
which don't have a location.
"""
if not isinstance(force, Force):
force = Force(self, id=force)
if isinstance(category, CrimeCategory):
category = category.id
kwargs = {
'force': force.id,
'category': category or 'all-crime',
}
crimes = []
if date is not None:
kwargs['date'] = date
for c in self.service.request('GET', 'crimes-no-location', **kwargs):
crimes.append(NoLocationCrime(self, data=c))
return crimes | python | def get_crimes_no_location(self, force, date=None, category=None):
"""
Get crimes with no location for a force. Uses the crimes-no-location_
API call.
.. _crimes-no-location:
https://data.police.uk/docs/method/crimes-no-location/
:rtype: list
:param force: The force to get no-location crimes for.
:type force: str or Force
:param date: The month in which the crimes were reported in the format
``YYYY-MM`` (the latest date is used if ``None``).
:type date: str or None
:param category: The category of the crimes to filter by (either by ID
or CrimeCategory object)
:type category: str or CrimeCategory
:return: A ``list`` of :class:`crime.NoLocationCrime` objects which
were reported in the given month, by the specified force, but
which don't have a location.
"""
if not isinstance(force, Force):
force = Force(self, id=force)
if isinstance(category, CrimeCategory):
category = category.id
kwargs = {
'force': force.id,
'category': category or 'all-crime',
}
crimes = []
if date is not None:
kwargs['date'] = date
for c in self.service.request('GET', 'crimes-no-location', **kwargs):
crimes.append(NoLocationCrime(self, data=c))
return crimes | Get crimes with no location for a force. Uses the crimes-no-location_
API call.
.. _crimes-no-location:
https://data.police.uk/docs/method/crimes-no-location/
:rtype: list
:param force: The force to get no-location crimes for.
:type force: str or Force
:param date: The month in which the crimes were reported in the format
``YYYY-MM`` (the latest date is used if ``None``).
:type date: str or None
:param category: The category of the crimes to filter by (either by ID
or CrimeCategory object)
:type category: str or CrimeCategory
:return: A ``list`` of :class:`crime.NoLocationCrime` objects which
were reported in the given month, by the specified force, but
which don't have a location. | https://github.com/rkhleics/police-api-client-python/blob/b5c1e493487eb2409e2c04ed9fbd304f73d89fdc/police_api/__init__.py#L331-L368 |
MeaningCloud/meaningcloud-python | meaningcloud/SentimentResponse.py | SentimentResponse.scoreTagToString | def scoreTagToString(self, scoreTag):
"""
:param scoreTag:
:return:
"""
scoreTagToString = ""
if scoreTag == "P+":
scoreTagToString = 'strong positive'
elif scoreTag == "P":
scoreTagToString = 'positive'
elif scoreTag == "NEU":
scoreTagToString = 'neutral'
elif scoreTag == "N":
scoreTagToString = 'negative'
elif scoreTag == "N+":
scoreTagToString = 'strong negative'
elif scoreTag == "NONE":
scoreTagToString = 'no sentiment'
return scoreTagToString | python | def scoreTagToString(self, scoreTag):
"""
:param scoreTag:
:return:
"""
scoreTagToString = ""
if scoreTag == "P+":
scoreTagToString = 'strong positive'
elif scoreTag == "P":
scoreTagToString = 'positive'
elif scoreTag == "NEU":
scoreTagToString = 'neutral'
elif scoreTag == "N":
scoreTagToString = 'negative'
elif scoreTag == "N+":
scoreTagToString = 'strong negative'
elif scoreTag == "NONE":
scoreTagToString = 'no sentiment'
return scoreTagToString | :param scoreTag:
:return: | https://github.com/MeaningCloud/meaningcloud-python/blob/1dd76ecabeedd80c9bb14a1716d39657d645775f/meaningcloud/SentimentResponse.py#L177-L197 |
MaxStrange/retrowrapper | retrowrapper.py | _retrocom | def _retrocom(rx, tx, game, kwargs):
"""
This function is the target for RetroWrapper's internal
process and does all the work of communicating with the
environment.
"""
env = RetroWrapper.retro_make_func(game, **kwargs)
# Sit around on the queue, waiting for calls from RetroWrapper
while True:
attr, args, kwargs = rx.get()
# First, handle special case where the wrapper is asking if attr is callable.
# In this case, we actually have RetroWrapper.symbol, attr, and {}.
if attr == RetroWrapper.symbol:
result = env.__getattribute__(args)
tx.put(callable(result))
elif attr == "close":
env.close()
break
else:
# Otherwise, handle the request
result = getattr(env, attr)
if callable(result):
result = result(*args, **kwargs)
tx.put(result) | python | def _retrocom(rx, tx, game, kwargs):
"""
This function is the target for RetroWrapper's internal
process and does all the work of communicating with the
environment.
"""
env = RetroWrapper.retro_make_func(game, **kwargs)
# Sit around on the queue, waiting for calls from RetroWrapper
while True:
attr, args, kwargs = rx.get()
# First, handle special case where the wrapper is asking if attr is callable.
# In this case, we actually have RetroWrapper.symbol, attr, and {}.
if attr == RetroWrapper.symbol:
result = env.__getattribute__(args)
tx.put(callable(result))
elif attr == "close":
env.close()
break
else:
# Otherwise, handle the request
result = getattr(env, attr)
if callable(result):
result = result(*args, **kwargs)
tx.put(result) | This function is the target for RetroWrapper's internal
process and does all the work of communicating with the
environment. | https://github.com/MaxStrange/retrowrapper/blob/f9a112e07ee432d5f34b3a167902e808cfb0e84f/retrowrapper.py#L13-L38 |
MaxStrange/retrowrapper | retrowrapper.py | RetroWrapper._ask_if_attr_is_callable | def _ask_if_attr_is_callable(self, attr):
"""
Returns whether or not the attribute is a callable.
"""
self._tx.put((RetroWrapper.symbol, attr, {}))
return self._rx.get() | python | def _ask_if_attr_is_callable(self, attr):
"""
Returns whether or not the attribute is a callable.
"""
self._tx.put((RetroWrapper.symbol, attr, {}))
return self._rx.get() | Returns whether or not the attribute is a callable. | https://github.com/MaxStrange/retrowrapper/blob/f9a112e07ee432d5f34b3a167902e808cfb0e84f/retrowrapper.py#L133-L138 |
MaxStrange/retrowrapper | retrowrapper.py | RetroWrapper.close | def close(self):
"""
Shutdown the environment.
"""
if "_tx" in self.__dict__ and "_proc" in self.__dict__:
self._tx.put(("close", (), {}))
self._proc.join() | python | def close(self):
"""
Shutdown the environment.
"""
if "_tx" in self.__dict__ and "_proc" in self.__dict__:
self._tx.put(("close", (), {}))
self._proc.join() | Shutdown the environment. | https://github.com/MaxStrange/retrowrapper/blob/f9a112e07ee432d5f34b3a167902e808cfb0e84f/retrowrapper.py#L140-L146 |
MeaningCloud/meaningcloud-python | meaningcloud/Request.py | Request.addParam | def addParam(self, paramName, paramValue):
"""
Add a parameter to the request
:param paramName:
Name of the parameter
:param paramValue:
Value of the parameter
"""
if not paramName:
raise ValueError('paramName cannot be empty')
self._params[paramName] = paramValue | python | def addParam(self, paramName, paramValue):
"""
Add a parameter to the request
:param paramName:
Name of the parameter
:param paramValue:
Value of the parameter
"""
if not paramName:
raise ValueError('paramName cannot be empty')
self._params[paramName] = paramValue | Add a parameter to the request
:param paramName:
Name of the parameter
:param paramValue:
Value of the parameter | https://github.com/MeaningCloud/meaningcloud-python/blob/1dd76ecabeedd80c9bb14a1716d39657d645775f/meaningcloud/Request.py#L37-L49 |
MeaningCloud/meaningcloud-python | meaningcloud/Request.py | Request.setContent | def setContent(self, type_, value):
"""
Sets the content that's going to be sent to analyze according to its type
:param type_:
Type of the content (text, file or url)
:param value:
Value of the content
"""
if type_ in [self.CONTENT_TYPE_TXT, self.CONTENT_TYPE_URL,
self.CONTENT_TYPE_FILE]:
if type_ == self.CONTENT_TYPE_FILE:
self._file = {}
self._file = {'doc': open(value, 'rb')}
else:
self.addParam(type_, value) | python | def setContent(self, type_, value):
"""
Sets the content that's going to be sent to analyze according to its type
:param type_:
Type of the content (text, file or url)
:param value:
Value of the content
"""
if type_ in [self.CONTENT_TYPE_TXT, self.CONTENT_TYPE_URL,
self.CONTENT_TYPE_FILE]:
if type_ == self.CONTENT_TYPE_FILE:
self._file = {}
self._file = {'doc': open(value, 'rb')}
else:
self.addParam(type_, value) | Sets the content that's going to be sent to analyze according to its type
:param type_:
Type of the content (text, file or url)
:param value:
Value of the content | https://github.com/MeaningCloud/meaningcloud-python/blob/1dd76ecabeedd80c9bb14a1716d39657d645775f/meaningcloud/Request.py#L51-L67 |
MeaningCloud/meaningcloud-python | meaningcloud/Request.py | Request.sendRequest | def sendRequest(self, extraHeaders=""):
"""
Sends a request to the URL specified and returns a response only if the HTTP code returned is OK
:param extraHeaders:
Allows to configure additional headers in the request
:return:
Response object set to None if there is an error
"""
self.addParam('src', 'mc-python')
params = urlencode(self._params)
url = self._url
if 'doc' in self._file.keys():
headers = {}
if (extraHeaders is not None) and (extraHeaders is dict):
headers = headers.update(extraHeaders)
result = requests.post(url=url, data=self._params, files=self._file, headers=headers)
result.encoding = 'utf-8'
return result
else:
headers = {'Content-Type': 'application/x-www-form-urlencoded'}
if (extraHeaders is not None) and (extraHeaders is dict):
headers = headers.update(extraHeaders)
result = requests.request("POST", url=url, data=params, headers=headers)
result.encoding = 'utf-8'
return result | python | def sendRequest(self, extraHeaders=""):
"""
Sends a request to the URL specified and returns a response only if the HTTP code returned is OK
:param extraHeaders:
Allows to configure additional headers in the request
:return:
Response object set to None if there is an error
"""
self.addParam('src', 'mc-python')
params = urlencode(self._params)
url = self._url
if 'doc' in self._file.keys():
headers = {}
if (extraHeaders is not None) and (extraHeaders is dict):
headers = headers.update(extraHeaders)
result = requests.post(url=url, data=self._params, files=self._file, headers=headers)
result.encoding = 'utf-8'
return result
else:
headers = {'Content-Type': 'application/x-www-form-urlencoded'}
if (extraHeaders is not None) and (extraHeaders is dict):
headers = headers.update(extraHeaders)
result = requests.request("POST", url=url, data=params, headers=headers)
result.encoding = 'utf-8'
return result | Sends a request to the URL specified and returns a response only if the HTTP code returned is OK
:param extraHeaders:
Allows to configure additional headers in the request
:return:
Response object set to None if there is an error | https://github.com/MeaningCloud/meaningcloud-python/blob/1dd76ecabeedd80c9bb14a1716d39657d645775f/meaningcloud/Request.py#L99-L130 |
MeaningCloud/meaningcloud-python | meaningcloud/ParserResponse.py | ParserResponse.getLemmatization | def getLemmatization(self, fullPOSTag=False):
"""
This function obtains the lemmas and PoS for the text sent
:param fullPOSTag:
Set to true to obtain the complete PoS tag
:return:
Dictionary of tokens from the syntactic tree with their lemmas and PoS
"""
leaves = self._getTreeLeaves()
lemmas = {}
for leaf in leaves:
analyses = []
if 'analysis_list' in leaf.keys():
for analysis in leaf['analysis_list']:
analyses.append({
'lemma': analysis['lemma'],
'pos': analysis['tag'] if fullPOSTag else analysis['tag'][:2]
})
lemmas[leaf['form']] = analyses
return lemmas | python | def getLemmatization(self, fullPOSTag=False):
"""
This function obtains the lemmas and PoS for the text sent
:param fullPOSTag:
Set to true to obtain the complete PoS tag
:return:
Dictionary of tokens from the syntactic tree with their lemmas and PoS
"""
leaves = self._getTreeLeaves()
lemmas = {}
for leaf in leaves:
analyses = []
if 'analysis_list' in leaf.keys():
for analysis in leaf['analysis_list']:
analyses.append({
'lemma': analysis['lemma'],
'pos': analysis['tag'] if fullPOSTag else analysis['tag'][:2]
})
lemmas[leaf['form']] = analyses
return lemmas | This function obtains the lemmas and PoS for the text sent
:param fullPOSTag:
Set to true to obtain the complete PoS tag
:return:
Dictionary of tokens from the syntactic tree with their lemmas and PoS | https://github.com/MeaningCloud/meaningcloud-python/blob/1dd76ecabeedd80c9bb14a1716d39657d645775f/meaningcloud/ParserResponse.py#L22-L44 |
MeaningCloud/meaningcloud-python | meaningcloud/TopicsResponse.py | TopicsResponse.getTypeLastNode | def getTypeLastNode(self, type_):
"""
Obtains the last node or leaf of the type specified
:param type_:
Type we want to analize (sementity, semtheme)
:return:
Last node of the type
"""
lastNode = ""
if type_ and (type(type_) is not list) and (type(type_) is not dict):
aType = type_.split('>')
lastNode = aType[len(aType) - 1]
return lastNode | python | def getTypeLastNode(self, type_):
"""
Obtains the last node or leaf of the type specified
:param type_:
Type we want to analize (sementity, semtheme)
:return:
Last node of the type
"""
lastNode = ""
if type_ and (type(type_) is not list) and (type(type_) is not dict):
aType = type_.split('>')
lastNode = aType[len(aType) - 1]
return lastNode | Obtains the last node or leaf of the type specified
:param type_:
Type we want to analize (sementity, semtheme)
:return:
Last node of the type | https://github.com/MeaningCloud/meaningcloud-python/blob/1dd76ecabeedd80c9bb14a1716d39657d645775f/meaningcloud/TopicsResponse.py#L161-L175 |
tcalmant/ipopo | pelix/remote/discovery/zookeeper.py | ZooKeeperClient.__conn_listener | def __conn_listener(self, state):
"""
Connection event listener
:param state: The new connection state
"""
if state == KazooState.CONNECTED:
self.__online = True
if not self.__connected:
self.__connected = True
self._logger.info("Connected to ZooKeeper")
self._queue.enqueue(self.on_first_connection)
else:
self._logger.warning("Re-connected to ZooKeeper")
self._queue.enqueue(self.on_client_reconnection)
elif state == KazooState.SUSPENDED:
self._logger.warning("Connection suspended")
self.__online = False
elif state == KazooState.LOST:
self.__online = False
self.__connected = False
if self.__stop:
self._logger.info("Disconnected from ZooKeeper (requested)")
else:
self._logger.warning("Connection lost") | python | def __conn_listener(self, state):
"""
Connection event listener
:param state: The new connection state
"""
if state == KazooState.CONNECTED:
self.__online = True
if not self.__connected:
self.__connected = True
self._logger.info("Connected to ZooKeeper")
self._queue.enqueue(self.on_first_connection)
else:
self._logger.warning("Re-connected to ZooKeeper")
self._queue.enqueue(self.on_client_reconnection)
elif state == KazooState.SUSPENDED:
self._logger.warning("Connection suspended")
self.__online = False
elif state == KazooState.LOST:
self.__online = False
self.__connected = False
if self.__stop:
self._logger.info("Disconnected from ZooKeeper (requested)")
else:
self._logger.warning("Connection lost") | Connection event listener
:param state: The new connection state | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/remote/discovery/zookeeper.py#L135-L160 |
tcalmant/ipopo | pelix/remote/discovery/zookeeper.py | ZooKeeperClient.start | def start(self):
"""
Starts the connection
"""
self.__stop = False
self._queue.start()
self._zk.start() | python | def start(self):
"""
Starts the connection
"""
self.__stop = False
self._queue.start()
self._zk.start() | Starts the connection | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/remote/discovery/zookeeper.py#L162-L168 |
tcalmant/ipopo | pelix/remote/discovery/zookeeper.py | ZooKeeperClient.stop | def stop(self):
"""
Stops the connection
"""
self.__stop = True
self._queue.stop()
self._zk.stop() | python | def stop(self):
"""
Stops the connection
"""
self.__stop = True
self._queue.stop()
self._zk.stop() | Stops the connection | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/remote/discovery/zookeeper.py#L170-L176 |
tcalmant/ipopo | pelix/remote/discovery/zookeeper.py | ZooKeeperClient.__path | def __path(self, path):
"""
Adds the prefix to the given path
:param path: Z-Path
:return: Prefixed Z-Path
"""
if path.startswith(self.__prefix):
return path
return "{}{}".format(self.__prefix, path) | python | def __path(self, path):
"""
Adds the prefix to the given path
:param path: Z-Path
:return: Prefixed Z-Path
"""
if path.startswith(self.__prefix):
return path
return "{}{}".format(self.__prefix, path) | Adds the prefix to the given path
:param path: Z-Path
:return: Prefixed Z-Path | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/remote/discovery/zookeeper.py#L192-L202 |
tcalmant/ipopo | pelix/remote/discovery/zookeeper.py | ZooKeeperClient.create | def create(self, path, data, ephemeral=False, sequence=False):
"""
Creates a ZooKeeper node
:param path: Z-Path
:param data: Node Content
:param ephemeral: Ephemeral flag
:param sequence: Sequential flag
"""
return self._zk.create(
self.__path(path), data, ephemeral=ephemeral, sequence=sequence
) | python | def create(self, path, data, ephemeral=False, sequence=False):
"""
Creates a ZooKeeper node
:param path: Z-Path
:param data: Node Content
:param ephemeral: Ephemeral flag
:param sequence: Sequential flag
"""
return self._zk.create(
self.__path(path), data, ephemeral=ephemeral, sequence=sequence
) | Creates a ZooKeeper node
:param path: Z-Path
:param data: Node Content
:param ephemeral: Ephemeral flag
:param sequence: Sequential flag | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/remote/discovery/zookeeper.py#L204-L215 |
tcalmant/ipopo | pelix/remote/discovery/zookeeper.py | ZooKeeperClient.get | def get(self, path, watch=None):
"""
Gets the content of a ZooKeeper node
:param path: Z-Path
:param watch: Watch method
"""
return self._zk.get(self.__path(path), watch=watch) | python | def get(self, path, watch=None):
"""
Gets the content of a ZooKeeper node
:param path: Z-Path
:param watch: Watch method
"""
return self._zk.get(self.__path(path), watch=watch) | Gets the content of a ZooKeeper node
:param path: Z-Path
:param watch: Watch method | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/remote/discovery/zookeeper.py#L225-L232 |
tcalmant/ipopo | pelix/remote/discovery/zookeeper.py | ZooKeeperClient.get_children | def get_children(self, path, watch=None):
"""
Gets the list of children of a node
:param path: Z-Path
:param watch: Watch method
"""
return self._zk.get_children(self.__path(path), watch=watch) | python | def get_children(self, path, watch=None):
"""
Gets the list of children of a node
:param path: Z-Path
:param watch: Watch method
"""
return self._zk.get_children(self.__path(path), watch=watch) | Gets the list of children of a node
:param path: Z-Path
:param watch: Watch method | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/remote/discovery/zookeeper.py#L234-L241 |
tcalmant/ipopo | pelix/remote/discovery/zookeeper.py | ZooKeeperClient.set | def set(self, path, data):
"""
Sets the content of a ZooKeeper node
:param path: Z-Path
:param data: New content
"""
return self._zk.set(self.__path(path), data) | python | def set(self, path, data):
"""
Sets the content of a ZooKeeper node
:param path: Z-Path
:param data: New content
"""
return self._zk.set(self.__path(path), data) | Sets the content of a ZooKeeper node
:param path: Z-Path
:param data: New content | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/remote/discovery/zookeeper.py#L243-L250 |
tcalmant/ipopo | pelix/ipopo/constants.py | get_ipopo_svc_ref | def get_ipopo_svc_ref(bundle_context):
# type: (BundleContext) -> Optional[Tuple[ServiceReference, Any]]
"""
Retrieves a tuple containing the service reference to iPOPO and the service
itself
:param bundle_context: The calling bundle context
:return: The reference to the iPOPO service and the service itself,
None if not available
"""
# Look after the service
ref = bundle_context.get_service_reference(SERVICE_IPOPO)
if ref is None:
return None
try:
# Get it
svc = bundle_context.get_service(ref)
except BundleException:
# Service reference has been invalidated
return None
# Return both the reference (to call unget_service()) and the service
return ref, svc | python | def get_ipopo_svc_ref(bundle_context):
# type: (BundleContext) -> Optional[Tuple[ServiceReference, Any]]
"""
Retrieves a tuple containing the service reference to iPOPO and the service
itself
:param bundle_context: The calling bundle context
:return: The reference to the iPOPO service and the service itself,
None if not available
"""
# Look after the service
ref = bundle_context.get_service_reference(SERVICE_IPOPO)
if ref is None:
return None
try:
# Get it
svc = bundle_context.get_service(ref)
except BundleException:
# Service reference has been invalidated
return None
# Return both the reference (to call unget_service()) and the service
return ref, svc | Retrieves a tuple containing the service reference to iPOPO and the service
itself
:param bundle_context: The calling bundle context
:return: The reference to the iPOPO service and the service itself,
None if not available | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ipopo/constants.py#L189-L212 |
tcalmant/ipopo | pelix/ipopo/constants.py | use_ipopo | def use_ipopo(bundle_context):
# type: (BundleContext) -> Any
"""
Utility context to use the iPOPO service safely in a "with" block.
It looks after the the iPOPO service and releases its reference when
exiting the context.
:param bundle_context: The calling bundle context
:return: The iPOPO service
:raise BundleException: Service not found
"""
# Get the service and its reference
ref_svc = get_ipopo_svc_ref(bundle_context)
if ref_svc is None:
raise BundleException("No iPOPO service available")
try:
# Give the service
yield ref_svc[1]
finally:
try:
# Release it
bundle_context.unget_service(ref_svc[0])
except BundleException:
# Service might have already been unregistered
pass | python | def use_ipopo(bundle_context):
# type: (BundleContext) -> Any
"""
Utility context to use the iPOPO service safely in a "with" block.
It looks after the the iPOPO service and releases its reference when
exiting the context.
:param bundle_context: The calling bundle context
:return: The iPOPO service
:raise BundleException: Service not found
"""
# Get the service and its reference
ref_svc = get_ipopo_svc_ref(bundle_context)
if ref_svc is None:
raise BundleException("No iPOPO service available")
try:
# Give the service
yield ref_svc[1]
finally:
try:
# Release it
bundle_context.unget_service(ref_svc[0])
except BundleException:
# Service might have already been unregistered
pass | Utility context to use the iPOPO service safely in a "with" block.
It looks after the the iPOPO service and releases its reference when
exiting the context.
:param bundle_context: The calling bundle context
:return: The iPOPO service
:raise BundleException: Service not found | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ipopo/constants.py#L216-L241 |
tcalmant/ipopo | pelix/ipopo/constants.py | use_waiting_list | def use_waiting_list(bundle_context):
# type: (BundleContext) -> Any
"""
Utility context to use the iPOPO waiting list safely in a "with" block.
It looks after the the iPOPO waiting list service and releases its
reference when exiting the context.
:param bundle_context: The calling bundle context
:return: The iPOPO waiting list service
:raise BundleException: Service not found
"""
# Get the service and its reference
ref = bundle_context.get_service_reference(SERVICE_IPOPO_WAITING_LIST)
if ref is None:
raise BundleException("No iPOPO waiting list service available")
try:
# Give the service
yield bundle_context.get_service(ref)
finally:
try:
# Release it
bundle_context.unget_service(ref)
except BundleException:
# Service might have already been unregistered
pass | python | def use_waiting_list(bundle_context):
# type: (BundleContext) -> Any
"""
Utility context to use the iPOPO waiting list safely in a "with" block.
It looks after the the iPOPO waiting list service and releases its
reference when exiting the context.
:param bundle_context: The calling bundle context
:return: The iPOPO waiting list service
:raise BundleException: Service not found
"""
# Get the service and its reference
ref = bundle_context.get_service_reference(SERVICE_IPOPO_WAITING_LIST)
if ref is None:
raise BundleException("No iPOPO waiting list service available")
try:
# Give the service
yield bundle_context.get_service(ref)
finally:
try:
# Release it
bundle_context.unget_service(ref)
except BundleException:
# Service might have already been unregistered
pass | Utility context to use the iPOPO waiting list safely in a "with" block.
It looks after the the iPOPO waiting list service and releases its
reference when exiting the context.
:param bundle_context: The calling bundle context
:return: The iPOPO waiting list service
:raise BundleException: Service not found | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ipopo/constants.py#L245-L270 |
tcalmant/ipopo | pelix/misc/jabsorb.py | _compute_jsonclass | def _compute_jsonclass(obj):
"""
Compute the content of the __jsonclass__ field for the given object
:param obj: An object
:return: The content of the __jsonclass__ field
"""
# It's not a standard type, so it needs __jsonclass__
module_name = inspect.getmodule(obj).__name__
json_class = obj.__class__.__name__
if module_name not in ("", "__main__"):
json_class = "{0}.{1}".format(module_name, json_class)
return [json_class, []] | python | def _compute_jsonclass(obj):
"""
Compute the content of the __jsonclass__ field for the given object
:param obj: An object
:return: The content of the __jsonclass__ field
"""
# It's not a standard type, so it needs __jsonclass__
module_name = inspect.getmodule(obj).__name__
json_class = obj.__class__.__name__
if module_name not in ("", "__main__"):
json_class = "{0}.{1}".format(module_name, json_class)
return [json_class, []] | Compute the content of the __jsonclass__ field for the given object
:param obj: An object
:return: The content of the __jsonclass__ field | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/misc/jabsorb.py#L141-L154 |
tcalmant/ipopo | pelix/misc/jabsorb.py | _is_builtin | def _is_builtin(obj):
"""
Checks if the type of the given object is a built-in one or not
:param obj: An object
:return: True if the object is of a built-in type
"""
module_ = inspect.getmodule(obj)
if module_ in (None, builtins):
return True
return module_.__name__ in ("", "__main__") | python | def _is_builtin(obj):
"""
Checks if the type of the given object is a built-in one or not
:param obj: An object
:return: True if the object is of a built-in type
"""
module_ = inspect.getmodule(obj)
if module_ in (None, builtins):
return True
return module_.__name__ in ("", "__main__") | Checks if the type of the given object is a built-in one or not
:param obj: An object
:return: True if the object is of a built-in type | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/misc/jabsorb.py#L157-L168 |
tcalmant/ipopo | pelix/misc/jabsorb.py | _is_converted_class | def _is_converted_class(java_class):
"""
Checks if the given Java class is one we *might* have set up
"""
if not java_class:
return False
return (
JAVA_MAPS_PATTERN.match(java_class) is not None
or JAVA_LISTS_PATTERN.match(java_class) is not None
or JAVA_SETS_PATTERN.match(java_class) is not None
) | python | def _is_converted_class(java_class):
"""
Checks if the given Java class is one we *might* have set up
"""
if not java_class:
return False
return (
JAVA_MAPS_PATTERN.match(java_class) is not None
or JAVA_LISTS_PATTERN.match(java_class) is not None
or JAVA_SETS_PATTERN.match(java_class) is not None
) | Checks if the given Java class is one we *might* have set up | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/misc/jabsorb.py#L171-L182 |
tcalmant/ipopo | pelix/misc/jabsorb.py | to_jabsorb | def to_jabsorb(value):
"""
Adds information for Jabsorb, if needed.
Converts maps and lists to a jabsorb form.
Keeps tuples as is, to let them be considered as arrays.
:param value: A Python result to send to Jabsorb
:return: The result in a Jabsorb map format (not a JSON object)
"""
# None ?
if value is None:
return None
# Map ?
elif isinstance(value, dict):
if JAVA_CLASS in value or JSON_CLASS in value:
if not _is_converted_class(value.get(JAVA_CLASS)):
# Bean representation
converted_result = {}
for key, content in value.items():
converted_result[key] = to_jabsorb(content)
try:
# Keep the raw jsonrpclib information
converted_result[JSON_CLASS] = value[JSON_CLASS]
except KeyError:
pass
else:
# We already worked on this value
converted_result = value
else:
# Needs the whole transformation
converted_result = {JAVA_CLASS: "java.util.HashMap"}
converted_result["map"] = map_pairs = {}
for key, content in value.items():
map_pairs[key] = to_jabsorb(content)
try:
# Keep the raw jsonrpclib information
map_pairs[JSON_CLASS] = value[JSON_CLASS]
except KeyError:
pass
# List ? (consider tuples as an array)
elif isinstance(value, list):
converted_result = {
JAVA_CLASS: "java.util.ArrayList",
"list": [to_jabsorb(entry) for entry in value],
}
# Set ?
elif isinstance(value, (set, frozenset)):
converted_result = {
JAVA_CLASS: "java.util.HashSet",
"set": [to_jabsorb(entry) for entry in value],
}
# Tuple ? (used as array, except if it is empty)
elif isinstance(value, tuple):
converted_result = [to_jabsorb(entry) for entry in value]
elif hasattr(value, JAVA_CLASS):
# Class with a Java class hint: convert into a dictionary
class_members = {
name: getattr(value, name)
for name in dir(value)
if not name.startswith("_")
}
converted_result = HashableDict(
(name, to_jabsorb(content))
for name, content in class_members.items()
if not inspect.ismethod(content)
)
# Do not forget the Java class
converted_result[JAVA_CLASS] = getattr(value, JAVA_CLASS)
# Also add a __jsonclass__ entry
converted_result[JSON_CLASS] = _compute_jsonclass(value)
# Other ?
else:
converted_result = value
return converted_result | python | def to_jabsorb(value):
"""
Adds information for Jabsorb, if needed.
Converts maps and lists to a jabsorb form.
Keeps tuples as is, to let them be considered as arrays.
:param value: A Python result to send to Jabsorb
:return: The result in a Jabsorb map format (not a JSON object)
"""
# None ?
if value is None:
return None
# Map ?
elif isinstance(value, dict):
if JAVA_CLASS in value or JSON_CLASS in value:
if not _is_converted_class(value.get(JAVA_CLASS)):
# Bean representation
converted_result = {}
for key, content in value.items():
converted_result[key] = to_jabsorb(content)
try:
# Keep the raw jsonrpclib information
converted_result[JSON_CLASS] = value[JSON_CLASS]
except KeyError:
pass
else:
# We already worked on this value
converted_result = value
else:
# Needs the whole transformation
converted_result = {JAVA_CLASS: "java.util.HashMap"}
converted_result["map"] = map_pairs = {}
for key, content in value.items():
map_pairs[key] = to_jabsorb(content)
try:
# Keep the raw jsonrpclib information
map_pairs[JSON_CLASS] = value[JSON_CLASS]
except KeyError:
pass
# List ? (consider tuples as an array)
elif isinstance(value, list):
converted_result = {
JAVA_CLASS: "java.util.ArrayList",
"list": [to_jabsorb(entry) for entry in value],
}
# Set ?
elif isinstance(value, (set, frozenset)):
converted_result = {
JAVA_CLASS: "java.util.HashSet",
"set": [to_jabsorb(entry) for entry in value],
}
# Tuple ? (used as array, except if it is empty)
elif isinstance(value, tuple):
converted_result = [to_jabsorb(entry) for entry in value]
elif hasattr(value, JAVA_CLASS):
# Class with a Java class hint: convert into a dictionary
class_members = {
name: getattr(value, name)
for name in dir(value)
if not name.startswith("_")
}
converted_result = HashableDict(
(name, to_jabsorb(content))
for name, content in class_members.items()
if not inspect.ismethod(content)
)
# Do not forget the Java class
converted_result[JAVA_CLASS] = getattr(value, JAVA_CLASS)
# Also add a __jsonclass__ entry
converted_result[JSON_CLASS] = _compute_jsonclass(value)
# Other ?
else:
converted_result = value
return converted_result | Adds information for Jabsorb, if needed.
Converts maps and lists to a jabsorb form.
Keeps tuples as is, to let them be considered as arrays.
:param value: A Python result to send to Jabsorb
:return: The result in a Jabsorb map format (not a JSON object) | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/misc/jabsorb.py#L188-L277 |
tcalmant/ipopo | pelix/misc/jabsorb.py | from_jabsorb | def from_jabsorb(request, seems_raw=False):
"""
Transforms a jabsorb request into a more Python data model (converts maps
and lists)
:param request: Data coming from Jabsorb
:param seems_raw: Set it to True if the given data seems to already have
been parsed (no Java class hint). If True, the lists will
be kept as lists instead of being converted to tuples.
:return: A Python representation of the given data
"""
if isinstance(request, (tuple, set, frozenset)):
# Special case : JSON arrays (Python lists)
return type(request)(from_jabsorb(element) for element in request)
elif isinstance(request, list):
# Check if we were a list or a tuple
if seems_raw:
return list(from_jabsorb(element) for element in request)
return tuple(from_jabsorb(element) for element in request)
elif isinstance(request, dict):
# Dictionary
java_class = request.get(JAVA_CLASS)
json_class = request.get(JSON_CLASS)
seems_raw = not java_class and not json_class
if java_class:
# Java Map ?
if JAVA_MAPS_PATTERN.match(java_class) is not None:
return HashableDict(
(from_jabsorb(key), from_jabsorb(value))
for key, value in request["map"].items()
)
# Java List ?
elif JAVA_LISTS_PATTERN.match(java_class) is not None:
return HashableList(
from_jabsorb(element) for element in request["list"]
)
# Java Set ?
elif JAVA_SETS_PATTERN.match(java_class) is not None:
return HashableSet(
from_jabsorb(element) for element in request["set"]
)
# Any other case
result = AttributeMap(
(from_jabsorb(key), from_jabsorb(value, seems_raw))
for key, value in request.items()
)
# Keep JSON class information as is
if json_class:
result[JSON_CLASS] = json_class
return result
elif not _is_builtin(request):
# Bean
for attr in dir(request):
# Only convert public fields
if not attr[0] == "_":
# Field conversion
setattr(request, attr, from_jabsorb(getattr(request, attr)))
return request
else:
# Any other case
return request | python | def from_jabsorb(request, seems_raw=False):
"""
Transforms a jabsorb request into a more Python data model (converts maps
and lists)
:param request: Data coming from Jabsorb
:param seems_raw: Set it to True if the given data seems to already have
been parsed (no Java class hint). If True, the lists will
be kept as lists instead of being converted to tuples.
:return: A Python representation of the given data
"""
if isinstance(request, (tuple, set, frozenset)):
# Special case : JSON arrays (Python lists)
return type(request)(from_jabsorb(element) for element in request)
elif isinstance(request, list):
# Check if we were a list or a tuple
if seems_raw:
return list(from_jabsorb(element) for element in request)
return tuple(from_jabsorb(element) for element in request)
elif isinstance(request, dict):
# Dictionary
java_class = request.get(JAVA_CLASS)
json_class = request.get(JSON_CLASS)
seems_raw = not java_class and not json_class
if java_class:
# Java Map ?
if JAVA_MAPS_PATTERN.match(java_class) is not None:
return HashableDict(
(from_jabsorb(key), from_jabsorb(value))
for key, value in request["map"].items()
)
# Java List ?
elif JAVA_LISTS_PATTERN.match(java_class) is not None:
return HashableList(
from_jabsorb(element) for element in request["list"]
)
# Java Set ?
elif JAVA_SETS_PATTERN.match(java_class) is not None:
return HashableSet(
from_jabsorb(element) for element in request["set"]
)
# Any other case
result = AttributeMap(
(from_jabsorb(key), from_jabsorb(value, seems_raw))
for key, value in request.items()
)
# Keep JSON class information as is
if json_class:
result[JSON_CLASS] = json_class
return result
elif not _is_builtin(request):
# Bean
for attr in dir(request):
# Only convert public fields
if not attr[0] == "_":
# Field conversion
setattr(request, attr, from_jabsorb(getattr(request, attr)))
return request
else:
# Any other case
return request | Transforms a jabsorb request into a more Python data model (converts maps
and lists)
:param request: Data coming from Jabsorb
:param seems_raw: Set it to True if the given data seems to already have
been parsed (no Java class hint). If True, the lists will
be kept as lists instead of being converted to tuples.
:return: A Python representation of the given data | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/misc/jabsorb.py#L280-L352 |
tcalmant/ipopo | pelix/ipopo/contexts.py | Requirement.copy | def copy(self):
# type: () -> Requirement
"""
Returns a copy of this instance
:return: A copy of this instance
"""
return Requirement(
self.specification,
self.aggregate,
self.optional,
self.__original_filter,
self.immediate_rebind,
) | python | def copy(self):
# type: () -> Requirement
"""
Returns a copy of this instance
:return: A copy of this instance
"""
return Requirement(
self.specification,
self.aggregate,
self.optional,
self.__original_filter,
self.immediate_rebind,
) | Returns a copy of this instance
:return: A copy of this instance | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ipopo/contexts.py#L146-L159 |
tcalmant/ipopo | pelix/ipopo/contexts.py | Requirement.set_filter | def set_filter(self, props_filter):
"""
Changes the current filter for the given one
:param props_filter: The new requirement filter on service properties
:raise TypeError: Unknown filter type
"""
if props_filter is not None and not (
is_string(props_filter)
or isinstance(
props_filter, (ldapfilter.LDAPFilter, ldapfilter.LDAPCriteria)
)
):
# Unknown type
raise TypeError(
"Invalid filter type {0}".format(type(props_filter).__name__)
)
if props_filter is not None:
# Filter given, keep its string form
self.__original_filter = str(props_filter)
else:
# No filter
self.__original_filter = None
# Parse the filter
self.filter = ldapfilter.get_ldap_filter(props_filter)
# Prepare the full filter
spec_filter = "({0}={1})".format(OBJECTCLASS, self.specification)
self.__full_filter = ldapfilter.combine_filters(
(spec_filter, self.filter)
) | python | def set_filter(self, props_filter):
"""
Changes the current filter for the given one
:param props_filter: The new requirement filter on service properties
:raise TypeError: Unknown filter type
"""
if props_filter is not None and not (
is_string(props_filter)
or isinstance(
props_filter, (ldapfilter.LDAPFilter, ldapfilter.LDAPCriteria)
)
):
# Unknown type
raise TypeError(
"Invalid filter type {0}".format(type(props_filter).__name__)
)
if props_filter is not None:
# Filter given, keep its string form
self.__original_filter = str(props_filter)
else:
# No filter
self.__original_filter = None
# Parse the filter
self.filter = ldapfilter.get_ldap_filter(props_filter)
# Prepare the full filter
spec_filter = "({0}={1})".format(OBJECTCLASS, self.specification)
self.__full_filter = ldapfilter.combine_filters(
(spec_filter, self.filter)
) | Changes the current filter for the given one
:param props_filter: The new requirement filter on service properties
:raise TypeError: Unknown filter type | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ipopo/contexts.py#L195-L227 |
tcalmant/ipopo | pelix/ipopo/contexts.py | FactoryContext._deepcopy | def _deepcopy(self, data):
"""
Deep copies the given object
:param data: Data to copy
:return: A copy of the data, if supported, else the data itself
"""
if isinstance(data, dict):
# Copy dictionary values
return {key: self._deepcopy(value) for key, value in data.items()}
elif isinstance(data, (list, tuple, set, frozenset)):
# Copy sequence types values
return type(data)(self._deepcopy(value) for value in data)
try:
# Try to use a copy() method, if any
return data.copy()
except AttributeError:
# Can't copy the data, return it as is
return data | python | def _deepcopy(self, data):
"""
Deep copies the given object
:param data: Data to copy
:return: A copy of the data, if supported, else the data itself
"""
if isinstance(data, dict):
# Copy dictionary values
return {key: self._deepcopy(value) for key, value in data.items()}
elif isinstance(data, (list, tuple, set, frozenset)):
# Copy sequence types values
return type(data)(self._deepcopy(value) for value in data)
try:
# Try to use a copy() method, if any
return data.copy()
except AttributeError:
# Can't copy the data, return it as is
return data | Deep copies the given object
:param data: Data to copy
:return: A copy of the data, if supported, else the data itself | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ipopo/contexts.py#L318-L337 |
tcalmant/ipopo | pelix/ipopo/contexts.py | FactoryContext.copy | def copy(self, inheritance=False):
# type: (bool) -> FactoryContext
"""
Returns a deep copy of the current FactoryContext instance
:param inheritance: If True, current handlers configurations are stored
as inherited ones
"""
# Create a new factory context and duplicate its values
new_context = FactoryContext()
for field in self.__slots__:
if not field.startswith("_"):
setattr(
new_context, field, self._deepcopy(getattr(self, field))
)
if inheritance:
# Store configuration as inherited one
new_context.__inherited_configuration = self.__handlers.copy()
new_context.__handlers = {}
# Remove instances in any case
new_context.__instances.clear()
new_context.is_singleton_active = False
return new_context | python | def copy(self, inheritance=False):
# type: (bool) -> FactoryContext
"""
Returns a deep copy of the current FactoryContext instance
:param inheritance: If True, current handlers configurations are stored
as inherited ones
"""
# Create a new factory context and duplicate its values
new_context = FactoryContext()
for field in self.__slots__:
if not field.startswith("_"):
setattr(
new_context, field, self._deepcopy(getattr(self, field))
)
if inheritance:
# Store configuration as inherited one
new_context.__inherited_configuration = self.__handlers.copy()
new_context.__handlers = {}
# Remove instances in any case
new_context.__instances.clear()
new_context.is_singleton_active = False
return new_context | Returns a deep copy of the current FactoryContext instance
:param inheritance: If True, current handlers configurations are stored
as inherited ones | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ipopo/contexts.py#L339-L363 |
tcalmant/ipopo | pelix/ipopo/contexts.py | FactoryContext.inherit_handlers | def inherit_handlers(self, excluded_handlers):
# type: (Iterable[str]) -> None
"""
Merges the inherited configuration with the current ones
:param excluded_handlers: Excluded handlers
"""
if not excluded_handlers:
excluded_handlers = tuple()
for handler, configuration in self.__inherited_configuration.items():
if handler in excluded_handlers:
# Excluded handler
continue
elif handler not in self.__handlers:
# Fully inherited configuration
self.__handlers[handler] = configuration
# Merge configuration...
elif isinstance(configuration, dict):
# Dictionary
self.__handlers.setdefault(handler, {}).update(configuration)
elif isinstance(configuration, list):
# List
handler_conf = self.__handlers.setdefault(handler, [])
for item in configuration:
if item not in handler_conf:
handler_conf.append(item)
# Clear the inherited configuration dictionary
self.__inherited_configuration.clear() | python | def inherit_handlers(self, excluded_handlers):
# type: (Iterable[str]) -> None
"""
Merges the inherited configuration with the current ones
:param excluded_handlers: Excluded handlers
"""
if not excluded_handlers:
excluded_handlers = tuple()
for handler, configuration in self.__inherited_configuration.items():
if handler in excluded_handlers:
# Excluded handler
continue
elif handler not in self.__handlers:
# Fully inherited configuration
self.__handlers[handler] = configuration
# Merge configuration...
elif isinstance(configuration, dict):
# Dictionary
self.__handlers.setdefault(handler, {}).update(configuration)
elif isinstance(configuration, list):
# List
handler_conf = self.__handlers.setdefault(handler, [])
for item in configuration:
if item not in handler_conf:
handler_conf.append(item)
# Clear the inherited configuration dictionary
self.__inherited_configuration.clear() | Merges the inherited configuration with the current ones
:param excluded_handlers: Excluded handlers | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ipopo/contexts.py#L365-L397 |
tcalmant/ipopo | pelix/ipopo/contexts.py | FactoryContext.add_instance | def add_instance(self, name, properties):
# type: (str, dict) -> None
"""
Stores the description of a component instance. The given properties
are stored as is.
:param name: Instance name
:param properties: Instance properties
:raise NameError: Already known instance name
"""
if name in self.__instances:
raise NameError(name)
# Store properties "as-is"
self.__instances[name] = properties | python | def add_instance(self, name, properties):
# type: (str, dict) -> None
"""
Stores the description of a component instance. The given properties
are stored as is.
:param name: Instance name
:param properties: Instance properties
:raise NameError: Already known instance name
"""
if name in self.__instances:
raise NameError(name)
# Store properties "as-is"
self.__instances[name] = properties | Stores the description of a component instance. The given properties
are stored as is.
:param name: Instance name
:param properties: Instance properties
:raise NameError: Already known instance name | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ipopo/contexts.py#L399-L413 |
tcalmant/ipopo | pelix/ipopo/contexts.py | ComponentContext.get_field_callback | def get_field_callback(self, field, event):
# type: (str, str) -> Optional[Tuple[Callable, bool]]
"""
Retrieves the registered method for the given event. Returns None if
not found
:param field: Name of the dependency field
:param event: A component life cycle event
:return: A 2-tuple containing the callback associated to the given
event and flag indicating if the callback must be called in
valid state only
"""
try:
return self.factory_context.field_callbacks[field][event]
except KeyError:
return None | python | def get_field_callback(self, field, event):
# type: (str, str) -> Optional[Tuple[Callable, bool]]
"""
Retrieves the registered method for the given event. Returns None if
not found
:param field: Name of the dependency field
:param event: A component life cycle event
:return: A 2-tuple containing the callback associated to the given
event and flag indicating if the callback must be called in
valid state only
"""
try:
return self.factory_context.field_callbacks[field][event]
except KeyError:
return None | Retrieves the registered method for the given event. Returns None if
not found
:param field: Name of the dependency field
:param event: A component life cycle event
:return: A 2-tuple containing the callback associated to the given
event and flag indicating if the callback must be called in
valid state only | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ipopo/contexts.py#L546-L561 |
tcalmant/ipopo | pelix/ipopo/contexts.py | ComponentContext.grab_hidden_properties | def grab_hidden_properties(self):
# type: () -> dict
"""
A one-shot access to hidden properties (the field is then destroyed)
:return: A copy of the hidden properties dictionary on the first call
:raise AttributeError: On any call after the first one
"""
# Copy properties
result = self.__hidden_properties.copy()
# Destroy the field
self.__hidden_properties.clear()
del self.__hidden_properties
return result | python | def grab_hidden_properties(self):
# type: () -> dict
"""
A one-shot access to hidden properties (the field is then destroyed)
:return: A copy of the hidden properties dictionary on the first call
:raise AttributeError: On any call after the first one
"""
# Copy properties
result = self.__hidden_properties.copy()
# Destroy the field
self.__hidden_properties.clear()
del self.__hidden_properties
return result | A one-shot access to hidden properties (the field is then destroyed)
:return: A copy of the hidden properties dictionary on the first call
:raise AttributeError: On any call after the first one | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ipopo/contexts.py#L590-L604 |
tcalmant/ipopo | pelix/ipopo/handlers/properties.py | PropertiesHandler._field_property_generator | def _field_property_generator(self, public_properties):
"""
Generates the methods called by the injected class properties
:param public_properties: If True, create a public property accessor,
else an hidden property accessor
:return: getter and setter methods
"""
# Local variable, to avoid messing with "self"
stored_instance = self._ipopo_instance
# Choose public or hidden properties
# and select the method to call to notify about the property update
if public_properties:
properties = stored_instance.context.properties
update_notifier = stored_instance.update_property
else:
# Copy Hidden properties and remove them from the context
properties = stored_instance.context.grab_hidden_properties()
update_notifier = stored_instance.update_hidden_property
def get_value(_, name):
"""
Retrieves the property value, from the iPOPO dictionaries
:param name: The property name
:return: The property value
"""
return properties.get(name)
def set_value(_, name, new_value):
"""
Sets the property value and trigger an update event
:param name: The property name
:param new_value: The new property value
"""
assert stored_instance.context is not None
# Get the previous value
old_value = properties.get(name)
if new_value != old_value:
# Change the property
properties[name] = new_value
# New value is different of the old one, trigger an event
update_notifier(name, old_value, new_value)
return new_value
return get_value, set_value | python | def _field_property_generator(self, public_properties):
"""
Generates the methods called by the injected class properties
:param public_properties: If True, create a public property accessor,
else an hidden property accessor
:return: getter and setter methods
"""
# Local variable, to avoid messing with "self"
stored_instance = self._ipopo_instance
# Choose public or hidden properties
# and select the method to call to notify about the property update
if public_properties:
properties = stored_instance.context.properties
update_notifier = stored_instance.update_property
else:
# Copy Hidden properties and remove them from the context
properties = stored_instance.context.grab_hidden_properties()
update_notifier = stored_instance.update_hidden_property
def get_value(_, name):
"""
Retrieves the property value, from the iPOPO dictionaries
:param name: The property name
:return: The property value
"""
return properties.get(name)
def set_value(_, name, new_value):
"""
Sets the property value and trigger an update event
:param name: The property name
:param new_value: The new property value
"""
assert stored_instance.context is not None
# Get the previous value
old_value = properties.get(name)
if new_value != old_value:
# Change the property
properties[name] = new_value
# New value is different of the old one, trigger an event
update_notifier(name, old_value, new_value)
return new_value
return get_value, set_value | Generates the methods called by the injected class properties
:param public_properties: If True, create a public property accessor,
else an hidden property accessor
:return: getter and setter methods | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ipopo/handlers/properties.py#L116-L166 |
tcalmant/ipopo | pelix/ipopo/handlers/properties.py | PropertiesHandler.get_methods_names | def get_methods_names(public_properties):
"""
Generates the names of the fields where to inject the getter and setter
methods
:param public_properties: If True, returns the names of public property
accessors, else of hidden property ones
:return: getter and a setter field names
"""
if public_properties:
prefix = ipopo_constants.IPOPO_PROPERTY_PREFIX
else:
prefix = ipopo_constants.IPOPO_HIDDEN_PROPERTY_PREFIX
return (
"{0}{1}".format(prefix, ipopo_constants.IPOPO_GETTER_SUFFIX),
"{0}{1}".format(prefix, ipopo_constants.IPOPO_SETTER_SUFFIX),
) | python | def get_methods_names(public_properties):
"""
Generates the names of the fields where to inject the getter and setter
methods
:param public_properties: If True, returns the names of public property
accessors, else of hidden property ones
:return: getter and a setter field names
"""
if public_properties:
prefix = ipopo_constants.IPOPO_PROPERTY_PREFIX
else:
prefix = ipopo_constants.IPOPO_HIDDEN_PROPERTY_PREFIX
return (
"{0}{1}".format(prefix, ipopo_constants.IPOPO_GETTER_SUFFIX),
"{0}{1}".format(prefix, ipopo_constants.IPOPO_SETTER_SUFFIX),
) | Generates the names of the fields where to inject the getter and setter
methods
:param public_properties: If True, returns the names of public property
accessors, else of hidden property ones
:return: getter and a setter field names | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ipopo/handlers/properties.py#L169-L186 |
tcalmant/ipopo | pelix/ipopo/handlers/properties.py | PropertiesHandler.manipulate | def manipulate(self, stored_instance, component_instance):
"""
Manipulates the component instance
:param stored_instance: The iPOPO component StoredInstance
:param component_instance: The component instance
"""
# Store the stored instance
self._ipopo_instance = stored_instance
# Public flags to generate (True for public accessors)
flags_to_generate = set()
if stored_instance.context.properties:
flags_to_generate.add(True)
# (False for hidden ones)
if stored_instance.context.has_hidden_properties():
flags_to_generate.add(False)
# Inject properties getters and setters
for public_flag in flags_to_generate:
# Prepare methods
getter, setter = self._field_property_generator(public_flag)
# Inject the getter and setter at the instance level
getter_name, setter_name = self.get_methods_names(public_flag)
setattr(component_instance, getter_name, getter)
setattr(component_instance, setter_name, setter) | python | def manipulate(self, stored_instance, component_instance):
"""
Manipulates the component instance
:param stored_instance: The iPOPO component StoredInstance
:param component_instance: The component instance
"""
# Store the stored instance
self._ipopo_instance = stored_instance
# Public flags to generate (True for public accessors)
flags_to_generate = set()
if stored_instance.context.properties:
flags_to_generate.add(True)
# (False for hidden ones)
if stored_instance.context.has_hidden_properties():
flags_to_generate.add(False)
# Inject properties getters and setters
for public_flag in flags_to_generate:
# Prepare methods
getter, setter = self._field_property_generator(public_flag)
# Inject the getter and setter at the instance level
getter_name, setter_name = self.get_methods_names(public_flag)
setattr(component_instance, getter_name, getter)
setattr(component_instance, setter_name, setter) | Manipulates the component instance
:param stored_instance: The iPOPO component StoredInstance
:param component_instance: The component instance | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ipopo/handlers/properties.py#L188-L215 |
tcalmant/ipopo | pelix/rsa/shell.py | _full_class_name | def _full_class_name(obj):
"""
Returns the full name of the class of the given object
:param obj: Any Python object
:return: The full name of the class of the object (if possible)
"""
module = obj.__class__.__module__
if module is None or module == str.__class__.__module__:
return obj.__class__.__name__
return module + "." + obj.__class__.__name__ | python | def _full_class_name(obj):
"""
Returns the full name of the class of the given object
:param obj: Any Python object
:return: The full name of the class of the object (if possible)
"""
module = obj.__class__.__module__
if module is None or module == str.__class__.__module__:
return obj.__class__.__name__
return module + "." + obj.__class__.__name__ | Returns the full name of the class of the given object
:param obj: Any Python object
:return: The full name of the class of the object (if possible) | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/rsa/shell.py#L87-L97 |
tcalmant/ipopo | pelix/shell/beans.py | IOHandler._prompt | def _prompt(self, prompt=None):
"""
Reads a line written by the user
:param prompt: An optional prompt message
:return: The read line, after a conversion to str
"""
if prompt:
# Print the prompt
self.write(prompt)
self.output.flush()
# Read the line
return to_str(self.input.readline()) | python | def _prompt(self, prompt=None):
"""
Reads a line written by the user
:param prompt: An optional prompt message
:return: The read line, after a conversion to str
"""
if prompt:
# Print the prompt
self.write(prompt)
self.output.flush()
# Read the line
return to_str(self.input.readline()) | Reads a line written by the user
:param prompt: An optional prompt message
:return: The read line, after a conversion to str | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/shell/beans.py#L195-L208 |
tcalmant/ipopo | pelix/shell/beans.py | IOHandler._write_bytes | def _write_bytes(self, data):
"""
Converts the given data then writes it
:param data: Data to be written
:return: The result of ``self.output.write()``
"""
with self.__lock:
self.output.write(to_bytes(data, self.encoding)) | python | def _write_bytes(self, data):
"""
Converts the given data then writes it
:param data: Data to be written
:return: The result of ``self.output.write()``
"""
with self.__lock:
self.output.write(to_bytes(data, self.encoding)) | Converts the given data then writes it
:param data: Data to be written
:return: The result of ``self.output.write()`` | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/shell/beans.py#L210-L218 |
tcalmant/ipopo | pelix/shell/beans.py | IOHandler._write_str | def _write_str(self, data):
"""
Converts the given data then writes it
:param data: Data to be written
:return: The result of ``self.output.write()``
"""
with self.__lock:
self.output.write(
to_str(data, self.encoding)
.encode()
.decode(self.out_encoding, errors="replace")
) | python | def _write_str(self, data):
"""
Converts the given data then writes it
:param data: Data to be written
:return: The result of ``self.output.write()``
"""
with self.__lock:
self.output.write(
to_str(data, self.encoding)
.encode()
.decode(self.out_encoding, errors="replace")
) | Converts the given data then writes it
:param data: Data to be written
:return: The result of ``self.output.write()`` | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/shell/beans.py#L220-L232 |
tcalmant/ipopo | pelix/shell/beans.py | IOHandler.write_line | def write_line(self, line=None, *args, **kwargs):
"""
Formats and writes a line to the output
"""
if line is None:
# Empty line
self.write("\n")
else:
# Format the line, if arguments have been given
if args or kwargs:
line = line.format(*args, **kwargs)
with self.__lock:
# Write it
self.write(line)
try:
if line[-1] != "\n":
# Add the trailing new line
self.write("\n")
except IndexError:
# Got an empty string
self.write("\n")
self.flush() | python | def write_line(self, line=None, *args, **kwargs):
"""
Formats and writes a line to the output
"""
if line is None:
# Empty line
self.write("\n")
else:
# Format the line, if arguments have been given
if args or kwargs:
line = line.format(*args, **kwargs)
with self.__lock:
# Write it
self.write(line)
try:
if line[-1] != "\n":
# Add the trailing new line
self.write("\n")
except IndexError:
# Got an empty string
self.write("\n")
self.flush() | Formats and writes a line to the output | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/shell/beans.py#L234-L257 |
tcalmant/ipopo | pelix/shell/beans.py | IOHandler.write_line_no_feed | def write_line_no_feed(self, line=None, *args, **kwargs):
"""
Formats and writes a line to the output
"""
if line is None:
# Empty line
line = ""
else:
# Format the line, if arguments have been given
if args or kwargs:
line = line.format(*args, **kwargs)
# Remove the trailing line feed
if line[-1] == "\n":
line = line[:-1]
# Write it
self.write(line)
self.flush() | python | def write_line_no_feed(self, line=None, *args, **kwargs):
"""
Formats and writes a line to the output
"""
if line is None:
# Empty line
line = ""
else:
# Format the line, if arguments have been given
if args or kwargs:
line = line.format(*args, **kwargs)
# Remove the trailing line feed
if line[-1] == "\n":
line = line[:-1]
# Write it
self.write(line)
self.flush() | Formats and writes a line to the output | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/shell/beans.py#L259-L277 |
tcalmant/ipopo | samples/handler/logger.py | _LoggerHandlerFactory.get_handlers | def get_handlers(self, component_context, instance):
"""
Sets up service providers for the given component
:param component_context: The ComponentContext bean
:param instance: The component instance
:return: The list of handlers associated to the given component
(never None)
"""
# Extract information from the context
logger_field = component_context.get_handler(constants.HANDLER_LOGGER)
if not logger_field:
# Error: log it and either raise an exception
# or ignore this handler
_logger.warning("Logger iPOPO handler can't find its configuration")
# Here, we ignore the error and do not give any handler to iPOPO
return []
else:
# Construct a handler and return it in a list
return [_LoggerHandler(logger_field, component_context.name)] | python | def get_handlers(self, component_context, instance):
"""
Sets up service providers for the given component
:param component_context: The ComponentContext bean
:param instance: The component instance
:return: The list of handlers associated to the given component
(never None)
"""
# Extract information from the context
logger_field = component_context.get_handler(constants.HANDLER_LOGGER)
if not logger_field:
# Error: log it and either raise an exception
# or ignore this handler
_logger.warning("Logger iPOPO handler can't find its configuration")
# Here, we ignore the error and do not give any handler to iPOPO
return []
else:
# Construct a handler and return it in a list
return [_LoggerHandler(logger_field, component_context.name)] | Sets up service providers for the given component
:param component_context: The ComponentContext bean
:param instance: The component instance
:return: The list of handlers associated to the given component
(never None) | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/samples/handler/logger.py#L100-L121 |
tcalmant/ipopo | samples/handler/logger.py | _LoggerHandler.manipulate | def manipulate(self, stored_instance, component_instance):
"""
Called by iPOPO right after the instantiation of the component.
This is the last chance to manipulate the component before the other
handlers start.
:param stored_instance: The iPOPO component StoredInstance
:param component_instance: The component instance
"""
# Create the logger for this component instance
self._logger = logging.getLogger(self._name)
# Inject it
setattr(component_instance, self._field, self._logger) | python | def manipulate(self, stored_instance, component_instance):
"""
Called by iPOPO right after the instantiation of the component.
This is the last chance to manipulate the component before the other
handlers start.
:param stored_instance: The iPOPO component StoredInstance
:param component_instance: The component instance
"""
# Create the logger for this component instance
self._logger = logging.getLogger(self._name)
# Inject it
setattr(component_instance, self._field, self._logger) | Called by iPOPO right after the instantiation of the component.
This is the last chance to manipulate the component before the other
handlers start.
:param stored_instance: The iPOPO component StoredInstance
:param component_instance: The component instance | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/samples/handler/logger.py#L140-L153 |
tcalmant/ipopo | samples/handler/logger.py | _LoggerHandler.clear | def clear(self):
"""
Cleans up the handler. The handler can't be used after this method has
been called
"""
self._logger.debug("Component handlers are cleared")
# Clean up everything to avoid stale references, ...
self._field = None
self._name = None
self._logger = None | python | def clear(self):
"""
Cleans up the handler. The handler can't be used after this method has
been called
"""
self._logger.debug("Component handlers are cleared")
# Clean up everything to avoid stale references, ...
self._field = None
self._name = None
self._logger = None | Cleans up the handler. The handler can't be used after this method has
been called | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/samples/handler/logger.py#L189-L199 |
tcalmant/ipopo | pelix/shell/completion/core.py | completion_hints | def completion_hints(config, prompt, session, context, current, arguments):
# type: (CompletionInfo, str, ShellSession, BundleContext, str, List[str]) -> List[str]
"""
Returns the possible completions of the current argument
:param config: Configuration of the current completion
:param prompt: The shell prompt string
:param session: Current shell session
:param context: Context of the shell UI bundle
:param current: Current argument (to be completed)
:param arguments: List of all arguments in their current state
:return: A list of possible completions
"""
if not current:
# No word yet, so the current position is after the existing ones
arg_idx = len(arguments)
else:
# Find the current word position
arg_idx = arguments.index(current)
# Find the ID of the next completer
completers = config.completers
if arg_idx > len(completers) - 1:
# Argument is too far to be positional, try
if config.multiple:
# Multiple calls allowed for the last completer
completer_id = completers[-1]
else:
# Nothing to return
return []
else:
completer_id = completers[arg_idx]
if completer_id == DUMMY:
# Dummy completer: do nothing
return []
# Find the matching service
svc_ref = context.get_service_reference(
SVC_COMPLETER, "({}={})".format(PROP_COMPLETER_ID, completer_id)
)
if svc_ref is None:
# Handler not found
_logger.debug("Unknown shell completer ID: %s", completer_id)
return []
# Call the completer
try:
with use_service(context, svc_ref) as completer:
matches = completer.complete(
config, prompt, session, context, arguments, current
)
if not matches:
return []
return matches
except Exception as ex:
_logger.exception("Error calling completer %s: %s", completer_id, ex)
return [] | python | def completion_hints(config, prompt, session, context, current, arguments):
# type: (CompletionInfo, str, ShellSession, BundleContext, str, List[str]) -> List[str]
"""
Returns the possible completions of the current argument
:param config: Configuration of the current completion
:param prompt: The shell prompt string
:param session: Current shell session
:param context: Context of the shell UI bundle
:param current: Current argument (to be completed)
:param arguments: List of all arguments in their current state
:return: A list of possible completions
"""
if not current:
# No word yet, so the current position is after the existing ones
arg_idx = len(arguments)
else:
# Find the current word position
arg_idx = arguments.index(current)
# Find the ID of the next completer
completers = config.completers
if arg_idx > len(completers) - 1:
# Argument is too far to be positional, try
if config.multiple:
# Multiple calls allowed for the last completer
completer_id = completers[-1]
else:
# Nothing to return
return []
else:
completer_id = completers[arg_idx]
if completer_id == DUMMY:
# Dummy completer: do nothing
return []
# Find the matching service
svc_ref = context.get_service_reference(
SVC_COMPLETER, "({}={})".format(PROP_COMPLETER_ID, completer_id)
)
if svc_ref is None:
# Handler not found
_logger.debug("Unknown shell completer ID: %s", completer_id)
return []
# Call the completer
try:
with use_service(context, svc_ref) as completer:
matches = completer.complete(
config, prompt, session, context, arguments, current
)
if not matches:
return []
return matches
except Exception as ex:
_logger.exception("Error calling completer %s: %s", completer_id, ex)
return [] | Returns the possible completions of the current argument
:param config: Configuration of the current completion
:param prompt: The shell prompt string
:param session: Current shell session
:param context: Context of the shell UI bundle
:param current: Current argument (to be completed)
:param arguments: List of all arguments in their current state
:return: A list of possible completions | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/shell/completion/core.py#L105-L163 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.