repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 75 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|
django-userena-ce/django-userena-ce | demo/profiles/forms.py | SignupFormExtra.save | def save(self):
"""
Override the save method to save the first and last name to the user
field.
"""
# First save the parent form and get the user.
new_user = super(SignupFormExtra, self).save()
new_user.first_name = self.cleaned_data['first_name']
new_u... | python | def save(self):
"""
Override the save method to save the first and last name to the user
field.
"""
# First save the parent form and get the user.
new_user = super(SignupFormExtra, self).save()
new_user.first_name = self.cleaned_data['first_name']
new_u... | [
"def",
"save",
"(",
"self",
")",
":",
"# First save the parent form and get the user.",
"new_user",
"=",
"super",
"(",
"SignupFormExtra",
",",
"self",
")",
".",
"save",
"(",
")",
"new_user",
".",
"first_name",
"=",
"self",
".",
"cleaned_data",
"[",
"'first_name'... | Override the save method to save the first and last name to the user
field. | [
"Override",
"the",
"save",
"method",
"to",
"save",
"the",
"first",
"and",
"last",
"name",
"to",
"the",
"user",
"field",
"."
] | 2d8b745eed25128134e961ca96c270802e730256 | https://github.com/django-userena-ce/django-userena-ce/blob/2d8b745eed25128134e961ca96c270802e730256/demo/profiles/forms.py#L38-L53 | train |
django-userena-ce/django-userena-ce | userena/contrib/umessages/forms.py | ComposeForm.save | def save(self, sender):
"""
Save the message and send it out into the wide world.
:param sender:
The :class:`User` that sends the message.
:param parent_msg:
The :class:`Message` that preceded this message in the thread.
:return: The saved :class:`Messa... | python | def save(self, sender):
"""
Save the message and send it out into the wide world.
:param sender:
The :class:`User` that sends the message.
:param parent_msg:
The :class:`Message` that preceded this message in the thread.
:return: The saved :class:`Messa... | [
"def",
"save",
"(",
"self",
",",
"sender",
")",
":",
"um_to_user_list",
"=",
"self",
".",
"cleaned_data",
"[",
"'to'",
"]",
"body",
"=",
"self",
".",
"cleaned_data",
"[",
"'body'",
"]",
"msg",
"=",
"Message",
".",
"objects",
".",
"send_message",
"(",
"... | Save the message and send it out into the wide world.
:param sender:
The :class:`User` that sends the message.
:param parent_msg:
The :class:`Message` that preceded this message in the thread.
:return: The saved :class:`Message`. | [
"Save",
"the",
"message",
"and",
"send",
"it",
"out",
"into",
"the",
"wide",
"world",
"."
] | 2d8b745eed25128134e961ca96c270802e730256 | https://github.com/django-userena-ce/django-userena-ce/blob/2d8b745eed25128134e961ca96c270802e730256/userena/contrib/umessages/forms.py#L15-L35 | train |
django-userena-ce/django-userena-ce | userena/forms.py | SignupForm.clean_username | def clean_username(self):
"""
Validate that the username is alphanumeric and is not already in use.
Also validates that the username is not listed in
``USERENA_FORBIDDEN_USERNAMES`` list.
"""
try:
user = get_user_model().objects.get(username__iexact=self.clea... | python | def clean_username(self):
"""
Validate that the username is alphanumeric and is not already in use.
Also validates that the username is not listed in
``USERENA_FORBIDDEN_USERNAMES`` list.
"""
try:
user = get_user_model().objects.get(username__iexact=self.clea... | [
"def",
"clean_username",
"(",
"self",
")",
":",
"try",
":",
"user",
"=",
"get_user_model",
"(",
")",
".",
"objects",
".",
"get",
"(",
"username__iexact",
"=",
"self",
".",
"cleaned_data",
"[",
"'username'",
"]",
")",
"except",
"get_user_model",
"(",
")",
... | Validate that the username is alphanumeric and is not already in use.
Also validates that the username is not listed in
``USERENA_FORBIDDEN_USERNAMES`` list. | [
"Validate",
"that",
"the",
"username",
"is",
"alphanumeric",
"and",
"is",
"not",
"already",
"in",
"use",
".",
"Also",
"validates",
"that",
"the",
"username",
"is",
"not",
"listed",
"in",
"USERENA_FORBIDDEN_USERNAMES",
"list",
"."
] | 2d8b745eed25128134e961ca96c270802e730256 | https://github.com/django-userena-ce/django-userena-ce/blob/2d8b745eed25128134e961ca96c270802e730256/userena/forms.py#L44-L61 | train |
django-userena-ce/django-userena-ce | userena/forms.py | SignupFormOnlyEmail.save | def save(self):
""" Generate a random username before falling back to parent signup form """
while True:
username = sha1(str(random.random()).encode('utf-8')).hexdigest()[:5]
try:
get_user_model().objects.get(username__iexact=username)
except get_user_... | python | def save(self):
""" Generate a random username before falling back to parent signup form """
while True:
username = sha1(str(random.random()).encode('utf-8')).hexdigest()[:5]
try:
get_user_model().objects.get(username__iexact=username)
except get_user_... | [
"def",
"save",
"(",
"self",
")",
":",
"while",
"True",
":",
"username",
"=",
"sha1",
"(",
"str",
"(",
"random",
".",
"random",
"(",
")",
")",
".",
"encode",
"(",
"'utf-8'",
")",
")",
".",
"hexdigest",
"(",
")",
"[",
":",
"5",
"]",
"try",
":",
... | Generate a random username before falling back to parent signup form | [
"Generate",
"a",
"random",
"username",
"before",
"falling",
"back",
"to",
"parent",
"signup",
"form"
] | 2d8b745eed25128134e961ca96c270802e730256 | https://github.com/django-userena-ce/django-userena-ce/blob/2d8b745eed25128134e961ca96c270802e730256/userena/forms.py#L110-L119 | train |
dogoncouch/logdissect | logdissect/parsers/linejson.py | ParseModule.parse_file | def parse_file(self, sourcepath):
"""Parse an object-per-line JSON file into a log data dict"""
# Open input file and read JSON array:
with open(sourcepath, 'r') as logfile:
jsonlist = logfile.readlines()
# Set our attributes for this entry and add it to data.entries:
... | python | def parse_file(self, sourcepath):
"""Parse an object-per-line JSON file into a log data dict"""
# Open input file and read JSON array:
with open(sourcepath, 'r') as logfile:
jsonlist = logfile.readlines()
# Set our attributes for this entry and add it to data.entries:
... | [
"def",
"parse_file",
"(",
"self",
",",
"sourcepath",
")",
":",
"# Open input file and read JSON array:",
"with",
"open",
"(",
"sourcepath",
",",
"'r'",
")",
"as",
"logfile",
":",
"jsonlist",
"=",
"logfile",
".",
"readlines",
"(",
")",
"# Set our attributes for thi... | Parse an object-per-line JSON file into a log data dict | [
"Parse",
"an",
"object",
"-",
"per",
"-",
"line",
"JSON",
"file",
"into",
"a",
"log",
"data",
"dict"
] | 426b50264cbfa9665c86df3781e1e415ba8dbbd3 | https://github.com/dogoncouch/logdissect/blob/426b50264cbfa9665c86df3781e1e415ba8dbbd3/logdissect/parsers/linejson.py#L41-L59 | train |
dogoncouch/logdissect | logdissect/parsers/sojson.py | ParseModule.parse_file | def parse_file(self, sourcepath):
"""Parse single JSON object into a LogData object"""
# Open input file and read JSON array:
with open(sourcepath, 'r') as logfile:
jsonstr = logfile.read()
# Set our attributes for this entry and add it to data.entries:
data = {}
... | python | def parse_file(self, sourcepath):
"""Parse single JSON object into a LogData object"""
# Open input file and read JSON array:
with open(sourcepath, 'r') as logfile:
jsonstr = logfile.read()
# Set our attributes for this entry and add it to data.entries:
data = {}
... | [
"def",
"parse_file",
"(",
"self",
",",
"sourcepath",
")",
":",
"# Open input file and read JSON array:",
"with",
"open",
"(",
"sourcepath",
",",
"'r'",
")",
"as",
"logfile",
":",
"jsonstr",
"=",
"logfile",
".",
"read",
"(",
")",
"# Set our attributes for this entr... | Parse single JSON object into a LogData object | [
"Parse",
"single",
"JSON",
"object",
"into",
"a",
"LogData",
"object"
] | 426b50264cbfa9665c86df3781e1e415ba8dbbd3 | https://github.com/dogoncouch/logdissect/blob/426b50264cbfa9665c86df3781e1e415ba8dbbd3/logdissect/parsers/sojson.py#L41-L56 | train |
dogoncouch/logdissect | logdissect/core.py | LogDissectCore.run_job | def run_job(self):
"""Execute a logdissect job"""
try:
self.load_parsers()
self.load_filters()
self.load_outputs()
self.config_args()
if self.args.list_parsers:
self.list_parsers()
if self.args.verbosemode: print('Lo... | python | def run_job(self):
"""Execute a logdissect job"""
try:
self.load_parsers()
self.load_filters()
self.load_outputs()
self.config_args()
if self.args.list_parsers:
self.list_parsers()
if self.args.verbosemode: print('Lo... | [
"def",
"run_job",
"(",
"self",
")",
":",
"try",
":",
"self",
".",
"load_parsers",
"(",
")",
"self",
".",
"load_filters",
"(",
")",
"self",
".",
"load_outputs",
"(",
")",
"self",
".",
"config_args",
"(",
")",
"if",
"self",
".",
"args",
".",
"list_pars... | Execute a logdissect job | [
"Execute",
"a",
"logdissect",
"job"
] | 426b50264cbfa9665c86df3781e1e415ba8dbbd3 | https://github.com/dogoncouch/logdissect/blob/426b50264cbfa9665c86df3781e1e415ba8dbbd3/logdissect/core.py#L58-L80 | train |
dogoncouch/logdissect | logdissect/core.py | LogDissectCore.run_parse | def run_parse(self):
"""Parse one or more log files"""
# Data set already has source file names from load_inputs
parsedset = {}
parsedset['data_set'] = []
for log in self.input_files:
parsemodule = self.parse_modules[self.args.parser]
try:
... | python | def run_parse(self):
"""Parse one or more log files"""
# Data set already has source file names from load_inputs
parsedset = {}
parsedset['data_set'] = []
for log in self.input_files:
parsemodule = self.parse_modules[self.args.parser]
try:
... | [
"def",
"run_parse",
"(",
"self",
")",
":",
"# Data set already has source file names from load_inputs",
"parsedset",
"=",
"{",
"}",
"parsedset",
"[",
"'data_set'",
"]",
"=",
"[",
"]",
"for",
"log",
"in",
"self",
".",
"input_files",
":",
"parsemodule",
"=",
"self... | Parse one or more log files | [
"Parse",
"one",
"or",
"more",
"log",
"files"
] | 426b50264cbfa9665c86df3781e1e415ba8dbbd3 | https://github.com/dogoncouch/logdissect/blob/426b50264cbfa9665c86df3781e1e415ba8dbbd3/logdissect/core.py#L82-L95 | train |
dogoncouch/logdissect | logdissect/core.py | LogDissectCore.run_output | def run_output(self):
"""Output finalized data"""
for f in logdissect.output.__formats__:
ouroutput = self.output_modules[f]
ouroutput.write_output(self.data_set['finalized_data'],
args=self.args)
del(ouroutput)
# Output to terminal if sil... | python | def run_output(self):
"""Output finalized data"""
for f in logdissect.output.__formats__:
ouroutput = self.output_modules[f]
ouroutput.write_output(self.data_set['finalized_data'],
args=self.args)
del(ouroutput)
# Output to terminal if sil... | [
"def",
"run_output",
"(",
"self",
")",
":",
"for",
"f",
"in",
"logdissect",
".",
"output",
".",
"__formats__",
":",
"ouroutput",
"=",
"self",
".",
"output_modules",
"[",
"f",
"]",
"ouroutput",
".",
"write_output",
"(",
"self",
".",
"data_set",
"[",
"'fin... | Output finalized data | [
"Output",
"finalized",
"data"
] | 426b50264cbfa9665c86df3781e1e415ba8dbbd3 | https://github.com/dogoncouch/logdissect/blob/426b50264cbfa9665c86df3781e1e415ba8dbbd3/logdissect/core.py#L107-L120 | train |
dogoncouch/logdissect | logdissect/core.py | LogDissectCore.config_args | def config_args(self):
"""Set config options"""
# Module list options:
self.arg_parser.add_argument('--version', action='version',
version='%(prog)s ' + str(__version__))
self.arg_parser.add_argument('--verbose',
action='store_true', dest = 'verbosemode',
... | python | def config_args(self):
"""Set config options"""
# Module list options:
self.arg_parser.add_argument('--version', action='version',
version='%(prog)s ' + str(__version__))
self.arg_parser.add_argument('--verbose',
action='store_true', dest = 'verbosemode',
... | [
"def",
"config_args",
"(",
"self",
")",
":",
"# Module list options:",
"self",
".",
"arg_parser",
".",
"add_argument",
"(",
"'--version'",
",",
"action",
"=",
"'version'",
",",
"version",
"=",
"'%(prog)s '",
"+",
"str",
"(",
"__version__",
")",
")",
"self",
... | Set config options | [
"Set",
"config",
"options"
] | 426b50264cbfa9665c86df3781e1e415ba8dbbd3 | https://github.com/dogoncouch/logdissect/blob/426b50264cbfa9665c86df3781e1e415ba8dbbd3/logdissect/core.py#L124-L156 | train |
dogoncouch/logdissect | logdissect/core.py | LogDissectCore.load_inputs | def load_inputs(self):
"""Load the specified inputs"""
for f in self.args.files:
if os.path.isfile(f):
fparts = str(f).split('.')
if fparts[-1] == 'gz':
if self.args.unzip:
fullpath = os.path.abspath(str(f))
... | python | def load_inputs(self):
"""Load the specified inputs"""
for f in self.args.files:
if os.path.isfile(f):
fparts = str(f).split('.')
if fparts[-1] == 'gz':
if self.args.unzip:
fullpath = os.path.abspath(str(f))
... | [
"def",
"load_inputs",
"(",
"self",
")",
":",
"for",
"f",
"in",
"self",
".",
"args",
".",
"files",
":",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"f",
")",
":",
"fparts",
"=",
"str",
"(",
"f",
")",
".",
"split",
"(",
"'.'",
")",
"if",
"fpar... | Load the specified inputs | [
"Load",
"the",
"specified",
"inputs"
] | 426b50264cbfa9665c86df3781e1e415ba8dbbd3 | https://github.com/dogoncouch/logdissect/blob/426b50264cbfa9665c86df3781e1e415ba8dbbd3/logdissect/core.py#L161-L179 | train |
dogoncouch/logdissect | logdissect/core.py | LogDissectCore.list_parsers | def list_parsers(self, *args):
"""Return a list of available parsing modules"""
print('==== Available parsing modules: ====\n')
for parser in sorted(self.parse_modules):
print(self.parse_modules[parser].name.ljust(16) + \
': ' + self.parse_modules[parser].desc)
... | python | def list_parsers(self, *args):
"""Return a list of available parsing modules"""
print('==== Available parsing modules: ====\n')
for parser in sorted(self.parse_modules):
print(self.parse_modules[parser].name.ljust(16) + \
': ' + self.parse_modules[parser].desc)
... | [
"def",
"list_parsers",
"(",
"self",
",",
"*",
"args",
")",
":",
"print",
"(",
"'==== Available parsing modules: ====\\n'",
")",
"for",
"parser",
"in",
"sorted",
"(",
"self",
".",
"parse_modules",
")",
":",
"print",
"(",
"self",
".",
"parse_modules",
"[",
"pa... | Return a list of available parsing modules | [
"Return",
"a",
"list",
"of",
"available",
"parsing",
"modules"
] | 426b50264cbfa9665c86df3781e1e415ba8dbbd3 | https://github.com/dogoncouch/logdissect/blob/426b50264cbfa9665c86df3781e1e415ba8dbbd3/logdissect/core.py#L182-L188 | train |
dogoncouch/logdissect | logdissect/utils.py | get_utc_date | def get_utc_date(entry):
"""Return datestamp converted to UTC"""
if entry['numeric_date_stamp'] == '0':
entry['numeric_date_stamp_utc'] = '0'
return entry
else:
if '.' in entry['numeric_date_stamp']:
t = datetime.strptime(entry['numeric_date_stamp'],
... | python | def get_utc_date(entry):
"""Return datestamp converted to UTC"""
if entry['numeric_date_stamp'] == '0':
entry['numeric_date_stamp_utc'] = '0'
return entry
else:
if '.' in entry['numeric_date_stamp']:
t = datetime.strptime(entry['numeric_date_stamp'],
... | [
"def",
"get_utc_date",
"(",
"entry",
")",
":",
"if",
"entry",
"[",
"'numeric_date_stamp'",
"]",
"==",
"'0'",
":",
"entry",
"[",
"'numeric_date_stamp_utc'",
"]",
"=",
"'0'",
"return",
"entry",
"else",
":",
"if",
"'.'",
"in",
"entry",
"[",
"'numeric_date_stamp... | Return datestamp converted to UTC | [
"Return",
"datestamp",
"converted",
"to",
"UTC"
] | 426b50264cbfa9665c86df3781e1e415ba8dbbd3 | https://github.com/dogoncouch/logdissect/blob/426b50264cbfa9665c86df3781e1e415ba8dbbd3/logdissect/utils.py#L145-L168 | train |
dogoncouch/logdissect | logdissect/utils.py | get_local_tzone | def get_local_tzone():
"""Get the current time zone on the local host"""
if localtime().tm_isdst:
if altzone < 0:
tzone = '+' + \
str(int(float(altzone) / 60 // 60)).rjust(2,
'0') + \
str(int(float(
... | python | def get_local_tzone():
"""Get the current time zone on the local host"""
if localtime().tm_isdst:
if altzone < 0:
tzone = '+' + \
str(int(float(altzone) / 60 // 60)).rjust(2,
'0') + \
str(int(float(
... | [
"def",
"get_local_tzone",
"(",
")",
":",
"if",
"localtime",
"(",
")",
".",
"tm_isdst",
":",
"if",
"altzone",
"<",
"0",
":",
"tzone",
"=",
"'+'",
"+",
"str",
"(",
"int",
"(",
"float",
"(",
"altzone",
")",
"/",
"60",
"//",
"60",
")",
")",
".",
"r... | Get the current time zone on the local host | [
"Get",
"the",
"current",
"time",
"zone",
"on",
"the",
"local",
"host"
] | 426b50264cbfa9665c86df3781e1e415ba8dbbd3 | https://github.com/dogoncouch/logdissect/blob/426b50264cbfa9665c86df3781e1e415ba8dbbd3/logdissect/utils.py#L171-L200 | train |
dogoncouch/logdissect | logdissect/utils.py | merge_logs | def merge_logs(dataset, sort=True):
"""Merge log dictionaries together into one log dictionary"""
ourlog = {}
ourlog['entries'] = []
for d in dataset:
ourlog['entries'] = ourlog['entries'] + d['entries']
if sort:
ourlog['entries'].sort(key= lambda x: x['numeric_date_stamp_utc'])
... | python | def merge_logs(dataset, sort=True):
"""Merge log dictionaries together into one log dictionary"""
ourlog = {}
ourlog['entries'] = []
for d in dataset:
ourlog['entries'] = ourlog['entries'] + d['entries']
if sort:
ourlog['entries'].sort(key= lambda x: x['numeric_date_stamp_utc'])
... | [
"def",
"merge_logs",
"(",
"dataset",
",",
"sort",
"=",
"True",
")",
":",
"ourlog",
"=",
"{",
"}",
"ourlog",
"[",
"'entries'",
"]",
"=",
"[",
"]",
"for",
"d",
"in",
"dataset",
":",
"ourlog",
"[",
"'entries'",
"]",
"=",
"ourlog",
"[",
"'entries'",
"]... | Merge log dictionaries together into one log dictionary | [
"Merge",
"log",
"dictionaries",
"together",
"into",
"one",
"log",
"dictionary"
] | 426b50264cbfa9665c86df3781e1e415ba8dbbd3 | https://github.com/dogoncouch/logdissect/blob/426b50264cbfa9665c86df3781e1e415ba8dbbd3/logdissect/utils.py#L203-L212 | train |
dogoncouch/logdissect | logdissect/output/log.py | OutputModule.write_output | def write_output(self, data, args=None, filename=None, label=None):
"""Write log data to a log file"""
if args:
if not args.outlog:
return 0
if not filename: filename=args.outlog
lastpath = ''
with open(str(filename), 'w') as output_file:
f... | python | def write_output(self, data, args=None, filename=None, label=None):
"""Write log data to a log file"""
if args:
if not args.outlog:
return 0
if not filename: filename=args.outlog
lastpath = ''
with open(str(filename), 'w') as output_file:
f... | [
"def",
"write_output",
"(",
"self",
",",
"data",
",",
"args",
"=",
"None",
",",
"filename",
"=",
"None",
",",
"label",
"=",
"None",
")",
":",
"if",
"args",
":",
"if",
"not",
"args",
".",
"outlog",
":",
"return",
"0",
"if",
"not",
"filename",
":",
... | Write log data to a log file | [
"Write",
"log",
"data",
"to",
"a",
"log",
"file"
] | 426b50264cbfa9665c86df3781e1e415ba8dbbd3 | https://github.com/dogoncouch/logdissect/blob/426b50264cbfa9665c86df3781e1e415ba8dbbd3/logdissect/output/log.py#L37-L58 | train |
dogoncouch/logdissect | logdissect/output/sojson.py | OutputModule.write_output | def write_output(self, data, args=None, filename=None, pretty=False):
"""Write log data to a single JSON object"""
if args:
if not args.sojson:
return 0
pretty = args.pretty
if not filename: filename = args.sojson
if pretty:
logstring =... | python | def write_output(self, data, args=None, filename=None, pretty=False):
"""Write log data to a single JSON object"""
if args:
if not args.sojson:
return 0
pretty = args.pretty
if not filename: filename = args.sojson
if pretty:
logstring =... | [
"def",
"write_output",
"(",
"self",
",",
"data",
",",
"args",
"=",
"None",
",",
"filename",
"=",
"None",
",",
"pretty",
"=",
"False",
")",
":",
"if",
"args",
":",
"if",
"not",
"args",
".",
"sojson",
":",
"return",
"0",
"pretty",
"=",
"args",
".",
... | Write log data to a single JSON object | [
"Write",
"log",
"data",
"to",
"a",
"single",
"JSON",
"object"
] | 426b50264cbfa9665c86df3781e1e415ba8dbbd3 | https://github.com/dogoncouch/logdissect/blob/426b50264cbfa9665c86df3781e1e415ba8dbbd3/logdissect/output/sojson.py#L38-L53 | train |
dogoncouch/logdissect | logdissect/output/linejson.py | OutputModule.write_output | def write_output(self, data, filename=None, args=None):
"""Write log data to a file with one JSON object per line"""
if args:
if not args.linejson:
return 0
if not filename: filename = args.linejson
entrylist = []
for entry in data['entries']:
... | python | def write_output(self, data, filename=None, args=None):
"""Write log data to a file with one JSON object per line"""
if args:
if not args.linejson:
return 0
if not filename: filename = args.linejson
entrylist = []
for entry in data['entries']:
... | [
"def",
"write_output",
"(",
"self",
",",
"data",
",",
"filename",
"=",
"None",
",",
"args",
"=",
"None",
")",
":",
"if",
"args",
":",
"if",
"not",
"args",
".",
"linejson",
":",
"return",
"0",
"if",
"not",
"filename",
":",
"filename",
"=",
"args",
"... | Write log data to a file with one JSON object per line | [
"Write",
"log",
"data",
"to",
"a",
"file",
"with",
"one",
"JSON",
"object",
"per",
"line"
] | 426b50264cbfa9665c86df3781e1e415ba8dbbd3 | https://github.com/dogoncouch/logdissect/blob/426b50264cbfa9665c86df3781e1e415ba8dbbd3/logdissect/output/linejson.py#L36-L48 | train |
dogoncouch/logdissect | logdissect/parsers/type.py | ParseModule.parse_file | def parse_file(self, sourcepath):
"""Parse a file into a LogData object"""
# Get regex objects:
self.date_regex = re.compile(
r'{}'.format(self.format_regex))
if self.backup_format_regex:
self.backup_date_regex = re.compile(
r'{}'.format(se... | python | def parse_file(self, sourcepath):
"""Parse a file into a LogData object"""
# Get regex objects:
self.date_regex = re.compile(
r'{}'.format(self.format_regex))
if self.backup_format_regex:
self.backup_date_regex = re.compile(
r'{}'.format(se... | [
"def",
"parse_file",
"(",
"self",
",",
"sourcepath",
")",
":",
"# Get regex objects:",
"self",
".",
"date_regex",
"=",
"re",
".",
"compile",
"(",
"r'{}'",
".",
"format",
"(",
"self",
".",
"format_regex",
")",
")",
"if",
"self",
".",
"backup_format_regex",
... | Parse a file into a LogData object | [
"Parse",
"a",
"file",
"into",
"a",
"LogData",
"object"
] | 426b50264cbfa9665c86df3781e1e415ba8dbbd3 | https://github.com/dogoncouch/logdissect/blob/426b50264cbfa9665c86df3781e1e415ba8dbbd3/logdissect/parsers/type.py#L46-L122 | train |
dogoncouch/logdissect | logdissect/parsers/type.py | ParseModule.parse_line | def parse_line(self, line):
"""Parse a line into a dictionary"""
match = re.findall(self.date_regex, line)
if match:
fields = self.fields
elif self.backup_format_regex and not match:
match = re.findall(self.backup_date_regex, line)
fields = self.backup... | python | def parse_line(self, line):
"""Parse a line into a dictionary"""
match = re.findall(self.date_regex, line)
if match:
fields = self.fields
elif self.backup_format_regex and not match:
match = re.findall(self.backup_date_regex, line)
fields = self.backup... | [
"def",
"parse_line",
"(",
"self",
",",
"line",
")",
":",
"match",
"=",
"re",
".",
"findall",
"(",
"self",
".",
"date_regex",
",",
"line",
")",
"if",
"match",
":",
"fields",
"=",
"self",
".",
"fields",
"elif",
"self",
".",
"backup_format_regex",
"and",
... | Parse a line into a dictionary | [
"Parse",
"a",
"line",
"into",
"a",
"dictionary"
] | 426b50264cbfa9665c86df3781e1e415ba8dbbd3 | https://github.com/dogoncouch/logdissect/blob/426b50264cbfa9665c86df3781e1e415ba8dbbd3/logdissect/parsers/type.py#L125-L167 | train |
dogoncouch/logdissect | logdissect/parsers/tcpdump.py | ParseModule.post_parse_action | def post_parse_action(self, entry):
"""separate hosts and ports after entry is parsed"""
if 'source_host' in entry.keys():
host = self.ip_port_regex.findall(entry['source_host'])
if host:
hlist = host[0].split('.')
entry['source_host'] = '.'.join(h... | python | def post_parse_action(self, entry):
"""separate hosts and ports after entry is parsed"""
if 'source_host' in entry.keys():
host = self.ip_port_regex.findall(entry['source_host'])
if host:
hlist = host[0].split('.')
entry['source_host'] = '.'.join(h... | [
"def",
"post_parse_action",
"(",
"self",
",",
"entry",
")",
":",
"if",
"'source_host'",
"in",
"entry",
".",
"keys",
"(",
")",
":",
"host",
"=",
"self",
".",
"ip_port_regex",
".",
"findall",
"(",
"entry",
"[",
"'source_host'",
"]",
")",
"if",
"host",
":... | separate hosts and ports after entry is parsed | [
"separate",
"hosts",
"and",
"ports",
"after",
"entry",
"is",
"parsed"
] | 426b50264cbfa9665c86df3781e1e415ba8dbbd3 | https://github.com/dogoncouch/logdissect/blob/426b50264cbfa9665c86df3781e1e415ba8dbbd3/logdissect/parsers/tcpdump.py#L42-L57 | train |
vtraag/louvain-igraph | src/functions.py | find_partition_multiplex | def find_partition_multiplex(graphs, partition_type, **kwargs):
""" Detect communities for multiplex graphs.
Each graph should be defined on the same set of vertices, only the edges may
differ for different graphs. See
:func:`Optimiser.optimise_partition_multiplex` for a more detailed
explanation.
Paramet... | python | def find_partition_multiplex(graphs, partition_type, **kwargs):
""" Detect communities for multiplex graphs.
Each graph should be defined on the same set of vertices, only the edges may
differ for different graphs. See
:func:`Optimiser.optimise_partition_multiplex` for a more detailed
explanation.
Paramet... | [
"def",
"find_partition_multiplex",
"(",
"graphs",
",",
"partition_type",
",",
"*",
"*",
"kwargs",
")",
":",
"n_layers",
"=",
"len",
"(",
"graphs",
")",
"partitions",
"=",
"[",
"]",
"layer_weights",
"=",
"[",
"1",
"]",
"*",
"n_layers",
"for",
"graph",
"in... | Detect communities for multiplex graphs.
Each graph should be defined on the same set of vertices, only the edges may
differ for different graphs. See
:func:`Optimiser.optimise_partition_multiplex` for a more detailed
explanation.
Parameters
----------
graphs : list of :class:`ig.Graph`
List of :cla... | [
"Detect",
"communities",
"for",
"multiplex",
"graphs",
"."
] | 8de2c3bad736a9deea90b80f104d8444769d331f | https://github.com/vtraag/louvain-igraph/blob/8de2c3bad736a9deea90b80f104d8444769d331f/src/functions.py#L81-L136 | train |
vtraag/louvain-igraph | src/functions.py | find_partition_temporal | def find_partition_temporal(graphs, partition_type,
interslice_weight=1,
slice_attr='slice', vertex_id_attr='id',
edge_type_attr='type', weight_attr='weight',
**kwargs):
""" Detect communities for temporal ... | python | def find_partition_temporal(graphs, partition_type,
interslice_weight=1,
slice_attr='slice', vertex_id_attr='id',
edge_type_attr='type', weight_attr='weight',
**kwargs):
""" Detect communities for temporal ... | [
"def",
"find_partition_temporal",
"(",
"graphs",
",",
"partition_type",
",",
"interslice_weight",
"=",
"1",
",",
"slice_attr",
"=",
"'slice'",
",",
"vertex_id_attr",
"=",
"'id'",
",",
"edge_type_attr",
"=",
"'type'",
",",
"weight_attr",
"=",
"'weight'",
",",
"*"... | Detect communities for temporal graphs.
Each graph is considered to represent a time slice and does not necessarily
need to be defined on the same set of vertices. Nodes in two consecutive
slices are identified on the basis of the ``vertex_id_attr``, i.e. if two
nodes in two consecutive slices have an identica... | [
"Detect",
"communities",
"for",
"temporal",
"graphs",
"."
] | 8de2c3bad736a9deea90b80f104d8444769d331f | https://github.com/vtraag/louvain-igraph/blob/8de2c3bad736a9deea90b80f104d8444769d331f/src/functions.py#L138-L245 | train |
vtraag/louvain-igraph | setup.py | BuildConfiguration.build_ext | def build_ext(self):
"""Returns a class that can be used as a replacement for the
``build_ext`` command in ``distutils`` and that will download and
compile the C core of igraph if needed."""
try:
from setuptools.command.build_ext import build_ext
except ImportError:
... | python | def build_ext(self):
"""Returns a class that can be used as a replacement for the
``build_ext`` command in ``distutils`` and that will download and
compile the C core of igraph if needed."""
try:
from setuptools.command.build_ext import build_ext
except ImportError:
... | [
"def",
"build_ext",
"(",
"self",
")",
":",
"try",
":",
"from",
"setuptools",
".",
"command",
".",
"build_ext",
"import",
"build_ext",
"except",
"ImportError",
":",
"from",
"distutils",
".",
"command",
".",
"build_ext",
"import",
"build_ext",
"buildcfg",
"=",
... | Returns a class that can be used as a replacement for the
``build_ext`` command in ``distutils`` and that will download and
compile the C core of igraph if needed. | [
"Returns",
"a",
"class",
"that",
"can",
"be",
"used",
"as",
"a",
"replacement",
"for",
"the",
"build_ext",
"command",
"in",
"distutils",
"and",
"that",
"will",
"download",
"and",
"compile",
"the",
"C",
"core",
"of",
"igraph",
"if",
"needed",
"."
] | 8de2c3bad736a9deea90b80f104d8444769d331f | https://github.com/vtraag/louvain-igraph/blob/8de2c3bad736a9deea90b80f104d8444769d331f/setup.py#L353-L405 | train |
vtraag/louvain-igraph | src/VertexPartition.py | CPMVertexPartition.Bipartite | def Bipartite(graph, resolution_parameter_01,
resolution_parameter_0 = 0, resolution_parameter_1 = 0,
degree_as_node_size=False, types='type', **kwargs):
""" Create three layers for bipartite partitions.
This creates three layers for bipartite partition necessary for detecting
... | python | def Bipartite(graph, resolution_parameter_01,
resolution_parameter_0 = 0, resolution_parameter_1 = 0,
degree_as_node_size=False, types='type', **kwargs):
""" Create three layers for bipartite partitions.
This creates three layers for bipartite partition necessary for detecting
... | [
"def",
"Bipartite",
"(",
"graph",
",",
"resolution_parameter_01",
",",
"resolution_parameter_0",
"=",
"0",
",",
"resolution_parameter_1",
"=",
"0",
",",
"degree_as_node_size",
"=",
"False",
",",
"types",
"=",
"'type'",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
... | Create three layers for bipartite partitions.
This creates three layers for bipartite partition necessary for detecting
communities in bipartite networks. These three layers should be passed to
:func:`Optimiser.optimise_partition_multiplex` with
``layer_weights=[1,-1,-1]``.
Parameters
--------... | [
"Create",
"three",
"layers",
"for",
"bipartite",
"partitions",
"."
] | 8de2c3bad736a9deea90b80f104d8444769d331f | https://github.com/vtraag/louvain-igraph/blob/8de2c3bad736a9deea90b80f104d8444769d331f/src/VertexPartition.py#L865-L1009 | train |
vinta/pangu.py | pangu.py | spacing_file | def spacing_file(path):
"""
Perform paranoid text spacing from file.
"""
# TODO: read line by line
with open(os.path.abspath(path)) as f:
return spacing_text(f.read()) | python | def spacing_file(path):
"""
Perform paranoid text spacing from file.
"""
# TODO: read line by line
with open(os.path.abspath(path)) as f:
return spacing_text(f.read()) | [
"def",
"spacing_file",
"(",
"path",
")",
":",
"# TODO: read line by line",
"with",
"open",
"(",
"os",
".",
"path",
".",
"abspath",
"(",
"path",
")",
")",
"as",
"f",
":",
"return",
"spacing_text",
"(",
"f",
".",
"read",
"(",
")",
")"
] | Perform paranoid text spacing from file. | [
"Perform",
"paranoid",
"text",
"spacing",
"from",
"file",
"."
] | 89407cf08dedf9d895c13053dd518d11a20f6c95 | https://github.com/vinta/pangu.py/blob/89407cf08dedf9d895c13053dd518d11a20f6c95/pangu.py#L156-L162 | train |
EventRegistry/event-registry-python | eventregistry/EventForText.py | GetEventForText.compute | def compute(self,
text, # text for which to find the most similar event
lang = "eng"): # language in which the text is written
"""
compute the list of most similar events for the given text
"""
params = { "lang": lang, "text": text, "topClusters... | python | def compute(self,
text, # text for which to find the most similar event
lang = "eng"): # language in which the text is written
"""
compute the list of most similar events for the given text
"""
params = { "lang": lang, "text": text, "topClusters... | [
"def",
"compute",
"(",
"self",
",",
"text",
",",
"# text for which to find the most similar event",
"lang",
"=",
"\"eng\"",
")",
":",
"# language in which the text is written",
"params",
"=",
"{",
"\"lang\"",
":",
"lang",
",",
"\"text\"",
":",
"text",
",",
"\"topClu... | compute the list of most similar events for the given text | [
"compute",
"the",
"list",
"of",
"most",
"similar",
"events",
"for",
"the",
"given",
"text"
] | 534d20b616de02f5e1cd73665a02d189645dbeb6 | https://github.com/EventRegistry/event-registry-python/blob/534d20b616de02f5e1cd73665a02d189645dbeb6/eventregistry/EventForText.py#L42-L57 | train |
EventRegistry/event-registry-python | eventregistry/Analytics.py | Analytics.annotate | def annotate(self, text, lang = None, customParams = None):
"""
identify the list of entities and nonentities mentioned in the text
@param text: input text to annotate
@param lang: language of the provided document (can be an ISO2 or ISO3 code). If None is provided, the language will be ... | python | def annotate(self, text, lang = None, customParams = None):
"""
identify the list of entities and nonentities mentioned in the text
@param text: input text to annotate
@param lang: language of the provided document (can be an ISO2 or ISO3 code). If None is provided, the language will be ... | [
"def",
"annotate",
"(",
"self",
",",
"text",
",",
"lang",
"=",
"None",
",",
"customParams",
"=",
"None",
")",
":",
"params",
"=",
"{",
"\"lang\"",
":",
"lang",
",",
"\"text\"",
":",
"text",
"}",
"if",
"customParams",
":",
"params",
".",
"update",
"("... | identify the list of entities and nonentities mentioned in the text
@param text: input text to annotate
@param lang: language of the provided document (can be an ISO2 or ISO3 code). If None is provided, the language will be automatically detected
@param customParams: None or a dict with custom p... | [
"identify",
"the",
"list",
"of",
"entities",
"and",
"nonentities",
"mentioned",
"in",
"the",
"text"
] | 534d20b616de02f5e1cd73665a02d189645dbeb6 | https://github.com/EventRegistry/event-registry-python/blob/534d20b616de02f5e1cd73665a02d189645dbeb6/eventregistry/Analytics.py#L25-L36 | train |
EventRegistry/event-registry-python | eventregistry/Analytics.py | Analytics.sentiment | def sentiment(self, text, method = "vocabulary"):
"""
determine the sentiment of the provided text in English language
@param text: input text to categorize
@param method: method to use to compute the sentiment. possible values are "vocabulary" (vocabulary based sentiment analysis)
... | python | def sentiment(self, text, method = "vocabulary"):
"""
determine the sentiment of the provided text in English language
@param text: input text to categorize
@param method: method to use to compute the sentiment. possible values are "vocabulary" (vocabulary based sentiment analysis)
... | [
"def",
"sentiment",
"(",
"self",
",",
"text",
",",
"method",
"=",
"\"vocabulary\"",
")",
":",
"assert",
"method",
"==",
"\"vocabulary\"",
"or",
"method",
"==",
"\"rnn\"",
"endpoint",
"=",
"method",
"==",
"\"vocabulary\"",
"and",
"\"sentiment\"",
"or",
"\"senti... | determine the sentiment of the provided text in English language
@param text: input text to categorize
@param method: method to use to compute the sentiment. possible values are "vocabulary" (vocabulary based sentiment analysis)
and "rnn" (neural network based sentiment classification)
... | [
"determine",
"the",
"sentiment",
"of",
"the",
"provided",
"text",
"in",
"English",
"language"
] | 534d20b616de02f5e1cd73665a02d189645dbeb6 | https://github.com/EventRegistry/event-registry-python/blob/534d20b616de02f5e1cd73665a02d189645dbeb6/eventregistry/Analytics.py#L50-L60 | train |
EventRegistry/event-registry-python | eventregistry/Analytics.py | Analytics.semanticSimilarity | def semanticSimilarity(self, text1, text2, distanceMeasure = "cosine"):
"""
determine the semantic similarity of the two provided documents
@param text1: first document to analyze
@param text2: second document to analyze
@param distanceMeasure: distance measure to use for compari... | python | def semanticSimilarity(self, text1, text2, distanceMeasure = "cosine"):
"""
determine the semantic similarity of the two provided documents
@param text1: first document to analyze
@param text2: second document to analyze
@param distanceMeasure: distance measure to use for compari... | [
"def",
"semanticSimilarity",
"(",
"self",
",",
"text1",
",",
"text2",
",",
"distanceMeasure",
"=",
"\"cosine\"",
")",
":",
"return",
"self",
".",
"_er",
".",
"jsonRequestAnalytics",
"(",
"\"/api/v1/semanticSimilarity\"",
",",
"{",
"\"text1\"",
":",
"text1",
",",... | determine the semantic similarity of the two provided documents
@param text1: first document to analyze
@param text2: second document to analyze
@param distanceMeasure: distance measure to use for comparing two documents. Possible values are "cosine" (default) or "jaccard"
@returns: dict | [
"determine",
"the",
"semantic",
"similarity",
"of",
"the",
"two",
"provided",
"documents"
] | 534d20b616de02f5e1cd73665a02d189645dbeb6 | https://github.com/EventRegistry/event-registry-python/blob/534d20b616de02f5e1cd73665a02d189645dbeb6/eventregistry/Analytics.py#L63-L71 | train |
EventRegistry/event-registry-python | eventregistry/Analytics.py | Analytics.extractArticleInfo | def extractArticleInfo(self, url, proxyUrl = None, headers = None, cookies = None):
"""
extract all available information about an article available at url `url`. Returned information will include
article title, body, authors, links in the articles, ...
@param url: article url to extract... | python | def extractArticleInfo(self, url, proxyUrl = None, headers = None, cookies = None):
"""
extract all available information about an article available at url `url`. Returned information will include
article title, body, authors, links in the articles, ...
@param url: article url to extract... | [
"def",
"extractArticleInfo",
"(",
"self",
",",
"url",
",",
"proxyUrl",
"=",
"None",
",",
"headers",
"=",
"None",
",",
"cookies",
"=",
"None",
")",
":",
"params",
"=",
"{",
"\"url\"",
":",
"url",
"}",
"if",
"proxyUrl",
":",
"params",
"[",
"\"proxyUrl\""... | extract all available information about an article available at url `url`. Returned information will include
article title, body, authors, links in the articles, ...
@param url: article url to extract article information from
@param proxyUrl: proxy that should be used for downloading article inf... | [
"extract",
"all",
"available",
"information",
"about",
"an",
"article",
"available",
"at",
"url",
"url",
".",
"Returned",
"information",
"will",
"include",
"article",
"title",
"body",
"authors",
"links",
"in",
"the",
"articles",
"..."
] | 534d20b616de02f5e1cd73665a02d189645dbeb6 | https://github.com/EventRegistry/event-registry-python/blob/534d20b616de02f5e1cd73665a02d189645dbeb6/eventregistry/Analytics.py#L83-L104 | train |
EventRegistry/event-registry-python | eventregistry/Analytics.py | Analytics.trainTopicOnTweets | def trainTopicOnTweets(self, twitterQuery, useTweetText=True, useIdfNormalization=True,
normalization="linear", maxTweets=2000, maxUsedLinks=500, ignoreConceptTypes=[],
maxConcepts = 20, maxCategories = 10, notifyEmailAddress = None):
"""
create a new topic and train it using the... | python | def trainTopicOnTweets(self, twitterQuery, useTweetText=True, useIdfNormalization=True,
normalization="linear", maxTweets=2000, maxUsedLinks=500, ignoreConceptTypes=[],
maxConcepts = 20, maxCategories = 10, notifyEmailAddress = None):
"""
create a new topic and train it using the... | [
"def",
"trainTopicOnTweets",
"(",
"self",
",",
"twitterQuery",
",",
"useTweetText",
"=",
"True",
",",
"useIdfNormalization",
"=",
"True",
",",
"normalization",
"=",
"\"linear\"",
",",
"maxTweets",
"=",
"2000",
",",
"maxUsedLinks",
"=",
"500",
",",
"ignoreConcept... | create a new topic and train it using the tweets that match the twitterQuery
@param twitterQuery: string containing the content to search for. It can be a Twitter user account (using "@" prefix or user's Twitter url),
a hash tag (using "#" prefix) or a regular keyword.
@param useTweetTex... | [
"create",
"a",
"new",
"topic",
"and",
"train",
"it",
"using",
"the",
"tweets",
"that",
"match",
"the",
"twitterQuery"
] | 534d20b616de02f5e1cd73665a02d189645dbeb6 | https://github.com/EventRegistry/event-registry-python/blob/534d20b616de02f5e1cd73665a02d189645dbeb6/eventregistry/Analytics.py#L116-L144 | train |
EventRegistry/event-registry-python | eventregistry/Analytics.py | Analytics.trainTopicGetTrainedTopic | def trainTopicGetTrainedTopic(self, uri, maxConcepts = 20, maxCategories = 10,
ignoreConceptTypes=[], idfNormalization = True):
"""
retrieve topic for the topic for which you have already finished training
@param uri: uri of the topic (obtained by calling trainTopicCreateTopic method... | python | def trainTopicGetTrainedTopic(self, uri, maxConcepts = 20, maxCategories = 10,
ignoreConceptTypes=[], idfNormalization = True):
"""
retrieve topic for the topic for which you have already finished training
@param uri: uri of the topic (obtained by calling trainTopicCreateTopic method... | [
"def",
"trainTopicGetTrainedTopic",
"(",
"self",
",",
"uri",
",",
"maxConcepts",
"=",
"20",
",",
"maxCategories",
"=",
"10",
",",
"ignoreConceptTypes",
"=",
"[",
"]",
",",
"idfNormalization",
"=",
"True",
")",
":",
"return",
"self",
".",
"_er",
".",
"jsonR... | retrieve topic for the topic for which you have already finished training
@param uri: uri of the topic (obtained by calling trainTopicCreateTopic method)
@param maxConcepts: number of top concepts to retrieve in the topic
@param maxCategories: number of top categories to retrieve in the topic
... | [
"retrieve",
"topic",
"for",
"the",
"topic",
"for",
"which",
"you",
"have",
"already",
"finished",
"training"
] | 534d20b616de02f5e1cd73665a02d189645dbeb6 | https://github.com/EventRegistry/event-registry-python/blob/534d20b616de02f5e1cd73665a02d189645dbeb6/eventregistry/Analytics.py#L172-L183 | train |
EventRegistry/event-registry-python | eventregistry/examples/TopicPagesExamples.py | createTopicPage1 | def createTopicPage1():
"""
create a topic page directly
"""
topic = TopicPage(er)
topic.addKeyword("renewable energy", 30)
topic.addConcept(er.getConceptUri("biofuel"), 50)
topic.addConcept(er.getConceptUri("solar energy"), 50)
topic.addCategory(er.getCategoryUri("renewable"), 50)
... | python | def createTopicPage1():
"""
create a topic page directly
"""
topic = TopicPage(er)
topic.addKeyword("renewable energy", 30)
topic.addConcept(er.getConceptUri("biofuel"), 50)
topic.addConcept(er.getConceptUri("solar energy"), 50)
topic.addCategory(er.getCategoryUri("renewable"), 50)
... | [
"def",
"createTopicPage1",
"(",
")",
":",
"topic",
"=",
"TopicPage",
"(",
"er",
")",
"topic",
".",
"addKeyword",
"(",
"\"renewable energy\"",
",",
"30",
")",
"topic",
".",
"addConcept",
"(",
"er",
".",
"getConceptUri",
"(",
"\"biofuel\"",
")",
",",
"50",
... | create a topic page directly | [
"create",
"a",
"topic",
"page",
"directly"
] | 534d20b616de02f5e1cd73665a02d189645dbeb6 | https://github.com/EventRegistry/event-registry-python/blob/534d20b616de02f5e1cd73665a02d189645dbeb6/eventregistry/examples/TopicPagesExamples.py#L6-L26 | train |
EventRegistry/event-registry-python | eventregistry/examples/TopicPagesExamples.py | createTopicPage2 | def createTopicPage2():
"""
create a topic page directly, set the article threshold, restrict results to set concepts and keywords
"""
topic = TopicPage(er)
topic.addCategory(er.getCategoryUri("renewable"), 50)
topic.addKeyword("renewable energy", 30)
topic.addConcept(er.getConceptUri("bio... | python | def createTopicPage2():
"""
create a topic page directly, set the article threshold, restrict results to set concepts and keywords
"""
topic = TopicPage(er)
topic.addCategory(er.getCategoryUri("renewable"), 50)
topic.addKeyword("renewable energy", 30)
topic.addConcept(er.getConceptUri("bio... | [
"def",
"createTopicPage2",
"(",
")",
":",
"topic",
"=",
"TopicPage",
"(",
"er",
")",
"topic",
".",
"addCategory",
"(",
"er",
".",
"getCategoryUri",
"(",
"\"renewable\"",
")",
",",
"50",
")",
"topic",
".",
"addKeyword",
"(",
"\"renewable energy\"",
",",
"30... | create a topic page directly, set the article threshold, restrict results to set concepts and keywords | [
"create",
"a",
"topic",
"page",
"directly",
"set",
"the",
"article",
"threshold",
"restrict",
"results",
"to",
"set",
"concepts",
"and",
"keywords"
] | 534d20b616de02f5e1cd73665a02d189645dbeb6 | https://github.com/EventRegistry/event-registry-python/blob/534d20b616de02f5e1cd73665a02d189645dbeb6/eventregistry/examples/TopicPagesExamples.py#L30-L63 | train |
EventRegistry/event-registry-python | eventregistry/QueryEvent.py | QueryEventArticlesIter.count | def count(self, eventRegistry):
"""
return the number of articles that match the criteria
@param eventRegistry: instance of EventRegistry class. used to obtain the necessary data
"""
self.setRequestedResult(RequestEventArticles(**self.queryParams))
res = eventRegistry.exe... | python | def count(self, eventRegistry):
"""
return the number of articles that match the criteria
@param eventRegistry: instance of EventRegistry class. used to obtain the necessary data
"""
self.setRequestedResult(RequestEventArticles(**self.queryParams))
res = eventRegistry.exe... | [
"def",
"count",
"(",
"self",
",",
"eventRegistry",
")",
":",
"self",
".",
"setRequestedResult",
"(",
"RequestEventArticles",
"(",
"*",
"*",
"self",
".",
"queryParams",
")",
")",
"res",
"=",
"eventRegistry",
".",
"execQuery",
"(",
"self",
")",
"if",
"\"erro... | return the number of articles that match the criteria
@param eventRegistry: instance of EventRegistry class. used to obtain the necessary data | [
"return",
"the",
"number",
"of",
"articles",
"that",
"match",
"the",
"criteria"
] | 534d20b616de02f5e1cd73665a02d189645dbeb6 | https://github.com/EventRegistry/event-registry-python/blob/534d20b616de02f5e1cd73665a02d189645dbeb6/eventregistry/QueryEvent.py#L150-L160 | train |
EventRegistry/event-registry-python | eventregistry/QueryArticles.py | QueryArticles.initWithComplexQuery | def initWithComplexQuery(query):
"""
create a query using a complex article query
"""
q = QueryArticles()
# provided an instance of ComplexArticleQuery
if isinstance(query, ComplexArticleQuery):
q._setVal("query", json.dumps(query.getQuery()))
# provid... | python | def initWithComplexQuery(query):
"""
create a query using a complex article query
"""
q = QueryArticles()
# provided an instance of ComplexArticleQuery
if isinstance(query, ComplexArticleQuery):
q._setVal("query", json.dumps(query.getQuery()))
# provid... | [
"def",
"initWithComplexQuery",
"(",
"query",
")",
":",
"q",
"=",
"QueryArticles",
"(",
")",
"# provided an instance of ComplexArticleQuery",
"if",
"isinstance",
"(",
"query",
",",
"ComplexArticleQuery",
")",
":",
"q",
".",
"_setVal",
"(",
"\"query\"",
",",
"json",... | create a query using a complex article query | [
"create",
"a",
"query",
"using",
"a",
"complex",
"article",
"query"
] | 534d20b616de02f5e1cd73665a02d189645dbeb6 | https://github.com/EventRegistry/event-registry-python/blob/534d20b616de02f5e1cd73665a02d189645dbeb6/eventregistry/QueryArticles.py#L218-L235 | train |
EventRegistry/event-registry-python | eventregistry/QueryArticles.py | QueryArticlesIter._getNextArticleBatch | def _getNextArticleBatch(self):
"""download next batch of articles based on the article uris in the uri list"""
# try to get more uris, if none
self._articlePage += 1
# if we have already obtained all pages, then exit
if self._totalPages != None and self._articlePage > self._tota... | python | def _getNextArticleBatch(self):
"""download next batch of articles based on the article uris in the uri list"""
# try to get more uris, if none
self._articlePage += 1
# if we have already obtained all pages, then exit
if self._totalPages != None and self._articlePage > self._tota... | [
"def",
"_getNextArticleBatch",
"(",
"self",
")",
":",
"# try to get more uris, if none",
"self",
".",
"_articlePage",
"+=",
"1",
"# if we have already obtained all pages, then exit",
"if",
"self",
".",
"_totalPages",
"!=",
"None",
"and",
"self",
".",
"_articlePage",
">"... | download next batch of articles based on the article uris in the uri list | [
"download",
"next",
"batch",
"of",
"articles",
"based",
"on",
"the",
"article",
"uris",
"in",
"the",
"uri",
"list"
] | 534d20b616de02f5e1cd73665a02d189645dbeb6 | https://github.com/EventRegistry/event-registry-python/blob/534d20b616de02f5e1cd73665a02d189645dbeb6/eventregistry/QueryArticles.py#L317-L335 | train |
EventRegistry/event-registry-python | eventregistry/QueryEvents.py | QueryEvents.initWithComplexQuery | def initWithComplexQuery(query):
"""
create a query using a complex event query
"""
q = QueryEvents()
# provided an instance of ComplexEventQuery
if isinstance(query, ComplexEventQuery):
q._setVal("query", json.dumps(query.getQuery()))
# provided query... | python | def initWithComplexQuery(query):
"""
create a query using a complex event query
"""
q = QueryEvents()
# provided an instance of ComplexEventQuery
if isinstance(query, ComplexEventQuery):
q._setVal("query", json.dumps(query.getQuery()))
# provided query... | [
"def",
"initWithComplexQuery",
"(",
"query",
")",
":",
"q",
"=",
"QueryEvents",
"(",
")",
"# provided an instance of ComplexEventQuery",
"if",
"isinstance",
"(",
"query",
",",
"ComplexEventQuery",
")",
":",
"q",
".",
"_setVal",
"(",
"\"query\"",
",",
"json",
"."... | create a query using a complex event query | [
"create",
"a",
"query",
"using",
"a",
"complex",
"event",
"query"
] | 534d20b616de02f5e1cd73665a02d189645dbeb6 | https://github.com/EventRegistry/event-registry-python/blob/534d20b616de02f5e1cd73665a02d189645dbeb6/eventregistry/QueryEvents.py#L183-L201 | train |
EventRegistry/event-registry-python | eventregistry/QueryEvents.py | QueryEventsIter.count | def count(self, eventRegistry):
"""
return the number of events that match the criteria
"""
self.setRequestedResult(RequestEventsInfo())
res = eventRegistry.execQuery(self)
if "error" in res:
print(res["error"])
count = res.get("events", {}).get("total... | python | def count(self, eventRegistry):
"""
return the number of events that match the criteria
"""
self.setRequestedResult(RequestEventsInfo())
res = eventRegistry.execQuery(self)
if "error" in res:
print(res["error"])
count = res.get("events", {}).get("total... | [
"def",
"count",
"(",
"self",
",",
"eventRegistry",
")",
":",
"self",
".",
"setRequestedResult",
"(",
"RequestEventsInfo",
"(",
")",
")",
"res",
"=",
"eventRegistry",
".",
"execQuery",
"(",
"self",
")",
"if",
"\"error\"",
"in",
"res",
":",
"print",
"(",
"... | return the number of events that match the criteria | [
"return",
"the",
"number",
"of",
"events",
"that",
"match",
"the",
"criteria"
] | 534d20b616de02f5e1cd73665a02d189645dbeb6 | https://github.com/EventRegistry/event-registry-python/blob/534d20b616de02f5e1cd73665a02d189645dbeb6/eventregistry/QueryEvents.py#L211-L220 | train |
EventRegistry/event-registry-python | eventregistry/ReturnInfo.py | ReturnInfoFlagsBase._setFlag | def _setFlag(self, name, val, defVal):
"""set the objects property propName if the dictKey key exists in dict and it is not the same as default value defVal"""
if not hasattr(self, "flags"):
self.flags = {}
if val != defVal:
self.flags[name] = val | python | def _setFlag(self, name, val, defVal):
"""set the objects property propName if the dictKey key exists in dict and it is not the same as default value defVal"""
if not hasattr(self, "flags"):
self.flags = {}
if val != defVal:
self.flags[name] = val | [
"def",
"_setFlag",
"(",
"self",
",",
"name",
",",
"val",
",",
"defVal",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"\"flags\"",
")",
":",
"self",
".",
"flags",
"=",
"{",
"}",
"if",
"val",
"!=",
"defVal",
":",
"self",
".",
"flags",
"[",
... | set the objects property propName if the dictKey key exists in dict and it is not the same as default value defVal | [
"set",
"the",
"objects",
"property",
"propName",
"if",
"the",
"dictKey",
"key",
"exists",
"in",
"dict",
"and",
"it",
"is",
"not",
"the",
"same",
"as",
"default",
"value",
"defVal"
] | 534d20b616de02f5e1cd73665a02d189645dbeb6 | https://github.com/EventRegistry/event-registry-python/blob/534d20b616de02f5e1cd73665a02d189645dbeb6/eventregistry/ReturnInfo.py#L15-L20 | train |
EventRegistry/event-registry-python | eventregistry/ReturnInfo.py | ReturnInfoFlagsBase._setVal | def _setVal(self, name, val, defVal = None):
"""set value of name to val in case the val != defVal"""
if val == defVal:
return
if not hasattr(self, "vals"):
self.vals = {}
self.vals[name] = val | python | def _setVal(self, name, val, defVal = None):
"""set value of name to val in case the val != defVal"""
if val == defVal:
return
if not hasattr(self, "vals"):
self.vals = {}
self.vals[name] = val | [
"def",
"_setVal",
"(",
"self",
",",
"name",
",",
"val",
",",
"defVal",
"=",
"None",
")",
":",
"if",
"val",
"==",
"defVal",
":",
"return",
"if",
"not",
"hasattr",
"(",
"self",
",",
"\"vals\"",
")",
":",
"self",
".",
"vals",
"=",
"{",
"}",
"self",
... | set value of name to val in case the val != defVal | [
"set",
"value",
"of",
"name",
"to",
"val",
"in",
"case",
"the",
"val",
"!",
"=",
"defVal"
] | 534d20b616de02f5e1cd73665a02d189645dbeb6 | https://github.com/EventRegistry/event-registry-python/blob/534d20b616de02f5e1cd73665a02d189645dbeb6/eventregistry/ReturnInfo.py#L30-L36 | train |
EventRegistry/event-registry-python | eventregistry/ReturnInfo.py | ReturnInfoFlagsBase._getVals | def _getVals(self, prefix = ""):
"""
return the values in the vals dict
in case prefix is "", change the first letter of the name to lowercase, otherwise use prefix+name as the new name
"""
if not hasattr(self, "vals"):
self.vals = {}
dict = {}
for key... | python | def _getVals(self, prefix = ""):
"""
return the values in the vals dict
in case prefix is "", change the first letter of the name to lowercase, otherwise use prefix+name as the new name
"""
if not hasattr(self, "vals"):
self.vals = {}
dict = {}
for key... | [
"def",
"_getVals",
"(",
"self",
",",
"prefix",
"=",
"\"\"",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"\"vals\"",
")",
":",
"self",
".",
"vals",
"=",
"{",
"}",
"dict",
"=",
"{",
"}",
"for",
"key",
"in",
"list",
"(",
"self",
".",
"vals... | return the values in the vals dict
in case prefix is "", change the first letter of the name to lowercase, otherwise use prefix+name as the new name | [
"return",
"the",
"values",
"in",
"the",
"vals",
"dict",
"in",
"case",
"prefix",
"is",
"change",
"the",
"first",
"letter",
"of",
"the",
"name",
"to",
"lowercase",
"otherwise",
"use",
"prefix",
"+",
"name",
"as",
"the",
"new",
"name"
] | 534d20b616de02f5e1cd73665a02d189645dbeb6 | https://github.com/EventRegistry/event-registry-python/blob/534d20b616de02f5e1cd73665a02d189645dbeb6/eventregistry/ReturnInfo.py#L39-L55 | train |
EventRegistry/event-registry-python | eventregistry/ReturnInfo.py | ReturnInfo.loadFromFile | def loadFromFile(fileName):
"""
load the configuration for the ReturnInfo from a fileName
@param fileName: filename that contains the json configuration to use in the ReturnInfo
"""
assert os.path.exists(fileName), "File " + fileName + " does not exist"
conf = json.load(o... | python | def loadFromFile(fileName):
"""
load the configuration for the ReturnInfo from a fileName
@param fileName: filename that contains the json configuration to use in the ReturnInfo
"""
assert os.path.exists(fileName), "File " + fileName + " does not exist"
conf = json.load(o... | [
"def",
"loadFromFile",
"(",
"fileName",
")",
":",
"assert",
"os",
".",
"path",
".",
"exists",
"(",
"fileName",
")",
",",
"\"File \"",
"+",
"fileName",
"+",
"\" does not exist\"",
"conf",
"=",
"json",
".",
"load",
"(",
"open",
"(",
"fileName",
")",
")",
... | load the configuration for the ReturnInfo from a fileName
@param fileName: filename that contains the json configuration to use in the ReturnInfo | [
"load",
"the",
"configuration",
"for",
"the",
"ReturnInfo",
"from",
"a",
"fileName"
] | 534d20b616de02f5e1cd73665a02d189645dbeb6 | https://github.com/EventRegistry/event-registry-python/blob/534d20b616de02f5e1cd73665a02d189645dbeb6/eventregistry/ReturnInfo.py#L453-L470 | train |
EventRegistry/event-registry-python | eventregistry/TopicPage.py | TopicPage.loadTopicPageFromER | def loadTopicPageFromER(self, uri):
"""
load an existing topic page from Event Registry based on the topic page URI
@param uri: uri of the topic page saved in your Event Registry account
"""
params = {
"action": "getTopicPageJson",
"includeConceptDescripti... | python | def loadTopicPageFromER(self, uri):
"""
load an existing topic page from Event Registry based on the topic page URI
@param uri: uri of the topic page saved in your Event Registry account
"""
params = {
"action": "getTopicPageJson",
"includeConceptDescripti... | [
"def",
"loadTopicPageFromER",
"(",
"self",
",",
"uri",
")",
":",
"params",
"=",
"{",
"\"action\"",
":",
"\"getTopicPageJson\"",
",",
"\"includeConceptDescription\"",
":",
"True",
",",
"\"includeTopicPageDefinition\"",
":",
"True",
",",
"\"includeTopicPageOwner\"",
":"... | load an existing topic page from Event Registry based on the topic page URI
@param uri: uri of the topic page saved in your Event Registry account | [
"load",
"an",
"existing",
"topic",
"page",
"from",
"Event",
"Registry",
"based",
"on",
"the",
"topic",
"page",
"URI"
] | 534d20b616de02f5e1cd73665a02d189645dbeb6 | https://github.com/EventRegistry/event-registry-python/blob/534d20b616de02f5e1cd73665a02d189645dbeb6/eventregistry/TopicPage.py#L51-L65 | train |
EventRegistry/event-registry-python | eventregistry/TopicPage.py | TopicPage.loadTopicPageFromFile | def loadTopicPageFromFile(self, fname):
"""
load topic page from an existing file
"""
assert os.path.exists(fname)
f = open(fname, "r", encoding="utf-8")
self.topicPage = json.load(f) | python | def loadTopicPageFromFile(self, fname):
"""
load topic page from an existing file
"""
assert os.path.exists(fname)
f = open(fname, "r", encoding="utf-8")
self.topicPage = json.load(f) | [
"def",
"loadTopicPageFromFile",
"(",
"self",
",",
"fname",
")",
":",
"assert",
"os",
".",
"path",
".",
"exists",
"(",
"fname",
")",
"f",
"=",
"open",
"(",
"fname",
",",
"\"r\"",
",",
"encoding",
"=",
"\"utf-8\"",
")",
"self",
".",
"topicPage",
"=",
"... | load topic page from an existing file | [
"load",
"topic",
"page",
"from",
"an",
"existing",
"file"
] | 534d20b616de02f5e1cd73665a02d189645dbeb6 | https://github.com/EventRegistry/event-registry-python/blob/534d20b616de02f5e1cd73665a02d189645dbeb6/eventregistry/TopicPage.py#L76-L82 | train |
EventRegistry/event-registry-python | eventregistry/TopicPage.py | TopicPage.saveTopicPageDefinitionToFile | def saveTopicPageDefinitionToFile(self, fname):
"""
save the topic page definition to a file
"""
open(fname, "w", encoding="utf-8").write(json.dumps(self.topicPage, indent = 4, sort_keys = True)) | python | def saveTopicPageDefinitionToFile(self, fname):
"""
save the topic page definition to a file
"""
open(fname, "w", encoding="utf-8").write(json.dumps(self.topicPage, indent = 4, sort_keys = True)) | [
"def",
"saveTopicPageDefinitionToFile",
"(",
"self",
",",
"fname",
")",
":",
"open",
"(",
"fname",
",",
"\"w\"",
",",
"encoding",
"=",
"\"utf-8\"",
")",
".",
"write",
"(",
"json",
".",
"dumps",
"(",
"self",
".",
"topicPage",
",",
"indent",
"=",
"4",
",... | save the topic page definition to a file | [
"save",
"the",
"topic",
"page",
"definition",
"to",
"a",
"file"
] | 534d20b616de02f5e1cd73665a02d189645dbeb6 | https://github.com/EventRegistry/event-registry-python/blob/534d20b616de02f5e1cd73665a02d189645dbeb6/eventregistry/TopicPage.py#L92-L96 | train |
EventRegistry/event-registry-python | eventregistry/TopicPage.py | TopicPage.setArticleThreshold | def setArticleThreshold(self, value):
"""
what is the minimum total weight that an article has to have in order to get it among the results?
@param value: threshold to use
"""
assert isinstance(value, int)
assert value >= 0
self.topicPage["articleTreshWgt"] = valu... | python | def setArticleThreshold(self, value):
"""
what is the minimum total weight that an article has to have in order to get it among the results?
@param value: threshold to use
"""
assert isinstance(value, int)
assert value >= 0
self.topicPage["articleTreshWgt"] = valu... | [
"def",
"setArticleThreshold",
"(",
"self",
",",
"value",
")",
":",
"assert",
"isinstance",
"(",
"value",
",",
"int",
")",
"assert",
"value",
">=",
"0",
"self",
".",
"topicPage",
"[",
"\"articleTreshWgt\"",
"]",
"=",
"value"
] | what is the minimum total weight that an article has to have in order to get it among the results?
@param value: threshold to use | [
"what",
"is",
"the",
"minimum",
"total",
"weight",
"that",
"an",
"article",
"has",
"to",
"have",
"in",
"order",
"to",
"get",
"it",
"among",
"the",
"results?"
] | 534d20b616de02f5e1cd73665a02d189645dbeb6 | https://github.com/EventRegistry/event-registry-python/blob/534d20b616de02f5e1cd73665a02d189645dbeb6/eventregistry/TopicPage.py#L102-L109 | train |
EventRegistry/event-registry-python | eventregistry/TopicPage.py | TopicPage.setEventThreshold | def setEventThreshold(self, value):
"""
what is the minimum total weight that an event has to have in order to get it among the results?
@param value: threshold to use
"""
assert isinstance(value, int)
assert value >= 0
self.topicPage["eventTreshWgt"] = value | python | def setEventThreshold(self, value):
"""
what is the minimum total weight that an event has to have in order to get it among the results?
@param value: threshold to use
"""
assert isinstance(value, int)
assert value >= 0
self.topicPage["eventTreshWgt"] = value | [
"def",
"setEventThreshold",
"(",
"self",
",",
"value",
")",
":",
"assert",
"isinstance",
"(",
"value",
",",
"int",
")",
"assert",
"value",
">=",
"0",
"self",
".",
"topicPage",
"[",
"\"eventTreshWgt\"",
"]",
"=",
"value"
] | what is the minimum total weight that an event has to have in order to get it among the results?
@param value: threshold to use | [
"what",
"is",
"the",
"minimum",
"total",
"weight",
"that",
"an",
"event",
"has",
"to",
"have",
"in",
"order",
"to",
"get",
"it",
"among",
"the",
"results?"
] | 534d20b616de02f5e1cd73665a02d189645dbeb6 | https://github.com/EventRegistry/event-registry-python/blob/534d20b616de02f5e1cd73665a02d189645dbeb6/eventregistry/TopicPage.py#L112-L119 | train |
EventRegistry/event-registry-python | eventregistry/TopicPage.py | TopicPage.setMaxDaysBack | def setMaxDaysBack(self, maxDaysBack):
"""
what is the maximum allowed age of the results?
"""
assert isinstance(maxDaysBack, int), "maxDaysBack value has to be a positive integer"
assert maxDaysBack >= 1
self.topicPage["maxDaysBack"] = maxDaysBack | python | def setMaxDaysBack(self, maxDaysBack):
"""
what is the maximum allowed age of the results?
"""
assert isinstance(maxDaysBack, int), "maxDaysBack value has to be a positive integer"
assert maxDaysBack >= 1
self.topicPage["maxDaysBack"] = maxDaysBack | [
"def",
"setMaxDaysBack",
"(",
"self",
",",
"maxDaysBack",
")",
":",
"assert",
"isinstance",
"(",
"maxDaysBack",
",",
"int",
")",
",",
"\"maxDaysBack value has to be a positive integer\"",
"assert",
"maxDaysBack",
">=",
"1",
"self",
".",
"topicPage",
"[",
"\"maxDaysB... | what is the maximum allowed age of the results? | [
"what",
"is",
"the",
"maximum",
"allowed",
"age",
"of",
"the",
"results?"
] | 534d20b616de02f5e1cd73665a02d189645dbeb6 | https://github.com/EventRegistry/event-registry-python/blob/534d20b616de02f5e1cd73665a02d189645dbeb6/eventregistry/TopicPage.py#L164-L170 | train |
EventRegistry/event-registry-python | eventregistry/TopicPage.py | TopicPage.addConcept | def addConcept(self, conceptUri, weight, label = None, conceptType = None):
"""
add a relevant concept to the topic page
@param conceptUri: uri of the concept to be added
@param weight: importance of the provided concept (typically in range 1 - 50)
"""
assert isinstance(w... | python | def addConcept(self, conceptUri, weight, label = None, conceptType = None):
"""
add a relevant concept to the topic page
@param conceptUri: uri of the concept to be added
@param weight: importance of the provided concept (typically in range 1 - 50)
"""
assert isinstance(w... | [
"def",
"addConcept",
"(",
"self",
",",
"conceptUri",
",",
"weight",
",",
"label",
"=",
"None",
",",
"conceptType",
"=",
"None",
")",
":",
"assert",
"isinstance",
"(",
"weight",
",",
"(",
"float",
",",
"int",
")",
")",
",",
"\"weight value has to be a posit... | add a relevant concept to the topic page
@param conceptUri: uri of the concept to be added
@param weight: importance of the provided concept (typically in range 1 - 50) | [
"add",
"a",
"relevant",
"concept",
"to",
"the",
"topic",
"page"
] | 534d20b616de02f5e1cd73665a02d189645dbeb6 | https://github.com/EventRegistry/event-registry-python/blob/534d20b616de02f5e1cd73665a02d189645dbeb6/eventregistry/TopicPage.py#L211-L221 | train |
EventRegistry/event-registry-python | eventregistry/TopicPage.py | TopicPage.addKeyword | def addKeyword(self, keyword, weight):
"""
add a relevant keyword to the topic page
@param keyword: keyword or phrase to be added
@param weight: importance of the provided keyword (typically in range 1 - 50)
"""
assert isinstance(weight, (float, int)), "weight value has t... | python | def addKeyword(self, keyword, weight):
"""
add a relevant keyword to the topic page
@param keyword: keyword or phrase to be added
@param weight: importance of the provided keyword (typically in range 1 - 50)
"""
assert isinstance(weight, (float, int)), "weight value has t... | [
"def",
"addKeyword",
"(",
"self",
",",
"keyword",
",",
"weight",
")",
":",
"assert",
"isinstance",
"(",
"weight",
",",
"(",
"float",
",",
"int",
")",
")",
",",
"\"weight value has to be a positive or negative integer\"",
"self",
".",
"topicPage",
"[",
"\"keyword... | add a relevant keyword to the topic page
@param keyword: keyword or phrase to be added
@param weight: importance of the provided keyword (typically in range 1 - 50) | [
"add",
"a",
"relevant",
"keyword",
"to",
"the",
"topic",
"page"
] | 534d20b616de02f5e1cd73665a02d189645dbeb6 | https://github.com/EventRegistry/event-registry-python/blob/534d20b616de02f5e1cd73665a02d189645dbeb6/eventregistry/TopicPage.py#L224-L231 | train |
EventRegistry/event-registry-python | eventregistry/TopicPage.py | TopicPage.addCategory | def addCategory(self, categoryUri, weight):
"""
add a relevant category to the topic page
@param categoryUri: uri of the category to be added
@param weight: importance of the provided category (typically in range 1 - 50)
"""
assert isinstance(weight, (float, int)), "weigh... | python | def addCategory(self, categoryUri, weight):
"""
add a relevant category to the topic page
@param categoryUri: uri of the category to be added
@param weight: importance of the provided category (typically in range 1 - 50)
"""
assert isinstance(weight, (float, int)), "weigh... | [
"def",
"addCategory",
"(",
"self",
",",
"categoryUri",
",",
"weight",
")",
":",
"assert",
"isinstance",
"(",
"weight",
",",
"(",
"float",
",",
"int",
")",
")",
",",
"\"weight value has to be a positive or negative integer\"",
"self",
".",
"topicPage",
"[",
"\"ca... | add a relevant category to the topic page
@param categoryUri: uri of the category to be added
@param weight: importance of the provided category (typically in range 1 - 50) | [
"add",
"a",
"relevant",
"category",
"to",
"the",
"topic",
"page"
] | 534d20b616de02f5e1cd73665a02d189645dbeb6 | https://github.com/EventRegistry/event-registry-python/blob/534d20b616de02f5e1cd73665a02d189645dbeb6/eventregistry/TopicPage.py#L234-L241 | train |
EventRegistry/event-registry-python | eventregistry/TopicPage.py | TopicPage.addSource | def addSource(self, sourceUri, weight):
"""
add a news source to the topic page
@param sourceUri: uri of the news source to add to the topic page
@param weight: importance of the news source (typically in range 1 - 50)
"""
assert isinstance(weight, (float, int)), "weight ... | python | def addSource(self, sourceUri, weight):
"""
add a news source to the topic page
@param sourceUri: uri of the news source to add to the topic page
@param weight: importance of the news source (typically in range 1 - 50)
"""
assert isinstance(weight, (float, int)), "weight ... | [
"def",
"addSource",
"(",
"self",
",",
"sourceUri",
",",
"weight",
")",
":",
"assert",
"isinstance",
"(",
"weight",
",",
"(",
"float",
",",
"int",
")",
")",
",",
"\"weight value has to be a positive or negative integer\"",
"self",
".",
"topicPage",
"[",
"\"source... | add a news source to the topic page
@param sourceUri: uri of the news source to add to the topic page
@param weight: importance of the news source (typically in range 1 - 50) | [
"add",
"a",
"news",
"source",
"to",
"the",
"topic",
"page"
] | 534d20b616de02f5e1cd73665a02d189645dbeb6 | https://github.com/EventRegistry/event-registry-python/blob/534d20b616de02f5e1cd73665a02d189645dbeb6/eventregistry/TopicPage.py#L244-L251 | train |
EventRegistry/event-registry-python | eventregistry/TopicPage.py | TopicPage.addSourceLocation | def addSourceLocation(self, sourceLocationUri, weight):
"""
add a list of relevant sources by identifying them by their geographic location
@param sourceLocationUri: uri of the location where the sources should be geographically located
@param weight: importance of the provided list of s... | python | def addSourceLocation(self, sourceLocationUri, weight):
"""
add a list of relevant sources by identifying them by their geographic location
@param sourceLocationUri: uri of the location where the sources should be geographically located
@param weight: importance of the provided list of s... | [
"def",
"addSourceLocation",
"(",
"self",
",",
"sourceLocationUri",
",",
"weight",
")",
":",
"assert",
"isinstance",
"(",
"weight",
",",
"(",
"float",
",",
"int",
")",
")",
",",
"\"weight value has to be a positive or negative integer\"",
"self",
".",
"topicPage",
... | add a list of relevant sources by identifying them by their geographic location
@param sourceLocationUri: uri of the location where the sources should be geographically located
@param weight: importance of the provided list of sources (typically in range 1 - 50) | [
"add",
"a",
"list",
"of",
"relevant",
"sources",
"by",
"identifying",
"them",
"by",
"their",
"geographic",
"location"
] | 534d20b616de02f5e1cd73665a02d189645dbeb6 | https://github.com/EventRegistry/event-registry-python/blob/534d20b616de02f5e1cd73665a02d189645dbeb6/eventregistry/TopicPage.py#L254-L261 | train |
EventRegistry/event-registry-python | eventregistry/TopicPage.py | TopicPage.addSourceGroup | def addSourceGroup(self, sourceGroupUri, weight):
"""
add a list of relevant sources by specifying a whole source group to the topic page
@param sourceGroupUri: uri of the source group to add
@param weight: importance of the provided list of sources (typically in range 1 - 50)
""... | python | def addSourceGroup(self, sourceGroupUri, weight):
"""
add a list of relevant sources by specifying a whole source group to the topic page
@param sourceGroupUri: uri of the source group to add
@param weight: importance of the provided list of sources (typically in range 1 - 50)
""... | [
"def",
"addSourceGroup",
"(",
"self",
",",
"sourceGroupUri",
",",
"weight",
")",
":",
"assert",
"isinstance",
"(",
"weight",
",",
"(",
"float",
",",
"int",
")",
")",
",",
"\"weight value has to be a positive or negative integer\"",
"self",
".",
"topicPage",
"[",
... | add a list of relevant sources by specifying a whole source group to the topic page
@param sourceGroupUri: uri of the source group to add
@param weight: importance of the provided list of sources (typically in range 1 - 50) | [
"add",
"a",
"list",
"of",
"relevant",
"sources",
"by",
"specifying",
"a",
"whole",
"source",
"group",
"to",
"the",
"topic",
"page"
] | 534d20b616de02f5e1cd73665a02d189645dbeb6 | https://github.com/EventRegistry/event-registry-python/blob/534d20b616de02f5e1cd73665a02d189645dbeb6/eventregistry/TopicPage.py#L264-L271 | train |
EventRegistry/event-registry-python | eventregistry/TopicPage.py | TopicPage.addLocation | def addLocation(self, locationUri, weight):
"""
add relevant location to the topic page
@param locationUri: uri of the location to add
@param weight: importance of the provided location (typically in range 1 - 50)
"""
assert isinstance(weight, (float, int)), "weight value... | python | def addLocation(self, locationUri, weight):
"""
add relevant location to the topic page
@param locationUri: uri of the location to add
@param weight: importance of the provided location (typically in range 1 - 50)
"""
assert isinstance(weight, (float, int)), "weight value... | [
"def",
"addLocation",
"(",
"self",
",",
"locationUri",
",",
"weight",
")",
":",
"assert",
"isinstance",
"(",
"weight",
",",
"(",
"float",
",",
"int",
")",
")",
",",
"\"weight value has to be a positive or negative integer\"",
"self",
".",
"topicPage",
"[",
"\"lo... | add relevant location to the topic page
@param locationUri: uri of the location to add
@param weight: importance of the provided location (typically in range 1 - 50) | [
"add",
"relevant",
"location",
"to",
"the",
"topic",
"page"
] | 534d20b616de02f5e1cd73665a02d189645dbeb6 | https://github.com/EventRegistry/event-registry-python/blob/534d20b616de02f5e1cd73665a02d189645dbeb6/eventregistry/TopicPage.py#L274-L281 | train |
EventRegistry/event-registry-python | eventregistry/TopicPage.py | TopicPage.setLanguages | def setLanguages(self, languages):
"""
restrict the results to the list of specified languages
"""
if isinstance(languages, six.string_types):
languages = [languages]
for lang in languages:
assert len(lang) == 3, "Expected to get language in ISO3 code"
... | python | def setLanguages(self, languages):
"""
restrict the results to the list of specified languages
"""
if isinstance(languages, six.string_types):
languages = [languages]
for lang in languages:
assert len(lang) == 3, "Expected to get language in ISO3 code"
... | [
"def",
"setLanguages",
"(",
"self",
",",
"languages",
")",
":",
"if",
"isinstance",
"(",
"languages",
",",
"six",
".",
"string_types",
")",
":",
"languages",
"=",
"[",
"languages",
"]",
"for",
"lang",
"in",
"languages",
":",
"assert",
"len",
"(",
"lang",... | restrict the results to the list of specified languages | [
"restrict",
"the",
"results",
"to",
"the",
"list",
"of",
"specified",
"languages"
] | 534d20b616de02f5e1cd73665a02d189645dbeb6 | https://github.com/EventRegistry/event-registry-python/blob/534d20b616de02f5e1cd73665a02d189645dbeb6/eventregistry/TopicPage.py#L284-L292 | train |
EventRegistry/event-registry-python | eventregistry/TopicPage.py | TopicPage.getArticles | def getArticles(self,
page=1,
count=100,
sortBy = "rel",
sortByAsc = False,
returnInfo=ReturnInfo()):
"""
return a list of articles that match the topic page
@param page: which page of the results to return (default:... | python | def getArticles(self,
page=1,
count=100,
sortBy = "rel",
sortByAsc = False,
returnInfo=ReturnInfo()):
"""
return a list of articles that match the topic page
@param page: which page of the results to return (default:... | [
"def",
"getArticles",
"(",
"self",
",",
"page",
"=",
"1",
",",
"count",
"=",
"100",
",",
"sortBy",
"=",
"\"rel\"",
",",
"sortByAsc",
"=",
"False",
",",
"returnInfo",
"=",
"ReturnInfo",
"(",
")",
")",
":",
"assert",
"page",
">=",
"1",
"assert",
"count... | return a list of articles that match the topic page
@param page: which page of the results to return (default: 1)
@param count: number of articles to return (default: 100)
@param sortBy: how are articles sorted. Options: id (internal id), date (publishing date), cosSim (closeness to the event ce... | [
"return",
"a",
"list",
"of",
"articles",
"that",
"match",
"the",
"topic",
"page"
] | 534d20b616de02f5e1cd73665a02d189645dbeb6 | https://github.com/EventRegistry/event-registry-python/blob/534d20b616de02f5e1cd73665a02d189645dbeb6/eventregistry/TopicPage.py#L333-L360 | train |
EventRegistry/event-registry-python | eventregistry/Query.py | CombinedQuery.AND | def AND(queryArr,
exclude = None):
"""
create a combined query with multiple items on which to perform an AND operation
@param queryArr: a list of items on which to perform an AND operation. Items can be either a CombinedQuery or BaseQuery instances.
@param exclude: a instanc... | python | def AND(queryArr,
exclude = None):
"""
create a combined query with multiple items on which to perform an AND operation
@param queryArr: a list of items on which to perform an AND operation. Items can be either a CombinedQuery or BaseQuery instances.
@param exclude: a instanc... | [
"def",
"AND",
"(",
"queryArr",
",",
"exclude",
"=",
"None",
")",
":",
"assert",
"isinstance",
"(",
"queryArr",
",",
"list",
")",
",",
"\"provided argument as not a list\"",
"assert",
"len",
"(",
"queryArr",
")",
">",
"0",
",",
"\"queryArr had an empty list\"",
... | create a combined query with multiple items on which to perform an AND operation
@param queryArr: a list of items on which to perform an AND operation. Items can be either a CombinedQuery or BaseQuery instances.
@param exclude: a instance of BaseQuery, CombinedQuery or None. Used to filter out results m... | [
"create",
"a",
"combined",
"query",
"with",
"multiple",
"items",
"on",
"which",
"to",
"perform",
"an",
"AND",
"operation"
] | 534d20b616de02f5e1cd73665a02d189645dbeb6 | https://github.com/EventRegistry/event-registry-python/blob/534d20b616de02f5e1cd73665a02d189645dbeb6/eventregistry/Query.py#L121-L138 | train |
postlund/pyatv | pyatv/mrp/pairing.py | MrpPairingProcedure.start_pairing | async def start_pairing(self):
"""Start pairing procedure."""
self.srp.initialize()
msg = messages.crypto_pairing({
tlv8.TLV_METHOD: b'\x00',
tlv8.TLV_SEQ_NO: b'\x01'})
resp = await self.protocol.send_and_receive(
msg, generate_identifier=False)
... | python | async def start_pairing(self):
"""Start pairing procedure."""
self.srp.initialize()
msg = messages.crypto_pairing({
tlv8.TLV_METHOD: b'\x00',
tlv8.TLV_SEQ_NO: b'\x01'})
resp = await self.protocol.send_and_receive(
msg, generate_identifier=False)
... | [
"async",
"def",
"start_pairing",
"(",
"self",
")",
":",
"self",
".",
"srp",
".",
"initialize",
"(",
")",
"msg",
"=",
"messages",
".",
"crypto_pairing",
"(",
"{",
"tlv8",
".",
"TLV_METHOD",
":",
"b'\\x00'",
",",
"tlv8",
".",
"TLV_SEQ_NO",
":",
"b'\\x01'",... | Start pairing procedure. | [
"Start",
"pairing",
"procedure",
"."
] | 655dfcda4e2f9d1c501540e18da4f480d8bf0e70 | https://github.com/postlund/pyatv/blob/655dfcda4e2f9d1c501540e18da4f480d8bf0e70/pyatv/mrp/pairing.py#L27-L45 | train |
postlund/pyatv | pyatv/mrp/pairing.py | MrpPairingProcedure.finish_pairing | async def finish_pairing(self, pin):
"""Finish pairing process."""
self.srp.step1(pin)
pub_key, proof = self.srp.step2(self._atv_pub_key, self._atv_salt)
msg = messages.crypto_pairing({
tlv8.TLV_SEQ_NO: b'\x03',
tlv8.TLV_PUBLIC_KEY: pub_key,
tlv8.TLV... | python | async def finish_pairing(self, pin):
"""Finish pairing process."""
self.srp.step1(pin)
pub_key, proof = self.srp.step2(self._atv_pub_key, self._atv_salt)
msg = messages.crypto_pairing({
tlv8.TLV_SEQ_NO: b'\x03',
tlv8.TLV_PUBLIC_KEY: pub_key,
tlv8.TLV... | [
"async",
"def",
"finish_pairing",
"(",
"self",
",",
"pin",
")",
":",
"self",
".",
"srp",
".",
"step1",
"(",
"pin",
")",
"pub_key",
",",
"proof",
"=",
"self",
".",
"srp",
".",
"step2",
"(",
"self",
".",
"_atv_pub_key",
",",
"self",
".",
"_atv_salt",
... | Finish pairing process. | [
"Finish",
"pairing",
"process",
"."
] | 655dfcda4e2f9d1c501540e18da4f480d8bf0e70 | https://github.com/postlund/pyatv/blob/655dfcda4e2f9d1c501540e18da4f480d8bf0e70/pyatv/mrp/pairing.py#L47-L74 | train |
postlund/pyatv | pyatv/mrp/pairing.py | MrpPairingVerifier.verify_credentials | async def verify_credentials(self):
"""Verify credentials with device."""
_, public_key = self.srp.initialize()
msg = messages.crypto_pairing({
tlv8.TLV_SEQ_NO: b'\x01',
tlv8.TLV_PUBLIC_KEY: public_key})
resp = await self.protocol.send_and_receive(
ms... | python | async def verify_credentials(self):
"""Verify credentials with device."""
_, public_key = self.srp.initialize()
msg = messages.crypto_pairing({
tlv8.TLV_SEQ_NO: b'\x01',
tlv8.TLV_PUBLIC_KEY: public_key})
resp = await self.protocol.send_and_receive(
ms... | [
"async",
"def",
"verify_credentials",
"(",
"self",
")",
":",
"_",
",",
"public_key",
"=",
"self",
".",
"srp",
".",
"initialize",
"(",
")",
"msg",
"=",
"messages",
".",
"crypto_pairing",
"(",
"{",
"tlv8",
".",
"TLV_SEQ_NO",
":",
"b'\\x01'",
",",
"tlv8",
... | Verify credentials with device. | [
"Verify",
"credentials",
"with",
"device",
"."
] | 655dfcda4e2f9d1c501540e18da4f480d8bf0e70 | https://github.com/postlund/pyatv/blob/655dfcda4e2f9d1c501540e18da4f480d8bf0e70/pyatv/mrp/pairing.py#L88-L116 | train |
postlund/pyatv | pyatv/dmap/tag_definitions.py | lookup_tag | def lookup_tag(name):
"""Look up a tag based on its key. Returns a DmapTag."""
return next((_TAGS[t] for t in _TAGS if t == name),
DmapTag(_read_unknown, 'unknown tag')) | python | def lookup_tag(name):
"""Look up a tag based on its key. Returns a DmapTag."""
return next((_TAGS[t] for t in _TAGS if t == name),
DmapTag(_read_unknown, 'unknown tag')) | [
"def",
"lookup_tag",
"(",
"name",
")",
":",
"return",
"next",
"(",
"(",
"_TAGS",
"[",
"t",
"]",
"for",
"t",
"in",
"_TAGS",
"if",
"t",
"==",
"name",
")",
",",
"DmapTag",
"(",
"_read_unknown",
",",
"'unknown tag'",
")",
")"
] | Look up a tag based on its key. Returns a DmapTag. | [
"Look",
"up",
"a",
"tag",
"based",
"on",
"its",
"key",
".",
"Returns",
"a",
"DmapTag",
"."
] | 655dfcda4e2f9d1c501540e18da4f480d8bf0e70 | https://github.com/postlund/pyatv/blob/655dfcda4e2f9d1c501540e18da4f480d8bf0e70/pyatv/dmap/tag_definitions.py#L105-L108 | train |
postlund/pyatv | pyatv/__init__.py | connect_to_apple_tv | def connect_to_apple_tv(details, loop, protocol=None, session=None):
"""Connect and logins to an Apple TV."""
service = _get_service_used_to_connect(details, protocol)
# If no session is given, create a default one
if session is None:
session = ClientSession(loop=loop)
# AirPlay service is... | python | def connect_to_apple_tv(details, loop, protocol=None, session=None):
"""Connect and logins to an Apple TV."""
service = _get_service_used_to_connect(details, protocol)
# If no session is given, create a default one
if session is None:
session = ClientSession(loop=loop)
# AirPlay service is... | [
"def",
"connect_to_apple_tv",
"(",
"details",
",",
"loop",
",",
"protocol",
"=",
"None",
",",
"session",
"=",
"None",
")",
":",
"service",
"=",
"_get_service_used_to_connect",
"(",
"details",
",",
"protocol",
")",
"# If no session is given, create a default one",
"i... | Connect and logins to an Apple TV. | [
"Connect",
"and",
"logins",
"to",
"an",
"Apple",
"TV",
"."
] | 655dfcda4e2f9d1c501540e18da4f480d8bf0e70 | https://github.com/postlund/pyatv/blob/655dfcda4e2f9d1c501540e18da4f480d8bf0e70/pyatv/__init__.py#L165-L180 | train |
postlund/pyatv | pyatv/__init__.py | _ServiceListener.add_service | def add_service(self, zeroconf, service_type, name):
"""Handle callback from zeroconf when a service has been discovered."""
self.lock.acquire()
try:
self._internal_add(zeroconf, service_type, name)
finally:
self.lock.release() | python | def add_service(self, zeroconf, service_type, name):
"""Handle callback from zeroconf when a service has been discovered."""
self.lock.acquire()
try:
self._internal_add(zeroconf, service_type, name)
finally:
self.lock.release() | [
"def",
"add_service",
"(",
"self",
",",
"zeroconf",
",",
"service_type",
",",
"name",
")",
":",
"self",
".",
"lock",
".",
"acquire",
"(",
")",
"try",
":",
"self",
".",
"_internal_add",
"(",
"zeroconf",
",",
"service_type",
",",
"name",
")",
"finally",
... | Handle callback from zeroconf when a service has been discovered. | [
"Handle",
"callback",
"from",
"zeroconf",
"when",
"a",
"service",
"has",
"been",
"discovered",
"."
] | 655dfcda4e2f9d1c501540e18da4f480d8bf0e70 | https://github.com/postlund/pyatv/blob/655dfcda4e2f9d1c501540e18da4f480d8bf0e70/pyatv/__init__.py#L43-L49 | train |
postlund/pyatv | pyatv/__init__.py | _ServiceListener.add_hs_service | def add_hs_service(self, info, address):
"""Add a new device to discovered list."""
if self.protocol and self.protocol != PROTOCOL_DMAP:
return
name = info.properties[b'Name'].decode('utf-8')
hsgid = info.properties[b'hG'].decode('utf-8')
self._handle_service(
... | python | def add_hs_service(self, info, address):
"""Add a new device to discovered list."""
if self.protocol and self.protocol != PROTOCOL_DMAP:
return
name = info.properties[b'Name'].decode('utf-8')
hsgid = info.properties[b'hG'].decode('utf-8')
self._handle_service(
... | [
"def",
"add_hs_service",
"(",
"self",
",",
"info",
",",
"address",
")",
":",
"if",
"self",
".",
"protocol",
"and",
"self",
".",
"protocol",
"!=",
"PROTOCOL_DMAP",
":",
"return",
"name",
"=",
"info",
".",
"properties",
"[",
"b'Name'",
"]",
".",
"decode",
... | Add a new device to discovered list. | [
"Add",
"a",
"new",
"device",
"to",
"discovered",
"list",
"."
] | 655dfcda4e2f9d1c501540e18da4f480d8bf0e70 | https://github.com/postlund/pyatv/blob/655dfcda4e2f9d1c501540e18da4f480d8bf0e70/pyatv/__init__.py#L75-L83 | train |
postlund/pyatv | pyatv/__init__.py | _ServiceListener.add_non_hs_service | def add_non_hs_service(self, info, address):
"""Add a new device without Home Sharing to discovered list."""
if self.protocol and self.protocol != PROTOCOL_DMAP:
return
name = info.properties[b'CtlN'].decode('utf-8')
self._handle_service(
address, name, conf.Dmap... | python | def add_non_hs_service(self, info, address):
"""Add a new device without Home Sharing to discovered list."""
if self.protocol and self.protocol != PROTOCOL_DMAP:
return
name = info.properties[b'CtlN'].decode('utf-8')
self._handle_service(
address, name, conf.Dmap... | [
"def",
"add_non_hs_service",
"(",
"self",
",",
"info",
",",
"address",
")",
":",
"if",
"self",
".",
"protocol",
"and",
"self",
".",
"protocol",
"!=",
"PROTOCOL_DMAP",
":",
"return",
"name",
"=",
"info",
".",
"properties",
"[",
"b'CtlN'",
"]",
".",
"decod... | Add a new device without Home Sharing to discovered list. | [
"Add",
"a",
"new",
"device",
"without",
"Home",
"Sharing",
"to",
"discovered",
"list",
"."
] | 655dfcda4e2f9d1c501540e18da4f480d8bf0e70 | https://github.com/postlund/pyatv/blob/655dfcda4e2f9d1c501540e18da4f480d8bf0e70/pyatv/__init__.py#L85-L92 | train |
postlund/pyatv | pyatv/__init__.py | _ServiceListener.add_mrp_service | def add_mrp_service(self, info, address):
"""Add a new MediaRemoteProtocol device to discovered list."""
if self.protocol and self.protocol != PROTOCOL_MRP:
return
name = info.properties[b'Name'].decode('utf-8')
self._handle_service(address, name, conf.MrpService(info.port)) | python | def add_mrp_service(self, info, address):
"""Add a new MediaRemoteProtocol device to discovered list."""
if self.protocol and self.protocol != PROTOCOL_MRP:
return
name = info.properties[b'Name'].decode('utf-8')
self._handle_service(address, name, conf.MrpService(info.port)) | [
"def",
"add_mrp_service",
"(",
"self",
",",
"info",
",",
"address",
")",
":",
"if",
"self",
".",
"protocol",
"and",
"self",
".",
"protocol",
"!=",
"PROTOCOL_MRP",
":",
"return",
"name",
"=",
"info",
".",
"properties",
"[",
"b'Name'",
"]",
".",
"decode",
... | Add a new MediaRemoteProtocol device to discovered list. | [
"Add",
"a",
"new",
"MediaRemoteProtocol",
"device",
"to",
"discovered",
"list",
"."
] | 655dfcda4e2f9d1c501540e18da4f480d8bf0e70 | https://github.com/postlund/pyatv/blob/655dfcda4e2f9d1c501540e18da4f480d8bf0e70/pyatv/__init__.py#L94-L100 | train |
postlund/pyatv | pyatv/__init__.py | _ServiceListener.add_airplay_service | def add_airplay_service(self, info, address):
"""Add a new AirPlay device to discovered list."""
name = info.name.replace('._airplay._tcp.local.', '')
self._handle_service(address, name, conf.AirPlayService(info.port)) | python | def add_airplay_service(self, info, address):
"""Add a new AirPlay device to discovered list."""
name = info.name.replace('._airplay._tcp.local.', '')
self._handle_service(address, name, conf.AirPlayService(info.port)) | [
"def",
"add_airplay_service",
"(",
"self",
",",
"info",
",",
"address",
")",
":",
"name",
"=",
"info",
".",
"name",
".",
"replace",
"(",
"'._airplay._tcp.local.'",
",",
"''",
")",
"self",
".",
"_handle_service",
"(",
"address",
",",
"name",
",",
"conf",
... | Add a new AirPlay device to discovered list. | [
"Add",
"a",
"new",
"AirPlay",
"device",
"to",
"discovered",
"list",
"."
] | 655dfcda4e2f9d1c501540e18da4f480d8bf0e70 | https://github.com/postlund/pyatv/blob/655dfcda4e2f9d1c501540e18da4f480d8bf0e70/pyatv/__init__.py#L102-L105 | train |
postlund/pyatv | pyatv/conf.py | AppleTV.usable_service | def usable_service(self):
"""Return a usable service or None if there is none.
A service is usable if enough configuration to be able to make a
connection is available. If several protocols are usable, MRP will be
preferred over DMAP.
"""
services = self._services
... | python | def usable_service(self):
"""Return a usable service or None if there is none.
A service is usable if enough configuration to be able to make a
connection is available. If several protocols are usable, MRP will be
preferred over DMAP.
"""
services = self._services
... | [
"def",
"usable_service",
"(",
"self",
")",
":",
"services",
"=",
"self",
".",
"_services",
"for",
"protocol",
"in",
"self",
".",
"_supported_protocols",
":",
"if",
"protocol",
"in",
"services",
"and",
"services",
"[",
"protocol",
"]",
".",
"is_usable",
"(",
... | Return a usable service or None if there is none.
A service is usable if enough configuration to be able to make a
connection is available. If several protocols are usable, MRP will be
preferred over DMAP. | [
"Return",
"a",
"usable",
"service",
"or",
"None",
"if",
"there",
"is",
"none",
"."
] | 655dfcda4e2f9d1c501540e18da4f480d8bf0e70 | https://github.com/postlund/pyatv/blob/655dfcda4e2f9d1c501540e18da4f480d8bf0e70/pyatv/conf.py#L49-L61 | train |
postlund/pyatv | pyatv/conf.py | DmapService.superseeded_by | def superseeded_by(self, other_service):
"""Return True if input service has login id and this has not."""
if not other_service or \
other_service.__class__ != self.__class__ or \
other_service.protocol != self.protocol or \
other_service.port != self.port... | python | def superseeded_by(self, other_service):
"""Return True if input service has login id and this has not."""
if not other_service or \
other_service.__class__ != self.__class__ or \
other_service.protocol != self.protocol or \
other_service.port != self.port... | [
"def",
"superseeded_by",
"(",
"self",
",",
"other_service",
")",
":",
"if",
"not",
"other_service",
"or",
"other_service",
".",
"__class__",
"!=",
"self",
".",
"__class__",
"or",
"other_service",
".",
"protocol",
"!=",
"self",
".",
"protocol",
"or",
"other_ser... | Return True if input service has login id and this has not. | [
"Return",
"True",
"if",
"input",
"service",
"has",
"login",
"id",
"and",
"this",
"has",
"not",
"."
] | 655dfcda4e2f9d1c501540e18da4f480d8bf0e70 | https://github.com/postlund/pyatv/blob/655dfcda4e2f9d1c501540e18da4f480d8bf0e70/pyatv/conf.py#L130-L140 | train |
postlund/pyatv | examples/autodiscover.py | print_what_is_playing | async def print_what_is_playing(loop):
"""Find a device and print what is playing."""
print('Discovering devices on network...')
atvs = await pyatv.scan_for_apple_tvs(loop, timeout=5)
if not atvs:
print('no device found', file=sys.stderr)
return
print('Connecting to {0}'.format(atv... | python | async def print_what_is_playing(loop):
"""Find a device and print what is playing."""
print('Discovering devices on network...')
atvs = await pyatv.scan_for_apple_tvs(loop, timeout=5)
if not atvs:
print('no device found', file=sys.stderr)
return
print('Connecting to {0}'.format(atv... | [
"async",
"def",
"print_what_is_playing",
"(",
"loop",
")",
":",
"print",
"(",
"'Discovering devices on network...'",
")",
"atvs",
"=",
"await",
"pyatv",
".",
"scan_for_apple_tvs",
"(",
"loop",
",",
"timeout",
"=",
"5",
")",
"if",
"not",
"atvs",
":",
"print",
... | Find a device and print what is playing. | [
"Find",
"a",
"device",
"and",
"print",
"what",
"is",
"playing",
"."
] | 655dfcda4e2f9d1c501540e18da4f480d8bf0e70 | https://github.com/postlund/pyatv/blob/655dfcda4e2f9d1c501540e18da4f480d8bf0e70/examples/autodiscover.py#L11-L29 | train |
postlund/pyatv | pyatv/dmap/pairing.py | DmapPairingHandler.start | async def start(self, **kwargs):
"""Start the pairing server and publish service."""
zeroconf = kwargs['zeroconf']
self._name = kwargs['name']
self._pairing_guid = kwargs.get('pairing_guid', None) or \
self._generate_random_guid()
self._web_server = web.Server(self.h... | python | async def start(self, **kwargs):
"""Start the pairing server and publish service."""
zeroconf = kwargs['zeroconf']
self._name = kwargs['name']
self._pairing_guid = kwargs.get('pairing_guid', None) or \
self._generate_random_guid()
self._web_server = web.Server(self.h... | [
"async",
"def",
"start",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"zeroconf",
"=",
"kwargs",
"[",
"'zeroconf'",
"]",
"self",
".",
"_name",
"=",
"kwargs",
"[",
"'name'",
"]",
"self",
".",
"_pairing_guid",
"=",
"kwargs",
".",
"get",
"(",
"'pairi... | Start the pairing server and publish service. | [
"Start",
"the",
"pairing",
"server",
"and",
"publish",
"service",
"."
] | 655dfcda4e2f9d1c501540e18da4f480d8bf0e70 | https://github.com/postlund/pyatv/blob/655dfcda4e2f9d1c501540e18da4f480d8bf0e70/pyatv/dmap/pairing.py#L71-L86 | train |
postlund/pyatv | pyatv/dmap/pairing.py | DmapPairingHandler.stop | async def stop(self, **kwargs):
"""Stop pairing server and unpublish service."""
_LOGGER.debug('Shutting down pairing server')
if self._web_server is not None:
await self._web_server.shutdown()
self._server.close()
if self._server is not None:
await s... | python | async def stop(self, **kwargs):
"""Stop pairing server and unpublish service."""
_LOGGER.debug('Shutting down pairing server')
if self._web_server is not None:
await self._web_server.shutdown()
self._server.close()
if self._server is not None:
await s... | [
"async",
"def",
"stop",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"_LOGGER",
".",
"debug",
"(",
"'Shutting down pairing server'",
")",
"if",
"self",
".",
"_web_server",
"is",
"not",
"None",
":",
"await",
"self",
".",
"_web_server",
".",
"shutdown",
... | Stop pairing server and unpublish service. | [
"Stop",
"pairing",
"server",
"and",
"unpublish",
"service",
"."
] | 655dfcda4e2f9d1c501540e18da4f480d8bf0e70 | https://github.com/postlund/pyatv/blob/655dfcda4e2f9d1c501540e18da4f480d8bf0e70/pyatv/dmap/pairing.py#L88-L96 | train |
postlund/pyatv | pyatv/dmap/pairing.py | DmapPairingHandler.handle_request | async def handle_request(self, request):
"""Respond to request if PIN is correct."""
service_name = request.rel_url.query['servicename']
received_code = request.rel_url.query['pairingcode'].lower()
_LOGGER.info('Got pairing request from %s with code %s',
service_name... | python | async def handle_request(self, request):
"""Respond to request if PIN is correct."""
service_name = request.rel_url.query['servicename']
received_code = request.rel_url.query['pairingcode'].lower()
_LOGGER.info('Got pairing request from %s with code %s',
service_name... | [
"async",
"def",
"handle_request",
"(",
"self",
",",
"request",
")",
":",
"service_name",
"=",
"request",
".",
"rel_url",
".",
"query",
"[",
"'servicename'",
"]",
"received_code",
"=",
"request",
".",
"rel_url",
".",
"query",
"[",
"'pairingcode'",
"]",
".",
... | Respond to request if PIN is correct. | [
"Respond",
"to",
"request",
"if",
"PIN",
"is",
"correct",
"."
] | 655dfcda4e2f9d1c501540e18da4f480d8bf0e70 | https://github.com/postlund/pyatv/blob/655dfcda4e2f9d1c501540e18da4f480d8bf0e70/pyatv/dmap/pairing.py#L129-L145 | train |
postlund/pyatv | pyatv/log.py | log_binary | def log_binary(logger, message, **kwargs):
"""Log binary data if debug is enabled."""
if logger.isEnabledFor(logging.DEBUG):
output = ('{0}={1}'.format(k, binascii.hexlify(
bytearray(v)).decode()) for k, v in sorted(kwargs.items()))
logger.debug('%s (%s)', message, ', '.join(output)) | python | def log_binary(logger, message, **kwargs):
"""Log binary data if debug is enabled."""
if logger.isEnabledFor(logging.DEBUG):
output = ('{0}={1}'.format(k, binascii.hexlify(
bytearray(v)).decode()) for k, v in sorted(kwargs.items()))
logger.debug('%s (%s)', message, ', '.join(output)) | [
"def",
"log_binary",
"(",
"logger",
",",
"message",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"logger",
".",
"isEnabledFor",
"(",
"logging",
".",
"DEBUG",
")",
":",
"output",
"=",
"(",
"'{0}={1}'",
".",
"format",
"(",
"k",
",",
"binascii",
".",
"hexli... | Log binary data if debug is enabled. | [
"Log",
"binary",
"data",
"if",
"debug",
"is",
"enabled",
"."
] | 655dfcda4e2f9d1c501540e18da4f480d8bf0e70 | https://github.com/postlund/pyatv/blob/655dfcda4e2f9d1c501540e18da4f480d8bf0e70/pyatv/log.py#L8-L13 | train |
postlund/pyatv | pyatv/__main__.py | _extract_command_with_args | def _extract_command_with_args(cmd):
"""Parse input command with arguments.
Parses the input command in such a way that the user may
provide additional argument to the command. The format used is this:
command=arg1,arg2,arg3,...
all the additional arguments are passed as arguments to the target
... | python | def _extract_command_with_args(cmd):
"""Parse input command with arguments.
Parses the input command in such a way that the user may
provide additional argument to the command. The format used is this:
command=arg1,arg2,arg3,...
all the additional arguments are passed as arguments to the target
... | [
"def",
"_extract_command_with_args",
"(",
"cmd",
")",
":",
"def",
"_isint",
"(",
"value",
")",
":",
"try",
":",
"int",
"(",
"value",
")",
"return",
"True",
"except",
"ValueError",
":",
"return",
"False",
"equal_sign",
"=",
"cmd",
".",
"find",
"(",
"'='",... | Parse input command with arguments.
Parses the input command in such a way that the user may
provide additional argument to the command. The format used is this:
command=arg1,arg2,arg3,...
all the additional arguments are passed as arguments to the target
method. | [
"Parse",
"input",
"command",
"with",
"arguments",
"."
] | 655dfcda4e2f9d1c501540e18da4f480d8bf0e70 | https://github.com/postlund/pyatv/blob/655dfcda4e2f9d1c501540e18da4f480d8bf0e70/pyatv/__main__.py#L362-L385 | train |
postlund/pyatv | pyatv/__main__.py | main | def main():
"""Start the asyncio event loop and runs the application."""
# Helper method so that the coroutine exits cleanly if an exception
# happens (which would leave resources dangling)
async def _run_application(loop):
try:
return await cli_handler(loop)
except Keyboard... | python | def main():
"""Start the asyncio event loop and runs the application."""
# Helper method so that the coroutine exits cleanly if an exception
# happens (which would leave resources dangling)
async def _run_application(loop):
try:
return await cli_handler(loop)
except Keyboard... | [
"def",
"main",
"(",
")",
":",
"# Helper method so that the coroutine exits cleanly if an exception",
"# happens (which would leave resources dangling)",
"async",
"def",
"_run_application",
"(",
"loop",
")",
":",
"try",
":",
"return",
"await",
"cli_handler",
"(",
"loop",
")"... | Start the asyncio event loop and runs the application. | [
"Start",
"the",
"asyncio",
"event",
"loop",
"and",
"runs",
"the",
"application",
"."
] | 655dfcda4e2f9d1c501540e18da4f480d8bf0e70 | https://github.com/postlund/pyatv/blob/655dfcda4e2f9d1c501540e18da4f480d8bf0e70/pyatv/__main__.py#L484-L513 | train |
postlund/pyatv | pyatv/__main__.py | GlobalCommands.commands | async def commands(self):
"""Print a list with available commands."""
_print_commands('Remote control', interface.RemoteControl)
_print_commands('Metadata', interface.Metadata)
_print_commands('Playing', interface.Playing)
_print_commands('AirPlay', interface.AirPlay)
_pr... | python | async def commands(self):
"""Print a list with available commands."""
_print_commands('Remote control', interface.RemoteControl)
_print_commands('Metadata', interface.Metadata)
_print_commands('Playing', interface.Playing)
_print_commands('AirPlay', interface.AirPlay)
_pr... | [
"async",
"def",
"commands",
"(",
"self",
")",
":",
"_print_commands",
"(",
"'Remote control'",
",",
"interface",
".",
"RemoteControl",
")",
"_print_commands",
"(",
"'Metadata'",
",",
"interface",
".",
"Metadata",
")",
"_print_commands",
"(",
"'Playing'",
",",
"i... | Print a list with available commands. | [
"Print",
"a",
"list",
"with",
"available",
"commands",
"."
] | 655dfcda4e2f9d1c501540e18da4f480d8bf0e70 | https://github.com/postlund/pyatv/blob/655dfcda4e2f9d1c501540e18da4f480d8bf0e70/pyatv/__main__.py#L43-L52 | train |
postlund/pyatv | pyatv/__main__.py | GlobalCommands.help | async def help(self):
"""Print help text for a command."""
if len(self.args.command) != 2:
print('Which command do you want help with?', file=sys.stderr)
return 1
iface = [interface.RemoteControl,
interface.Metadata,
interface.Playing,
... | python | async def help(self):
"""Print help text for a command."""
if len(self.args.command) != 2:
print('Which command do you want help with?', file=sys.stderr)
return 1
iface = [interface.RemoteControl,
interface.Metadata,
interface.Playing,
... | [
"async",
"def",
"help",
"(",
"self",
")",
":",
"if",
"len",
"(",
"self",
".",
"args",
".",
"command",
")",
"!=",
"2",
":",
"print",
"(",
"'Which command do you want help with?'",
",",
"file",
"=",
"sys",
".",
"stderr",
")",
"return",
"1",
"iface",
"=",... | Print help text for a command. | [
"Print",
"help",
"text",
"for",
"a",
"command",
"."
] | 655dfcda4e2f9d1c501540e18da4f480d8bf0e70 | https://github.com/postlund/pyatv/blob/655dfcda4e2f9d1c501540e18da4f480d8bf0e70/pyatv/__main__.py#L54-L78 | train |
postlund/pyatv | pyatv/__main__.py | GlobalCommands.scan | async def scan(self):
"""Scan for Apple TVs on the network."""
atvs = await pyatv.scan_for_apple_tvs(
self.loop, timeout=self.args.scan_timeout, only_usable=False)
_print_found_apple_tvs(atvs)
return 0 | python | async def scan(self):
"""Scan for Apple TVs on the network."""
atvs = await pyatv.scan_for_apple_tvs(
self.loop, timeout=self.args.scan_timeout, only_usable=False)
_print_found_apple_tvs(atvs)
return 0 | [
"async",
"def",
"scan",
"(",
"self",
")",
":",
"atvs",
"=",
"await",
"pyatv",
".",
"scan_for_apple_tvs",
"(",
"self",
".",
"loop",
",",
"timeout",
"=",
"self",
".",
"args",
".",
"scan_timeout",
",",
"only_usable",
"=",
"False",
")",
"_print_found_apple_tvs... | Scan for Apple TVs on the network. | [
"Scan",
"for",
"Apple",
"TVs",
"on",
"the",
"network",
"."
] | 655dfcda4e2f9d1c501540e18da4f480d8bf0e70 | https://github.com/postlund/pyatv/blob/655dfcda4e2f9d1c501540e18da4f480d8bf0e70/pyatv/__main__.py#L80-L86 | train |
postlund/pyatv | pyatv/__main__.py | DeviceCommands.cli | async def cli(self):
"""Enter commands in a simple CLI."""
print('Enter commands and press enter')
print('Type help for help and exit to quit')
while True:
command = await _read_input(self.loop, 'pyatv> ')
if command.lower() == 'exit':
break
... | python | async def cli(self):
"""Enter commands in a simple CLI."""
print('Enter commands and press enter')
print('Type help for help and exit to quit')
while True:
command = await _read_input(self.loop, 'pyatv> ')
if command.lower() == 'exit':
break
... | [
"async",
"def",
"cli",
"(",
"self",
")",
":",
"print",
"(",
"'Enter commands and press enter'",
")",
"print",
"(",
"'Type help for help and exit to quit'",
")",
"while",
"True",
":",
"command",
"=",
"await",
"_read_input",
"(",
"self",
".",
"loop",
",",
"'pyatv>... | Enter commands in a simple CLI. | [
"Enter",
"commands",
"in",
"a",
"simple",
"CLI",
"."
] | 655dfcda4e2f9d1c501540e18da4f480d8bf0e70 | https://github.com/postlund/pyatv/blob/655dfcda4e2f9d1c501540e18da4f480d8bf0e70/pyatv/__main__.py#L101-L115 | train |
postlund/pyatv | pyatv/__main__.py | DeviceCommands.artwork_save | async def artwork_save(self):
"""Download artwork and save it to artwork.png."""
artwork = await self.atv.metadata.artwork()
if artwork is not None:
with open('artwork.png', 'wb') as file:
file.write(artwork)
else:
print('No artwork is currently av... | python | async def artwork_save(self):
"""Download artwork and save it to artwork.png."""
artwork = await self.atv.metadata.artwork()
if artwork is not None:
with open('artwork.png', 'wb') as file:
file.write(artwork)
else:
print('No artwork is currently av... | [
"async",
"def",
"artwork_save",
"(",
"self",
")",
":",
"artwork",
"=",
"await",
"self",
".",
"atv",
".",
"metadata",
".",
"artwork",
"(",
")",
"if",
"artwork",
"is",
"not",
"None",
":",
"with",
"open",
"(",
"'artwork.png'",
",",
"'wb'",
")",
"as",
"f... | Download artwork and save it to artwork.png. | [
"Download",
"artwork",
"and",
"save",
"it",
"to",
"artwork",
".",
"png",
"."
] | 655dfcda4e2f9d1c501540e18da4f480d8bf0e70 | https://github.com/postlund/pyatv/blob/655dfcda4e2f9d1c501540e18da4f480d8bf0e70/pyatv/__main__.py#L117-L126 | train |
postlund/pyatv | pyatv/__main__.py | DeviceCommands.push_updates | async def push_updates(self):
"""Listen for push updates."""
print('Press ENTER to stop')
self.atv.push_updater.start()
await self.atv.login()
await self.loop.run_in_executor(None, sys.stdin.readline)
self.atv.push_updater.stop()
return 0 | python | async def push_updates(self):
"""Listen for push updates."""
print('Press ENTER to stop')
self.atv.push_updater.start()
await self.atv.login()
await self.loop.run_in_executor(None, sys.stdin.readline)
self.atv.push_updater.stop()
return 0 | [
"async",
"def",
"push_updates",
"(",
"self",
")",
":",
"print",
"(",
"'Press ENTER to stop'",
")",
"self",
".",
"atv",
".",
"push_updater",
".",
"start",
"(",
")",
"await",
"self",
".",
"atv",
".",
"login",
"(",
")",
"await",
"self",
".",
"loop",
".",
... | Listen for push updates. | [
"Listen",
"for",
"push",
"updates",
"."
] | 655dfcda4e2f9d1c501540e18da4f480d8bf0e70 | https://github.com/postlund/pyatv/blob/655dfcda4e2f9d1c501540e18da4f480d8bf0e70/pyatv/__main__.py#L128-L136 | train |
postlund/pyatv | pyatv/__main__.py | DeviceCommands.auth | async def auth(self):
"""Perform AirPlay device authentication."""
credentials = await self.atv.airplay.generate_credentials()
await self.atv.airplay.load_credentials(credentials)
try:
await self.atv.airplay.start_authentication()
pin = await _read_input(self.loo... | python | async def auth(self):
"""Perform AirPlay device authentication."""
credentials = await self.atv.airplay.generate_credentials()
await self.atv.airplay.load_credentials(credentials)
try:
await self.atv.airplay.start_authentication()
pin = await _read_input(self.loo... | [
"async",
"def",
"auth",
"(",
"self",
")",
":",
"credentials",
"=",
"await",
"self",
".",
"atv",
".",
"airplay",
".",
"generate_credentials",
"(",
")",
"await",
"self",
".",
"atv",
".",
"airplay",
".",
"load_credentials",
"(",
"credentials",
")",
"try",
"... | Perform AirPlay device authentication. | [
"Perform",
"AirPlay",
"device",
"authentication",
"."
] | 655dfcda4e2f9d1c501540e18da4f480d8bf0e70 | https://github.com/postlund/pyatv/blob/655dfcda4e2f9d1c501540e18da4f480d8bf0e70/pyatv/__main__.py#L138-L154 | train |
postlund/pyatv | pyatv/__main__.py | DeviceCommands.pair | async def pair(self):
"""Pair pyatv as a remote control with an Apple TV."""
# Connect using the specified protocol
# TODO: config should be stored elsewhere so that API is same for both
protocol = self.atv.service.protocol
if protocol == const.PROTOCOL_DMAP:
await se... | python | async def pair(self):
"""Pair pyatv as a remote control with an Apple TV."""
# Connect using the specified protocol
# TODO: config should be stored elsewhere so that API is same for both
protocol = self.atv.service.protocol
if protocol == const.PROTOCOL_DMAP:
await se... | [
"async",
"def",
"pair",
"(",
"self",
")",
":",
"# Connect using the specified protocol",
"# TODO: config should be stored elsewhere so that API is same for both",
"protocol",
"=",
"self",
".",
"atv",
".",
"service",
".",
"protocol",
"if",
"protocol",
"==",
"const",
".",
... | Pair pyatv as a remote control with an Apple TV. | [
"Pair",
"pyatv",
"as",
"a",
"remote",
"control",
"with",
"an",
"Apple",
"TV",
"."
] | 655dfcda4e2f9d1c501540e18da4f480d8bf0e70 | https://github.com/postlund/pyatv/blob/655dfcda4e2f9d1c501540e18da4f480d8bf0e70/pyatv/__main__.py#L156-L198 | train |
postlund/pyatv | pyatv/convert.py | media_kind | def media_kind(kind):
"""Convert iTunes media kind to API representation."""
if kind in [1]:
return const.MEDIA_TYPE_UNKNOWN
if kind in [3, 7, 11, 12, 13, 18, 32]:
return const.MEDIA_TYPE_VIDEO
if kind in [2, 4, 10, 14, 17, 21, 36]:
return const.MEDIA_TYPE_MUSIC
if kind in [8... | python | def media_kind(kind):
"""Convert iTunes media kind to API representation."""
if kind in [1]:
return const.MEDIA_TYPE_UNKNOWN
if kind in [3, 7, 11, 12, 13, 18, 32]:
return const.MEDIA_TYPE_VIDEO
if kind in [2, 4, 10, 14, 17, 21, 36]:
return const.MEDIA_TYPE_MUSIC
if kind in [8... | [
"def",
"media_kind",
"(",
"kind",
")",
":",
"if",
"kind",
"in",
"[",
"1",
"]",
":",
"return",
"const",
".",
"MEDIA_TYPE_UNKNOWN",
"if",
"kind",
"in",
"[",
"3",
",",
"7",
",",
"11",
",",
"12",
",",
"13",
",",
"18",
",",
"32",
"]",
":",
"return",... | Convert iTunes media kind to API representation. | [
"Convert",
"iTunes",
"media",
"kind",
"to",
"API",
"representation",
"."
] | 655dfcda4e2f9d1c501540e18da4f480d8bf0e70 | https://github.com/postlund/pyatv/blob/655dfcda4e2f9d1c501540e18da4f480d8bf0e70/pyatv/convert.py#L6-L17 | train |
postlund/pyatv | pyatv/convert.py | media_type_str | def media_type_str(mediatype):
"""Convert internal API media type to string."""
if mediatype == const.MEDIA_TYPE_UNKNOWN:
return 'Unknown'
if mediatype == const.MEDIA_TYPE_VIDEO:
return 'Video'
if mediatype == const.MEDIA_TYPE_MUSIC:
return 'Music'
if mediatype == const.MEDIA... | python | def media_type_str(mediatype):
"""Convert internal API media type to string."""
if mediatype == const.MEDIA_TYPE_UNKNOWN:
return 'Unknown'
if mediatype == const.MEDIA_TYPE_VIDEO:
return 'Video'
if mediatype == const.MEDIA_TYPE_MUSIC:
return 'Music'
if mediatype == const.MEDIA... | [
"def",
"media_type_str",
"(",
"mediatype",
")",
":",
"if",
"mediatype",
"==",
"const",
".",
"MEDIA_TYPE_UNKNOWN",
":",
"return",
"'Unknown'",
"if",
"mediatype",
"==",
"const",
".",
"MEDIA_TYPE_VIDEO",
":",
"return",
"'Video'",
"if",
"mediatype",
"==",
"const",
... | Convert internal API media type to string. | [
"Convert",
"internal",
"API",
"media",
"type",
"to",
"string",
"."
] | 655dfcda4e2f9d1c501540e18da4f480d8bf0e70 | https://github.com/postlund/pyatv/blob/655dfcda4e2f9d1c501540e18da4f480d8bf0e70/pyatv/convert.py#L20-L30 | train |
postlund/pyatv | pyatv/convert.py | playstate | def playstate(state):
"""Convert iTunes playstate to API representation."""
# pylint: disable=too-many-return-statements
if state is None:
return const.PLAY_STATE_NO_MEDIA
if state == 0:
return const.PLAY_STATE_IDLE
if state == 1:
return const.PLAY_STATE_LOADING
if state ... | python | def playstate(state):
"""Convert iTunes playstate to API representation."""
# pylint: disable=too-many-return-statements
if state is None:
return const.PLAY_STATE_NO_MEDIA
if state == 0:
return const.PLAY_STATE_IDLE
if state == 1:
return const.PLAY_STATE_LOADING
if state ... | [
"def",
"playstate",
"(",
"state",
")",
":",
"# pylint: disable=too-many-return-statements",
"if",
"state",
"is",
"None",
":",
"return",
"const",
".",
"PLAY_STATE_NO_MEDIA",
"if",
"state",
"==",
"0",
":",
"return",
"const",
".",
"PLAY_STATE_IDLE",
"if",
"state",
... | Convert iTunes playstate to API representation. | [
"Convert",
"iTunes",
"playstate",
"to",
"API",
"representation",
"."
] | 655dfcda4e2f9d1c501540e18da4f480d8bf0e70 | https://github.com/postlund/pyatv/blob/655dfcda4e2f9d1c501540e18da4f480d8bf0e70/pyatv/convert.py#L33-L51 | train |
postlund/pyatv | pyatv/convert.py | playstate_str | def playstate_str(state):
"""Convert internal API playstate to string."""
if state == const.PLAY_STATE_NO_MEDIA:
return 'No media'
if state == const.PLAY_STATE_IDLE:
return 'Idle'
if state == const.PLAY_STATE_LOADING:
return 'Loading'
if state == const.PLAY_STATE_PAUSED:
... | python | def playstate_str(state):
"""Convert internal API playstate to string."""
if state == const.PLAY_STATE_NO_MEDIA:
return 'No media'
if state == const.PLAY_STATE_IDLE:
return 'Idle'
if state == const.PLAY_STATE_LOADING:
return 'Loading'
if state == const.PLAY_STATE_PAUSED:
... | [
"def",
"playstate_str",
"(",
"state",
")",
":",
"if",
"state",
"==",
"const",
".",
"PLAY_STATE_NO_MEDIA",
":",
"return",
"'No media'",
"if",
"state",
"==",
"const",
".",
"PLAY_STATE_IDLE",
":",
"return",
"'Idle'",
"if",
"state",
"==",
"const",
".",
"PLAY_STA... | Convert internal API playstate to string. | [
"Convert",
"internal",
"API",
"playstate",
"to",
"string",
"."
] | 655dfcda4e2f9d1c501540e18da4f480d8bf0e70 | https://github.com/postlund/pyatv/blob/655dfcda4e2f9d1c501540e18da4f480d8bf0e70/pyatv/convert.py#L55-L71 | train |
postlund/pyatv | pyatv/convert.py | repeat_str | def repeat_str(state):
"""Convert internal API repeat state to string."""
if state == const.REPEAT_STATE_OFF:
return 'Off'
if state == const.REPEAT_STATE_TRACK:
return 'Track'
if state == const.REPEAT_STATE_ALL:
return 'All'
return 'Unsupported' | python | def repeat_str(state):
"""Convert internal API repeat state to string."""
if state == const.REPEAT_STATE_OFF:
return 'Off'
if state == const.REPEAT_STATE_TRACK:
return 'Track'
if state == const.REPEAT_STATE_ALL:
return 'All'
return 'Unsupported' | [
"def",
"repeat_str",
"(",
"state",
")",
":",
"if",
"state",
"==",
"const",
".",
"REPEAT_STATE_OFF",
":",
"return",
"'Off'",
"if",
"state",
"==",
"const",
".",
"REPEAT_STATE_TRACK",
":",
"return",
"'Track'",
"if",
"state",
"==",
"const",
".",
"REPEAT_STATE_AL... | Convert internal API repeat state to string. | [
"Convert",
"internal",
"API",
"repeat",
"state",
"to",
"string",
"."
] | 655dfcda4e2f9d1c501540e18da4f480d8bf0e70 | https://github.com/postlund/pyatv/blob/655dfcda4e2f9d1c501540e18da4f480d8bf0e70/pyatv/convert.py#L74-L82 | train |
postlund/pyatv | pyatv/convert.py | protocol_str | def protocol_str(protocol):
"""Convert internal API protocol to string."""
if protocol == const.PROTOCOL_MRP:
return 'MRP'
if protocol == const.PROTOCOL_DMAP:
return 'DMAP'
if protocol == const.PROTOCOL_AIRPLAY:
return 'AirPlay'
return 'Unknown' | python | def protocol_str(protocol):
"""Convert internal API protocol to string."""
if protocol == const.PROTOCOL_MRP:
return 'MRP'
if protocol == const.PROTOCOL_DMAP:
return 'DMAP'
if protocol == const.PROTOCOL_AIRPLAY:
return 'AirPlay'
return 'Unknown' | [
"def",
"protocol_str",
"(",
"protocol",
")",
":",
"if",
"protocol",
"==",
"const",
".",
"PROTOCOL_MRP",
":",
"return",
"'MRP'",
"if",
"protocol",
"==",
"const",
".",
"PROTOCOL_DMAP",
":",
"return",
"'DMAP'",
"if",
"protocol",
"==",
"const",
".",
"PROTOCOL_AI... | Convert internal API protocol to string. | [
"Convert",
"internal",
"API",
"protocol",
"to",
"string",
"."
] | 655dfcda4e2f9d1c501540e18da4f480d8bf0e70 | https://github.com/postlund/pyatv/blob/655dfcda4e2f9d1c501540e18da4f480d8bf0e70/pyatv/convert.py#L96-L104 | train |
postlund/pyatv | pyatv/dmap/parser.py | first | def first(dmap_data, *path):
"""Look up a value given a path in some parsed DMAP data."""
if not (path and isinstance(dmap_data, list)):
return dmap_data
for key in dmap_data:
if path[0] in key:
return first(key[path[0]], *path[1:])
return None | python | def first(dmap_data, *path):
"""Look up a value given a path in some parsed DMAP data."""
if not (path and isinstance(dmap_data, list)):
return dmap_data
for key in dmap_data:
if path[0] in key:
return first(key[path[0]], *path[1:])
return None | [
"def",
"first",
"(",
"dmap_data",
",",
"*",
"path",
")",
":",
"if",
"not",
"(",
"path",
"and",
"isinstance",
"(",
"dmap_data",
",",
"list",
")",
")",
":",
"return",
"dmap_data",
"for",
"key",
"in",
"dmap_data",
":",
"if",
"path",
"[",
"0",
"]",
"in... | Look up a value given a path in some parsed DMAP data. | [
"Look",
"up",
"a",
"value",
"given",
"a",
"path",
"in",
"some",
"parsed",
"DMAP",
"data",
"."
] | 655dfcda4e2f9d1c501540e18da4f480d8bf0e70 | https://github.com/postlund/pyatv/blob/655dfcda4e2f9d1c501540e18da4f480d8bf0e70/pyatv/dmap/parser.py#L56-L65 | train |
postlund/pyatv | pyatv/dmap/parser.py | pprint | def pprint(data, tag_lookup, indent=0):
"""Return a pretty formatted string of parsed DMAP data."""
output = ''
if isinstance(data, dict):
for key, value in data.items():
tag = tag_lookup(key)
if isinstance(value, (dict, list)) and tag.type is not read_bplist:
... | python | def pprint(data, tag_lookup, indent=0):
"""Return a pretty formatted string of parsed DMAP data."""
output = ''
if isinstance(data, dict):
for key, value in data.items():
tag = tag_lookup(key)
if isinstance(value, (dict, list)) and tag.type is not read_bplist:
... | [
"def",
"pprint",
"(",
"data",
",",
"tag_lookup",
",",
"indent",
"=",
"0",
")",
":",
"output",
"=",
"''",
"if",
"isinstance",
"(",
"data",
",",
"dict",
")",
":",
"for",
"key",
",",
"value",
"in",
"data",
".",
"items",
"(",
")",
":",
"tag",
"=",
... | Return a pretty formatted string of parsed DMAP data. | [
"Return",
"a",
"pretty",
"formatted",
"string",
"of",
"parsed",
"DMAP",
"data",
"."
] | 655dfcda4e2f9d1c501540e18da4f480d8bf0e70 | https://github.com/postlund/pyatv/blob/655dfcda4e2f9d1c501540e18da4f480d8bf0e70/pyatv/dmap/parser.py#L69-L87 | train |
postlund/pyatv | pyatv/interface.py | retrieve_commands | def retrieve_commands(obj):
"""Retrieve all commands and help texts from an API object."""
commands = {} # Name and help
for func in obj.__dict__:
if not inspect.isfunction(obj.__dict__[func]) and \
not isinstance(obj.__dict__[func], property):
continue
if func.starts... | python | def retrieve_commands(obj):
"""Retrieve all commands and help texts from an API object."""
commands = {} # Name and help
for func in obj.__dict__:
if not inspect.isfunction(obj.__dict__[func]) and \
not isinstance(obj.__dict__[func], property):
continue
if func.starts... | [
"def",
"retrieve_commands",
"(",
"obj",
")",
":",
"commands",
"=",
"{",
"}",
"# Name and help",
"for",
"func",
"in",
"obj",
".",
"__dict__",
":",
"if",
"not",
"inspect",
".",
"isfunction",
"(",
"obj",
".",
"__dict__",
"[",
"func",
"]",
")",
"and",
"not... | Retrieve all commands and help texts from an API object. | [
"Retrieve",
"all",
"commands",
"and",
"help",
"texts",
"from",
"an",
"API",
"object",
"."
] | 655dfcda4e2f9d1c501540e18da4f480d8bf0e70 | https://github.com/postlund/pyatv/blob/655dfcda4e2f9d1c501540e18da4f480d8bf0e70/pyatv/interface.py#L28-L39 | train |
postlund/pyatv | pyatv/interface.py | Playing.hash | def hash(self):
"""Create a unique hash for what is currently playing.
The hash is based on title, artist, album and total time. It should
always be the same for the same content, but it is not guaranteed.
"""
base = '{0}{1}{2}{3}'.format(
self.title, self.artist, se... | python | def hash(self):
"""Create a unique hash for what is currently playing.
The hash is based on title, artist, album and total time. It should
always be the same for the same content, but it is not guaranteed.
"""
base = '{0}{1}{2}{3}'.format(
self.title, self.artist, se... | [
"def",
"hash",
"(",
"self",
")",
":",
"base",
"=",
"'{0}{1}{2}{3}'",
".",
"format",
"(",
"self",
".",
"title",
",",
"self",
".",
"artist",
",",
"self",
".",
"album",
",",
"self",
".",
"total_time",
")",
"return",
"hashlib",
".",
"sha256",
"(",
"base"... | Create a unique hash for what is currently playing.
The hash is based on title, artist, album and total time. It should
always be the same for the same content, but it is not guaranteed. | [
"Create",
"a",
"unique",
"hash",
"for",
"what",
"is",
"currently",
"playing",
"."
] | 655dfcda4e2f9d1c501540e18da4f480d8bf0e70 | https://github.com/postlund/pyatv/blob/655dfcda4e2f9d1c501540e18da4f480d8bf0e70/pyatv/interface.py#L213-L221 | train |
postlund/pyatv | scripts/autogen_protobuf_extensions.py | extract_message_info | def extract_message_info():
"""Get information about all messages of interest."""
base_path = BASE_PACKAGE.replace('.', '/')
filename = os.path.join(base_path, 'ProtocolMessage.proto')
with open(filename, 'r') as file:
types_found = False
for line in file:
stripped = line.l... | python | def extract_message_info():
"""Get information about all messages of interest."""
base_path = BASE_PACKAGE.replace('.', '/')
filename = os.path.join(base_path, 'ProtocolMessage.proto')
with open(filename, 'r') as file:
types_found = False
for line in file:
stripped = line.l... | [
"def",
"extract_message_info",
"(",
")",
":",
"base_path",
"=",
"BASE_PACKAGE",
".",
"replace",
"(",
"'.'",
",",
"'/'",
")",
"filename",
"=",
"os",
".",
"path",
".",
"join",
"(",
"base_path",
",",
"'ProtocolMessage.proto'",
")",
"with",
"open",
"(",
"filen... | Get information about all messages of interest. | [
"Get",
"information",
"about",
"all",
"messages",
"of",
"interest",
"."
] | 655dfcda4e2f9d1c501540e18da4f480d8bf0e70 | https://github.com/postlund/pyatv/blob/655dfcda4e2f9d1c501540e18da4f480d8bf0e70/scripts/autogen_protobuf_extensions.py#L54-L83 | train |
postlund/pyatv | scripts/autogen_protobuf_extensions.py | main | def main():
"""Script starts somewhere around here."""
message_names = set()
packages = []
messages = []
extensions = []
constants = []
# Extract everything needed to generate output file
for info in extract_message_info():
message_names.add(info.title)
packages.append(
... | python | def main():
"""Script starts somewhere around here."""
message_names = set()
packages = []
messages = []
extensions = []
constants = []
# Extract everything needed to generate output file
for info in extract_message_info():
message_names.add(info.title)
packages.append(
... | [
"def",
"main",
"(",
")",
":",
"message_names",
"=",
"set",
"(",
")",
"packages",
"=",
"[",
"]",
"messages",
"=",
"[",
"]",
"extensions",
"=",
"[",
"]",
"constants",
"=",
"[",
"]",
"# Extract everything needed to generate output file",
"for",
"info",
"in",
... | Script starts somewhere around here. | [
"Script",
"starts",
"somewhere",
"around",
"here",
"."
] | 655dfcda4e2f9d1c501540e18da4f480d8bf0e70 | https://github.com/postlund/pyatv/blob/655dfcda4e2f9d1c501540e18da4f480d8bf0e70/scripts/autogen_protobuf_extensions.py#L101-L140 | train |
postlund/pyatv | pyatv/mrp/srp.py | hkdf_expand | def hkdf_expand(salt, info, shared_secret):
"""Derive encryption keys from shared secret."""
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.kdf.hkdf import HKDF
from cryptography.hazmat.backends import default_backend
hkdf = HKDF(
algorithm=hashes.SHA51... | python | def hkdf_expand(salt, info, shared_secret):
"""Derive encryption keys from shared secret."""
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.kdf.hkdf import HKDF
from cryptography.hazmat.backends import default_backend
hkdf = HKDF(
algorithm=hashes.SHA51... | [
"def",
"hkdf_expand",
"(",
"salt",
",",
"info",
",",
"shared_secret",
")",
":",
"from",
"cryptography",
".",
"hazmat",
".",
"primitives",
"import",
"hashes",
"from",
"cryptography",
".",
"hazmat",
".",
"primitives",
".",
"kdf",
".",
"hkdf",
"import",
"HKDF",... | Derive encryption keys from shared secret. | [
"Derive",
"encryption",
"keys",
"from",
"shared",
"secret",
"."
] | 655dfcda4e2f9d1c501540e18da4f480d8bf0e70 | https://github.com/postlund/pyatv/blob/655dfcda4e2f9d1c501540e18da4f480d8bf0e70/pyatv/mrp/srp.py#L53-L65 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.