partition
stringclasses 3
values | func_name
stringlengths 1
134
| docstring
stringlengths 1
46.9k
| path
stringlengths 4
223
| original_string
stringlengths 75
104k
| code
stringlengths 75
104k
| docstring_tokens
listlengths 1
1.97k
| repo
stringlengths 7
55
| language
stringclasses 1
value | url
stringlengths 87
315
| code_tokens
listlengths 19
28.4k
| sha
stringlengths 40
40
|
|---|---|---|---|---|---|---|---|---|---|---|---|
valid
|
pack_into_dict
|
Same as :func:`~bitstruct.pack_into()`, but data is read from a
dictionary.
See :func:`~bitstruct.pack_dict()` for details on `names`.
|
bitstruct.py
|
def pack_into_dict(fmt, names, buf, offset, data, **kwargs):
"""Same as :func:`~bitstruct.pack_into()`, but data is read from a
dictionary.
See :func:`~bitstruct.pack_dict()` for details on `names`.
"""
return CompiledFormatDict(fmt, names).pack_into(buf,
offset,
data,
**kwargs)
|
def pack_into_dict(fmt, names, buf, offset, data, **kwargs):
"""Same as :func:`~bitstruct.pack_into()`, but data is read from a
dictionary.
See :func:`~bitstruct.pack_dict()` for details on `names`.
"""
return CompiledFormatDict(fmt, names).pack_into(buf,
offset,
data,
**kwargs)
|
[
"Same",
"as",
":",
"func",
":",
"~bitstruct",
".",
"pack_into",
"()",
"but",
"data",
"is",
"read",
"from",
"a",
"dictionary",
"."
] |
eerimoq/bitstruct
|
python
|
https://github.com/eerimoq/bitstruct/blob/8e887c10241aa51c2a77c10e9923bb3978b15bcb/bitstruct.py#L575-L586
|
[
"def",
"pack_into_dict",
"(",
"fmt",
",",
"names",
",",
"buf",
",",
"offset",
",",
"data",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"CompiledFormatDict",
"(",
"fmt",
",",
"names",
")",
".",
"pack_into",
"(",
"buf",
",",
"offset",
",",
"data",
",",
"*",
"*",
"kwargs",
")"
] |
8e887c10241aa51c2a77c10e9923bb3978b15bcb
|
valid
|
unpack_from_dict
|
Same as :func:`~bitstruct.unpack_from_dict()`, but returns a
dictionary.
See :func:`~bitstruct.pack_dict()` for details on `names`.
|
bitstruct.py
|
def unpack_from_dict(fmt, names, data, offset=0):
"""Same as :func:`~bitstruct.unpack_from_dict()`, but returns a
dictionary.
See :func:`~bitstruct.pack_dict()` for details on `names`.
"""
return CompiledFormatDict(fmt, names).unpack_from(data, offset)
|
def unpack_from_dict(fmt, names, data, offset=0):
"""Same as :func:`~bitstruct.unpack_from_dict()`, but returns a
dictionary.
See :func:`~bitstruct.pack_dict()` for details on `names`.
"""
return CompiledFormatDict(fmt, names).unpack_from(data, offset)
|
[
"Same",
"as",
":",
"func",
":",
"~bitstruct",
".",
"unpack_from_dict",
"()",
"but",
"returns",
"a",
"dictionary",
"."
] |
eerimoq/bitstruct
|
python
|
https://github.com/eerimoq/bitstruct/blob/8e887c10241aa51c2a77c10e9923bb3978b15bcb/bitstruct.py#L589-L597
|
[
"def",
"unpack_from_dict",
"(",
"fmt",
",",
"names",
",",
"data",
",",
"offset",
"=",
"0",
")",
":",
"return",
"CompiledFormatDict",
"(",
"fmt",
",",
"names",
")",
".",
"unpack_from",
"(",
"data",
",",
"offset",
")"
] |
8e887c10241aa51c2a77c10e9923bb3978b15bcb
|
valid
|
byteswap
|
Swap bytes in `data` according to `fmt`, starting at byte `offset`
and return the result. `fmt` must be an iterable, iterating over
number of bytes to swap. For example, the format string ``'24'``
applied to the bytes ``b'\\x00\\x11\\x22\\x33\\x44\\x55'`` will
produce the result ``b'\\x11\\x00\\x55\\x44\\x33\\x22'``.
|
bitstruct.py
|
def byteswap(fmt, data, offset=0):
"""Swap bytes in `data` according to `fmt`, starting at byte `offset`
and return the result. `fmt` must be an iterable, iterating over
number of bytes to swap. For example, the format string ``'24'``
applied to the bytes ``b'\\x00\\x11\\x22\\x33\\x44\\x55'`` will
produce the result ``b'\\x11\\x00\\x55\\x44\\x33\\x22'``.
"""
data = BytesIO(data)
data.seek(offset)
data_swapped = BytesIO()
for f in fmt:
swapped = data.read(int(f))[::-1]
data_swapped.write(swapped)
return data_swapped.getvalue()
|
def byteswap(fmt, data, offset=0):
"""Swap bytes in `data` according to `fmt`, starting at byte `offset`
and return the result. `fmt` must be an iterable, iterating over
number of bytes to swap. For example, the format string ``'24'``
applied to the bytes ``b'\\x00\\x11\\x22\\x33\\x44\\x55'`` will
produce the result ``b'\\x11\\x00\\x55\\x44\\x33\\x22'``.
"""
data = BytesIO(data)
data.seek(offset)
data_swapped = BytesIO()
for f in fmt:
swapped = data.read(int(f))[::-1]
data_swapped.write(swapped)
return data_swapped.getvalue()
|
[
"Swap",
"bytes",
"in",
"data",
"according",
"to",
"fmt",
"starting",
"at",
"byte",
"offset",
"and",
"return",
"the",
"result",
".",
"fmt",
"must",
"be",
"an",
"iterable",
"iterating",
"over",
"number",
"of",
"bytes",
"to",
"swap",
".",
"For",
"example",
"the",
"format",
"string",
"24",
"applied",
"to",
"the",
"bytes",
"b",
"\\\\",
"x00",
"\\\\",
"x11",
"\\\\",
"x22",
"\\\\",
"x33",
"\\\\",
"x44",
"\\\\",
"x55",
"will",
"produce",
"the",
"result",
"b",
"\\\\",
"x11",
"\\\\",
"x00",
"\\\\",
"x55",
"\\\\",
"x44",
"\\\\",
"x33",
"\\\\",
"x22",
"."
] |
eerimoq/bitstruct
|
python
|
https://github.com/eerimoq/bitstruct/blob/8e887c10241aa51c2a77c10e9923bb3978b15bcb/bitstruct.py#L611-L628
|
[
"def",
"byteswap",
"(",
"fmt",
",",
"data",
",",
"offset",
"=",
"0",
")",
":",
"data",
"=",
"BytesIO",
"(",
"data",
")",
"data",
".",
"seek",
"(",
"offset",
")",
"data_swapped",
"=",
"BytesIO",
"(",
")",
"for",
"f",
"in",
"fmt",
":",
"swapped",
"=",
"data",
".",
"read",
"(",
"int",
"(",
"f",
")",
")",
"[",
":",
":",
"-",
"1",
"]",
"data_swapped",
".",
"write",
"(",
"swapped",
")",
"return",
"data_swapped",
".",
"getvalue",
"(",
")"
] |
8e887c10241aa51c2a77c10e9923bb3978b15bcb
|
valid
|
CompiledFormat.pack
|
See :func:`~bitstruct.pack()`.
|
bitstruct.py
|
def pack(self, *args):
"""See :func:`~bitstruct.pack()`.
"""
# Sanity check of the number of arguments.
if len(args) < self._number_of_arguments:
raise Error(
"pack expected {} item(s) for packing (got {})".format(
self._number_of_arguments,
len(args)))
return self.pack_any(args)
|
def pack(self, *args):
"""See :func:`~bitstruct.pack()`.
"""
# Sanity check of the number of arguments.
if len(args) < self._number_of_arguments:
raise Error(
"pack expected {} item(s) for packing (got {})".format(
self._number_of_arguments,
len(args)))
return self.pack_any(args)
|
[
"See",
":",
"func",
":",
"~bitstruct",
".",
"pack",
"()",
"."
] |
eerimoq/bitstruct
|
python
|
https://github.com/eerimoq/bitstruct/blob/8e887c10241aa51c2a77c10e9923bb3978b15bcb/bitstruct.py#L379-L391
|
[
"def",
"pack",
"(",
"self",
",",
"*",
"args",
")",
":",
"# Sanity check of the number of arguments.",
"if",
"len",
"(",
"args",
")",
"<",
"self",
".",
"_number_of_arguments",
":",
"raise",
"Error",
"(",
"\"pack expected {} item(s) for packing (got {})\"",
".",
"format",
"(",
"self",
".",
"_number_of_arguments",
",",
"len",
"(",
"args",
")",
")",
")",
"return",
"self",
".",
"pack_any",
"(",
"args",
")"
] |
8e887c10241aa51c2a77c10e9923bb3978b15bcb
|
valid
|
CompiledFormat.pack_into
|
See :func:`~bitstruct.pack_into()`.
|
bitstruct.py
|
def pack_into(self, buf, offset, *args, **kwargs):
"""See :func:`~bitstruct.pack_into()`.
"""
# Sanity check of the number of arguments.
if len(args) < self._number_of_arguments:
raise Error(
"pack expected {} item(s) for packing (got {})".format(
self._number_of_arguments,
len(args)))
self.pack_into_any(buf, offset, args, **kwargs)
|
def pack_into(self, buf, offset, *args, **kwargs):
"""See :func:`~bitstruct.pack_into()`.
"""
# Sanity check of the number of arguments.
if len(args) < self._number_of_arguments:
raise Error(
"pack expected {} item(s) for packing (got {})".format(
self._number_of_arguments,
len(args)))
self.pack_into_any(buf, offset, args, **kwargs)
|
[
"See",
":",
"func",
":",
"~bitstruct",
".",
"pack_into",
"()",
"."
] |
eerimoq/bitstruct
|
python
|
https://github.com/eerimoq/bitstruct/blob/8e887c10241aa51c2a77c10e9923bb3978b15bcb/bitstruct.py#L400-L412
|
[
"def",
"pack_into",
"(",
"self",
",",
"buf",
",",
"offset",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# Sanity check of the number of arguments.",
"if",
"len",
"(",
"args",
")",
"<",
"self",
".",
"_number_of_arguments",
":",
"raise",
"Error",
"(",
"\"pack expected {} item(s) for packing (got {})\"",
".",
"format",
"(",
"self",
".",
"_number_of_arguments",
",",
"len",
"(",
"args",
")",
")",
")",
"self",
".",
"pack_into_any",
"(",
"buf",
",",
"offset",
",",
"args",
",",
"*",
"*",
"kwargs",
")"
] |
8e887c10241aa51c2a77c10e9923bb3978b15bcb
|
valid
|
CompiledFormat.unpack_from
|
See :func:`~bitstruct.unpack_from()`.
|
bitstruct.py
|
def unpack_from(self, data, offset=0):
"""See :func:`~bitstruct.unpack_from()`.
"""
return tuple([v[1] for v in self.unpack_from_any(data, offset)])
|
def unpack_from(self, data, offset=0):
"""See :func:`~bitstruct.unpack_from()`.
"""
return tuple([v[1] for v in self.unpack_from_any(data, offset)])
|
[
"See",
":",
"func",
":",
"~bitstruct",
".",
"unpack_from",
"()",
"."
] |
eerimoq/bitstruct
|
python
|
https://github.com/eerimoq/bitstruct/blob/8e887c10241aa51c2a77c10e9923bb3978b15bcb/bitstruct.py#L414-L419
|
[
"def",
"unpack_from",
"(",
"self",
",",
"data",
",",
"offset",
"=",
"0",
")",
":",
"return",
"tuple",
"(",
"[",
"v",
"[",
"1",
"]",
"for",
"v",
"in",
"self",
".",
"unpack_from_any",
"(",
"data",
",",
"offset",
")",
"]",
")"
] |
8e887c10241aa51c2a77c10e9923bb3978b15bcb
|
valid
|
CompiledFormatDict.pack
|
See :func:`~bitstruct.pack_dict()`.
|
bitstruct.py
|
def pack(self, data):
"""See :func:`~bitstruct.pack_dict()`.
"""
try:
return self.pack_any(data)
except KeyError as e:
raise Error('{} not found in data dictionary'.format(str(e)))
|
def pack(self, data):
"""See :func:`~bitstruct.pack_dict()`.
"""
try:
return self.pack_any(data)
except KeyError as e:
raise Error('{} not found in data dictionary'.format(str(e)))
|
[
"See",
":",
"func",
":",
"~bitstruct",
".",
"pack_dict",
"()",
"."
] |
eerimoq/bitstruct
|
python
|
https://github.com/eerimoq/bitstruct/blob/8e887c10241aa51c2a77c10e9923bb3978b15bcb/bitstruct.py#L427-L435
|
[
"def",
"pack",
"(",
"self",
",",
"data",
")",
":",
"try",
":",
"return",
"self",
".",
"pack_any",
"(",
"data",
")",
"except",
"KeyError",
"as",
"e",
":",
"raise",
"Error",
"(",
"'{} not found in data dictionary'",
".",
"format",
"(",
"str",
"(",
"e",
")",
")",
")"
] |
8e887c10241aa51c2a77c10e9923bb3978b15bcb
|
valid
|
CompiledFormatDict.pack_into
|
See :func:`~bitstruct.pack_into_dict()`.
|
bitstruct.py
|
def pack_into(self, buf, offset, data, **kwargs):
"""See :func:`~bitstruct.pack_into_dict()`.
"""
try:
self.pack_into_any(buf, offset, data, **kwargs)
except KeyError as e:
raise Error('{} not found in data dictionary'.format(str(e)))
|
def pack_into(self, buf, offset, data, **kwargs):
"""See :func:`~bitstruct.pack_into_dict()`.
"""
try:
self.pack_into_any(buf, offset, data, **kwargs)
except KeyError as e:
raise Error('{} not found in data dictionary'.format(str(e)))
|
[
"See",
":",
"func",
":",
"~bitstruct",
".",
"pack_into_dict",
"()",
"."
] |
eerimoq/bitstruct
|
python
|
https://github.com/eerimoq/bitstruct/blob/8e887c10241aa51c2a77c10e9923bb3978b15bcb/bitstruct.py#L444-L452
|
[
"def",
"pack_into",
"(",
"self",
",",
"buf",
",",
"offset",
",",
"data",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"self",
".",
"pack_into_any",
"(",
"buf",
",",
"offset",
",",
"data",
",",
"*",
"*",
"kwargs",
")",
"except",
"KeyError",
"as",
"e",
":",
"raise",
"Error",
"(",
"'{} not found in data dictionary'",
".",
"format",
"(",
"str",
"(",
"e",
")",
")",
")"
] |
8e887c10241aa51c2a77c10e9923bb3978b15bcb
|
valid
|
CompiledFormatDict.unpack_from
|
See :func:`~bitstruct.unpack_from_dict()`.
|
bitstruct.py
|
def unpack_from(self, data, offset=0):
"""See :func:`~bitstruct.unpack_from_dict()`.
"""
return {info.name: v for info, v in self.unpack_from_any(data, offset)}
|
def unpack_from(self, data, offset=0):
"""See :func:`~bitstruct.unpack_from_dict()`.
"""
return {info.name: v for info, v in self.unpack_from_any(data, offset)}
|
[
"See",
":",
"func",
":",
"~bitstruct",
".",
"unpack_from_dict",
"()",
"."
] |
eerimoq/bitstruct
|
python
|
https://github.com/eerimoq/bitstruct/blob/8e887c10241aa51c2a77c10e9923bb3978b15bcb/bitstruct.py#L454-L459
|
[
"def",
"unpack_from",
"(",
"self",
",",
"data",
",",
"offset",
"=",
"0",
")",
":",
"return",
"{",
"info",
".",
"name",
":",
"v",
"for",
"info",
",",
"v",
"in",
"self",
".",
"unpack_from_any",
"(",
"data",
",",
"offset",
")",
"}"
] |
8e887c10241aa51c2a77c10e9923bb3978b15bcb
|
valid
|
cli
|
Bottery
|
bottery/cli.py
|
def cli(ctx, version):
"""Bottery"""
# If no subcommand was given and the version flag is true, shows
# Bottery version
if not ctx.invoked_subcommand and version:
click.echo(bottery.__version__)
ctx.exit()
# If no subcommand but neither the version flag, shows help message
elif not ctx.invoked_subcommand:
click.echo(ctx.get_help())
ctx.exit()
|
def cli(ctx, version):
"""Bottery"""
# If no subcommand was given and the version flag is true, shows
# Bottery version
if not ctx.invoked_subcommand and version:
click.echo(bottery.__version__)
ctx.exit()
# If no subcommand but neither the version flag, shows help message
elif not ctx.invoked_subcommand:
click.echo(ctx.get_help())
ctx.exit()
|
[
"Bottery"
] |
rougeth/bottery
|
python
|
https://github.com/rougeth/bottery/blob/1c724b867fa16708d59a3dbba5dd2c3de85147a9/bottery/cli.py#L20-L32
|
[
"def",
"cli",
"(",
"ctx",
",",
"version",
")",
":",
"# If no subcommand was given and the version flag is true, shows",
"# Bottery version",
"if",
"not",
"ctx",
".",
"invoked_subcommand",
"and",
"version",
":",
"click",
".",
"echo",
"(",
"bottery",
".",
"__version__",
")",
"ctx",
".",
"exit",
"(",
")",
"# If no subcommand but neither the version flag, shows help message",
"elif",
"not",
"ctx",
".",
"invoked_subcommand",
":",
"click",
".",
"echo",
"(",
"ctx",
".",
"get_help",
"(",
")",
")",
"ctx",
".",
"exit",
"(",
")"
] |
1c724b867fa16708d59a3dbba5dd2c3de85147a9
|
valid
|
TelegramEngine.build_message
|
Return a Message instance according to the data received from
Telegram API.
https://core.telegram.org/bots/api#update
|
bottery/telegram/engine.py
|
def build_message(self, data):
'''
Return a Message instance according to the data received from
Telegram API.
https://core.telegram.org/bots/api#update
'''
message_data = data.get('message') or data.get('edited_message')
if not message_data:
return None
edited = 'edited_message' in data
return Message(
id=message_data['message_id'],
platform=self.platform,
text=message_data.get('text', ''),
user=TelegramUser(message_data['from']),
chat=TelegramChat(message_data['chat']),
timestamp=message_data['date'],
raw=data,
edited=edited,
)
|
def build_message(self, data):
'''
Return a Message instance according to the data received from
Telegram API.
https://core.telegram.org/bots/api#update
'''
message_data = data.get('message') or data.get('edited_message')
if not message_data:
return None
edited = 'edited_message' in data
return Message(
id=message_data['message_id'],
platform=self.platform,
text=message_data.get('text', ''),
user=TelegramUser(message_data['from']),
chat=TelegramChat(message_data['chat']),
timestamp=message_data['date'],
raw=data,
edited=edited,
)
|
[
"Return",
"a",
"Message",
"instance",
"according",
"to",
"the",
"data",
"received",
"from",
"Telegram",
"API",
".",
"https",
":",
"//",
"core",
".",
"telegram",
".",
"org",
"/",
"bots",
"/",
"api#update"
] |
rougeth/bottery
|
python
|
https://github.com/rougeth/bottery/blob/1c724b867fa16708d59a3dbba5dd2c3de85147a9/bottery/telegram/engine.py#L124-L145
|
[
"def",
"build_message",
"(",
"self",
",",
"data",
")",
":",
"message_data",
"=",
"data",
".",
"get",
"(",
"'message'",
")",
"or",
"data",
".",
"get",
"(",
"'edited_message'",
")",
"if",
"not",
"message_data",
":",
"return",
"None",
"edited",
"=",
"'edited_message'",
"in",
"data",
"return",
"Message",
"(",
"id",
"=",
"message_data",
"[",
"'message_id'",
"]",
",",
"platform",
"=",
"self",
".",
"platform",
",",
"text",
"=",
"message_data",
".",
"get",
"(",
"'text'",
",",
"''",
")",
",",
"user",
"=",
"TelegramUser",
"(",
"message_data",
"[",
"'from'",
"]",
")",
",",
"chat",
"=",
"TelegramChat",
"(",
"message_data",
"[",
"'chat'",
"]",
")",
",",
"timestamp",
"=",
"message_data",
"[",
"'date'",
"]",
",",
"raw",
"=",
"data",
",",
"edited",
"=",
"edited",
",",
")"
] |
1c724b867fa16708d59a3dbba5dd2c3de85147a9
|
valid
|
TelegramEngine.get_chat_id
|
Telegram chat type can be either "private", "group", "supergroup" or
"channel".
Return user ID if it is of type "private", chat ID otherwise.
|
bottery/telegram/engine.py
|
def get_chat_id(self, message):
'''
Telegram chat type can be either "private", "group", "supergroup" or
"channel".
Return user ID if it is of type "private", chat ID otherwise.
'''
if message.chat.type == 'private':
return message.user.id
return message.chat.id
|
def get_chat_id(self, message):
'''
Telegram chat type can be either "private", "group", "supergroup" or
"channel".
Return user ID if it is of type "private", chat ID otherwise.
'''
if message.chat.type == 'private':
return message.user.id
return message.chat.id
|
[
"Telegram",
"chat",
"type",
"can",
"be",
"either",
"private",
"group",
"supergroup",
"or",
"channel",
".",
"Return",
"user",
"ID",
"if",
"it",
"is",
"of",
"type",
"private",
"chat",
"ID",
"otherwise",
"."
] |
rougeth/bottery
|
python
|
https://github.com/rougeth/bottery/blob/1c724b867fa16708d59a3dbba5dd2c3de85147a9/bottery/telegram/engine.py#L147-L156
|
[
"def",
"get_chat_id",
"(",
"self",
",",
"message",
")",
":",
"if",
"message",
".",
"chat",
".",
"type",
"==",
"'private'",
":",
"return",
"message",
".",
"user",
".",
"id",
"return",
"message",
".",
"chat",
".",
"id"
] |
1c724b867fa16708d59a3dbba5dd2c3de85147a9
|
valid
|
MessengerEngine.build_message
|
Return a Message instance according to the data received from
Facebook Messenger API.
|
bottery/messenger/engine.py
|
def build_message(self, data):
'''
Return a Message instance according to the data received from
Facebook Messenger API.
'''
if not data:
return None
return Message(
id=data['message']['mid'],
platform=self.platform,
text=data['message']['text'],
user=data['sender']['id'],
timestamp=data['timestamp'],
raw=data,
chat=None, # TODO: Refactor build_messages and Message class
)
|
def build_message(self, data):
'''
Return a Message instance according to the data received from
Facebook Messenger API.
'''
if not data:
return None
return Message(
id=data['message']['mid'],
platform=self.platform,
text=data['message']['text'],
user=data['sender']['id'],
timestamp=data['timestamp'],
raw=data,
chat=None, # TODO: Refactor build_messages and Message class
)
|
[
"Return",
"a",
"Message",
"instance",
"according",
"to",
"the",
"data",
"received",
"from",
"Facebook",
"Messenger",
"API",
"."
] |
rougeth/bottery
|
python
|
https://github.com/rougeth/bottery/blob/1c724b867fa16708d59a3dbba5dd2c3de85147a9/bottery/messenger/engine.py#L51-L67
|
[
"def",
"build_message",
"(",
"self",
",",
"data",
")",
":",
"if",
"not",
"data",
":",
"return",
"None",
"return",
"Message",
"(",
"id",
"=",
"data",
"[",
"'message'",
"]",
"[",
"'mid'",
"]",
",",
"platform",
"=",
"self",
".",
"platform",
",",
"text",
"=",
"data",
"[",
"'message'",
"]",
"[",
"'text'",
"]",
",",
"user",
"=",
"data",
"[",
"'sender'",
"]",
"[",
"'id'",
"]",
",",
"timestamp",
"=",
"data",
"[",
"'timestamp'",
"]",
",",
"raw",
"=",
"data",
",",
"chat",
"=",
"None",
",",
"# TODO: Refactor build_messages and Message class",
")"
] |
1c724b867fa16708d59a3dbba5dd2c3de85147a9
|
valid
|
BaseEngine._get_response
|
Get response running the view with await syntax if it is a
coroutine function, otherwise just run it the normal way.
|
bottery/platforms.py
|
async def _get_response(self, message):
"""
Get response running the view with await syntax if it is a
coroutine function, otherwise just run it the normal way.
"""
view = self.discovery_view(message)
if not view:
return
if inspect.iscoroutinefunction(view):
response = await view(message)
else:
response = view(message)
return self.prepare_response(response, message)
|
async def _get_response(self, message):
"""
Get response running the view with await syntax if it is a
coroutine function, otherwise just run it the normal way.
"""
view = self.discovery_view(message)
if not view:
return
if inspect.iscoroutinefunction(view):
response = await view(message)
else:
response = view(message)
return self.prepare_response(response, message)
|
[
"Get",
"response",
"running",
"the",
"view",
"with",
"await",
"syntax",
"if",
"it",
"is",
"a",
"coroutine",
"function",
"otherwise",
"just",
"run",
"it",
"the",
"normal",
"way",
"."
] |
rougeth/bottery
|
python
|
https://github.com/rougeth/bottery/blob/1c724b867fa16708d59a3dbba5dd2c3de85147a9/bottery/platforms.py#L38-L53
|
[
"async",
"def",
"_get_response",
"(",
"self",
",",
"message",
")",
":",
"view",
"=",
"self",
".",
"discovery_view",
"(",
"message",
")",
"if",
"not",
"view",
":",
"return",
"if",
"inspect",
".",
"iscoroutinefunction",
"(",
"view",
")",
":",
"response",
"=",
"await",
"view",
"(",
"message",
")",
"else",
":",
"response",
"=",
"view",
"(",
"message",
")",
"return",
"self",
".",
"prepare_response",
"(",
"response",
",",
"message",
")"
] |
1c724b867fa16708d59a3dbba5dd2c3de85147a9
|
valid
|
BaseEngine.discovery_view
|
Use the new message to search for a registered view according
to its pattern.
|
bottery/platforms.py
|
def discovery_view(self, message):
"""
Use the new message to search for a registered view according
to its pattern.
"""
for handler in self.registered_handlers:
if handler.check(message):
return handler.view
return None
|
def discovery_view(self, message):
"""
Use the new message to search for a registered view according
to its pattern.
"""
for handler in self.registered_handlers:
if handler.check(message):
return handler.view
return None
|
[
"Use",
"the",
"new",
"message",
"to",
"search",
"for",
"a",
"registered",
"view",
"according",
"to",
"its",
"pattern",
"."
] |
rougeth/bottery
|
python
|
https://github.com/rougeth/bottery/blob/1c724b867fa16708d59a3dbba5dd2c3de85147a9/bottery/platforms.py#L81-L90
|
[
"def",
"discovery_view",
"(",
"self",
",",
"message",
")",
":",
"for",
"handler",
"in",
"self",
".",
"registered_handlers",
":",
"if",
"handler",
".",
"check",
"(",
"message",
")",
":",
"return",
"handler",
".",
"view",
"return",
"None"
] |
1c724b867fa16708d59a3dbba5dd2c3de85147a9
|
valid
|
BaseEngine.message_handler
|
For each new message, build its platform specific message
object and get a response.
|
bottery/platforms.py
|
async def message_handler(self, data):
"""
For each new message, build its platform specific message
object and get a response.
"""
message = self.build_message(data)
if not message:
logger.error(
'[%s] Unable to build Message with data, data=%s, error',
self.engine_name,
data
)
return
logger.info('[%s] New message from %s: %s', self.engine_name,
message.user, message.text)
response = await self.get_response(message)
if response:
await self.send_response(response)
|
async def message_handler(self, data):
"""
For each new message, build its platform specific message
object and get a response.
"""
message = self.build_message(data)
if not message:
logger.error(
'[%s] Unable to build Message with data, data=%s, error',
self.engine_name,
data
)
return
logger.info('[%s] New message from %s: %s', self.engine_name,
message.user, message.text)
response = await self.get_response(message)
if response:
await self.send_response(response)
|
[
"For",
"each",
"new",
"message",
"build",
"its",
"platform",
"specific",
"message",
"object",
"and",
"get",
"a",
"response",
"."
] |
rougeth/bottery
|
python
|
https://github.com/rougeth/bottery/blob/1c724b867fa16708d59a3dbba5dd2c3de85147a9/bottery/platforms.py#L92-L112
|
[
"async",
"def",
"message_handler",
"(",
"self",
",",
"data",
")",
":",
"message",
"=",
"self",
".",
"build_message",
"(",
"data",
")",
"if",
"not",
"message",
":",
"logger",
".",
"error",
"(",
"'[%s] Unable to build Message with data, data=%s, error'",
",",
"self",
".",
"engine_name",
",",
"data",
")",
"return",
"logger",
".",
"info",
"(",
"'[%s] New message from %s: %s'",
",",
"self",
".",
"engine_name",
",",
"message",
".",
"user",
",",
"message",
".",
"text",
")",
"response",
"=",
"await",
"self",
".",
"get_response",
"(",
"message",
")",
"if",
"response",
":",
"await",
"self",
".",
"send_response",
"(",
"response",
")"
] |
1c724b867fa16708d59a3dbba5dd2c3de85147a9
|
valid
|
diff
|
Diff elements of a sequence:
s -> s0 - s1, s1 - s2, s2 - s3, ...
|
mat4py/loadmat.py
|
def diff(iterable):
"""Diff elements of a sequence:
s -> s0 - s1, s1 - s2, s2 - s3, ...
"""
a, b = tee(iterable)
next(b, None)
return (i - j for i, j in izip(a, b))
|
def diff(iterable):
"""Diff elements of a sequence:
s -> s0 - s1, s1 - s2, s2 - s3, ...
"""
a, b = tee(iterable)
next(b, None)
return (i - j for i, j in izip(a, b))
|
[
"Diff",
"elements",
"of",
"a",
"sequence",
":",
"s",
"-",
">",
"s0",
"-",
"s1",
"s1",
"-",
"s2",
"s2",
"-",
"s3",
"..."
] |
nephics/mat4py
|
python
|
https://github.com/nephics/mat4py/blob/6c1a2ad903937437cc5f24f3c3f5aa2c5a77a1c1/mat4py/loadmat.py#L94-L100
|
[
"def",
"diff",
"(",
"iterable",
")",
":",
"a",
",",
"b",
"=",
"tee",
"(",
"iterable",
")",
"next",
"(",
"b",
",",
"None",
")",
"return",
"(",
"i",
"-",
"j",
"for",
"i",
",",
"j",
"in",
"izip",
"(",
"a",
",",
"b",
")",
")"
] |
6c1a2ad903937437cc5f24f3c3f5aa2c5a77a1c1
|
valid
|
unpack
|
Unpack a byte string to the given format. If the byte string
contains more bytes than required for the given format, the function
returns a tuple of values.
|
mat4py/loadmat.py
|
def unpack(endian, fmt, data):
"""Unpack a byte string to the given format. If the byte string
contains more bytes than required for the given format, the function
returns a tuple of values.
"""
if fmt == 's':
# read data as an array of chars
val = struct.unpack(''.join([endian, str(len(data)), 's']),
data)[0]
else:
# read a number of values
num = len(data) // struct.calcsize(fmt)
val = struct.unpack(''.join([endian, str(num), fmt]), data)
if len(val) == 1:
val = val[0]
return val
|
def unpack(endian, fmt, data):
"""Unpack a byte string to the given format. If the byte string
contains more bytes than required for the given format, the function
returns a tuple of values.
"""
if fmt == 's':
# read data as an array of chars
val = struct.unpack(''.join([endian, str(len(data)), 's']),
data)[0]
else:
# read a number of values
num = len(data) // struct.calcsize(fmt)
val = struct.unpack(''.join([endian, str(num), fmt]), data)
if len(val) == 1:
val = val[0]
return val
|
[
"Unpack",
"a",
"byte",
"string",
"to",
"the",
"given",
"format",
".",
"If",
"the",
"byte",
"string",
"contains",
"more",
"bytes",
"than",
"required",
"for",
"the",
"given",
"format",
"the",
"function",
"returns",
"a",
"tuple",
"of",
"values",
"."
] |
nephics/mat4py
|
python
|
https://github.com/nephics/mat4py/blob/6c1a2ad903937437cc5f24f3c3f5aa2c5a77a1c1/mat4py/loadmat.py#L107-L122
|
[
"def",
"unpack",
"(",
"endian",
",",
"fmt",
",",
"data",
")",
":",
"if",
"fmt",
"==",
"'s'",
":",
"# read data as an array of chars",
"val",
"=",
"struct",
".",
"unpack",
"(",
"''",
".",
"join",
"(",
"[",
"endian",
",",
"str",
"(",
"len",
"(",
"data",
")",
")",
",",
"'s'",
"]",
")",
",",
"data",
")",
"[",
"0",
"]",
"else",
":",
"# read a number of values",
"num",
"=",
"len",
"(",
"data",
")",
"//",
"struct",
".",
"calcsize",
"(",
"fmt",
")",
"val",
"=",
"struct",
".",
"unpack",
"(",
"''",
".",
"join",
"(",
"[",
"endian",
",",
"str",
"(",
"num",
")",
",",
"fmt",
"]",
")",
",",
"data",
")",
"if",
"len",
"(",
"val",
")",
"==",
"1",
":",
"val",
"=",
"val",
"[",
"0",
"]",
"return",
"val"
] |
6c1a2ad903937437cc5f24f3c3f5aa2c5a77a1c1
|
valid
|
read_file_header
|
Read mat 5 file header of the file fd.
Returns a dict with header values.
|
mat4py/loadmat.py
|
def read_file_header(fd, endian):
"""Read mat 5 file header of the file fd.
Returns a dict with header values.
"""
fields = [
('description', 's', 116),
('subsystem_offset', 's', 8),
('version', 'H', 2),
('endian_test', 's', 2)
]
hdict = {}
for name, fmt, num_bytes in fields:
data = fd.read(num_bytes)
hdict[name] = unpack(endian, fmt, data)
hdict['description'] = hdict['description'].strip()
v_major = hdict['version'] >> 8
v_minor = hdict['version'] & 0xFF
hdict['__version__'] = '%d.%d' % (v_major, v_minor)
return hdict
|
def read_file_header(fd, endian):
"""Read mat 5 file header of the file fd.
Returns a dict with header values.
"""
fields = [
('description', 's', 116),
('subsystem_offset', 's', 8),
('version', 'H', 2),
('endian_test', 's', 2)
]
hdict = {}
for name, fmt, num_bytes in fields:
data = fd.read(num_bytes)
hdict[name] = unpack(endian, fmt, data)
hdict['description'] = hdict['description'].strip()
v_major = hdict['version'] >> 8
v_minor = hdict['version'] & 0xFF
hdict['__version__'] = '%d.%d' % (v_major, v_minor)
return hdict
|
[
"Read",
"mat",
"5",
"file",
"header",
"of",
"the",
"file",
"fd",
".",
"Returns",
"a",
"dict",
"with",
"header",
"values",
"."
] |
nephics/mat4py
|
python
|
https://github.com/nephics/mat4py/blob/6c1a2ad903937437cc5f24f3c3f5aa2c5a77a1c1/mat4py/loadmat.py#L125-L143
|
[
"def",
"read_file_header",
"(",
"fd",
",",
"endian",
")",
":",
"fields",
"=",
"[",
"(",
"'description'",
",",
"'s'",
",",
"116",
")",
",",
"(",
"'subsystem_offset'",
",",
"'s'",
",",
"8",
")",
",",
"(",
"'version'",
",",
"'H'",
",",
"2",
")",
",",
"(",
"'endian_test'",
",",
"'s'",
",",
"2",
")",
"]",
"hdict",
"=",
"{",
"}",
"for",
"name",
",",
"fmt",
",",
"num_bytes",
"in",
"fields",
":",
"data",
"=",
"fd",
".",
"read",
"(",
"num_bytes",
")",
"hdict",
"[",
"name",
"]",
"=",
"unpack",
"(",
"endian",
",",
"fmt",
",",
"data",
")",
"hdict",
"[",
"'description'",
"]",
"=",
"hdict",
"[",
"'description'",
"]",
".",
"strip",
"(",
")",
"v_major",
"=",
"hdict",
"[",
"'version'",
"]",
">>",
"8",
"v_minor",
"=",
"hdict",
"[",
"'version'",
"]",
"&",
"0xFF",
"hdict",
"[",
"'__version__'",
"]",
"=",
"'%d.%d'",
"%",
"(",
"v_major",
",",
"v_minor",
")",
"return",
"hdict"
] |
6c1a2ad903937437cc5f24f3c3f5aa2c5a77a1c1
|
valid
|
read_element_tag
|
Read data element tag: type and number of bytes.
If tag is of the Small Data Element (SDE) type the element data
is also returned.
|
mat4py/loadmat.py
|
def read_element_tag(fd, endian):
"""Read data element tag: type and number of bytes.
If tag is of the Small Data Element (SDE) type the element data
is also returned.
"""
data = fd.read(8)
mtpn = unpack(endian, 'I', data[:4])
# The most significant two bytes of mtpn will always be 0,
# if they are not, this must be SDE format
num_bytes = mtpn >> 16
if num_bytes > 0:
# small data element format
mtpn = mtpn & 0xFFFF
if num_bytes > 4:
raise ParseError('Error parsing Small Data Element (SDE) '
'formatted data')
data = data[4:4 + num_bytes]
else:
# regular element
num_bytes = unpack(endian, 'I', data[4:])
data = None
return (mtpn, num_bytes, data)
|
def read_element_tag(fd, endian):
"""Read data element tag: type and number of bytes.
If tag is of the Small Data Element (SDE) type the element data
is also returned.
"""
data = fd.read(8)
mtpn = unpack(endian, 'I', data[:4])
# The most significant two bytes of mtpn will always be 0,
# if they are not, this must be SDE format
num_bytes = mtpn >> 16
if num_bytes > 0:
# small data element format
mtpn = mtpn & 0xFFFF
if num_bytes > 4:
raise ParseError('Error parsing Small Data Element (SDE) '
'formatted data')
data = data[4:4 + num_bytes]
else:
# regular element
num_bytes = unpack(endian, 'I', data[4:])
data = None
return (mtpn, num_bytes, data)
|
[
"Read",
"data",
"element",
"tag",
":",
"type",
"and",
"number",
"of",
"bytes",
".",
"If",
"tag",
"is",
"of",
"the",
"Small",
"Data",
"Element",
"(",
"SDE",
")",
"type",
"the",
"element",
"data",
"is",
"also",
"returned",
"."
] |
nephics/mat4py
|
python
|
https://github.com/nephics/mat4py/blob/6c1a2ad903937437cc5f24f3c3f5aa2c5a77a1c1/mat4py/loadmat.py#L146-L167
|
[
"def",
"read_element_tag",
"(",
"fd",
",",
"endian",
")",
":",
"data",
"=",
"fd",
".",
"read",
"(",
"8",
")",
"mtpn",
"=",
"unpack",
"(",
"endian",
",",
"'I'",
",",
"data",
"[",
":",
"4",
"]",
")",
"# The most significant two bytes of mtpn will always be 0,",
"# if they are not, this must be SDE format",
"num_bytes",
"=",
"mtpn",
">>",
"16",
"if",
"num_bytes",
">",
"0",
":",
"# small data element format",
"mtpn",
"=",
"mtpn",
"&",
"0xFFFF",
"if",
"num_bytes",
">",
"4",
":",
"raise",
"ParseError",
"(",
"'Error parsing Small Data Element (SDE) '",
"'formatted data'",
")",
"data",
"=",
"data",
"[",
"4",
":",
"4",
"+",
"num_bytes",
"]",
"else",
":",
"# regular element",
"num_bytes",
"=",
"unpack",
"(",
"endian",
",",
"'I'",
",",
"data",
"[",
"4",
":",
"]",
")",
"data",
"=",
"None",
"return",
"(",
"mtpn",
",",
"num_bytes",
",",
"data",
")"
] |
6c1a2ad903937437cc5f24f3c3f5aa2c5a77a1c1
|
valid
|
read_elements
|
Read elements from the file.
If list of possible matrix data types mtps is provided, the data type
of the elements are verified.
|
mat4py/loadmat.py
|
def read_elements(fd, endian, mtps, is_name=False):
"""Read elements from the file.
If list of possible matrix data types mtps is provided, the data type
of the elements are verified.
"""
mtpn, num_bytes, data = read_element_tag(fd, endian)
if mtps and mtpn not in [etypes[mtp]['n'] for mtp in mtps]:
raise ParseError('Got type {}, expected {}'.format(
mtpn, ' / '.join('{} ({})'.format(
etypes[mtp]['n'], mtp) for mtp in mtps)))
if not data:
# full format, read data
data = fd.read(num_bytes)
# Seek to next 64-bit boundary
mod8 = num_bytes % 8
if mod8:
fd.seek(8 - mod8, 1)
# parse data and return values
if is_name:
# names are stored as miINT8 bytes
fmt = 's'
val = [unpack(endian, fmt, s)
for s in data.split(b'\0') if s]
if len(val) == 0:
val = ''
elif len(val) == 1:
val = asstr(val[0])
else:
val = [asstr(s) for s in val]
else:
fmt = etypes[inv_etypes[mtpn]]['fmt']
val = unpack(endian, fmt, data)
return val
|
def read_elements(fd, endian, mtps, is_name=False):
"""Read elements from the file.
If list of possible matrix data types mtps is provided, the data type
of the elements are verified.
"""
mtpn, num_bytes, data = read_element_tag(fd, endian)
if mtps and mtpn not in [etypes[mtp]['n'] for mtp in mtps]:
raise ParseError('Got type {}, expected {}'.format(
mtpn, ' / '.join('{} ({})'.format(
etypes[mtp]['n'], mtp) for mtp in mtps)))
if not data:
# full format, read data
data = fd.read(num_bytes)
# Seek to next 64-bit boundary
mod8 = num_bytes % 8
if mod8:
fd.seek(8 - mod8, 1)
# parse data and return values
if is_name:
# names are stored as miINT8 bytes
fmt = 's'
val = [unpack(endian, fmt, s)
for s in data.split(b'\0') if s]
if len(val) == 0:
val = ''
elif len(val) == 1:
val = asstr(val[0])
else:
val = [asstr(s) for s in val]
else:
fmt = etypes[inv_etypes[mtpn]]['fmt']
val = unpack(endian, fmt, data)
return val
|
[
"Read",
"elements",
"from",
"the",
"file",
"."
] |
nephics/mat4py
|
python
|
https://github.com/nephics/mat4py/blob/6c1a2ad903937437cc5f24f3c3f5aa2c5a77a1c1/mat4py/loadmat.py#L170-L204
|
[
"def",
"read_elements",
"(",
"fd",
",",
"endian",
",",
"mtps",
",",
"is_name",
"=",
"False",
")",
":",
"mtpn",
",",
"num_bytes",
",",
"data",
"=",
"read_element_tag",
"(",
"fd",
",",
"endian",
")",
"if",
"mtps",
"and",
"mtpn",
"not",
"in",
"[",
"etypes",
"[",
"mtp",
"]",
"[",
"'n'",
"]",
"for",
"mtp",
"in",
"mtps",
"]",
":",
"raise",
"ParseError",
"(",
"'Got type {}, expected {}'",
".",
"format",
"(",
"mtpn",
",",
"' / '",
".",
"join",
"(",
"'{} ({})'",
".",
"format",
"(",
"etypes",
"[",
"mtp",
"]",
"[",
"'n'",
"]",
",",
"mtp",
")",
"for",
"mtp",
"in",
"mtps",
")",
")",
")",
"if",
"not",
"data",
":",
"# full format, read data",
"data",
"=",
"fd",
".",
"read",
"(",
"num_bytes",
")",
"# Seek to next 64-bit boundary",
"mod8",
"=",
"num_bytes",
"%",
"8",
"if",
"mod8",
":",
"fd",
".",
"seek",
"(",
"8",
"-",
"mod8",
",",
"1",
")",
"# parse data and return values",
"if",
"is_name",
":",
"# names are stored as miINT8 bytes",
"fmt",
"=",
"'s'",
"val",
"=",
"[",
"unpack",
"(",
"endian",
",",
"fmt",
",",
"s",
")",
"for",
"s",
"in",
"data",
".",
"split",
"(",
"b'\\0'",
")",
"if",
"s",
"]",
"if",
"len",
"(",
"val",
")",
"==",
"0",
":",
"val",
"=",
"''",
"elif",
"len",
"(",
"val",
")",
"==",
"1",
":",
"val",
"=",
"asstr",
"(",
"val",
"[",
"0",
"]",
")",
"else",
":",
"val",
"=",
"[",
"asstr",
"(",
"s",
")",
"for",
"s",
"in",
"val",
"]",
"else",
":",
"fmt",
"=",
"etypes",
"[",
"inv_etypes",
"[",
"mtpn",
"]",
"]",
"[",
"'fmt'",
"]",
"val",
"=",
"unpack",
"(",
"endian",
",",
"fmt",
",",
"data",
")",
"return",
"val"
] |
6c1a2ad903937437cc5f24f3c3f5aa2c5a77a1c1
|
valid
|
read_header
|
Read and return the matrix header.
|
mat4py/loadmat.py
|
def read_header(fd, endian):
"""Read and return the matrix header."""
flag_class, nzmax = read_elements(fd, endian, ['miUINT32'])
header = {
'mclass': flag_class & 0x0FF,
'is_logical': (flag_class >> 9 & 1) == 1,
'is_global': (flag_class >> 10 & 1) == 1,
'is_complex': (flag_class >> 11 & 1) == 1,
'nzmax': nzmax
}
header['dims'] = read_elements(fd, endian, ['miINT32'])
header['n_dims'] = len(header['dims'])
if header['n_dims'] != 2:
raise ParseError('Only matrices with dimension 2 are supported.')
header['name'] = read_elements(fd, endian, ['miINT8'], is_name=True)
return header
|
def read_header(fd, endian):
"""Read and return the matrix header."""
flag_class, nzmax = read_elements(fd, endian, ['miUINT32'])
header = {
'mclass': flag_class & 0x0FF,
'is_logical': (flag_class >> 9 & 1) == 1,
'is_global': (flag_class >> 10 & 1) == 1,
'is_complex': (flag_class >> 11 & 1) == 1,
'nzmax': nzmax
}
header['dims'] = read_elements(fd, endian, ['miINT32'])
header['n_dims'] = len(header['dims'])
if header['n_dims'] != 2:
raise ParseError('Only matrices with dimension 2 are supported.')
header['name'] = read_elements(fd, endian, ['miINT8'], is_name=True)
return header
|
[
"Read",
"and",
"return",
"the",
"matrix",
"header",
"."
] |
nephics/mat4py
|
python
|
https://github.com/nephics/mat4py/blob/6c1a2ad903937437cc5f24f3c3f5aa2c5a77a1c1/mat4py/loadmat.py#L207-L222
|
[
"def",
"read_header",
"(",
"fd",
",",
"endian",
")",
":",
"flag_class",
",",
"nzmax",
"=",
"read_elements",
"(",
"fd",
",",
"endian",
",",
"[",
"'miUINT32'",
"]",
")",
"header",
"=",
"{",
"'mclass'",
":",
"flag_class",
"&",
"0x0FF",
",",
"'is_logical'",
":",
"(",
"flag_class",
">>",
"9",
"&",
"1",
")",
"==",
"1",
",",
"'is_global'",
":",
"(",
"flag_class",
">>",
"10",
"&",
"1",
")",
"==",
"1",
",",
"'is_complex'",
":",
"(",
"flag_class",
">>",
"11",
"&",
"1",
")",
"==",
"1",
",",
"'nzmax'",
":",
"nzmax",
"}",
"header",
"[",
"'dims'",
"]",
"=",
"read_elements",
"(",
"fd",
",",
"endian",
",",
"[",
"'miINT32'",
"]",
")",
"header",
"[",
"'n_dims'",
"]",
"=",
"len",
"(",
"header",
"[",
"'dims'",
"]",
")",
"if",
"header",
"[",
"'n_dims'",
"]",
"!=",
"2",
":",
"raise",
"ParseError",
"(",
"'Only matrices with dimension 2 are supported.'",
")",
"header",
"[",
"'name'",
"]",
"=",
"read_elements",
"(",
"fd",
",",
"endian",
",",
"[",
"'miINT8'",
"]",
",",
"is_name",
"=",
"True",
")",
"return",
"header"
] |
6c1a2ad903937437cc5f24f3c3f5aa2c5a77a1c1
|
valid
|
read_var_header
|
Read full header tag.
Return a dict with the parsed header, the file position of next tag,
a file like object for reading the uncompressed element data.
|
mat4py/loadmat.py
|
def read_var_header(fd, endian):
"""Read full header tag.
Return a dict with the parsed header, the file position of next tag,
a file like object for reading the uncompressed element data.
"""
mtpn, num_bytes = unpack(endian, 'II', fd.read(8))
next_pos = fd.tell() + num_bytes
if mtpn == etypes['miCOMPRESSED']['n']:
# read compressed data
data = fd.read(num_bytes)
dcor = zlib.decompressobj()
# from here, read of the decompressed data
fd_var = BytesIO(dcor.decompress(data))
del data
fd = fd_var
# Check the stream is not so broken as to leave cruft behind
if dcor.flush() != b'':
raise ParseError('Error in compressed data.')
# read full tag from the uncompressed data
mtpn, num_bytes = unpack(endian, 'II', fd.read(8))
if mtpn != etypes['miMATRIX']['n']:
raise ParseError('Expecting miMATRIX type number {}, '
'got {}'.format(etypes['miMATRIX']['n'], mtpn))
# read the header
header = read_header(fd, endian)
return header, next_pos, fd
|
def read_var_header(fd, endian):
"""Read full header tag.
Return a dict with the parsed header, the file position of next tag,
a file like object for reading the uncompressed element data.
"""
mtpn, num_bytes = unpack(endian, 'II', fd.read(8))
next_pos = fd.tell() + num_bytes
if mtpn == etypes['miCOMPRESSED']['n']:
# read compressed data
data = fd.read(num_bytes)
dcor = zlib.decompressobj()
# from here, read of the decompressed data
fd_var = BytesIO(dcor.decompress(data))
del data
fd = fd_var
# Check the stream is not so broken as to leave cruft behind
if dcor.flush() != b'':
raise ParseError('Error in compressed data.')
# read full tag from the uncompressed data
mtpn, num_bytes = unpack(endian, 'II', fd.read(8))
if mtpn != etypes['miMATRIX']['n']:
raise ParseError('Expecting miMATRIX type number {}, '
'got {}'.format(etypes['miMATRIX']['n'], mtpn))
# read the header
header = read_header(fd, endian)
return header, next_pos, fd
|
[
"Read",
"full",
"header",
"tag",
"."
] |
nephics/mat4py
|
python
|
https://github.com/nephics/mat4py/blob/6c1a2ad903937437cc5f24f3c3f5aa2c5a77a1c1/mat4py/loadmat.py#L225-L253
|
[
"def",
"read_var_header",
"(",
"fd",
",",
"endian",
")",
":",
"mtpn",
",",
"num_bytes",
"=",
"unpack",
"(",
"endian",
",",
"'II'",
",",
"fd",
".",
"read",
"(",
"8",
")",
")",
"next_pos",
"=",
"fd",
".",
"tell",
"(",
")",
"+",
"num_bytes",
"if",
"mtpn",
"==",
"etypes",
"[",
"'miCOMPRESSED'",
"]",
"[",
"'n'",
"]",
":",
"# read compressed data",
"data",
"=",
"fd",
".",
"read",
"(",
"num_bytes",
")",
"dcor",
"=",
"zlib",
".",
"decompressobj",
"(",
")",
"# from here, read of the decompressed data",
"fd_var",
"=",
"BytesIO",
"(",
"dcor",
".",
"decompress",
"(",
"data",
")",
")",
"del",
"data",
"fd",
"=",
"fd_var",
"# Check the stream is not so broken as to leave cruft behind",
"if",
"dcor",
".",
"flush",
"(",
")",
"!=",
"b''",
":",
"raise",
"ParseError",
"(",
"'Error in compressed data.'",
")",
"# read full tag from the uncompressed data",
"mtpn",
",",
"num_bytes",
"=",
"unpack",
"(",
"endian",
",",
"'II'",
",",
"fd",
".",
"read",
"(",
"8",
")",
")",
"if",
"mtpn",
"!=",
"etypes",
"[",
"'miMATRIX'",
"]",
"[",
"'n'",
"]",
":",
"raise",
"ParseError",
"(",
"'Expecting miMATRIX type number {}, '",
"'got {}'",
".",
"format",
"(",
"etypes",
"[",
"'miMATRIX'",
"]",
"[",
"'n'",
"]",
",",
"mtpn",
")",
")",
"# read the header",
"header",
"=",
"read_header",
"(",
"fd",
",",
"endian",
")",
"return",
"header",
",",
"next_pos",
",",
"fd"
] |
6c1a2ad903937437cc5f24f3c3f5aa2c5a77a1c1
|
valid
|
read_numeric_array
|
Read a numeric matrix.
Returns an array with rows of the numeric matrix.
|
mat4py/loadmat.py
|
def read_numeric_array(fd, endian, header, data_etypes):
"""Read a numeric matrix.
Returns an array with rows of the numeric matrix.
"""
if header['is_complex']:
raise ParseError('Complex arrays are not supported')
# read array data (stored as column-major)
data = read_elements(fd, endian, data_etypes)
if not isinstance(data, Sequence):
# not an array, just a value
return data
# transform column major data continous array to
# a row major array of nested lists
rowcount = header['dims'][0]
colcount = header['dims'][1]
array = [list(data[c * rowcount + r] for c in range(colcount))
for r in range(rowcount)]
# pack and return the array
return squeeze(array)
|
def read_numeric_array(fd, endian, header, data_etypes):
"""Read a numeric matrix.
Returns an array with rows of the numeric matrix.
"""
if header['is_complex']:
raise ParseError('Complex arrays are not supported')
# read array data (stored as column-major)
data = read_elements(fd, endian, data_etypes)
if not isinstance(data, Sequence):
# not an array, just a value
return data
# transform column major data continous array to
# a row major array of nested lists
rowcount = header['dims'][0]
colcount = header['dims'][1]
array = [list(data[c * rowcount + r] for c in range(colcount))
for r in range(rowcount)]
# pack and return the array
return squeeze(array)
|
[
"Read",
"a",
"numeric",
"matrix",
".",
"Returns",
"an",
"array",
"with",
"rows",
"of",
"the",
"numeric",
"matrix",
"."
] |
nephics/mat4py
|
python
|
https://github.com/nephics/mat4py/blob/6c1a2ad903937437cc5f24f3c3f5aa2c5a77a1c1/mat4py/loadmat.py#L265-L283
|
[
"def",
"read_numeric_array",
"(",
"fd",
",",
"endian",
",",
"header",
",",
"data_etypes",
")",
":",
"if",
"header",
"[",
"'is_complex'",
"]",
":",
"raise",
"ParseError",
"(",
"'Complex arrays are not supported'",
")",
"# read array data (stored as column-major)",
"data",
"=",
"read_elements",
"(",
"fd",
",",
"endian",
",",
"data_etypes",
")",
"if",
"not",
"isinstance",
"(",
"data",
",",
"Sequence",
")",
":",
"# not an array, just a value",
"return",
"data",
"# transform column major data continous array to",
"# a row major array of nested lists",
"rowcount",
"=",
"header",
"[",
"'dims'",
"]",
"[",
"0",
"]",
"colcount",
"=",
"header",
"[",
"'dims'",
"]",
"[",
"1",
"]",
"array",
"=",
"[",
"list",
"(",
"data",
"[",
"c",
"*",
"rowcount",
"+",
"r",
"]",
"for",
"c",
"in",
"range",
"(",
"colcount",
")",
")",
"for",
"r",
"in",
"range",
"(",
"rowcount",
")",
"]",
"# pack and return the array",
"return",
"squeeze",
"(",
"array",
")"
] |
6c1a2ad903937437cc5f24f3c3f5aa2c5a77a1c1
|
valid
|
read_cell_array
|
Read a cell array.
Returns an array with rows of the cell array.
|
mat4py/loadmat.py
|
def read_cell_array(fd, endian, header):
"""Read a cell array.
Returns an array with rows of the cell array.
"""
array = [list() for i in range(header['dims'][0])]
for row in range(header['dims'][0]):
for col in range(header['dims'][1]):
# read the matrix header and array
vheader, next_pos, fd_var = read_var_header(fd, endian)
varray = read_var_array(fd_var, endian, vheader)
array[row].append(varray)
# move on to next field
fd.seek(next_pos)
# pack and return the array
if header['dims'][0] == 1:
return squeeze(array[0])
return squeeze(array)
|
def read_cell_array(fd, endian, header):
"""Read a cell array.
Returns an array with rows of the cell array.
"""
array = [list() for i in range(header['dims'][0])]
for row in range(header['dims'][0]):
for col in range(header['dims'][1]):
# read the matrix header and array
vheader, next_pos, fd_var = read_var_header(fd, endian)
varray = read_var_array(fd_var, endian, vheader)
array[row].append(varray)
# move on to next field
fd.seek(next_pos)
# pack and return the array
if header['dims'][0] == 1:
return squeeze(array[0])
return squeeze(array)
|
[
"Read",
"a",
"cell",
"array",
".",
"Returns",
"an",
"array",
"with",
"rows",
"of",
"the",
"cell",
"array",
"."
] |
nephics/mat4py
|
python
|
https://github.com/nephics/mat4py/blob/6c1a2ad903937437cc5f24f3c3f5aa2c5a77a1c1/mat4py/loadmat.py#L286-L302
|
[
"def",
"read_cell_array",
"(",
"fd",
",",
"endian",
",",
"header",
")",
":",
"array",
"=",
"[",
"list",
"(",
")",
"for",
"i",
"in",
"range",
"(",
"header",
"[",
"'dims'",
"]",
"[",
"0",
"]",
")",
"]",
"for",
"row",
"in",
"range",
"(",
"header",
"[",
"'dims'",
"]",
"[",
"0",
"]",
")",
":",
"for",
"col",
"in",
"range",
"(",
"header",
"[",
"'dims'",
"]",
"[",
"1",
"]",
")",
":",
"# read the matrix header and array",
"vheader",
",",
"next_pos",
",",
"fd_var",
"=",
"read_var_header",
"(",
"fd",
",",
"endian",
")",
"varray",
"=",
"read_var_array",
"(",
"fd_var",
",",
"endian",
",",
"vheader",
")",
"array",
"[",
"row",
"]",
".",
"append",
"(",
"varray",
")",
"# move on to next field",
"fd",
".",
"seek",
"(",
"next_pos",
")",
"# pack and return the array",
"if",
"header",
"[",
"'dims'",
"]",
"[",
"0",
"]",
"==",
"1",
":",
"return",
"squeeze",
"(",
"array",
"[",
"0",
"]",
")",
"return",
"squeeze",
"(",
"array",
")"
] |
6c1a2ad903937437cc5f24f3c3f5aa2c5a77a1c1
|
valid
|
read_struct_array
|
Read a struct array.
Returns a dict with fields of the struct array.
|
mat4py/loadmat.py
|
def read_struct_array(fd, endian, header):
"""Read a struct array.
Returns a dict with fields of the struct array.
"""
# read field name length (unused, as strings are null terminated)
field_name_length = read_elements(fd, endian, ['miINT32'])
if field_name_length > 32:
raise ParseError('Unexpected field name length: {}'.format(
field_name_length))
# read field names
fields = read_elements(fd, endian, ['miINT8'], is_name=True)
if isinstance(fields, basestring):
fields = [fields]
# read rows and columns of each field
empty = lambda: [list() for i in range(header['dims'][0])]
array = {}
for row in range(header['dims'][0]):
for col in range(header['dims'][1]):
for field in fields:
# read the matrix header and array
vheader, next_pos, fd_var = read_var_header(fd, endian)
data = read_var_array(fd_var, endian, vheader)
if field not in array:
array[field] = empty()
array[field][row].append(data)
# move on to next field
fd.seek(next_pos)
# pack the nested arrays
for field in fields:
rows = array[field]
for i in range(header['dims'][0]):
rows[i] = squeeze(rows[i])
array[field] = squeeze(array[field])
return array
|
def read_struct_array(fd, endian, header):
"""Read a struct array.
Returns a dict with fields of the struct array.
"""
# read field name length (unused, as strings are null terminated)
field_name_length = read_elements(fd, endian, ['miINT32'])
if field_name_length > 32:
raise ParseError('Unexpected field name length: {}'.format(
field_name_length))
# read field names
fields = read_elements(fd, endian, ['miINT8'], is_name=True)
if isinstance(fields, basestring):
fields = [fields]
# read rows and columns of each field
empty = lambda: [list() for i in range(header['dims'][0])]
array = {}
for row in range(header['dims'][0]):
for col in range(header['dims'][1]):
for field in fields:
# read the matrix header and array
vheader, next_pos, fd_var = read_var_header(fd, endian)
data = read_var_array(fd_var, endian, vheader)
if field not in array:
array[field] = empty()
array[field][row].append(data)
# move on to next field
fd.seek(next_pos)
# pack the nested arrays
for field in fields:
rows = array[field]
for i in range(header['dims'][0]):
rows[i] = squeeze(rows[i])
array[field] = squeeze(array[field])
return array
|
[
"Read",
"a",
"struct",
"array",
".",
"Returns",
"a",
"dict",
"with",
"fields",
"of",
"the",
"struct",
"array",
"."
] |
nephics/mat4py
|
python
|
https://github.com/nephics/mat4py/blob/6c1a2ad903937437cc5f24f3c3f5aa2c5a77a1c1/mat4py/loadmat.py#L305-L340
|
[
"def",
"read_struct_array",
"(",
"fd",
",",
"endian",
",",
"header",
")",
":",
"# read field name length (unused, as strings are null terminated)",
"field_name_length",
"=",
"read_elements",
"(",
"fd",
",",
"endian",
",",
"[",
"'miINT32'",
"]",
")",
"if",
"field_name_length",
">",
"32",
":",
"raise",
"ParseError",
"(",
"'Unexpected field name length: {}'",
".",
"format",
"(",
"field_name_length",
")",
")",
"# read field names",
"fields",
"=",
"read_elements",
"(",
"fd",
",",
"endian",
",",
"[",
"'miINT8'",
"]",
",",
"is_name",
"=",
"True",
")",
"if",
"isinstance",
"(",
"fields",
",",
"basestring",
")",
":",
"fields",
"=",
"[",
"fields",
"]",
"# read rows and columns of each field",
"empty",
"=",
"lambda",
":",
"[",
"list",
"(",
")",
"for",
"i",
"in",
"range",
"(",
"header",
"[",
"'dims'",
"]",
"[",
"0",
"]",
")",
"]",
"array",
"=",
"{",
"}",
"for",
"row",
"in",
"range",
"(",
"header",
"[",
"'dims'",
"]",
"[",
"0",
"]",
")",
":",
"for",
"col",
"in",
"range",
"(",
"header",
"[",
"'dims'",
"]",
"[",
"1",
"]",
")",
":",
"for",
"field",
"in",
"fields",
":",
"# read the matrix header and array",
"vheader",
",",
"next_pos",
",",
"fd_var",
"=",
"read_var_header",
"(",
"fd",
",",
"endian",
")",
"data",
"=",
"read_var_array",
"(",
"fd_var",
",",
"endian",
",",
"vheader",
")",
"if",
"field",
"not",
"in",
"array",
":",
"array",
"[",
"field",
"]",
"=",
"empty",
"(",
")",
"array",
"[",
"field",
"]",
"[",
"row",
"]",
".",
"append",
"(",
"data",
")",
"# move on to next field",
"fd",
".",
"seek",
"(",
"next_pos",
")",
"# pack the nested arrays",
"for",
"field",
"in",
"fields",
":",
"rows",
"=",
"array",
"[",
"field",
"]",
"for",
"i",
"in",
"range",
"(",
"header",
"[",
"'dims'",
"]",
"[",
"0",
"]",
")",
":",
"rows",
"[",
"i",
"]",
"=",
"squeeze",
"(",
"rows",
"[",
"i",
"]",
")",
"array",
"[",
"field",
"]",
"=",
"squeeze",
"(",
"array",
"[",
"field",
"]",
")",
"return",
"array"
] |
6c1a2ad903937437cc5f24f3c3f5aa2c5a77a1c1
|
valid
|
read_var_array
|
Read variable array (of any supported type).
|
mat4py/loadmat.py
|
def read_var_array(fd, endian, header):
"""Read variable array (of any supported type)."""
mc = inv_mclasses[header['mclass']]
if mc in numeric_class_etypes:
return read_numeric_array(
fd, endian, header,
set(compressed_numeric).union([numeric_class_etypes[mc]])
)
elif mc == 'mxSPARSE_CLASS':
raise ParseError('Sparse matrices not supported')
elif mc == 'mxCHAR_CLASS':
return read_char_array(fd, endian, header)
elif mc == 'mxCELL_CLASS':
return read_cell_array(fd, endian, header)
elif mc == 'mxSTRUCT_CLASS':
return read_struct_array(fd, endian, header)
elif mc == 'mxOBJECT_CLASS':
raise ParseError('Object classes not supported')
elif mc == 'mxFUNCTION_CLASS':
raise ParseError('Function classes not supported')
elif mc == 'mxOPAQUE_CLASS':
raise ParseError('Anonymous function classes not supported')
|
def read_var_array(fd, endian, header):
"""Read variable array (of any supported type)."""
mc = inv_mclasses[header['mclass']]
if mc in numeric_class_etypes:
return read_numeric_array(
fd, endian, header,
set(compressed_numeric).union([numeric_class_etypes[mc]])
)
elif mc == 'mxSPARSE_CLASS':
raise ParseError('Sparse matrices not supported')
elif mc == 'mxCHAR_CLASS':
return read_char_array(fd, endian, header)
elif mc == 'mxCELL_CLASS':
return read_cell_array(fd, endian, header)
elif mc == 'mxSTRUCT_CLASS':
return read_struct_array(fd, endian, header)
elif mc == 'mxOBJECT_CLASS':
raise ParseError('Object classes not supported')
elif mc == 'mxFUNCTION_CLASS':
raise ParseError('Function classes not supported')
elif mc == 'mxOPAQUE_CLASS':
raise ParseError('Anonymous function classes not supported')
|
[
"Read",
"variable",
"array",
"(",
"of",
"any",
"supported",
"type",
")",
"."
] |
nephics/mat4py
|
python
|
https://github.com/nephics/mat4py/blob/6c1a2ad903937437cc5f24f3c3f5aa2c5a77a1c1/mat4py/loadmat.py#L354-L376
|
[
"def",
"read_var_array",
"(",
"fd",
",",
"endian",
",",
"header",
")",
":",
"mc",
"=",
"inv_mclasses",
"[",
"header",
"[",
"'mclass'",
"]",
"]",
"if",
"mc",
"in",
"numeric_class_etypes",
":",
"return",
"read_numeric_array",
"(",
"fd",
",",
"endian",
",",
"header",
",",
"set",
"(",
"compressed_numeric",
")",
".",
"union",
"(",
"[",
"numeric_class_etypes",
"[",
"mc",
"]",
"]",
")",
")",
"elif",
"mc",
"==",
"'mxSPARSE_CLASS'",
":",
"raise",
"ParseError",
"(",
"'Sparse matrices not supported'",
")",
"elif",
"mc",
"==",
"'mxCHAR_CLASS'",
":",
"return",
"read_char_array",
"(",
"fd",
",",
"endian",
",",
"header",
")",
"elif",
"mc",
"==",
"'mxCELL_CLASS'",
":",
"return",
"read_cell_array",
"(",
"fd",
",",
"endian",
",",
"header",
")",
"elif",
"mc",
"==",
"'mxSTRUCT_CLASS'",
":",
"return",
"read_struct_array",
"(",
"fd",
",",
"endian",
",",
"header",
")",
"elif",
"mc",
"==",
"'mxOBJECT_CLASS'",
":",
"raise",
"ParseError",
"(",
"'Object classes not supported'",
")",
"elif",
"mc",
"==",
"'mxFUNCTION_CLASS'",
":",
"raise",
"ParseError",
"(",
"'Function classes not supported'",
")",
"elif",
"mc",
"==",
"'mxOPAQUE_CLASS'",
":",
"raise",
"ParseError",
"(",
"'Anonymous function classes not supported'",
")"
] |
6c1a2ad903937437cc5f24f3c3f5aa2c5a77a1c1
|
valid
|
eof
|
Determine if end-of-file is reached for file fd.
|
mat4py/loadmat.py
|
def eof(fd):
"""Determine if end-of-file is reached for file fd."""
b = fd.read(1)
end = len(b) == 0
if not end:
curpos = fd.tell()
fd.seek(curpos - 1)
return end
|
def eof(fd):
"""Determine if end-of-file is reached for file fd."""
b = fd.read(1)
end = len(b) == 0
if not end:
curpos = fd.tell()
fd.seek(curpos - 1)
return end
|
[
"Determine",
"if",
"end",
"-",
"of",
"-",
"file",
"is",
"reached",
"for",
"file",
"fd",
"."
] |
nephics/mat4py
|
python
|
https://github.com/nephics/mat4py/blob/6c1a2ad903937437cc5f24f3c3f5aa2c5a77a1c1/mat4py/loadmat.py#L379-L386
|
[
"def",
"eof",
"(",
"fd",
")",
":",
"b",
"=",
"fd",
".",
"read",
"(",
"1",
")",
"end",
"=",
"len",
"(",
"b",
")",
"==",
"0",
"if",
"not",
"end",
":",
"curpos",
"=",
"fd",
".",
"tell",
"(",
")",
"fd",
".",
"seek",
"(",
"curpos",
"-",
"1",
")",
"return",
"end"
] |
6c1a2ad903937437cc5f24f3c3f5aa2c5a77a1c1
|
valid
|
loadmat
|
Load data from MAT-file:
data = loadmat(filename, meta=False)
The filename argument is either a string with the filename, or
a file like object.
The returned parameter ``data`` is a dict with the variables found
in the MAT file.
Call ``loadmat`` with parameter meta=True to include meta data, such
as file header information and list of globals.
A ``ParseError`` exception is raised if the MAT-file is corrupt or
contains a data type that cannot be parsed.
|
mat4py/loadmat.py
|
def loadmat(filename, meta=False):
"""Load data from MAT-file:
data = loadmat(filename, meta=False)
The filename argument is either a string with the filename, or
a file like object.
The returned parameter ``data`` is a dict with the variables found
in the MAT file.
Call ``loadmat`` with parameter meta=True to include meta data, such
as file header information and list of globals.
A ``ParseError`` exception is raised if the MAT-file is corrupt or
contains a data type that cannot be parsed.
"""
if isinstance(filename, basestring):
fd = open(filename, 'rb')
else:
fd = filename
# Check mat file format is version 5
# For 5 format we need to read an integer in the header.
# Bytes 124 through 128 contain a version integer and an
# endian test string
fd.seek(124)
tst_str = fd.read(4)
little_endian = (tst_str[2:4] == b'IM')
endian = ''
if (sys.byteorder == 'little' and little_endian) or \
(sys.byteorder == 'big' and not little_endian):
# no byte swapping same endian
pass
elif sys.byteorder == 'little':
# byte swapping
endian = '>'
else:
# byte swapping
endian = '<'
maj_ind = int(little_endian)
# major version number
maj_val = ord(tst_str[maj_ind]) if ispy2 else tst_str[maj_ind]
if maj_val != 1:
raise ParseError('Can only read from Matlab level 5 MAT-files')
# the minor version number (unused value)
# min_val = ord(tst_str[1 - maj_ind]) if ispy2 else tst_str[1 - maj_ind]
mdict = {}
if meta:
# read the file header
fd.seek(0)
mdict['__header__'] = read_file_header(fd, endian)
mdict['__globals__'] = []
# read data elements
while not eof(fd):
hdr, next_position, fd_var = read_var_header(fd, endian)
name = hdr['name']
if name in mdict:
raise ParseError('Duplicate variable name "{}" in mat file.'
.format(name))
# read the matrix
mdict[name] = read_var_array(fd_var, endian, hdr)
if meta and hdr['is_global']:
mdict['__globals__'].append(name)
# move on to next entry in file
fd.seek(next_position)
fd.close()
return mdict
|
def loadmat(filename, meta=False):
"""Load data from MAT-file:
data = loadmat(filename, meta=False)
The filename argument is either a string with the filename, or
a file like object.
The returned parameter ``data`` is a dict with the variables found
in the MAT file.
Call ``loadmat`` with parameter meta=True to include meta data, such
as file header information and list of globals.
A ``ParseError`` exception is raised if the MAT-file is corrupt or
contains a data type that cannot be parsed.
"""
if isinstance(filename, basestring):
fd = open(filename, 'rb')
else:
fd = filename
# Check mat file format is version 5
# For 5 format we need to read an integer in the header.
# Bytes 124 through 128 contain a version integer and an
# endian test string
fd.seek(124)
tst_str = fd.read(4)
little_endian = (tst_str[2:4] == b'IM')
endian = ''
if (sys.byteorder == 'little' and little_endian) or \
(sys.byteorder == 'big' and not little_endian):
# no byte swapping same endian
pass
elif sys.byteorder == 'little':
# byte swapping
endian = '>'
else:
# byte swapping
endian = '<'
maj_ind = int(little_endian)
# major version number
maj_val = ord(tst_str[maj_ind]) if ispy2 else tst_str[maj_ind]
if maj_val != 1:
raise ParseError('Can only read from Matlab level 5 MAT-files')
# the minor version number (unused value)
# min_val = ord(tst_str[1 - maj_ind]) if ispy2 else tst_str[1 - maj_ind]
mdict = {}
if meta:
# read the file header
fd.seek(0)
mdict['__header__'] = read_file_header(fd, endian)
mdict['__globals__'] = []
# read data elements
while not eof(fd):
hdr, next_position, fd_var = read_var_header(fd, endian)
name = hdr['name']
if name in mdict:
raise ParseError('Duplicate variable name "{}" in mat file.'
.format(name))
# read the matrix
mdict[name] = read_var_array(fd_var, endian, hdr)
if meta and hdr['is_global']:
mdict['__globals__'].append(name)
# move on to next entry in file
fd.seek(next_position)
fd.close()
return mdict
|
[
"Load",
"data",
"from",
"MAT",
"-",
"file",
":"
] |
nephics/mat4py
|
python
|
https://github.com/nephics/mat4py/blob/6c1a2ad903937437cc5f24f3c3f5aa2c5a77a1c1/mat4py/loadmat.py#L398-L471
|
[
"def",
"loadmat",
"(",
"filename",
",",
"meta",
"=",
"False",
")",
":",
"if",
"isinstance",
"(",
"filename",
",",
"basestring",
")",
":",
"fd",
"=",
"open",
"(",
"filename",
",",
"'rb'",
")",
"else",
":",
"fd",
"=",
"filename",
"# Check mat file format is version 5",
"# For 5 format we need to read an integer in the header.",
"# Bytes 124 through 128 contain a version integer and an",
"# endian test string",
"fd",
".",
"seek",
"(",
"124",
")",
"tst_str",
"=",
"fd",
".",
"read",
"(",
"4",
")",
"little_endian",
"=",
"(",
"tst_str",
"[",
"2",
":",
"4",
"]",
"==",
"b'IM'",
")",
"endian",
"=",
"''",
"if",
"(",
"sys",
".",
"byteorder",
"==",
"'little'",
"and",
"little_endian",
")",
"or",
"(",
"sys",
".",
"byteorder",
"==",
"'big'",
"and",
"not",
"little_endian",
")",
":",
"# no byte swapping same endian",
"pass",
"elif",
"sys",
".",
"byteorder",
"==",
"'little'",
":",
"# byte swapping",
"endian",
"=",
"'>'",
"else",
":",
"# byte swapping",
"endian",
"=",
"'<'",
"maj_ind",
"=",
"int",
"(",
"little_endian",
")",
"# major version number",
"maj_val",
"=",
"ord",
"(",
"tst_str",
"[",
"maj_ind",
"]",
")",
"if",
"ispy2",
"else",
"tst_str",
"[",
"maj_ind",
"]",
"if",
"maj_val",
"!=",
"1",
":",
"raise",
"ParseError",
"(",
"'Can only read from Matlab level 5 MAT-files'",
")",
"# the minor version number (unused value)",
"# min_val = ord(tst_str[1 - maj_ind]) if ispy2 else tst_str[1 - maj_ind]",
"mdict",
"=",
"{",
"}",
"if",
"meta",
":",
"# read the file header",
"fd",
".",
"seek",
"(",
"0",
")",
"mdict",
"[",
"'__header__'",
"]",
"=",
"read_file_header",
"(",
"fd",
",",
"endian",
")",
"mdict",
"[",
"'__globals__'",
"]",
"=",
"[",
"]",
"# read data elements",
"while",
"not",
"eof",
"(",
"fd",
")",
":",
"hdr",
",",
"next_position",
",",
"fd_var",
"=",
"read_var_header",
"(",
"fd",
",",
"endian",
")",
"name",
"=",
"hdr",
"[",
"'name'",
"]",
"if",
"name",
"in",
"mdict",
":",
"raise",
"ParseError",
"(",
"'Duplicate variable name \"{}\" in mat file.'",
".",
"format",
"(",
"name",
")",
")",
"# read the matrix",
"mdict",
"[",
"name",
"]",
"=",
"read_var_array",
"(",
"fd_var",
",",
"endian",
",",
"hdr",
")",
"if",
"meta",
"and",
"hdr",
"[",
"'is_global'",
"]",
":",
"mdict",
"[",
"'__globals__'",
"]",
".",
"append",
"(",
"name",
")",
"# move on to next entry in file",
"fd",
".",
"seek",
"(",
"next_position",
")",
"fd",
".",
"close",
"(",
")",
"return",
"mdict"
] |
6c1a2ad903937437cc5f24f3c3f5aa2c5a77a1c1
|
valid
|
write_elements
|
Write data element tag and data.
The tag contains the array type and the number of
bytes the array data will occupy when written to file.
If data occupies 4 bytes or less, it is written immediately
as a Small Data Element (SDE).
|
mat4py/savemat.py
|
def write_elements(fd, mtp, data, is_name=False):
"""Write data element tag and data.
The tag contains the array type and the number of
bytes the array data will occupy when written to file.
If data occupies 4 bytes or less, it is written immediately
as a Small Data Element (SDE).
"""
fmt = etypes[mtp]['fmt']
if isinstance(data, Sequence):
if fmt == 's' or is_name:
if isinstance(data, bytes):
if is_name and len(data) > 31:
raise ValueError(
'Name "{}" is too long (max. 31 '
'characters allowed)'.format(data))
fmt = '{}s'.format(len(data))
data = (data,)
else:
fmt = ''.join('{}s'.format(len(s)) for s in data)
else:
l = len(data)
if l == 0:
# empty array
fmt = ''
if l > 1:
# more than one element to be written
fmt = '{}{}'.format(l, fmt)
else:
data = (data,)
num_bytes = struct.calcsize(fmt)
if num_bytes <= 4:
# write SDE
if num_bytes < 4:
# add pad bytes
fmt += '{}x'.format(4 - num_bytes)
fd.write(struct.pack('hh' + fmt, etypes[mtp]['n'],
*chain([num_bytes], data)))
return
# write tag: element type and number of bytes
fd.write(struct.pack('b3xI', etypes[mtp]['n'], num_bytes))
# add pad bytes to fmt, if needed
mod8 = num_bytes % 8
if mod8:
fmt += '{}x'.format(8 - mod8)
# write data
fd.write(struct.pack(fmt, *data))
|
def write_elements(fd, mtp, data, is_name=False):
"""Write data element tag and data.
The tag contains the array type and the number of
bytes the array data will occupy when written to file.
If data occupies 4 bytes or less, it is written immediately
as a Small Data Element (SDE).
"""
fmt = etypes[mtp]['fmt']
if isinstance(data, Sequence):
if fmt == 's' or is_name:
if isinstance(data, bytes):
if is_name and len(data) > 31:
raise ValueError(
'Name "{}" is too long (max. 31 '
'characters allowed)'.format(data))
fmt = '{}s'.format(len(data))
data = (data,)
else:
fmt = ''.join('{}s'.format(len(s)) for s in data)
else:
l = len(data)
if l == 0:
# empty array
fmt = ''
if l > 1:
# more than one element to be written
fmt = '{}{}'.format(l, fmt)
else:
data = (data,)
num_bytes = struct.calcsize(fmt)
if num_bytes <= 4:
# write SDE
if num_bytes < 4:
# add pad bytes
fmt += '{}x'.format(4 - num_bytes)
fd.write(struct.pack('hh' + fmt, etypes[mtp]['n'],
*chain([num_bytes], data)))
return
# write tag: element type and number of bytes
fd.write(struct.pack('b3xI', etypes[mtp]['n'], num_bytes))
# add pad bytes to fmt, if needed
mod8 = num_bytes % 8
if mod8:
fmt += '{}x'.format(8 - mod8)
# write data
fd.write(struct.pack(fmt, *data))
|
[
"Write",
"data",
"element",
"tag",
"and",
"data",
"."
] |
nephics/mat4py
|
python
|
https://github.com/nephics/mat4py/blob/6c1a2ad903937437cc5f24f3c3f5aa2c5a77a1c1/mat4py/savemat.py#L121-L168
|
[
"def",
"write_elements",
"(",
"fd",
",",
"mtp",
",",
"data",
",",
"is_name",
"=",
"False",
")",
":",
"fmt",
"=",
"etypes",
"[",
"mtp",
"]",
"[",
"'fmt'",
"]",
"if",
"isinstance",
"(",
"data",
",",
"Sequence",
")",
":",
"if",
"fmt",
"==",
"'s'",
"or",
"is_name",
":",
"if",
"isinstance",
"(",
"data",
",",
"bytes",
")",
":",
"if",
"is_name",
"and",
"len",
"(",
"data",
")",
">",
"31",
":",
"raise",
"ValueError",
"(",
"'Name \"{}\" is too long (max. 31 '",
"'characters allowed)'",
".",
"format",
"(",
"data",
")",
")",
"fmt",
"=",
"'{}s'",
".",
"format",
"(",
"len",
"(",
"data",
")",
")",
"data",
"=",
"(",
"data",
",",
")",
"else",
":",
"fmt",
"=",
"''",
".",
"join",
"(",
"'{}s'",
".",
"format",
"(",
"len",
"(",
"s",
")",
")",
"for",
"s",
"in",
"data",
")",
"else",
":",
"l",
"=",
"len",
"(",
"data",
")",
"if",
"l",
"==",
"0",
":",
"# empty array",
"fmt",
"=",
"''",
"if",
"l",
">",
"1",
":",
"# more than one element to be written",
"fmt",
"=",
"'{}{}'",
".",
"format",
"(",
"l",
",",
"fmt",
")",
"else",
":",
"data",
"=",
"(",
"data",
",",
")",
"num_bytes",
"=",
"struct",
".",
"calcsize",
"(",
"fmt",
")",
"if",
"num_bytes",
"<=",
"4",
":",
"# write SDE",
"if",
"num_bytes",
"<",
"4",
":",
"# add pad bytes",
"fmt",
"+=",
"'{}x'",
".",
"format",
"(",
"4",
"-",
"num_bytes",
")",
"fd",
".",
"write",
"(",
"struct",
".",
"pack",
"(",
"'hh'",
"+",
"fmt",
",",
"etypes",
"[",
"mtp",
"]",
"[",
"'n'",
"]",
",",
"*",
"chain",
"(",
"[",
"num_bytes",
"]",
",",
"data",
")",
")",
")",
"return",
"# write tag: element type and number of bytes",
"fd",
".",
"write",
"(",
"struct",
".",
"pack",
"(",
"'b3xI'",
",",
"etypes",
"[",
"mtp",
"]",
"[",
"'n'",
"]",
",",
"num_bytes",
")",
")",
"# add pad bytes to fmt, if needed",
"mod8",
"=",
"num_bytes",
"%",
"8",
"if",
"mod8",
":",
"fmt",
"+=",
"'{}x'",
".",
"format",
"(",
"8",
"-",
"mod8",
")",
"# write data",
"fd",
".",
"write",
"(",
"struct",
".",
"pack",
"(",
"fmt",
",",
"*",
"data",
")",
")"
] |
6c1a2ad903937437cc5f24f3c3f5aa2c5a77a1c1
|
valid
|
write_var_header
|
Write variable header
|
mat4py/savemat.py
|
def write_var_header(fd, header):
"""Write variable header"""
# write tag bytes,
# and array flags + class and nzmax (null bytes)
fd.write(struct.pack('b3xI', etypes['miUINT32']['n'], 8))
fd.write(struct.pack('b3x4x', mclasses[header['mclass']]))
# write dimensions array
write_elements(fd, 'miINT32', header['dims'])
# write var name
write_elements(fd, 'miINT8', asbytes(header['name']), is_name=True)
|
def write_var_header(fd, header):
"""Write variable header"""
# write tag bytes,
# and array flags + class and nzmax (null bytes)
fd.write(struct.pack('b3xI', etypes['miUINT32']['n'], 8))
fd.write(struct.pack('b3x4x', mclasses[header['mclass']]))
# write dimensions array
write_elements(fd, 'miINT32', header['dims'])
# write var name
write_elements(fd, 'miINT8', asbytes(header['name']), is_name=True)
|
[
"Write",
"variable",
"header"
] |
nephics/mat4py
|
python
|
https://github.com/nephics/mat4py/blob/6c1a2ad903937437cc5f24f3c3f5aa2c5a77a1c1/mat4py/savemat.py#L170-L182
|
[
"def",
"write_var_header",
"(",
"fd",
",",
"header",
")",
":",
"# write tag bytes,",
"# and array flags + class and nzmax (null bytes)",
"fd",
".",
"write",
"(",
"struct",
".",
"pack",
"(",
"'b3xI'",
",",
"etypes",
"[",
"'miUINT32'",
"]",
"[",
"'n'",
"]",
",",
"8",
")",
")",
"fd",
".",
"write",
"(",
"struct",
".",
"pack",
"(",
"'b3x4x'",
",",
"mclasses",
"[",
"header",
"[",
"'mclass'",
"]",
"]",
")",
")",
"# write dimensions array",
"write_elements",
"(",
"fd",
",",
"'miINT32'",
",",
"header",
"[",
"'dims'",
"]",
")",
"# write var name",
"write_elements",
"(",
"fd",
",",
"'miINT8'",
",",
"asbytes",
"(",
"header",
"[",
"'name'",
"]",
")",
",",
"is_name",
"=",
"True",
")"
] |
6c1a2ad903937437cc5f24f3c3f5aa2c5a77a1c1
|
valid
|
write_var_data
|
Write variable data to file
|
mat4py/savemat.py
|
def write_var_data(fd, data):
"""Write variable data to file"""
# write array data elements (size info)
fd.write(struct.pack('b3xI', etypes['miMATRIX']['n'], len(data)))
# write the data
fd.write(data)
|
def write_var_data(fd, data):
"""Write variable data to file"""
# write array data elements (size info)
fd.write(struct.pack('b3xI', etypes['miMATRIX']['n'], len(data)))
# write the data
fd.write(data)
|
[
"Write",
"variable",
"data",
"to",
"file"
] |
nephics/mat4py
|
python
|
https://github.com/nephics/mat4py/blob/6c1a2ad903937437cc5f24f3c3f5aa2c5a77a1c1/mat4py/savemat.py#L184-L190
|
[
"def",
"write_var_data",
"(",
"fd",
",",
"data",
")",
":",
"# write array data elements (size info)",
"fd",
".",
"write",
"(",
"struct",
".",
"pack",
"(",
"'b3xI'",
",",
"etypes",
"[",
"'miMATRIX'",
"]",
"[",
"'n'",
"]",
",",
"len",
"(",
"data",
")",
")",
")",
"# write the data",
"fd",
".",
"write",
"(",
"data",
")"
] |
6c1a2ad903937437cc5f24f3c3f5aa2c5a77a1c1
|
valid
|
write_compressed_var_array
|
Write compressed variable data to file
|
mat4py/savemat.py
|
def write_compressed_var_array(fd, array, name):
"""Write compressed variable data to file"""
bd = BytesIO()
write_var_array(bd, array, name)
data = zlib.compress(bd.getvalue())
bd.close()
# write array data elements (size info)
fd.write(struct.pack('b3xI', etypes['miCOMPRESSED']['n'], len(data)))
# write the compressed data
fd.write(data)
|
def write_compressed_var_array(fd, array, name):
"""Write compressed variable data to file"""
bd = BytesIO()
write_var_array(bd, array, name)
data = zlib.compress(bd.getvalue())
bd.close()
# write array data elements (size info)
fd.write(struct.pack('b3xI', etypes['miCOMPRESSED']['n'], len(data)))
# write the compressed data
fd.write(data)
|
[
"Write",
"compressed",
"variable",
"data",
"to",
"file"
] |
nephics/mat4py
|
python
|
https://github.com/nephics/mat4py/blob/6c1a2ad903937437cc5f24f3c3f5aa2c5a77a1c1/mat4py/savemat.py#L192-L205
|
[
"def",
"write_compressed_var_array",
"(",
"fd",
",",
"array",
",",
"name",
")",
":",
"bd",
"=",
"BytesIO",
"(",
")",
"write_var_array",
"(",
"bd",
",",
"array",
",",
"name",
")",
"data",
"=",
"zlib",
".",
"compress",
"(",
"bd",
".",
"getvalue",
"(",
")",
")",
"bd",
".",
"close",
"(",
")",
"# write array data elements (size info)",
"fd",
".",
"write",
"(",
"struct",
".",
"pack",
"(",
"'b3xI'",
",",
"etypes",
"[",
"'miCOMPRESSED'",
"]",
"[",
"'n'",
"]",
",",
"len",
"(",
"data",
")",
")",
")",
"# write the compressed data",
"fd",
".",
"write",
"(",
"data",
")"
] |
6c1a2ad903937437cc5f24f3c3f5aa2c5a77a1c1
|
valid
|
write_numeric_array
|
Write the numeric array
|
mat4py/savemat.py
|
def write_numeric_array(fd, header, array):
"""Write the numeric array"""
# make a memory file for writing array data
bd = BytesIO()
# write matrix header to memory file
write_var_header(bd, header)
if not isinstance(array, basestring) and header['dims'][0] > 1:
# list array data in column major order
array = list(chain.from_iterable(izip(*array)))
# write matrix data to memory file
write_elements(bd, header['mtp'], array)
# write the variable to disk file
data = bd.getvalue()
bd.close()
write_var_data(fd, data)
|
def write_numeric_array(fd, header, array):
"""Write the numeric array"""
# make a memory file for writing array data
bd = BytesIO()
# write matrix header to memory file
write_var_header(bd, header)
if not isinstance(array, basestring) and header['dims'][0] > 1:
# list array data in column major order
array = list(chain.from_iterable(izip(*array)))
# write matrix data to memory file
write_elements(bd, header['mtp'], array)
# write the variable to disk file
data = bd.getvalue()
bd.close()
write_var_data(fd, data)
|
[
"Write",
"the",
"numeric",
"array"
] |
nephics/mat4py
|
python
|
https://github.com/nephics/mat4py/blob/6c1a2ad903937437cc5f24f3c3f5aa2c5a77a1c1/mat4py/savemat.py#L207-L225
|
[
"def",
"write_numeric_array",
"(",
"fd",
",",
"header",
",",
"array",
")",
":",
"# make a memory file for writing array data",
"bd",
"=",
"BytesIO",
"(",
")",
"# write matrix header to memory file",
"write_var_header",
"(",
"bd",
",",
"header",
")",
"if",
"not",
"isinstance",
"(",
"array",
",",
"basestring",
")",
"and",
"header",
"[",
"'dims'",
"]",
"[",
"0",
"]",
">",
"1",
":",
"# list array data in column major order",
"array",
"=",
"list",
"(",
"chain",
".",
"from_iterable",
"(",
"izip",
"(",
"*",
"array",
")",
")",
")",
"# write matrix data to memory file",
"write_elements",
"(",
"bd",
",",
"header",
"[",
"'mtp'",
"]",
",",
"array",
")",
"# write the variable to disk file",
"data",
"=",
"bd",
".",
"getvalue",
"(",
")",
"bd",
".",
"close",
"(",
")",
"write_var_data",
"(",
"fd",
",",
"data",
")"
] |
6c1a2ad903937437cc5f24f3c3f5aa2c5a77a1c1
|
valid
|
write_var_array
|
Write variable array (of any supported type)
|
mat4py/savemat.py
|
def write_var_array(fd, array, name=''):
"""Write variable array (of any supported type)"""
header, array = guess_header(array, name)
mc = header['mclass']
if mc in numeric_class_etypes:
return write_numeric_array(fd, header, array)
elif mc == 'mxCHAR_CLASS':
return write_char_array(fd, header, array)
elif mc == 'mxCELL_CLASS':
return write_cell_array(fd, header, array)
elif mc == 'mxSTRUCT_CLASS':
return write_struct_array(fd, header, array)
else:
raise ValueError('Unknown mclass {}'.format(mc))
|
def write_var_array(fd, array, name=''):
"""Write variable array (of any supported type)"""
header, array = guess_header(array, name)
mc = header['mclass']
if mc in numeric_class_etypes:
return write_numeric_array(fd, header, array)
elif mc == 'mxCHAR_CLASS':
return write_char_array(fd, header, array)
elif mc == 'mxCELL_CLASS':
return write_cell_array(fd, header, array)
elif mc == 'mxSTRUCT_CLASS':
return write_struct_array(fd, header, array)
else:
raise ValueError('Unknown mclass {}'.format(mc))
|
[
"Write",
"variable",
"array",
"(",
"of",
"any",
"supported",
"type",
")"
] |
nephics/mat4py
|
python
|
https://github.com/nephics/mat4py/blob/6c1a2ad903937437cc5f24f3c3f5aa2c5a77a1c1/mat4py/savemat.py#L299-L312
|
[
"def",
"write_var_array",
"(",
"fd",
",",
"array",
",",
"name",
"=",
"''",
")",
":",
"header",
",",
"array",
"=",
"guess_header",
"(",
"array",
",",
"name",
")",
"mc",
"=",
"header",
"[",
"'mclass'",
"]",
"if",
"mc",
"in",
"numeric_class_etypes",
":",
"return",
"write_numeric_array",
"(",
"fd",
",",
"header",
",",
"array",
")",
"elif",
"mc",
"==",
"'mxCHAR_CLASS'",
":",
"return",
"write_char_array",
"(",
"fd",
",",
"header",
",",
"array",
")",
"elif",
"mc",
"==",
"'mxCELL_CLASS'",
":",
"return",
"write_cell_array",
"(",
"fd",
",",
"header",
",",
"array",
")",
"elif",
"mc",
"==",
"'mxSTRUCT_CLASS'",
":",
"return",
"write_struct_array",
"(",
"fd",
",",
"header",
",",
"array",
")",
"else",
":",
"raise",
"ValueError",
"(",
"'Unknown mclass {}'",
".",
"format",
"(",
"mc",
")",
")"
] |
6c1a2ad903937437cc5f24f3c3f5aa2c5a77a1c1
|
valid
|
isarray
|
Returns True if test is True for all array elements.
Otherwise, returns False.
|
mat4py/savemat.py
|
def isarray(array, test, dim=2):
"""Returns True if test is True for all array elements.
Otherwise, returns False.
"""
if dim > 1:
return all(isarray(array[i], test, dim - 1)
for i in range(len(array)))
return all(test(i) for i in array)
|
def isarray(array, test, dim=2):
"""Returns True if test is True for all array elements.
Otherwise, returns False.
"""
if dim > 1:
return all(isarray(array[i], test, dim - 1)
for i in range(len(array)))
return all(test(i) for i in array)
|
[
"Returns",
"True",
"if",
"test",
"is",
"True",
"for",
"all",
"array",
"elements",
".",
"Otherwise",
"returns",
"False",
"."
] |
nephics/mat4py
|
python
|
https://github.com/nephics/mat4py/blob/6c1a2ad903937437cc5f24f3c3f5aa2c5a77a1c1/mat4py/savemat.py#L314-L321
|
[
"def",
"isarray",
"(",
"array",
",",
"test",
",",
"dim",
"=",
"2",
")",
":",
"if",
"dim",
">",
"1",
":",
"return",
"all",
"(",
"isarray",
"(",
"array",
"[",
"i",
"]",
",",
"test",
",",
"dim",
"-",
"1",
")",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"array",
")",
")",
")",
"return",
"all",
"(",
"test",
"(",
"i",
")",
"for",
"i",
"in",
"array",
")"
] |
6c1a2ad903937437cc5f24f3c3f5aa2c5a77a1c1
|
valid
|
guess_header
|
Guess the array header information.
Returns a header dict, with class, data type, and size information.
|
mat4py/savemat.py
|
def guess_header(array, name=''):
"""Guess the array header information.
Returns a header dict, with class, data type, and size information.
"""
header = {}
if isinstance(array, Sequence) and len(array) == 1:
# sequence with only one element, squeeze the array
array = array[0]
if isinstance(array, basestring):
header.update({
'mclass': 'mxCHAR_CLASS', 'mtp': 'miUTF8',
'dims': (1 if len(array) > 0 else 0, len(array))})
elif isinstance(array, Sequence) and len(array) == 0:
# empty (int) array
header.update({
'mclass': 'mxINT32_CLASS', 'mtp': 'miINT32', 'dims': (0, 0)})
elif isinstance(array, Mapping):
# test if cells (values) of all fields are of equal type and
# have equal length
field_types = [type(j) for j in array.values()]
field_lengths = [1 if isinstance(j, (basestring, int, float))
else len(j) for j in array.values()]
if len(field_lengths) == 1:
equal_lengths = True
equal_types = True
else:
equal_lengths = not any(diff(field_lengths))
equal_types = all([field_types[0] == f for f in field_types])
# if of unqeual lengths or unequal types, then treat each value
# as a cell in a 1x1 struct
header.update({
'mclass': 'mxSTRUCT_CLASS',
'dims': (
1,
field_lengths[0] if equal_lengths and equal_types else 1)}
)
elif isinstance(array, int):
header.update({
'mclass': 'mxINT32_CLASS', 'mtp': 'miINT32', 'dims': (1, 1)})
elif isinstance(array, float):
header.update({
'mclass': 'mxDOUBLE_CLASS', 'mtp': 'miDOUBLE', 'dims': (1, 1)})
elif isinstance(array, Sequence):
if isarray(array, lambda i: isinstance(i, int), 1):
# 1D int array
header.update({
'mclass': 'mxINT32_CLASS', 'mtp': 'miINT32',
'dims': (1, len(array))})
elif isarray(array, lambda i: isinstance(i, (int, float)), 1):
# 1D double array
header.update({
'mclass': 'mxDOUBLE_CLASS', 'mtp': 'miDOUBLE',
'dims': (1, len(array))})
elif (isarray(array, lambda i: isinstance(i, Sequence), 1) and
any(diff(len(s) for s in array))):
# sequence of unequal length, assume cell array
header.update({
'mclass': 'mxCELL_CLASS',
'dims': (1, len(array))
})
elif isarray(array, lambda i: isinstance(i, basestring), 1):
# char array
header.update({
'mclass': 'mxCHAR_CLASS', 'mtp': 'miUTF8',
'dims': (len(array), len(array[0]))})
elif isarray(array, lambda i: isinstance(i, Sequence), 1):
# 2D array
if any(diff(len(j) for j in array)):
# rows are of unequal length, make it a cell array
header.update({
'mclass': 'mxCELL_CLASS',
'dims': (len(array), len(array[0]))})
elif isarray(array, lambda i: isinstance(i, int)):
# 2D int array
header.update({
'mclass': 'mxINT32_CLASS', 'mtp': 'miINT32',
'dims': (len(array), len(array[0]))})
elif isarray(array, lambda i: isinstance(i, (int, float))):
# 2D double array
header.update({
'mclass': 'mxDOUBLE_CLASS',
'mtp': 'miDOUBLE',
'dims': (len(array), len(array[0]))})
elif isarray(array, lambda i: isinstance(
i, (int, float, basestring, Sequence, Mapping))):
# mixed contents, make it a cell array
header.update({
'mclass': 'mxCELL_CLASS',
'dims': (1, len(array))})
if not header:
raise ValueError(
'Only dicts, two dimensional numeric, '
'and char arrays are currently supported')
header['name'] = name
return header, array
|
def guess_header(array, name=''):
"""Guess the array header information.
Returns a header dict, with class, data type, and size information.
"""
header = {}
if isinstance(array, Sequence) and len(array) == 1:
# sequence with only one element, squeeze the array
array = array[0]
if isinstance(array, basestring):
header.update({
'mclass': 'mxCHAR_CLASS', 'mtp': 'miUTF8',
'dims': (1 if len(array) > 0 else 0, len(array))})
elif isinstance(array, Sequence) and len(array) == 0:
# empty (int) array
header.update({
'mclass': 'mxINT32_CLASS', 'mtp': 'miINT32', 'dims': (0, 0)})
elif isinstance(array, Mapping):
# test if cells (values) of all fields are of equal type and
# have equal length
field_types = [type(j) for j in array.values()]
field_lengths = [1 if isinstance(j, (basestring, int, float))
else len(j) for j in array.values()]
if len(field_lengths) == 1:
equal_lengths = True
equal_types = True
else:
equal_lengths = not any(diff(field_lengths))
equal_types = all([field_types[0] == f for f in field_types])
# if of unqeual lengths or unequal types, then treat each value
# as a cell in a 1x1 struct
header.update({
'mclass': 'mxSTRUCT_CLASS',
'dims': (
1,
field_lengths[0] if equal_lengths and equal_types else 1)}
)
elif isinstance(array, int):
header.update({
'mclass': 'mxINT32_CLASS', 'mtp': 'miINT32', 'dims': (1, 1)})
elif isinstance(array, float):
header.update({
'mclass': 'mxDOUBLE_CLASS', 'mtp': 'miDOUBLE', 'dims': (1, 1)})
elif isinstance(array, Sequence):
if isarray(array, lambda i: isinstance(i, int), 1):
# 1D int array
header.update({
'mclass': 'mxINT32_CLASS', 'mtp': 'miINT32',
'dims': (1, len(array))})
elif isarray(array, lambda i: isinstance(i, (int, float)), 1):
# 1D double array
header.update({
'mclass': 'mxDOUBLE_CLASS', 'mtp': 'miDOUBLE',
'dims': (1, len(array))})
elif (isarray(array, lambda i: isinstance(i, Sequence), 1) and
any(diff(len(s) for s in array))):
# sequence of unequal length, assume cell array
header.update({
'mclass': 'mxCELL_CLASS',
'dims': (1, len(array))
})
elif isarray(array, lambda i: isinstance(i, basestring), 1):
# char array
header.update({
'mclass': 'mxCHAR_CLASS', 'mtp': 'miUTF8',
'dims': (len(array), len(array[0]))})
elif isarray(array, lambda i: isinstance(i, Sequence), 1):
# 2D array
if any(diff(len(j) for j in array)):
# rows are of unequal length, make it a cell array
header.update({
'mclass': 'mxCELL_CLASS',
'dims': (len(array), len(array[0]))})
elif isarray(array, lambda i: isinstance(i, int)):
# 2D int array
header.update({
'mclass': 'mxINT32_CLASS', 'mtp': 'miINT32',
'dims': (len(array), len(array[0]))})
elif isarray(array, lambda i: isinstance(i, (int, float))):
# 2D double array
header.update({
'mclass': 'mxDOUBLE_CLASS',
'mtp': 'miDOUBLE',
'dims': (len(array), len(array[0]))})
elif isarray(array, lambda i: isinstance(
i, (int, float, basestring, Sequence, Mapping))):
# mixed contents, make it a cell array
header.update({
'mclass': 'mxCELL_CLASS',
'dims': (1, len(array))})
if not header:
raise ValueError(
'Only dicts, two dimensional numeric, '
'and char arrays are currently supported')
header['name'] = name
return header, array
|
[
"Guess",
"the",
"array",
"header",
"information",
".",
"Returns",
"a",
"header",
"dict",
"with",
"class",
"data",
"type",
"and",
"size",
"information",
"."
] |
nephics/mat4py
|
python
|
https://github.com/nephics/mat4py/blob/6c1a2ad903937437cc5f24f3c3f5aa2c5a77a1c1/mat4py/savemat.py#L323-L435
|
[
"def",
"guess_header",
"(",
"array",
",",
"name",
"=",
"''",
")",
":",
"header",
"=",
"{",
"}",
"if",
"isinstance",
"(",
"array",
",",
"Sequence",
")",
"and",
"len",
"(",
"array",
")",
"==",
"1",
":",
"# sequence with only one element, squeeze the array",
"array",
"=",
"array",
"[",
"0",
"]",
"if",
"isinstance",
"(",
"array",
",",
"basestring",
")",
":",
"header",
".",
"update",
"(",
"{",
"'mclass'",
":",
"'mxCHAR_CLASS'",
",",
"'mtp'",
":",
"'miUTF8'",
",",
"'dims'",
":",
"(",
"1",
"if",
"len",
"(",
"array",
")",
">",
"0",
"else",
"0",
",",
"len",
"(",
"array",
")",
")",
"}",
")",
"elif",
"isinstance",
"(",
"array",
",",
"Sequence",
")",
"and",
"len",
"(",
"array",
")",
"==",
"0",
":",
"# empty (int) array",
"header",
".",
"update",
"(",
"{",
"'mclass'",
":",
"'mxINT32_CLASS'",
",",
"'mtp'",
":",
"'miINT32'",
",",
"'dims'",
":",
"(",
"0",
",",
"0",
")",
"}",
")",
"elif",
"isinstance",
"(",
"array",
",",
"Mapping",
")",
":",
"# test if cells (values) of all fields are of equal type and",
"# have equal length",
"field_types",
"=",
"[",
"type",
"(",
"j",
")",
"for",
"j",
"in",
"array",
".",
"values",
"(",
")",
"]",
"field_lengths",
"=",
"[",
"1",
"if",
"isinstance",
"(",
"j",
",",
"(",
"basestring",
",",
"int",
",",
"float",
")",
")",
"else",
"len",
"(",
"j",
")",
"for",
"j",
"in",
"array",
".",
"values",
"(",
")",
"]",
"if",
"len",
"(",
"field_lengths",
")",
"==",
"1",
":",
"equal_lengths",
"=",
"True",
"equal_types",
"=",
"True",
"else",
":",
"equal_lengths",
"=",
"not",
"any",
"(",
"diff",
"(",
"field_lengths",
")",
")",
"equal_types",
"=",
"all",
"(",
"[",
"field_types",
"[",
"0",
"]",
"==",
"f",
"for",
"f",
"in",
"field_types",
"]",
")",
"# if of unqeual lengths or unequal types, then treat each value",
"# as a cell in a 1x1 struct",
"header",
".",
"update",
"(",
"{",
"'mclass'",
":",
"'mxSTRUCT_CLASS'",
",",
"'dims'",
":",
"(",
"1",
",",
"field_lengths",
"[",
"0",
"]",
"if",
"equal_lengths",
"and",
"equal_types",
"else",
"1",
")",
"}",
")",
"elif",
"isinstance",
"(",
"array",
",",
"int",
")",
":",
"header",
".",
"update",
"(",
"{",
"'mclass'",
":",
"'mxINT32_CLASS'",
",",
"'mtp'",
":",
"'miINT32'",
",",
"'dims'",
":",
"(",
"1",
",",
"1",
")",
"}",
")",
"elif",
"isinstance",
"(",
"array",
",",
"float",
")",
":",
"header",
".",
"update",
"(",
"{",
"'mclass'",
":",
"'mxDOUBLE_CLASS'",
",",
"'mtp'",
":",
"'miDOUBLE'",
",",
"'dims'",
":",
"(",
"1",
",",
"1",
")",
"}",
")",
"elif",
"isinstance",
"(",
"array",
",",
"Sequence",
")",
":",
"if",
"isarray",
"(",
"array",
",",
"lambda",
"i",
":",
"isinstance",
"(",
"i",
",",
"int",
")",
",",
"1",
")",
":",
"# 1D int array",
"header",
".",
"update",
"(",
"{",
"'mclass'",
":",
"'mxINT32_CLASS'",
",",
"'mtp'",
":",
"'miINT32'",
",",
"'dims'",
":",
"(",
"1",
",",
"len",
"(",
"array",
")",
")",
"}",
")",
"elif",
"isarray",
"(",
"array",
",",
"lambda",
"i",
":",
"isinstance",
"(",
"i",
",",
"(",
"int",
",",
"float",
")",
")",
",",
"1",
")",
":",
"# 1D double array",
"header",
".",
"update",
"(",
"{",
"'mclass'",
":",
"'mxDOUBLE_CLASS'",
",",
"'mtp'",
":",
"'miDOUBLE'",
",",
"'dims'",
":",
"(",
"1",
",",
"len",
"(",
"array",
")",
")",
"}",
")",
"elif",
"(",
"isarray",
"(",
"array",
",",
"lambda",
"i",
":",
"isinstance",
"(",
"i",
",",
"Sequence",
")",
",",
"1",
")",
"and",
"any",
"(",
"diff",
"(",
"len",
"(",
"s",
")",
"for",
"s",
"in",
"array",
")",
")",
")",
":",
"# sequence of unequal length, assume cell array",
"header",
".",
"update",
"(",
"{",
"'mclass'",
":",
"'mxCELL_CLASS'",
",",
"'dims'",
":",
"(",
"1",
",",
"len",
"(",
"array",
")",
")",
"}",
")",
"elif",
"isarray",
"(",
"array",
",",
"lambda",
"i",
":",
"isinstance",
"(",
"i",
",",
"basestring",
")",
",",
"1",
")",
":",
"# char array",
"header",
".",
"update",
"(",
"{",
"'mclass'",
":",
"'mxCHAR_CLASS'",
",",
"'mtp'",
":",
"'miUTF8'",
",",
"'dims'",
":",
"(",
"len",
"(",
"array",
")",
",",
"len",
"(",
"array",
"[",
"0",
"]",
")",
")",
"}",
")",
"elif",
"isarray",
"(",
"array",
",",
"lambda",
"i",
":",
"isinstance",
"(",
"i",
",",
"Sequence",
")",
",",
"1",
")",
":",
"# 2D array",
"if",
"any",
"(",
"diff",
"(",
"len",
"(",
"j",
")",
"for",
"j",
"in",
"array",
")",
")",
":",
"# rows are of unequal length, make it a cell array",
"header",
".",
"update",
"(",
"{",
"'mclass'",
":",
"'mxCELL_CLASS'",
",",
"'dims'",
":",
"(",
"len",
"(",
"array",
")",
",",
"len",
"(",
"array",
"[",
"0",
"]",
")",
")",
"}",
")",
"elif",
"isarray",
"(",
"array",
",",
"lambda",
"i",
":",
"isinstance",
"(",
"i",
",",
"int",
")",
")",
":",
"# 2D int array",
"header",
".",
"update",
"(",
"{",
"'mclass'",
":",
"'mxINT32_CLASS'",
",",
"'mtp'",
":",
"'miINT32'",
",",
"'dims'",
":",
"(",
"len",
"(",
"array",
")",
",",
"len",
"(",
"array",
"[",
"0",
"]",
")",
")",
"}",
")",
"elif",
"isarray",
"(",
"array",
",",
"lambda",
"i",
":",
"isinstance",
"(",
"i",
",",
"(",
"int",
",",
"float",
")",
")",
")",
":",
"# 2D double array",
"header",
".",
"update",
"(",
"{",
"'mclass'",
":",
"'mxDOUBLE_CLASS'",
",",
"'mtp'",
":",
"'miDOUBLE'",
",",
"'dims'",
":",
"(",
"len",
"(",
"array",
")",
",",
"len",
"(",
"array",
"[",
"0",
"]",
")",
")",
"}",
")",
"elif",
"isarray",
"(",
"array",
",",
"lambda",
"i",
":",
"isinstance",
"(",
"i",
",",
"(",
"int",
",",
"float",
",",
"basestring",
",",
"Sequence",
",",
"Mapping",
")",
")",
")",
":",
"# mixed contents, make it a cell array",
"header",
".",
"update",
"(",
"{",
"'mclass'",
":",
"'mxCELL_CLASS'",
",",
"'dims'",
":",
"(",
"1",
",",
"len",
"(",
"array",
")",
")",
"}",
")",
"if",
"not",
"header",
":",
"raise",
"ValueError",
"(",
"'Only dicts, two dimensional numeric, '",
"'and char arrays are currently supported'",
")",
"header",
"[",
"'name'",
"]",
"=",
"name",
"return",
"header",
",",
"array"
] |
6c1a2ad903937437cc5f24f3c3f5aa2c5a77a1c1
|
valid
|
savemat
|
Save data to MAT-file:
savemat(filename, data)
The filename argument is either a string with the filename, or
a file like object.
The parameter ``data`` shall be a dict with the variables.
A ``ValueError`` exception is raised if data has invalid format, or if the
data structure cannot be mapped to a known MAT array type.
|
mat4py/savemat.py
|
def savemat(filename, data):
"""Save data to MAT-file:
savemat(filename, data)
The filename argument is either a string with the filename, or
a file like object.
The parameter ``data`` shall be a dict with the variables.
A ``ValueError`` exception is raised if data has invalid format, or if the
data structure cannot be mapped to a known MAT array type.
"""
if not isinstance(data, Mapping):
raise ValueError('Data should be a dict of variable arrays')
if isinstance(filename, basestring):
fd = open(filename, 'wb')
else:
fd = filename
write_file_header(fd)
# write variables
for name, array in data.items():
write_compressed_var_array(fd, array, name)
fd.close()
|
def savemat(filename, data):
"""Save data to MAT-file:
savemat(filename, data)
The filename argument is either a string with the filename, or
a file like object.
The parameter ``data`` shall be a dict with the variables.
A ``ValueError`` exception is raised if data has invalid format, or if the
data structure cannot be mapped to a known MAT array type.
"""
if not isinstance(data, Mapping):
raise ValueError('Data should be a dict of variable arrays')
if isinstance(filename, basestring):
fd = open(filename, 'wb')
else:
fd = filename
write_file_header(fd)
# write variables
for name, array in data.items():
write_compressed_var_array(fd, array, name)
fd.close()
|
[
"Save",
"data",
"to",
"MAT",
"-",
"file",
":"
] |
nephics/mat4py
|
python
|
https://github.com/nephics/mat4py/blob/6c1a2ad903937437cc5f24f3c3f5aa2c5a77a1c1/mat4py/savemat.py#L443-L471
|
[
"def",
"savemat",
"(",
"filename",
",",
"data",
")",
":",
"if",
"not",
"isinstance",
"(",
"data",
",",
"Mapping",
")",
":",
"raise",
"ValueError",
"(",
"'Data should be a dict of variable arrays'",
")",
"if",
"isinstance",
"(",
"filename",
",",
"basestring",
")",
":",
"fd",
"=",
"open",
"(",
"filename",
",",
"'wb'",
")",
"else",
":",
"fd",
"=",
"filename",
"write_file_header",
"(",
"fd",
")",
"# write variables",
"for",
"name",
",",
"array",
"in",
"data",
".",
"items",
"(",
")",
":",
"write_compressed_var_array",
"(",
"fd",
",",
"array",
",",
"name",
")",
"fd",
".",
"close",
"(",
")"
] |
6c1a2ad903937437cc5f24f3c3f5aa2c5a77a1c1
|
valid
|
WebDriver._execute
|
Private method to execute command.
Args:
command(Command): The defined command.
data(dict): The uri variable and body.
uppack(bool): If unpack value from result.
Returns:
The unwrapped value field in the json response.
|
macaca/webdriver.py
|
def _execute(self, command, data=None, unpack=True):
""" Private method to execute command.
Args:
command(Command): The defined command.
data(dict): The uri variable and body.
uppack(bool): If unpack value from result.
Returns:
The unwrapped value field in the json response.
"""
if not data:
data = {}
if self.session_id is not None:
data.setdefault('session_id', self.session_id)
data = self._wrap_el(data)
res = self.remote_invoker.execute(command, data)
ret = WebDriverResult.from_object(res)
ret.raise_for_status()
ret.value = self._unwrap_el(ret.value)
if not unpack:
return ret
return ret.value
|
def _execute(self, command, data=None, unpack=True):
""" Private method to execute command.
Args:
command(Command): The defined command.
data(dict): The uri variable and body.
uppack(bool): If unpack value from result.
Returns:
The unwrapped value field in the json response.
"""
if not data:
data = {}
if self.session_id is not None:
data.setdefault('session_id', self.session_id)
data = self._wrap_el(data)
res = self.remote_invoker.execute(command, data)
ret = WebDriverResult.from_object(res)
ret.raise_for_status()
ret.value = self._unwrap_el(ret.value)
if not unpack:
return ret
return ret.value
|
[
"Private",
"method",
"to",
"execute",
"command",
"."
] |
macacajs/wd.py
|
python
|
https://github.com/macacajs/wd.py/blob/6d3c52060013e01a67cd52b68b5230b387427bad/macaca/webdriver.py#L50-L72
|
[
"def",
"_execute",
"(",
"self",
",",
"command",
",",
"data",
"=",
"None",
",",
"unpack",
"=",
"True",
")",
":",
"if",
"not",
"data",
":",
"data",
"=",
"{",
"}",
"if",
"self",
".",
"session_id",
"is",
"not",
"None",
":",
"data",
".",
"setdefault",
"(",
"'session_id'",
",",
"self",
".",
"session_id",
")",
"data",
"=",
"self",
".",
"_wrap_el",
"(",
"data",
")",
"res",
"=",
"self",
".",
"remote_invoker",
".",
"execute",
"(",
"command",
",",
"data",
")",
"ret",
"=",
"WebDriverResult",
".",
"from_object",
"(",
"res",
")",
"ret",
".",
"raise_for_status",
"(",
")",
"ret",
".",
"value",
"=",
"self",
".",
"_unwrap_el",
"(",
"ret",
".",
"value",
")",
"if",
"not",
"unpack",
":",
"return",
"ret",
"return",
"ret",
".",
"value"
] |
6d3c52060013e01a67cd52b68b5230b387427bad
|
valid
|
WebDriver._unwrap_el
|
Convert {'Element': 1234} to WebElement Object
Args:
value(str|list|dict): The value field in the json response.
Returns:
The unwrapped value.
|
macaca/webdriver.py
|
def _unwrap_el(self, value):
"""Convert {'Element': 1234} to WebElement Object
Args:
value(str|list|dict): The value field in the json response.
Returns:
The unwrapped value.
"""
if isinstance(value, dict) and 'ELEMENT' in value:
element_id = value.get('ELEMENT')
return WebElement(element_id, self)
elif isinstance(value, list) and not isinstance(value, str):
return [self._unwrap_el(item) for item in value]
else:
return value
|
def _unwrap_el(self, value):
"""Convert {'Element': 1234} to WebElement Object
Args:
value(str|list|dict): The value field in the json response.
Returns:
The unwrapped value.
"""
if isinstance(value, dict) and 'ELEMENT' in value:
element_id = value.get('ELEMENT')
return WebElement(element_id, self)
elif isinstance(value, list) and not isinstance(value, str):
return [self._unwrap_el(item) for item in value]
else:
return value
|
[
"Convert",
"{",
"Element",
":",
"1234",
"}",
"to",
"WebElement",
"Object"
] |
macacajs/wd.py
|
python
|
https://github.com/macacajs/wd.py/blob/6d3c52060013e01a67cd52b68b5230b387427bad/macaca/webdriver.py#L74-L89
|
[
"def",
"_unwrap_el",
"(",
"self",
",",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"dict",
")",
"and",
"'ELEMENT'",
"in",
"value",
":",
"element_id",
"=",
"value",
".",
"get",
"(",
"'ELEMENT'",
")",
"return",
"WebElement",
"(",
"element_id",
",",
"self",
")",
"elif",
"isinstance",
"(",
"value",
",",
"list",
")",
"and",
"not",
"isinstance",
"(",
"value",
",",
"str",
")",
":",
"return",
"[",
"self",
".",
"_unwrap_el",
"(",
"item",
")",
"for",
"item",
"in",
"value",
"]",
"else",
":",
"return",
"value"
] |
6d3c52060013e01a67cd52b68b5230b387427bad
|
valid
|
WebDriver._wrap_el
|
Convert WebElement Object to {'Element': 1234}
Args:
value(str|list|dict): The local value.
Returns:
The wrapped value.
|
macaca/webdriver.py
|
def _wrap_el(self, value):
"""Convert WebElement Object to {'Element': 1234}
Args:
value(str|list|dict): The local value.
Returns:
The wrapped value.
"""
if isinstance(value, dict):
return {k: self._wrap_el(v) for k, v in value.items()}
elif isinstance(value, WebElement):
return {'ELEMENT': value.element_id}
elif isinstance(value, list) and not isinstance(value, str):
return [self._wrap_el(item) for item in value]
else:
return value
|
def _wrap_el(self, value):
"""Convert WebElement Object to {'Element': 1234}
Args:
value(str|list|dict): The local value.
Returns:
The wrapped value.
"""
if isinstance(value, dict):
return {k: self._wrap_el(v) for k, v in value.items()}
elif isinstance(value, WebElement):
return {'ELEMENT': value.element_id}
elif isinstance(value, list) and not isinstance(value, str):
return [self._wrap_el(item) for item in value]
else:
return value
|
[
"Convert",
"WebElement",
"Object",
"to",
"{",
"Element",
":",
"1234",
"}"
] |
macacajs/wd.py
|
python
|
https://github.com/macacajs/wd.py/blob/6d3c52060013e01a67cd52b68b5230b387427bad/macaca/webdriver.py#L91-L107
|
[
"def",
"_wrap_el",
"(",
"self",
",",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"dict",
")",
":",
"return",
"{",
"k",
":",
"self",
".",
"_wrap_el",
"(",
"v",
")",
"for",
"k",
",",
"v",
"in",
"value",
".",
"items",
"(",
")",
"}",
"elif",
"isinstance",
"(",
"value",
",",
"WebElement",
")",
":",
"return",
"{",
"'ELEMENT'",
":",
"value",
".",
"element_id",
"}",
"elif",
"isinstance",
"(",
"value",
",",
"list",
")",
"and",
"not",
"isinstance",
"(",
"value",
",",
"str",
")",
":",
"return",
"[",
"self",
".",
"_wrap_el",
"(",
"item",
")",
"for",
"item",
"in",
"value",
"]",
"else",
":",
"return",
"value"
] |
6d3c52060013e01a67cd52b68b5230b387427bad
|
valid
|
WebDriver.init
|
Create Session by desiredCapabilities
Support:
Android iOS Web(WebView)
Returns:
WebDriver Object.
|
macaca/webdriver.py
|
def init(self):
"""Create Session by desiredCapabilities
Support:
Android iOS Web(WebView)
Returns:
WebDriver Object.
"""
resp = self._execute(Command.NEW_SESSION, {
'desiredCapabilities': self.desired_capabilities
}, False)
resp.raise_for_status()
self.session_id = str(resp.session_id)
self.capabilities = resp.value
|
def init(self):
"""Create Session by desiredCapabilities
Support:
Android iOS Web(WebView)
Returns:
WebDriver Object.
"""
resp = self._execute(Command.NEW_SESSION, {
'desiredCapabilities': self.desired_capabilities
}, False)
resp.raise_for_status()
self.session_id = str(resp.session_id)
self.capabilities = resp.value
|
[
"Create",
"Session",
"by",
"desiredCapabilities"
] |
macacajs/wd.py
|
python
|
https://github.com/macacajs/wd.py/blob/6d3c52060013e01a67cd52b68b5230b387427bad/macaca/webdriver.py#L137-L151
|
[
"def",
"init",
"(",
"self",
")",
":",
"resp",
"=",
"self",
".",
"_execute",
"(",
"Command",
".",
"NEW_SESSION",
",",
"{",
"'desiredCapabilities'",
":",
"self",
".",
"desired_capabilities",
"}",
",",
"False",
")",
"resp",
".",
"raise_for_status",
"(",
")",
"self",
".",
"session_id",
"=",
"str",
"(",
"resp",
".",
"session_id",
")",
"self",
".",
"capabilities",
"=",
"resp",
".",
"value"
] |
6d3c52060013e01a67cd52b68b5230b387427bad
|
valid
|
WebDriver.switch_to_window
|
Switch to the given window.
Support:
Web(WebView)
Args:
window_name(str): The window to change focus to.
Returns:
WebDriver Object.
|
macaca/webdriver.py
|
def switch_to_window(self, window_name):
"""Switch to the given window.
Support:
Web(WebView)
Args:
window_name(str): The window to change focus to.
Returns:
WebDriver Object.
"""
data = {
'name': window_name
}
self._execute(Command.SWITCH_TO_WINDOW, data)
|
def switch_to_window(self, window_name):
"""Switch to the given window.
Support:
Web(WebView)
Args:
window_name(str): The window to change focus to.
Returns:
WebDriver Object.
"""
data = {
'name': window_name
}
self._execute(Command.SWITCH_TO_WINDOW, data)
|
[
"Switch",
"to",
"the",
"given",
"window",
"."
] |
macacajs/wd.py
|
python
|
https://github.com/macacajs/wd.py/blob/6d3c52060013e01a67cd52b68b5230b387427bad/macaca/webdriver.py#L262-L277
|
[
"def",
"switch_to_window",
"(",
"self",
",",
"window_name",
")",
":",
"data",
"=",
"{",
"'name'",
":",
"window_name",
"}",
"self",
".",
"_execute",
"(",
"Command",
".",
"SWITCH_TO_WINDOW",
",",
"data",
")"
] |
6d3c52060013e01a67cd52b68b5230b387427bad
|
valid
|
WebDriver.set_window_size
|
Sets the width and height of the current window.
Support:
Web(WebView)
Args:
width(int): the width in pixels.
height(int): the height in pixels.
window_handle(str): Identifier of window_handle,
default to 'current'.
Returns:
WebDriver Object.
|
macaca/webdriver.py
|
def set_window_size(self, width, height, window_handle='current'):
"""Sets the width and height of the current window.
Support:
Web(WebView)
Args:
width(int): the width in pixels.
height(int): the height in pixels.
window_handle(str): Identifier of window_handle,
default to 'current'.
Returns:
WebDriver Object.
"""
self._execute(Command.SET_WINDOW_SIZE, {
'width': int(width),
'height': int(height),
'window_handle': window_handle})
|
def set_window_size(self, width, height, window_handle='current'):
"""Sets the width and height of the current window.
Support:
Web(WebView)
Args:
width(int): the width in pixels.
height(int): the height in pixels.
window_handle(str): Identifier of window_handle,
default to 'current'.
Returns:
WebDriver Object.
"""
self._execute(Command.SET_WINDOW_SIZE, {
'width': int(width),
'height': int(height),
'window_handle': window_handle})
|
[
"Sets",
"the",
"width",
"and",
"height",
"of",
"the",
"current",
"window",
"."
] |
macacajs/wd.py
|
python
|
https://github.com/macacajs/wd.py/blob/6d3c52060013e01a67cd52b68b5230b387427bad/macaca/webdriver.py#L302-L320
|
[
"def",
"set_window_size",
"(",
"self",
",",
"width",
",",
"height",
",",
"window_handle",
"=",
"'current'",
")",
":",
"self",
".",
"_execute",
"(",
"Command",
".",
"SET_WINDOW_SIZE",
",",
"{",
"'width'",
":",
"int",
"(",
"width",
")",
",",
"'height'",
":",
"int",
"(",
"height",
")",
",",
"'window_handle'",
":",
"window_handle",
"}",
")"
] |
6d3c52060013e01a67cd52b68b5230b387427bad
|
valid
|
WebDriver.set_window_position
|
Sets the x,y position of the current window.
Support:
Web(WebView)
Args:
x(int): the x-coordinate in pixels.
y(int): the y-coordinate in pixels.
window_handle(str): Identifier of window_handle,
default to 'current'.
Returns:
WebDriver Object.
|
macaca/webdriver.py
|
def set_window_position(self, x, y, window_handle='current'):
"""Sets the x,y position of the current window.
Support:
Web(WebView)
Args:
x(int): the x-coordinate in pixels.
y(int): the y-coordinate in pixels.
window_handle(str): Identifier of window_handle,
default to 'current'.
Returns:
WebDriver Object.
"""
self._execute(Command.SET_WINDOW_POSITION, {
'x': int(x),
'y': int(y),
'window_handle': window_handle})
|
def set_window_position(self, x, y, window_handle='current'):
"""Sets the x,y position of the current window.
Support:
Web(WebView)
Args:
x(int): the x-coordinate in pixels.
y(int): the y-coordinate in pixels.
window_handle(str): Identifier of window_handle,
default to 'current'.
Returns:
WebDriver Object.
"""
self._execute(Command.SET_WINDOW_POSITION, {
'x': int(x),
'y': int(y),
'window_handle': window_handle})
|
[
"Sets",
"the",
"x",
"y",
"position",
"of",
"the",
"current",
"window",
"."
] |
macacajs/wd.py
|
python
|
https://github.com/macacajs/wd.py/blob/6d3c52060013e01a67cd52b68b5230b387427bad/macaca/webdriver.py#L339-L357
|
[
"def",
"set_window_position",
"(",
"self",
",",
"x",
",",
"y",
",",
"window_handle",
"=",
"'current'",
")",
":",
"self",
".",
"_execute",
"(",
"Command",
".",
"SET_WINDOW_POSITION",
",",
"{",
"'x'",
":",
"int",
"(",
"x",
")",
",",
"'y'",
":",
"int",
"(",
"y",
")",
",",
"'window_handle'",
":",
"window_handle",
"}",
")"
] |
6d3c52060013e01a67cd52b68b5230b387427bad
|
valid
|
WebDriver.move_to
|
Deprecated use element.touch('drag', { toX, toY, duration(s) }) instead.
Move the mouse by an offset of the specificed element.
Support:
Android
Args:
element(WebElement): WebElement Object.
x(float): X offset to move to, relative to the
top-left corner of the element.
y(float): Y offset to move to, relative to the
top-left corner of the element.
Returns:
WebDriver object.
|
macaca/webdriver.py
|
def move_to(self, element, x=0, y=0):
"""Deprecated use element.touch('drag', { toX, toY, duration(s) }) instead.
Move the mouse by an offset of the specificed element.
Support:
Android
Args:
element(WebElement): WebElement Object.
x(float): X offset to move to, relative to the
top-left corner of the element.
y(float): Y offset to move to, relative to the
top-left corner of the element.
Returns:
WebDriver object.
"""
self._execute(Command.MOVE_TO, {
'element': element.element_id,
'x': x,
'y': y
})
|
def move_to(self, element, x=0, y=0):
"""Deprecated use element.touch('drag', { toX, toY, duration(s) }) instead.
Move the mouse by an offset of the specificed element.
Support:
Android
Args:
element(WebElement): WebElement Object.
x(float): X offset to move to, relative to the
top-left corner of the element.
y(float): Y offset to move to, relative to the
top-left corner of the element.
Returns:
WebDriver object.
"""
self._execute(Command.MOVE_TO, {
'element': element.element_id,
'x': x,
'y': y
})
|
[
"Deprecated",
"use",
"element",
".",
"touch",
"(",
"drag",
"{",
"toX",
"toY",
"duration",
"(",
"s",
")",
"}",
")",
"instead",
".",
"Move",
"the",
"mouse",
"by",
"an",
"offset",
"of",
"the",
"specificed",
"element",
"."
] |
macacajs/wd.py
|
python
|
https://github.com/macacajs/wd.py/blob/6d3c52060013e01a67cd52b68b5230b387427bad/macaca/webdriver.py#L403-L424
|
[
"def",
"move_to",
"(",
"self",
",",
"element",
",",
"x",
"=",
"0",
",",
"y",
"=",
"0",
")",
":",
"self",
".",
"_execute",
"(",
"Command",
".",
"MOVE_TO",
",",
"{",
"'element'",
":",
"element",
".",
"element_id",
",",
"'x'",
":",
"x",
",",
"'y'",
":",
"y",
"}",
")"
] |
6d3c52060013e01a67cd52b68b5230b387427bad
|
valid
|
WebDriver.flick
|
Deprecated use touch('drag', { fromX, fromY, toX, toY, duration(s) }) instead.
Flick on the touch screen using finger motion events.
This flickcommand starts at a particulat screen location.
Support:
iOS
Args:
element(WebElement): WebElement Object where the flick starts.
x(float}: The x offset in pixels to flick by.
y(float): The y offset in pixels to flick by.
speed(float) The speed in pixels per seconds.
Returns:
WebDriver object.
|
macaca/webdriver.py
|
def flick(self, element, x, y, speed):
"""Deprecated use touch('drag', { fromX, fromY, toX, toY, duration(s) }) instead.
Flick on the touch screen using finger motion events.
This flickcommand starts at a particulat screen location.
Support:
iOS
Args:
element(WebElement): WebElement Object where the flick starts.
x(float}: The x offset in pixels to flick by.
y(float): The y offset in pixels to flick by.
speed(float) The speed in pixels per seconds.
Returns:
WebDriver object.
"""
self._execute(Command.FLICK, {
'element': element.element_id,
'x': x,
'y': y,
'speed': speed
})
|
def flick(self, element, x, y, speed):
"""Deprecated use touch('drag', { fromX, fromY, toX, toY, duration(s) }) instead.
Flick on the touch screen using finger motion events.
This flickcommand starts at a particulat screen location.
Support:
iOS
Args:
element(WebElement): WebElement Object where the flick starts.
x(float}: The x offset in pixels to flick by.
y(float): The y offset in pixels to flick by.
speed(float) The speed in pixels per seconds.
Returns:
WebDriver object.
"""
self._execute(Command.FLICK, {
'element': element.element_id,
'x': x,
'y': y,
'speed': speed
})
|
[
"Deprecated",
"use",
"touch",
"(",
"drag",
"{",
"fromX",
"fromY",
"toX",
"toY",
"duration",
"(",
"s",
")",
"}",
")",
"instead",
".",
"Flick",
"on",
"the",
"touch",
"screen",
"using",
"finger",
"motion",
"events",
".",
"This",
"flickcommand",
"starts",
"at",
"a",
"particulat",
"screen",
"location",
"."
] |
macacajs/wd.py
|
python
|
https://github.com/macacajs/wd.py/blob/6d3c52060013e01a67cd52b68b5230b387427bad/macaca/webdriver.py#L427-L450
|
[
"def",
"flick",
"(",
"self",
",",
"element",
",",
"x",
",",
"y",
",",
"speed",
")",
":",
"self",
".",
"_execute",
"(",
"Command",
".",
"FLICK",
",",
"{",
"'element'",
":",
"element",
".",
"element_id",
",",
"'x'",
":",
"x",
",",
"'y'",
":",
"y",
",",
"'speed'",
":",
"speed",
"}",
")"
] |
6d3c52060013e01a67cd52b68b5230b387427bad
|
valid
|
WebDriver.switch_to_frame
|
Switches focus to the specified frame, by index, name, or webelement.
Support:
Web(WebView)
Args:
frame_reference(None|int|WebElement):
The identifier of the frame to switch to.
None means to set to the default context.
An integer representing the index.
A webelement means that is an (i)frame to switch to.
Otherwise throw an error.
Returns:
WebDriver Object.
|
macaca/webdriver.py
|
def switch_to_frame(self, frame_reference=None):
"""Switches focus to the specified frame, by index, name, or webelement.
Support:
Web(WebView)
Args:
frame_reference(None|int|WebElement):
The identifier of the frame to switch to.
None means to set to the default context.
An integer representing the index.
A webelement means that is an (i)frame to switch to.
Otherwise throw an error.
Returns:
WebDriver Object.
"""
if frame_reference is not None and type(frame_reference) not in [int, WebElement]:
raise TypeError('Type of frame_reference must be None or int or WebElement')
self._execute(Command.SWITCH_TO_FRAME,
{'id': frame_reference})
|
def switch_to_frame(self, frame_reference=None):
"""Switches focus to the specified frame, by index, name, or webelement.
Support:
Web(WebView)
Args:
frame_reference(None|int|WebElement):
The identifier of the frame to switch to.
None means to set to the default context.
An integer representing the index.
A webelement means that is an (i)frame to switch to.
Otherwise throw an error.
Returns:
WebDriver Object.
"""
if frame_reference is not None and type(frame_reference) not in [int, WebElement]:
raise TypeError('Type of frame_reference must be None or int or WebElement')
self._execute(Command.SWITCH_TO_FRAME,
{'id': frame_reference})
|
[
"Switches",
"focus",
"to",
"the",
"specified",
"frame",
"by",
"index",
"name",
"or",
"webelement",
"."
] |
macacajs/wd.py
|
python
|
https://github.com/macacajs/wd.py/blob/6d3c52060013e01a67cd52b68b5230b387427bad/macaca/webdriver.py#L501-L521
|
[
"def",
"switch_to_frame",
"(",
"self",
",",
"frame_reference",
"=",
"None",
")",
":",
"if",
"frame_reference",
"is",
"not",
"None",
"and",
"type",
"(",
"frame_reference",
")",
"not",
"in",
"[",
"int",
",",
"WebElement",
"]",
":",
"raise",
"TypeError",
"(",
"'Type of frame_reference must be None or int or WebElement'",
")",
"self",
".",
"_execute",
"(",
"Command",
".",
"SWITCH_TO_FRAME",
",",
"{",
"'id'",
":",
"frame_reference",
"}",
")"
] |
6d3c52060013e01a67cd52b68b5230b387427bad
|
valid
|
WebDriver.execute_script
|
Execute JavaScript Synchronously in current context.
Support:
Web(WebView)
Args:
script: The JavaScript to execute.
*args: Arguments for your JavaScript.
Returns:
Returns the return value of the function.
|
macaca/webdriver.py
|
def execute_script(self, script, *args):
"""Execute JavaScript Synchronously in current context.
Support:
Web(WebView)
Args:
script: The JavaScript to execute.
*args: Arguments for your JavaScript.
Returns:
Returns the return value of the function.
"""
return self._execute(Command.EXECUTE_SCRIPT, {
'script': script,
'args': list(args)})
|
def execute_script(self, script, *args):
"""Execute JavaScript Synchronously in current context.
Support:
Web(WebView)
Args:
script: The JavaScript to execute.
*args: Arguments for your JavaScript.
Returns:
Returns the return value of the function.
"""
return self._execute(Command.EXECUTE_SCRIPT, {
'script': script,
'args': list(args)})
|
[
"Execute",
"JavaScript",
"Synchronously",
"in",
"current",
"context",
"."
] |
macacajs/wd.py
|
python
|
https://github.com/macacajs/wd.py/blob/6d3c52060013e01a67cd52b68b5230b387427bad/macaca/webdriver.py#L554-L569
|
[
"def",
"execute_script",
"(",
"self",
",",
"script",
",",
"*",
"args",
")",
":",
"return",
"self",
".",
"_execute",
"(",
"Command",
".",
"EXECUTE_SCRIPT",
",",
"{",
"'script'",
":",
"script",
",",
"'args'",
":",
"list",
"(",
"args",
")",
"}",
")"
] |
6d3c52060013e01a67cd52b68b5230b387427bad
|
valid
|
WebDriver.execute_async_script
|
Execute JavaScript Asynchronously in current context.
Support:
Web(WebView)
Args:
script: The JavaScript to execute.
*args: Arguments for your JavaScript.
Returns:
Returns the return value of the function.
|
macaca/webdriver.py
|
def execute_async_script(self, script, *args):
"""Execute JavaScript Asynchronously in current context.
Support:
Web(WebView)
Args:
script: The JavaScript to execute.
*args: Arguments for your JavaScript.
Returns:
Returns the return value of the function.
"""
return self._execute(Command.EXECUTE_ASYNC_SCRIPT, {
'script': script,
'args': list(args)})
|
def execute_async_script(self, script, *args):
"""Execute JavaScript Asynchronously in current context.
Support:
Web(WebView)
Args:
script: The JavaScript to execute.
*args: Arguments for your JavaScript.
Returns:
Returns the return value of the function.
"""
return self._execute(Command.EXECUTE_ASYNC_SCRIPT, {
'script': script,
'args': list(args)})
|
[
"Execute",
"JavaScript",
"Asynchronously",
"in",
"current",
"context",
"."
] |
macacajs/wd.py
|
python
|
https://github.com/macacajs/wd.py/blob/6d3c52060013e01a67cd52b68b5230b387427bad/macaca/webdriver.py#L572-L587
|
[
"def",
"execute_async_script",
"(",
"self",
",",
"script",
",",
"*",
"args",
")",
":",
"return",
"self",
".",
"_execute",
"(",
"Command",
".",
"EXECUTE_ASYNC_SCRIPT",
",",
"{",
"'script'",
":",
"script",
",",
"'args'",
":",
"list",
"(",
"args",
")",
"}",
")"
] |
6d3c52060013e01a67cd52b68b5230b387427bad
|
valid
|
WebDriver.add_cookie
|
Set a cookie.
Support:
Web(WebView)
Args:
cookie_dict: A dictionary contain keys: "name", "value",
["path"], ["domain"], ["secure"], ["httpOnly"], ["expiry"].
Returns:
WebElement Object.
|
macaca/webdriver.py
|
def add_cookie(self, cookie_dict):
"""Set a cookie.
Support:
Web(WebView)
Args:
cookie_dict: A dictionary contain keys: "name", "value",
["path"], ["domain"], ["secure"], ["httpOnly"], ["expiry"].
Returns:
WebElement Object.
"""
if not isinstance(cookie_dict, dict):
raise TypeError('Type of the cookie must be a dict.')
if not cookie_dict.get(
'name', None
) or not cookie_dict.get(
'value', None):
raise KeyError('Missing required keys, \'name\' and \'value\' must be provided.')
self._execute(Command.ADD_COOKIE, {'cookie': cookie_dict})
|
def add_cookie(self, cookie_dict):
"""Set a cookie.
Support:
Web(WebView)
Args:
cookie_dict: A dictionary contain keys: "name", "value",
["path"], ["domain"], ["secure"], ["httpOnly"], ["expiry"].
Returns:
WebElement Object.
"""
if not isinstance(cookie_dict, dict):
raise TypeError('Type of the cookie must be a dict.')
if not cookie_dict.get(
'name', None
) or not cookie_dict.get(
'value', None):
raise KeyError('Missing required keys, \'name\' and \'value\' must be provided.')
self._execute(Command.ADD_COOKIE, {'cookie': cookie_dict})
|
[
"Set",
"a",
"cookie",
"."
] |
macacajs/wd.py
|
python
|
https://github.com/macacajs/wd.py/blob/6d3c52060013e01a67cd52b68b5230b387427bad/macaca/webdriver.py#L634-L654
|
[
"def",
"add_cookie",
"(",
"self",
",",
"cookie_dict",
")",
":",
"if",
"not",
"isinstance",
"(",
"cookie_dict",
",",
"dict",
")",
":",
"raise",
"TypeError",
"(",
"'Type of the cookie must be a dict.'",
")",
"if",
"not",
"cookie_dict",
".",
"get",
"(",
"'name'",
",",
"None",
")",
"or",
"not",
"cookie_dict",
".",
"get",
"(",
"'value'",
",",
"None",
")",
":",
"raise",
"KeyError",
"(",
"'Missing required keys, \\'name\\' and \\'value\\' must be provided.'",
")",
"self",
".",
"_execute",
"(",
"Command",
".",
"ADD_COOKIE",
",",
"{",
"'cookie'",
":",
"cookie_dict",
"}",
")"
] |
6d3c52060013e01a67cd52b68b5230b387427bad
|
valid
|
WebDriver.save_screenshot
|
Save the screenshot to local.
Support:
Android iOS Web(WebView)
Args:
filename(str): The path to save the image.
quietly(bool): If True, omit the IOError when
failed to save the image.
Returns:
WebElement Object.
Raises:
WebDriverException.
IOError.
|
macaca/webdriver.py
|
def save_screenshot(self, filename, quietly = False):
"""Save the screenshot to local.
Support:
Android iOS Web(WebView)
Args:
filename(str): The path to save the image.
quietly(bool): If True, omit the IOError when
failed to save the image.
Returns:
WebElement Object.
Raises:
WebDriverException.
IOError.
"""
imgData = self.take_screenshot()
try:
with open(filename, "wb") as f:
f.write(b64decode(imgData.encode('ascii')))
except IOError as err:
if not quietly:
raise err
|
def save_screenshot(self, filename, quietly = False):
"""Save the screenshot to local.
Support:
Android iOS Web(WebView)
Args:
filename(str): The path to save the image.
quietly(bool): If True, omit the IOError when
failed to save the image.
Returns:
WebElement Object.
Raises:
WebDriverException.
IOError.
"""
imgData = self.take_screenshot()
try:
with open(filename, "wb") as f:
f.write(b64decode(imgData.encode('ascii')))
except IOError as err:
if not quietly:
raise err
|
[
"Save",
"the",
"screenshot",
"to",
"local",
"."
] |
macacajs/wd.py
|
python
|
https://github.com/macacajs/wd.py/blob/6d3c52060013e01a67cd52b68b5230b387427bad/macaca/webdriver.py#L763-L787
|
[
"def",
"save_screenshot",
"(",
"self",
",",
"filename",
",",
"quietly",
"=",
"False",
")",
":",
"imgData",
"=",
"self",
".",
"take_screenshot",
"(",
")",
"try",
":",
"with",
"open",
"(",
"filename",
",",
"\"wb\"",
")",
"as",
"f",
":",
"f",
".",
"write",
"(",
"b64decode",
"(",
"imgData",
".",
"encode",
"(",
"'ascii'",
")",
")",
")",
"except",
"IOError",
"as",
"err",
":",
"if",
"not",
"quietly",
":",
"raise",
"err"
] |
6d3c52060013e01a67cd52b68b5230b387427bad
|
valid
|
WebDriver.element
|
Find an element in the current context.
Support:
Android iOS Web(WebView)
Args:
using(str): The element location strategy.
value(str): The value of the location strategy.
Returns:
WebElement Object.
Raises:
WebDriverException.
|
macaca/webdriver.py
|
def element(self, using, value):
"""Find an element in the current context.
Support:
Android iOS Web(WebView)
Args:
using(str): The element location strategy.
value(str): The value of the location strategy.
Returns:
WebElement Object.
Raises:
WebDriverException.
"""
return self._execute(Command.FIND_ELEMENT, {
'using': using,
'value': value
})
|
def element(self, using, value):
"""Find an element in the current context.
Support:
Android iOS Web(WebView)
Args:
using(str): The element location strategy.
value(str): The value of the location strategy.
Returns:
WebElement Object.
Raises:
WebDriverException.
"""
return self._execute(Command.FIND_ELEMENT, {
'using': using,
'value': value
})
|
[
"Find",
"an",
"element",
"in",
"the",
"current",
"context",
"."
] |
macacajs/wd.py
|
python
|
https://github.com/macacajs/wd.py/blob/6d3c52060013e01a67cd52b68b5230b387427bad/macaca/webdriver.py#L789-L808
|
[
"def",
"element",
"(",
"self",
",",
"using",
",",
"value",
")",
":",
"return",
"self",
".",
"_execute",
"(",
"Command",
".",
"FIND_ELEMENT",
",",
"{",
"'using'",
":",
"using",
",",
"'value'",
":",
"value",
"}",
")"
] |
6d3c52060013e01a67cd52b68b5230b387427bad
|
valid
|
WebDriver.element_if_exists
|
Check if an element in the current context.
Support:
Android iOS Web(WebView)
Args:
using(str): The element location strategy.
value(str): The value of the location strategy.
Returns:
Return True if the element does exists and return False otherwise.
Raises:
WebDriverException.
|
macaca/webdriver.py
|
def element_if_exists(self, using, value):
"""Check if an element in the current context.
Support:
Android iOS Web(WebView)
Args:
using(str): The element location strategy.
value(str): The value of the location strategy.
Returns:
Return True if the element does exists and return False otherwise.
Raises:
WebDriverException.
"""
try:
self._execute(Command.FIND_ELEMENT, {
'using': using,
'value': value
})
return True
except:
return False
|
def element_if_exists(self, using, value):
"""Check if an element in the current context.
Support:
Android iOS Web(WebView)
Args:
using(str): The element location strategy.
value(str): The value of the location strategy.
Returns:
Return True if the element does exists and return False otherwise.
Raises:
WebDriverException.
"""
try:
self._execute(Command.FIND_ELEMENT, {
'using': using,
'value': value
})
return True
except:
return False
|
[
"Check",
"if",
"an",
"element",
"in",
"the",
"current",
"context",
"."
] |
macacajs/wd.py
|
python
|
https://github.com/macacajs/wd.py/blob/6d3c52060013e01a67cd52b68b5230b387427bad/macaca/webdriver.py#L810-L833
|
[
"def",
"element_if_exists",
"(",
"self",
",",
"using",
",",
"value",
")",
":",
"try",
":",
"self",
".",
"_execute",
"(",
"Command",
".",
"FIND_ELEMENT",
",",
"{",
"'using'",
":",
"using",
",",
"'value'",
":",
"value",
"}",
")",
"return",
"True",
"except",
":",
"return",
"False"
] |
6d3c52060013e01a67cd52b68b5230b387427bad
|
valid
|
WebDriver.element_or_none
|
Check if an element in the current context.
Support:
Android iOS Web(WebView)
Args:
using(str): The element location strategy.
value(str): The value of the location strategy.
Returns:
Return Element if the element does exists and return None otherwise.
Raises:
WebDriverException.
|
macaca/webdriver.py
|
def element_or_none(self, using, value):
"""Check if an element in the current context.
Support:
Android iOS Web(WebView)
Args:
using(str): The element location strategy.
value(str): The value of the location strategy.
Returns:
Return Element if the element does exists and return None otherwise.
Raises:
WebDriverException.
"""
try:
return self._execute(Command.FIND_ELEMENT, {
'using': using,
'value': value
})
except:
return None
|
def element_or_none(self, using, value):
"""Check if an element in the current context.
Support:
Android iOS Web(WebView)
Args:
using(str): The element location strategy.
value(str): The value of the location strategy.
Returns:
Return Element if the element does exists and return None otherwise.
Raises:
WebDriverException.
"""
try:
return self._execute(Command.FIND_ELEMENT, {
'using': using,
'value': value
})
except:
return None
|
[
"Check",
"if",
"an",
"element",
"in",
"the",
"current",
"context",
"."
] |
macacajs/wd.py
|
python
|
https://github.com/macacajs/wd.py/blob/6d3c52060013e01a67cd52b68b5230b387427bad/macaca/webdriver.py#L835-L857
|
[
"def",
"element_or_none",
"(",
"self",
",",
"using",
",",
"value",
")",
":",
"try",
":",
"return",
"self",
".",
"_execute",
"(",
"Command",
".",
"FIND_ELEMENT",
",",
"{",
"'using'",
":",
"using",
",",
"'value'",
":",
"value",
"}",
")",
"except",
":",
"return",
"None"
] |
6d3c52060013e01a67cd52b68b5230b387427bad
|
valid
|
WebDriver.elements
|
Find elements in the current context.
Support:
Android iOS Web(WebView)
Args:
using(str): The element location strategy.
value(str): The value of the location strategy.
Returns:
Return a List<Element | None>, if no element matched, the list is empty.
Raises:
WebDriverException.
|
macaca/webdriver.py
|
def elements(self, using, value):
"""Find elements in the current context.
Support:
Android iOS Web(WebView)
Args:
using(str): The element location strategy.
value(str): The value of the location strategy.
Returns:
Return a List<Element | None>, if no element matched, the list is empty.
Raises:
WebDriverException.
"""
return self._execute(Command.FIND_ELEMENTS, {
'using': using,
'value': value
})
|
def elements(self, using, value):
"""Find elements in the current context.
Support:
Android iOS Web(WebView)
Args:
using(str): The element location strategy.
value(str): The value of the location strategy.
Returns:
Return a List<Element | None>, if no element matched, the list is empty.
Raises:
WebDriverException.
"""
return self._execute(Command.FIND_ELEMENTS, {
'using': using,
'value': value
})
|
[
"Find",
"elements",
"in",
"the",
"current",
"context",
"."
] |
macacajs/wd.py
|
python
|
https://github.com/macacajs/wd.py/blob/6d3c52060013e01a67cd52b68b5230b387427bad/macaca/webdriver.py#L859-L878
|
[
"def",
"elements",
"(",
"self",
",",
"using",
",",
"value",
")",
":",
"return",
"self",
".",
"_execute",
"(",
"Command",
".",
"FIND_ELEMENTS",
",",
"{",
"'using'",
":",
"using",
",",
"'value'",
":",
"value",
"}",
")"
] |
6d3c52060013e01a67cd52b68b5230b387427bad
|
valid
|
WebDriver.wait_for
|
Wait for driver till satisfy the given condition
Support:
Android iOS Web(WebView)
Args:
timeout(int): How long we should be retrying stuff.
interval(int): How long between retries.
asserter(callable): The asserter func to determine the result.
Returns:
Return the driver.
Raises:
WebDriverException.
|
macaca/webdriver.py
|
def wait_for(
self, timeout=10000, interval=1000,
asserter=lambda x: x):
"""Wait for driver till satisfy the given condition
Support:
Android iOS Web(WebView)
Args:
timeout(int): How long we should be retrying stuff.
interval(int): How long between retries.
asserter(callable): The asserter func to determine the result.
Returns:
Return the driver.
Raises:
WebDriverException.
"""
if not callable(asserter):
raise TypeError('Asserter must be callable.')
@retry(
retry_on_exception=lambda ex: isinstance(ex, WebDriverException),
stop_max_delay=timeout,
wait_fixed=interval
)
def _wait_for(driver):
asserter(driver)
return driver
return _wait_for(self)
|
def wait_for(
self, timeout=10000, interval=1000,
asserter=lambda x: x):
"""Wait for driver till satisfy the given condition
Support:
Android iOS Web(WebView)
Args:
timeout(int): How long we should be retrying stuff.
interval(int): How long between retries.
asserter(callable): The asserter func to determine the result.
Returns:
Return the driver.
Raises:
WebDriverException.
"""
if not callable(asserter):
raise TypeError('Asserter must be callable.')
@retry(
retry_on_exception=lambda ex: isinstance(ex, WebDriverException),
stop_max_delay=timeout,
wait_fixed=interval
)
def _wait_for(driver):
asserter(driver)
return driver
return _wait_for(self)
|
[
"Wait",
"for",
"driver",
"till",
"satisfy",
"the",
"given",
"condition"
] |
macacajs/wd.py
|
python
|
https://github.com/macacajs/wd.py/blob/6d3c52060013e01a67cd52b68b5230b387427bad/macaca/webdriver.py#L880-L910
|
[
"def",
"wait_for",
"(",
"self",
",",
"timeout",
"=",
"10000",
",",
"interval",
"=",
"1000",
",",
"asserter",
"=",
"lambda",
"x",
":",
"x",
")",
":",
"if",
"not",
"callable",
"(",
"asserter",
")",
":",
"raise",
"TypeError",
"(",
"'Asserter must be callable.'",
")",
"@",
"retry",
"(",
"retry_on_exception",
"=",
"lambda",
"ex",
":",
"isinstance",
"(",
"ex",
",",
"WebDriverException",
")",
",",
"stop_max_delay",
"=",
"timeout",
",",
"wait_fixed",
"=",
"interval",
")",
"def",
"_wait_for",
"(",
"driver",
")",
":",
"asserter",
"(",
"driver",
")",
"return",
"driver",
"return",
"_wait_for",
"(",
"self",
")"
] |
6d3c52060013e01a67cd52b68b5230b387427bad
|
valid
|
WebDriver.wait_for_element
|
Wait for element till satisfy the given condition
Support:
Android iOS Web(WebView)
Args:
using(str): The element location strategy.
value(str): The value of the location strategy.
timeout(int): How long we should be retrying stuff.
interval(int): How long between retries.
asserter(callable): The asserter func to determine the result.
Returns:
Return the Element.
Raises:
WebDriverException.
|
macaca/webdriver.py
|
def wait_for_element(
self, using, value, timeout=10000,
interval=1000, asserter=is_displayed):
"""Wait for element till satisfy the given condition
Support:
Android iOS Web(WebView)
Args:
using(str): The element location strategy.
value(str): The value of the location strategy.
timeout(int): How long we should be retrying stuff.
interval(int): How long between retries.
asserter(callable): The asserter func to determine the result.
Returns:
Return the Element.
Raises:
WebDriverException.
"""
if not callable(asserter):
raise TypeError('Asserter must be callable.')
@retry(
retry_on_exception=lambda ex: isinstance(ex, WebDriverException),
stop_max_delay=timeout,
wait_fixed=interval
)
def _wait_for_element(ctx, using, value):
el = ctx.element(using, value)
asserter(el)
return el
return _wait_for_element(self, using, value)
|
def wait_for_element(
self, using, value, timeout=10000,
interval=1000, asserter=is_displayed):
"""Wait for element till satisfy the given condition
Support:
Android iOS Web(WebView)
Args:
using(str): The element location strategy.
value(str): The value of the location strategy.
timeout(int): How long we should be retrying stuff.
interval(int): How long between retries.
asserter(callable): The asserter func to determine the result.
Returns:
Return the Element.
Raises:
WebDriverException.
"""
if not callable(asserter):
raise TypeError('Asserter must be callable.')
@retry(
retry_on_exception=lambda ex: isinstance(ex, WebDriverException),
stop_max_delay=timeout,
wait_fixed=interval
)
def _wait_for_element(ctx, using, value):
el = ctx.element(using, value)
asserter(el)
return el
return _wait_for_element(self, using, value)
|
[
"Wait",
"for",
"element",
"till",
"satisfy",
"the",
"given",
"condition"
] |
macacajs/wd.py
|
python
|
https://github.com/macacajs/wd.py/blob/6d3c52060013e01a67cd52b68b5230b387427bad/macaca/webdriver.py#L912-L945
|
[
"def",
"wait_for_element",
"(",
"self",
",",
"using",
",",
"value",
",",
"timeout",
"=",
"10000",
",",
"interval",
"=",
"1000",
",",
"asserter",
"=",
"is_displayed",
")",
":",
"if",
"not",
"callable",
"(",
"asserter",
")",
":",
"raise",
"TypeError",
"(",
"'Asserter must be callable.'",
")",
"@",
"retry",
"(",
"retry_on_exception",
"=",
"lambda",
"ex",
":",
"isinstance",
"(",
"ex",
",",
"WebDriverException",
")",
",",
"stop_max_delay",
"=",
"timeout",
",",
"wait_fixed",
"=",
"interval",
")",
"def",
"_wait_for_element",
"(",
"ctx",
",",
"using",
",",
"value",
")",
":",
"el",
"=",
"ctx",
".",
"element",
"(",
"using",
",",
"value",
")",
"asserter",
"(",
"el",
")",
"return",
"el",
"return",
"_wait_for_element",
"(",
"self",
",",
"using",
",",
"value",
")"
] |
6d3c52060013e01a67cd52b68b5230b387427bad
|
valid
|
WebDriver.wait_for_elements
|
Wait for elements till satisfy the given condition
Support:
Android iOS Web(WebView)
Args:
using(str): The element location strategy.
value(str): The value of the location strategy.
timeout(int): How long we should be retrying stuff.
interval(int): How long between retries.
asserter(callable): The asserter func to determine the result.
Returns:
Return the list of Element if any of them satisfy the condition.
Raises:
WebDriverException.
|
macaca/webdriver.py
|
def wait_for_elements(
self, using, value, timeout=10000,
interval=1000, asserter=is_displayed):
"""Wait for elements till satisfy the given condition
Support:
Android iOS Web(WebView)
Args:
using(str): The element location strategy.
value(str): The value of the location strategy.
timeout(int): How long we should be retrying stuff.
interval(int): How long between retries.
asserter(callable): The asserter func to determine the result.
Returns:
Return the list of Element if any of them satisfy the condition.
Raises:
WebDriverException.
"""
if not callable(asserter):
raise TypeError('Asserter must be callable.')
@retry(
retry_on_exception=lambda ex: isinstance(ex, WebDriverException),
stop_max_delay=timeout,
wait_fixed=interval
)
def _wait_for_elements(ctx, using, value):
els = ctx.elements(using, value)
if not len(els):
raise WebDriverException('no such element')
else:
el = els[0]
asserter(el)
return els
return _wait_for_elements(self, using, value)
|
def wait_for_elements(
self, using, value, timeout=10000,
interval=1000, asserter=is_displayed):
"""Wait for elements till satisfy the given condition
Support:
Android iOS Web(WebView)
Args:
using(str): The element location strategy.
value(str): The value of the location strategy.
timeout(int): How long we should be retrying stuff.
interval(int): How long between retries.
asserter(callable): The asserter func to determine the result.
Returns:
Return the list of Element if any of them satisfy the condition.
Raises:
WebDriverException.
"""
if not callable(asserter):
raise TypeError('Asserter must be callable.')
@retry(
retry_on_exception=lambda ex: isinstance(ex, WebDriverException),
stop_max_delay=timeout,
wait_fixed=interval
)
def _wait_for_elements(ctx, using, value):
els = ctx.elements(using, value)
if not len(els):
raise WebDriverException('no such element')
else:
el = els[0]
asserter(el)
return els
return _wait_for_elements(self, using, value)
|
[
"Wait",
"for",
"elements",
"till",
"satisfy",
"the",
"given",
"condition"
] |
macacajs/wd.py
|
python
|
https://github.com/macacajs/wd.py/blob/6d3c52060013e01a67cd52b68b5230b387427bad/macaca/webdriver.py#L947-L984
|
[
"def",
"wait_for_elements",
"(",
"self",
",",
"using",
",",
"value",
",",
"timeout",
"=",
"10000",
",",
"interval",
"=",
"1000",
",",
"asserter",
"=",
"is_displayed",
")",
":",
"if",
"not",
"callable",
"(",
"asserter",
")",
":",
"raise",
"TypeError",
"(",
"'Asserter must be callable.'",
")",
"@",
"retry",
"(",
"retry_on_exception",
"=",
"lambda",
"ex",
":",
"isinstance",
"(",
"ex",
",",
"WebDriverException",
")",
",",
"stop_max_delay",
"=",
"timeout",
",",
"wait_fixed",
"=",
"interval",
")",
"def",
"_wait_for_elements",
"(",
"ctx",
",",
"using",
",",
"value",
")",
":",
"els",
"=",
"ctx",
".",
"elements",
"(",
"using",
",",
"value",
")",
"if",
"not",
"len",
"(",
"els",
")",
":",
"raise",
"WebDriverException",
"(",
"'no such element'",
")",
"else",
":",
"el",
"=",
"els",
"[",
"0",
"]",
"asserter",
"(",
"el",
")",
"return",
"els",
"return",
"_wait_for_elements",
"(",
"self",
",",
"using",
",",
"value",
")"
] |
6d3c52060013e01a67cd52b68b5230b387427bad
|
valid
|
WebDriverResult.from_object
|
The factory method to create WebDriverResult from JSON Object.
Args:
obj(dict): The JSON Object returned by server.
|
macaca/webdriverresult.py
|
def from_object(cls, obj):
"""The factory method to create WebDriverResult from JSON Object.
Args:
obj(dict): The JSON Object returned by server.
"""
return cls(
obj.get('sessionId', None),
obj.get('status', 0),
obj.get('value', None)
)
|
def from_object(cls, obj):
"""The factory method to create WebDriverResult from JSON Object.
Args:
obj(dict): The JSON Object returned by server.
"""
return cls(
obj.get('sessionId', None),
obj.get('status', 0),
obj.get('value', None)
)
|
[
"The",
"factory",
"method",
"to",
"create",
"WebDriverResult",
"from",
"JSON",
"Object",
"."
] |
macacajs/wd.py
|
python
|
https://github.com/macacajs/wd.py/blob/6d3c52060013e01a67cd52b68b5230b387427bad/macaca/webdriverresult.py#L25-L35
|
[
"def",
"from_object",
"(",
"cls",
",",
"obj",
")",
":",
"return",
"cls",
"(",
"obj",
".",
"get",
"(",
"'sessionId'",
",",
"None",
")",
",",
"obj",
".",
"get",
"(",
"'status'",
",",
"0",
")",
",",
"obj",
".",
"get",
"(",
"'value'",
",",
"None",
")",
")"
] |
6d3c52060013e01a67cd52b68b5230b387427bad
|
valid
|
WebDriverResult.raise_for_status
|
Raise WebDriverException if returned status is not zero.
|
macaca/webdriverresult.py
|
def raise_for_status(self):
"""Raise WebDriverException if returned status is not zero."""
if not self.status:
return
error = find_exception_by_code(self.status)
message = None
screen = None
stacktrace = None
if isinstance(self.value, str):
message = self.value
elif isinstance(self.value, dict):
message = self.value.get('message', None)
screen = self.value.get('screen', None)
stacktrace = self.value.get('stacktrace', None)
raise WebDriverException(error, message, screen, stacktrace)
|
def raise_for_status(self):
"""Raise WebDriverException if returned status is not zero."""
if not self.status:
return
error = find_exception_by_code(self.status)
message = None
screen = None
stacktrace = None
if isinstance(self.value, str):
message = self.value
elif isinstance(self.value, dict):
message = self.value.get('message', None)
screen = self.value.get('screen', None)
stacktrace = self.value.get('stacktrace', None)
raise WebDriverException(error, message, screen, stacktrace)
|
[
"Raise",
"WebDriverException",
"if",
"returned",
"status",
"is",
"not",
"zero",
"."
] |
macacajs/wd.py
|
python
|
https://github.com/macacajs/wd.py/blob/6d3c52060013e01a67cd52b68b5230b387427bad/macaca/webdriverresult.py#L37-L54
|
[
"def",
"raise_for_status",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"status",
":",
"return",
"error",
"=",
"find_exception_by_code",
"(",
"self",
".",
"status",
")",
"message",
"=",
"None",
"screen",
"=",
"None",
"stacktrace",
"=",
"None",
"if",
"isinstance",
"(",
"self",
".",
"value",
",",
"str",
")",
":",
"message",
"=",
"self",
".",
"value",
"elif",
"isinstance",
"(",
"self",
".",
"value",
",",
"dict",
")",
":",
"message",
"=",
"self",
".",
"value",
".",
"get",
"(",
"'message'",
",",
"None",
")",
"screen",
"=",
"self",
".",
"value",
".",
"get",
"(",
"'screen'",
",",
"None",
")",
"stacktrace",
"=",
"self",
".",
"value",
".",
"get",
"(",
"'stacktrace'",
",",
"None",
")",
"raise",
"WebDriverException",
"(",
"error",
",",
"message",
",",
"screen",
",",
"stacktrace",
")"
] |
6d3c52060013e01a67cd52b68b5230b387427bad
|
valid
|
add_element_extension_method
|
Add element_by alias and extension' methods(if_exists/or_none).
|
macaca/util.py
|
def add_element_extension_method(Klass):
"""Add element_by alias and extension' methods(if_exists/or_none)."""
def add_element_method(Klass, using):
locator = using.name.lower()
find_element_name = "element_by_" + locator
find_element_if_exists_name = "element_by_" + locator + "_if_exists"
find_element_or_none_name = "element_by_" + locator + "_or_none"
wait_for_element_name = "wait_for_element_by_" + locator
find_elements_name = "elements_by_" + locator
wait_for_elements_name = "wait_for_elements_by_" + locator
def find_element(self, value):
return self.element(using.value, value)
find_element.__name__ = find_element_name
find_element.__doc__ = (
"Set parameter 'using' to '{0}'.\n".format(using.value) +
"See more in \'element\' method."
)
def find_element_if_exists(self, value):
return self.element_if_exists(using.value, value)
find_element_if_exists.__name__ = find_element_if_exists_name
find_element_if_exists.__doc__ = (
"Set parameter 'using' to '{0}'.\n".format(using.value) +
"See more in \'element_if_exists\' method."
)
def find_element_or_none(self, value):
return self.element_or_none(using.value, value)
find_element_or_none.__name__ = find_element_or_none_name
find_element_or_none.__doc__ = (
"Set parameter 'using' to '{0}'.\n".format(using.value) +
"See more in \'element_or_none\' method."
)
def wait_for_element_by(self, *args, **kwargs):
return self.wait_for_element(using.value, *args, **kwargs)
wait_for_element_by.__name__ = wait_for_element_name
wait_for_element_by.__doc__ = (
"Set parameter 'using' to '{0}'.\n".format(using.value) +
"See more in \'wait_for_element\' method."
)
def find_elements(self, value):
return self.elements(using.value, value)
find_elements.__name__ = find_elements_name
find_elements.__doc__ = (
"Set parameter 'using' to '{0}'.\n".format(using.value) +
"See more in \'elements\' method."
)
def wait_for_elements_available(self, *args, **kwargs):
return self.wait_for_elements(using.value, *args, **kwargs)
wait_for_elements_available.__name__ = wait_for_elements_name
wait_for_elements_available.__doc__ = (
"Set parameter 'using' to '{0}'.\n".format(using.value) +
"See more in \'wait_for_elements\' method."
)
setattr(Klass, find_element_name, find_element)
setattr(Klass, find_element_if_exists_name, find_element_if_exists)
setattr(Klass, find_element_or_none_name, find_element_or_none)
setattr(Klass, wait_for_element_name, wait_for_element_by)
setattr(Klass, find_elements_name, find_elements)
setattr(Klass, wait_for_elements_name, wait_for_elements_available)
for locator in iter(Locator):
add_element_method(Klass, locator)
|
def add_element_extension_method(Klass):
"""Add element_by alias and extension' methods(if_exists/or_none)."""
def add_element_method(Klass, using):
locator = using.name.lower()
find_element_name = "element_by_" + locator
find_element_if_exists_name = "element_by_" + locator + "_if_exists"
find_element_or_none_name = "element_by_" + locator + "_or_none"
wait_for_element_name = "wait_for_element_by_" + locator
find_elements_name = "elements_by_" + locator
wait_for_elements_name = "wait_for_elements_by_" + locator
def find_element(self, value):
return self.element(using.value, value)
find_element.__name__ = find_element_name
find_element.__doc__ = (
"Set parameter 'using' to '{0}'.\n".format(using.value) +
"See more in \'element\' method."
)
def find_element_if_exists(self, value):
return self.element_if_exists(using.value, value)
find_element_if_exists.__name__ = find_element_if_exists_name
find_element_if_exists.__doc__ = (
"Set parameter 'using' to '{0}'.\n".format(using.value) +
"See more in \'element_if_exists\' method."
)
def find_element_or_none(self, value):
return self.element_or_none(using.value, value)
find_element_or_none.__name__ = find_element_or_none_name
find_element_or_none.__doc__ = (
"Set parameter 'using' to '{0}'.\n".format(using.value) +
"See more in \'element_or_none\' method."
)
def wait_for_element_by(self, *args, **kwargs):
return self.wait_for_element(using.value, *args, **kwargs)
wait_for_element_by.__name__ = wait_for_element_name
wait_for_element_by.__doc__ = (
"Set parameter 'using' to '{0}'.\n".format(using.value) +
"See more in \'wait_for_element\' method."
)
def find_elements(self, value):
return self.elements(using.value, value)
find_elements.__name__ = find_elements_name
find_elements.__doc__ = (
"Set parameter 'using' to '{0}'.\n".format(using.value) +
"See more in \'elements\' method."
)
def wait_for_elements_available(self, *args, **kwargs):
return self.wait_for_elements(using.value, *args, **kwargs)
wait_for_elements_available.__name__ = wait_for_elements_name
wait_for_elements_available.__doc__ = (
"Set parameter 'using' to '{0}'.\n".format(using.value) +
"See more in \'wait_for_elements\' method."
)
setattr(Klass, find_element_name, find_element)
setattr(Klass, find_element_if_exists_name, find_element_if_exists)
setattr(Klass, find_element_or_none_name, find_element_or_none)
setattr(Klass, wait_for_element_name, wait_for_element_by)
setattr(Klass, find_elements_name, find_elements)
setattr(Klass, wait_for_elements_name, wait_for_elements_available)
for locator in iter(Locator):
add_element_method(Klass, locator)
|
[
"Add",
"element_by",
"alias",
"and",
"extension",
"methods",
"(",
"if_exists",
"/",
"or_none",
")",
"."
] |
macacajs/wd.py
|
python
|
https://github.com/macacajs/wd.py/blob/6d3c52060013e01a67cd52b68b5230b387427bad/macaca/util.py#L64-L138
|
[
"def",
"add_element_extension_method",
"(",
"Klass",
")",
":",
"def",
"add_element_method",
"(",
"Klass",
",",
"using",
")",
":",
"locator",
"=",
"using",
".",
"name",
".",
"lower",
"(",
")",
"find_element_name",
"=",
"\"element_by_\"",
"+",
"locator",
"find_element_if_exists_name",
"=",
"\"element_by_\"",
"+",
"locator",
"+",
"\"_if_exists\"",
"find_element_or_none_name",
"=",
"\"element_by_\"",
"+",
"locator",
"+",
"\"_or_none\"",
"wait_for_element_name",
"=",
"\"wait_for_element_by_\"",
"+",
"locator",
"find_elements_name",
"=",
"\"elements_by_\"",
"+",
"locator",
"wait_for_elements_name",
"=",
"\"wait_for_elements_by_\"",
"+",
"locator",
"def",
"find_element",
"(",
"self",
",",
"value",
")",
":",
"return",
"self",
".",
"element",
"(",
"using",
".",
"value",
",",
"value",
")",
"find_element",
".",
"__name__",
"=",
"find_element_name",
"find_element",
".",
"__doc__",
"=",
"(",
"\"Set parameter 'using' to '{0}'.\\n\"",
".",
"format",
"(",
"using",
".",
"value",
")",
"+",
"\"See more in \\'element\\' method.\"",
")",
"def",
"find_element_if_exists",
"(",
"self",
",",
"value",
")",
":",
"return",
"self",
".",
"element_if_exists",
"(",
"using",
".",
"value",
",",
"value",
")",
"find_element_if_exists",
".",
"__name__",
"=",
"find_element_if_exists_name",
"find_element_if_exists",
".",
"__doc__",
"=",
"(",
"\"Set parameter 'using' to '{0}'.\\n\"",
".",
"format",
"(",
"using",
".",
"value",
")",
"+",
"\"See more in \\'element_if_exists\\' method.\"",
")",
"def",
"find_element_or_none",
"(",
"self",
",",
"value",
")",
":",
"return",
"self",
".",
"element_or_none",
"(",
"using",
".",
"value",
",",
"value",
")",
"find_element_or_none",
".",
"__name__",
"=",
"find_element_or_none_name",
"find_element_or_none",
".",
"__doc__",
"=",
"(",
"\"Set parameter 'using' to '{0}'.\\n\"",
".",
"format",
"(",
"using",
".",
"value",
")",
"+",
"\"See more in \\'element_or_none\\' method.\"",
")",
"def",
"wait_for_element_by",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"wait_for_element",
"(",
"using",
".",
"value",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"wait_for_element_by",
".",
"__name__",
"=",
"wait_for_element_name",
"wait_for_element_by",
".",
"__doc__",
"=",
"(",
"\"Set parameter 'using' to '{0}'.\\n\"",
".",
"format",
"(",
"using",
".",
"value",
")",
"+",
"\"See more in \\'wait_for_element\\' method.\"",
")",
"def",
"find_elements",
"(",
"self",
",",
"value",
")",
":",
"return",
"self",
".",
"elements",
"(",
"using",
".",
"value",
",",
"value",
")",
"find_elements",
".",
"__name__",
"=",
"find_elements_name",
"find_elements",
".",
"__doc__",
"=",
"(",
"\"Set parameter 'using' to '{0}'.\\n\"",
".",
"format",
"(",
"using",
".",
"value",
")",
"+",
"\"See more in \\'elements\\' method.\"",
")",
"def",
"wait_for_elements_available",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"wait_for_elements",
"(",
"using",
".",
"value",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"wait_for_elements_available",
".",
"__name__",
"=",
"wait_for_elements_name",
"wait_for_elements_available",
".",
"__doc__",
"=",
"(",
"\"Set parameter 'using' to '{0}'.\\n\"",
".",
"format",
"(",
"using",
".",
"value",
")",
"+",
"\"See more in \\'wait_for_elements\\' method.\"",
")",
"setattr",
"(",
"Klass",
",",
"find_element_name",
",",
"find_element",
")",
"setattr",
"(",
"Klass",
",",
"find_element_if_exists_name",
",",
"find_element_if_exists",
")",
"setattr",
"(",
"Klass",
",",
"find_element_or_none_name",
",",
"find_element_or_none",
")",
"setattr",
"(",
"Klass",
",",
"wait_for_element_name",
",",
"wait_for_element_by",
")",
"setattr",
"(",
"Klass",
",",
"find_elements_name",
",",
"find_elements",
")",
"setattr",
"(",
"Klass",
",",
"wait_for_elements_name",
",",
"wait_for_elements_available",
")",
"for",
"locator",
"in",
"iter",
"(",
"Locator",
")",
":",
"add_element_method",
"(",
"Klass",
",",
"locator",
")"
] |
6d3c52060013e01a67cd52b68b5230b387427bad
|
valid
|
fluent
|
Fluent interface decorator to return self if method return None.
|
macaca/util.py
|
def fluent(func):
"""Fluent interface decorator to return self if method return None."""
@wraps(func)
def fluent_interface(instance, *args, **kwargs):
ret = func(instance, *args, **kwargs)
if ret is not None:
return ret
return instance
return fluent_interface
|
def fluent(func):
"""Fluent interface decorator to return self if method return None."""
@wraps(func)
def fluent_interface(instance, *args, **kwargs):
ret = func(instance, *args, **kwargs)
if ret is not None:
return ret
return instance
return fluent_interface
|
[
"Fluent",
"interface",
"decorator",
"to",
"return",
"self",
"if",
"method",
"return",
"None",
"."
] |
macacajs/wd.py
|
python
|
https://github.com/macacajs/wd.py/blob/6d3c52060013e01a67cd52b68b5230b387427bad/macaca/util.py#L141-L149
|
[
"def",
"fluent",
"(",
"func",
")",
":",
"@",
"wraps",
"(",
"func",
")",
"def",
"fluent_interface",
"(",
"instance",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"ret",
"=",
"func",
"(",
"instance",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"if",
"ret",
"is",
"not",
"None",
":",
"return",
"ret",
"return",
"instance",
"return",
"fluent_interface"
] |
6d3c52060013e01a67cd52b68b5230b387427bad
|
valid
|
value_to_key_strokes
|
Convert value to a list of key strokes
>>> value_to_key_strokes(123)
['123']
>>> value_to_key_strokes('123')
['123']
>>> value_to_key_strokes([1, 2, 3])
['123']
>>> value_to_key_strokes(['1', '2', '3'])
['123']
Args:
value(int|str|list)
Returns:
A list of string.
|
macaca/util.py
|
def value_to_key_strokes(value):
"""Convert value to a list of key strokes
>>> value_to_key_strokes(123)
['123']
>>> value_to_key_strokes('123')
['123']
>>> value_to_key_strokes([1, 2, 3])
['123']
>>> value_to_key_strokes(['1', '2', '3'])
['123']
Args:
value(int|str|list)
Returns:
A list of string.
"""
result = ''
if isinstance(value, Integral):
value = str(value)
for v in value:
if isinstance(v, Keys):
result += v.value
elif isinstance(v, Integral):
result += str(v)
else:
result += v
return [result]
|
def value_to_key_strokes(value):
"""Convert value to a list of key strokes
>>> value_to_key_strokes(123)
['123']
>>> value_to_key_strokes('123')
['123']
>>> value_to_key_strokes([1, 2, 3])
['123']
>>> value_to_key_strokes(['1', '2', '3'])
['123']
Args:
value(int|str|list)
Returns:
A list of string.
"""
result = ''
if isinstance(value, Integral):
value = str(value)
for v in value:
if isinstance(v, Keys):
result += v.value
elif isinstance(v, Integral):
result += str(v)
else:
result += v
return [result]
|
[
"Convert",
"value",
"to",
"a",
"list",
"of",
"key",
"strokes",
">>>",
"value_to_key_strokes",
"(",
"123",
")",
"[",
"123",
"]",
">>>",
"value_to_key_strokes",
"(",
"123",
")",
"[",
"123",
"]",
">>>",
"value_to_key_strokes",
"(",
"[",
"1",
"2",
"3",
"]",
")",
"[",
"123",
"]",
">>>",
"value_to_key_strokes",
"(",
"[",
"1",
"2",
"3",
"]",
")",
"[",
"123",
"]"
] |
macacajs/wd.py
|
python
|
https://github.com/macacajs/wd.py/blob/6d3c52060013e01a67cd52b68b5230b387427bad/macaca/util.py#L152-L180
|
[
"def",
"value_to_key_strokes",
"(",
"value",
")",
":",
"result",
"=",
"''",
"if",
"isinstance",
"(",
"value",
",",
"Integral",
")",
":",
"value",
"=",
"str",
"(",
"value",
")",
"for",
"v",
"in",
"value",
":",
"if",
"isinstance",
"(",
"v",
",",
"Keys",
")",
":",
"result",
"+=",
"v",
".",
"value",
"elif",
"isinstance",
"(",
"v",
",",
"Integral",
")",
":",
"result",
"+=",
"str",
"(",
"v",
")",
"else",
":",
"result",
"+=",
"v",
"return",
"[",
"result",
"]"
] |
6d3c52060013e01a67cd52b68b5230b387427bad
|
valid
|
value_to_single_key_strokes
|
Convert value to a list of key strokes
>>> value_to_single_key_strokes(123)
['1', '2', '3']
>>> value_to_single_key_strokes('123')
['1', '2', '3']
>>> value_to_single_key_strokes([1, 2, 3])
['1', '2', '3']
>>> value_to_single_key_strokes(['1', '2', '3'])
['1', '2', '3']
Args:
value(int|str|list)
Returns:
A list of string.
|
macaca/util.py
|
def value_to_single_key_strokes(value):
"""Convert value to a list of key strokes
>>> value_to_single_key_strokes(123)
['1', '2', '3']
>>> value_to_single_key_strokes('123')
['1', '2', '3']
>>> value_to_single_key_strokes([1, 2, 3])
['1', '2', '3']
>>> value_to_single_key_strokes(['1', '2', '3'])
['1', '2', '3']
Args:
value(int|str|list)
Returns:
A list of string.
"""
result = []
if isinstance(value, Integral):
value = str(value)
for v in value:
if isinstance(v, Keys):
result.append(v.value)
elif isinstance(v, Integral):
result.append(str(v))
else:
result.append(v)
return result
|
def value_to_single_key_strokes(value):
"""Convert value to a list of key strokes
>>> value_to_single_key_strokes(123)
['1', '2', '3']
>>> value_to_single_key_strokes('123')
['1', '2', '3']
>>> value_to_single_key_strokes([1, 2, 3])
['1', '2', '3']
>>> value_to_single_key_strokes(['1', '2', '3'])
['1', '2', '3']
Args:
value(int|str|list)
Returns:
A list of string.
"""
result = []
if isinstance(value, Integral):
value = str(value)
for v in value:
if isinstance(v, Keys):
result.append(v.value)
elif isinstance(v, Integral):
result.append(str(v))
else:
result.append(v)
return result
|
[
"Convert",
"value",
"to",
"a",
"list",
"of",
"key",
"strokes",
">>>",
"value_to_single_key_strokes",
"(",
"123",
")",
"[",
"1",
"2",
"3",
"]",
">>>",
"value_to_single_key_strokes",
"(",
"123",
")",
"[",
"1",
"2",
"3",
"]",
">>>",
"value_to_single_key_strokes",
"(",
"[",
"1",
"2",
"3",
"]",
")",
"[",
"1",
"2",
"3",
"]",
">>>",
"value_to_single_key_strokes",
"(",
"[",
"1",
"2",
"3",
"]",
")",
"[",
"1",
"2",
"3",
"]",
"Args",
":",
"value",
"(",
"int|str|list",
")",
"Returns",
":",
"A",
"list",
"of",
"string",
"."
] |
macacajs/wd.py
|
python
|
https://github.com/macacajs/wd.py/blob/6d3c52060013e01a67cd52b68b5230b387427bad/macaca/util.py#L182-L208
|
[
"def",
"value_to_single_key_strokes",
"(",
"value",
")",
":",
"result",
"=",
"[",
"]",
"if",
"isinstance",
"(",
"value",
",",
"Integral",
")",
":",
"value",
"=",
"str",
"(",
"value",
")",
"for",
"v",
"in",
"value",
":",
"if",
"isinstance",
"(",
"v",
",",
"Keys",
")",
":",
"result",
".",
"append",
"(",
"v",
".",
"value",
")",
"elif",
"isinstance",
"(",
"v",
",",
"Integral",
")",
":",
"result",
".",
"append",
"(",
"str",
"(",
"v",
")",
")",
"else",
":",
"result",
".",
"append",
"(",
"v",
")",
"return",
"result"
] |
6d3c52060013e01a67cd52b68b5230b387427bad
|
valid
|
MemorizeFormatter.check_unused_args
|
Implement the check_unused_args in superclass.
|
macaca/util.py
|
def check_unused_args(self, used_args, args, kwargs):
"""Implement the check_unused_args in superclass."""
for k, v in kwargs.items():
if k in used_args:
self._used_kwargs.update({k: v})
else:
self._unused_kwargs.update({k: v})
|
def check_unused_args(self, used_args, args, kwargs):
"""Implement the check_unused_args in superclass."""
for k, v in kwargs.items():
if k in used_args:
self._used_kwargs.update({k: v})
else:
self._unused_kwargs.update({k: v})
|
[
"Implement",
"the",
"check_unused_args",
"in",
"superclass",
"."
] |
macacajs/wd.py
|
python
|
https://github.com/macacajs/wd.py/blob/6d3c52060013e01a67cd52b68b5230b387427bad/macaca/util.py#L26-L32
|
[
"def",
"check_unused_args",
"(",
"self",
",",
"used_args",
",",
"args",
",",
"kwargs",
")",
":",
"for",
"k",
",",
"v",
"in",
"kwargs",
".",
"items",
"(",
")",
":",
"if",
"k",
"in",
"used_args",
":",
"self",
".",
"_used_kwargs",
".",
"update",
"(",
"{",
"k",
":",
"v",
"}",
")",
"else",
":",
"self",
".",
"_unused_kwargs",
".",
"update",
"(",
"{",
"k",
":",
"v",
"}",
")"
] |
6d3c52060013e01a67cd52b68b5230b387427bad
|
valid
|
MemorizeFormatter.vformat
|
Clear used and unused dicts before each formatting.
|
macaca/util.py
|
def vformat(self, format_string, args, kwargs):
"""Clear used and unused dicts before each formatting."""
self._used_kwargs = {}
self._unused_kwargs = {}
return super(MemorizeFormatter, self).vformat(format_string, args, kwargs)
|
def vformat(self, format_string, args, kwargs):
"""Clear used and unused dicts before each formatting."""
self._used_kwargs = {}
self._unused_kwargs = {}
return super(MemorizeFormatter, self).vformat(format_string, args, kwargs)
|
[
"Clear",
"used",
"and",
"unused",
"dicts",
"before",
"each",
"formatting",
"."
] |
macacajs/wd.py
|
python
|
https://github.com/macacajs/wd.py/blob/6d3c52060013e01a67cd52b68b5230b387427bad/macaca/util.py#L34-L38
|
[
"def",
"vformat",
"(",
"self",
",",
"format_string",
",",
"args",
",",
"kwargs",
")",
":",
"self",
".",
"_used_kwargs",
"=",
"{",
"}",
"self",
".",
"_unused_kwargs",
"=",
"{",
"}",
"return",
"super",
"(",
"MemorizeFormatter",
",",
"self",
")",
".",
"vformat",
"(",
"format_string",
",",
"args",
",",
"kwargs",
")"
] |
6d3c52060013e01a67cd52b68b5230b387427bad
|
valid
|
MemorizeFormatter.format_map
|
format a string by a map
Args:
format_string(str): A format string
mapping(dict): A map to format the string
Returns:
A formatted string.
Raises:
KeyError: if key is not provided by the given map.
|
macaca/util.py
|
def format_map(self, format_string, mapping):
"""format a string by a map
Args:
format_string(str): A format string
mapping(dict): A map to format the string
Returns:
A formatted string.
Raises:
KeyError: if key is not provided by the given map.
"""
return self.vformat(format_string, args=None, kwargs=mapping)
|
def format_map(self, format_string, mapping):
"""format a string by a map
Args:
format_string(str): A format string
mapping(dict): A map to format the string
Returns:
A formatted string.
Raises:
KeyError: if key is not provided by the given map.
"""
return self.vformat(format_string, args=None, kwargs=mapping)
|
[
"format",
"a",
"string",
"by",
"a",
"map"
] |
macacajs/wd.py
|
python
|
https://github.com/macacajs/wd.py/blob/6d3c52060013e01a67cd52b68b5230b387427bad/macaca/util.py#L40-L53
|
[
"def",
"format_map",
"(",
"self",
",",
"format_string",
",",
"mapping",
")",
":",
"return",
"self",
".",
"vformat",
"(",
"format_string",
",",
"args",
"=",
"None",
",",
"kwargs",
"=",
"mapping",
")"
] |
6d3c52060013e01a67cd52b68b5230b387427bad
|
valid
|
find_exception_by_code
|
Find name of exception by WebDriver defined error code.
Args:
code(str): Error code defined in protocol.
Returns:
The error name defined in protocol.
|
macaca/webdriverexception.py
|
def find_exception_by_code(code):
"""Find name of exception by WebDriver defined error code.
Args:
code(str): Error code defined in protocol.
Returns:
The error name defined in protocol.
"""
errorName = None
for error in WebDriverError:
if error.value.code == code:
errorName = error
break
return errorName
|
def find_exception_by_code(code):
"""Find name of exception by WebDriver defined error code.
Args:
code(str): Error code defined in protocol.
Returns:
The error name defined in protocol.
"""
errorName = None
for error in WebDriverError:
if error.value.code == code:
errorName = error
break
return errorName
|
[
"Find",
"name",
"of",
"exception",
"by",
"WebDriver",
"defined",
"error",
"code",
"."
] |
macacajs/wd.py
|
python
|
https://github.com/macacajs/wd.py/blob/6d3c52060013e01a67cd52b68b5230b387427bad/macaca/webdriverexception.py#L41-L55
|
[
"def",
"find_exception_by_code",
"(",
"code",
")",
":",
"errorName",
"=",
"None",
"for",
"error",
"in",
"WebDriverError",
":",
"if",
"error",
".",
"value",
".",
"code",
"==",
"code",
":",
"errorName",
"=",
"error",
"break",
"return",
"errorName"
] |
6d3c52060013e01a67cd52b68b5230b387427bad
|
valid
|
RemoteInvoker.execute
|
Format the endpoint url by data and then request the remote server.
Args:
command(Command): WebDriver command to be executed.
data(dict): Data fulfill the uri template and json body.
Returns:
A dict represent the json body from server response.
Raises:
KeyError: Data cannot fulfill the variable which command needed.
ConnectionError: Meet network problem (e.g. DNS failure,
refused connection, etc).
Timeout: A request times out.
HTTPError: HTTP request returned an unsuccessful status code.
|
macaca/remote_invoker.py
|
def execute(self, command, data={}):
"""Format the endpoint url by data and then request the remote server.
Args:
command(Command): WebDriver command to be executed.
data(dict): Data fulfill the uri template and json body.
Returns:
A dict represent the json body from server response.
Raises:
KeyError: Data cannot fulfill the variable which command needed.
ConnectionError: Meet network problem (e.g. DNS failure,
refused connection, etc).
Timeout: A request times out.
HTTPError: HTTP request returned an unsuccessful status code.
"""
method, uri = command
try:
path = self._formatter.format_map(uri, data)
body = self._formatter.get_unused_kwargs()
url = "{0}{1}".format(self._url, path)
return self._request(method, url, body)
except KeyError as err:
LOGGER.debug(
'Endpoint {0} is missing argument {1}'.format(uri, err))
raise
|
def execute(self, command, data={}):
"""Format the endpoint url by data and then request the remote server.
Args:
command(Command): WebDriver command to be executed.
data(dict): Data fulfill the uri template and json body.
Returns:
A dict represent the json body from server response.
Raises:
KeyError: Data cannot fulfill the variable which command needed.
ConnectionError: Meet network problem (e.g. DNS failure,
refused connection, etc).
Timeout: A request times out.
HTTPError: HTTP request returned an unsuccessful status code.
"""
method, uri = command
try:
path = self._formatter.format_map(uri, data)
body = self._formatter.get_unused_kwargs()
url = "{0}{1}".format(self._url, path)
return self._request(method, url, body)
except KeyError as err:
LOGGER.debug(
'Endpoint {0} is missing argument {1}'.format(uri, err))
raise
|
[
"Format",
"the",
"endpoint",
"url",
"by",
"data",
"and",
"then",
"request",
"the",
"remote",
"server",
"."
] |
macacajs/wd.py
|
python
|
https://github.com/macacajs/wd.py/blob/6d3c52060013e01a67cd52b68b5230b387427bad/macaca/remote_invoker.py#L88-L114
|
[
"def",
"execute",
"(",
"self",
",",
"command",
",",
"data",
"=",
"{",
"}",
")",
":",
"method",
",",
"uri",
"=",
"command",
"try",
":",
"path",
"=",
"self",
".",
"_formatter",
".",
"format_map",
"(",
"uri",
",",
"data",
")",
"body",
"=",
"self",
".",
"_formatter",
".",
"get_unused_kwargs",
"(",
")",
"url",
"=",
"\"{0}{1}\"",
".",
"format",
"(",
"self",
".",
"_url",
",",
"path",
")",
"return",
"self",
".",
"_request",
"(",
"method",
",",
"url",
",",
"body",
")",
"except",
"KeyError",
"as",
"err",
":",
"LOGGER",
".",
"debug",
"(",
"'Endpoint {0} is missing argument {1}'",
".",
"format",
"(",
"uri",
",",
"err",
")",
")",
"raise"
] |
6d3c52060013e01a67cd52b68b5230b387427bad
|
valid
|
RemoteInvoker._request
|
Internal method to send request to the remote server.
Args:
method(str): HTTP Method(GET/POST/PUT/DELET/HEAD).
url(str): The request url.
body(dict): The JSON object to be sent.
Returns:
A dict represent the json body from server response.
Raises:
ConnectionError: Meet network problem (e.g. DNS failure,
refused connection, etc).
Timeout: A request times out.
HTTPError: HTTP request returned an unsuccessful status code.
|
macaca/remote_invoker.py
|
def _request(self, method, url, body):
"""Internal method to send request to the remote server.
Args:
method(str): HTTP Method(GET/POST/PUT/DELET/HEAD).
url(str): The request url.
body(dict): The JSON object to be sent.
Returns:
A dict represent the json body from server response.
Raises:
ConnectionError: Meet network problem (e.g. DNS failure,
refused connection, etc).
Timeout: A request times out.
HTTPError: HTTP request returned an unsuccessful status code.
"""
if method != 'POST' and method != 'PUT':
body = None
s = Session()
LOGGER.debug(
'Method: {0}, Url: {1}, Body: {2}.'.format(method, url, body))
req = Request(method, url, json=body)
prepped = s.prepare_request(req)
res = s.send(prepped, timeout=self._timeout or None)
res.raise_for_status()
# TODO try catch
return res.json()
|
def _request(self, method, url, body):
"""Internal method to send request to the remote server.
Args:
method(str): HTTP Method(GET/POST/PUT/DELET/HEAD).
url(str): The request url.
body(dict): The JSON object to be sent.
Returns:
A dict represent the json body from server response.
Raises:
ConnectionError: Meet network problem (e.g. DNS failure,
refused connection, etc).
Timeout: A request times out.
HTTPError: HTTP request returned an unsuccessful status code.
"""
if method != 'POST' and method != 'PUT':
body = None
s = Session()
LOGGER.debug(
'Method: {0}, Url: {1}, Body: {2}.'.format(method, url, body))
req = Request(method, url, json=body)
prepped = s.prepare_request(req)
res = s.send(prepped, timeout=self._timeout or None)
res.raise_for_status()
# TODO try catch
return res.json()
|
[
"Internal",
"method",
"to",
"send",
"request",
"to",
"the",
"remote",
"server",
"."
] |
macacajs/wd.py
|
python
|
https://github.com/macacajs/wd.py/blob/6d3c52060013e01a67cd52b68b5230b387427bad/macaca/remote_invoker.py#L116-L147
|
[
"def",
"_request",
"(",
"self",
",",
"method",
",",
"url",
",",
"body",
")",
":",
"if",
"method",
"!=",
"'POST'",
"and",
"method",
"!=",
"'PUT'",
":",
"body",
"=",
"None",
"s",
"=",
"Session",
"(",
")",
"LOGGER",
".",
"debug",
"(",
"'Method: {0}, Url: {1}, Body: {2}.'",
".",
"format",
"(",
"method",
",",
"url",
",",
"body",
")",
")",
"req",
"=",
"Request",
"(",
"method",
",",
"url",
",",
"json",
"=",
"body",
")",
"prepped",
"=",
"s",
".",
"prepare_request",
"(",
"req",
")",
"res",
"=",
"s",
".",
"send",
"(",
"prepped",
",",
"timeout",
"=",
"self",
".",
"_timeout",
"or",
"None",
")",
"res",
".",
"raise_for_status",
"(",
")",
"# TODO try catch",
"return",
"res",
".",
"json",
"(",
")"
] |
6d3c52060013e01a67cd52b68b5230b387427bad
|
valid
|
WebElement._execute
|
Private method to execute command with data.
Args:
command(Command): The defined command.
data(dict): The uri variable and body.
Returns:
The unwrapped value field in the json response.
|
macaca/webelement.py
|
def _execute(self, command, data=None, unpack=True):
"""Private method to execute command with data.
Args:
command(Command): The defined command.
data(dict): The uri variable and body.
Returns:
The unwrapped value field in the json response.
"""
if not data:
data = {}
data.setdefault('element_id', self.element_id)
return self._driver._execute(command, data, unpack)
|
def _execute(self, command, data=None, unpack=True):
"""Private method to execute command with data.
Args:
command(Command): The defined command.
data(dict): The uri variable and body.
Returns:
The unwrapped value field in the json response.
"""
if not data:
data = {}
data.setdefault('element_id', self.element_id)
return self._driver._execute(command, data, unpack)
|
[
"Private",
"method",
"to",
"execute",
"command",
"with",
"data",
"."
] |
macacajs/wd.py
|
python
|
https://github.com/macacajs/wd.py/blob/6d3c52060013e01a67cd52b68b5230b387427bad/macaca/webelement.py#L47-L60
|
[
"def",
"_execute",
"(",
"self",
",",
"command",
",",
"data",
"=",
"None",
",",
"unpack",
"=",
"True",
")",
":",
"if",
"not",
"data",
":",
"data",
"=",
"{",
"}",
"data",
".",
"setdefault",
"(",
"'element_id'",
",",
"self",
".",
"element_id",
")",
"return",
"self",
".",
"_driver",
".",
"_execute",
"(",
"command",
",",
"data",
",",
"unpack",
")"
] |
6d3c52060013e01a67cd52b68b5230b387427bad
|
valid
|
WebElement.element
|
find an element in the current element.
Support:
Android iOS Web(WebView)
Args:
using(str): The element location strategy.
value(str): The value of the location strategy.
Returns:
WebElement Object.
Raises:
WebDriverException.
|
macaca/webelement.py
|
def element(self, using, value):
"""find an element in the current element.
Support:
Android iOS Web(WebView)
Args:
using(str): The element location strategy.
value(str): The value of the location strategy.
Returns:
WebElement Object.
Raises:
WebDriverException.
"""
return self._execute(Command.FIND_CHILD_ELEMENT, {
'using': using,
'value': value
})
|
def element(self, using, value):
"""find an element in the current element.
Support:
Android iOS Web(WebView)
Args:
using(str): The element location strategy.
value(str): The value of the location strategy.
Returns:
WebElement Object.
Raises:
WebDriverException.
"""
return self._execute(Command.FIND_CHILD_ELEMENT, {
'using': using,
'value': value
})
|
[
"find",
"an",
"element",
"in",
"the",
"current",
"element",
"."
] |
macacajs/wd.py
|
python
|
https://github.com/macacajs/wd.py/blob/6d3c52060013e01a67cd52b68b5230b387427bad/macaca/webelement.py#L67-L86
|
[
"def",
"element",
"(",
"self",
",",
"using",
",",
"value",
")",
":",
"return",
"self",
".",
"_execute",
"(",
"Command",
".",
"FIND_CHILD_ELEMENT",
",",
"{",
"'using'",
":",
"using",
",",
"'value'",
":",
"value",
"}",
")"
] |
6d3c52060013e01a67cd52b68b5230b387427bad
|
valid
|
WebElement.element_or_none
|
Check if an element in the current element.
Support:
Android iOS Web(WebView)
Args:
using(str): The element location strategy.
value(str): The value of the location strategy.
Returns:
Return Element if the element does exists and return None otherwise.
Raises:
WebDriverException.
|
macaca/webelement.py
|
def element_or_none(self, using, value):
"""Check if an element in the current element.
Support:
Android iOS Web(WebView)
Args:
using(str): The element location strategy.
value(str): The value of the location strategy.
Returns:
Return Element if the element does exists and return None otherwise.
Raises:
WebDriverException.
"""
try:
return self._execute(Command.FIND_CHILD_ELEMENT, {
'using': using,
'value': value
})
except:
return None
|
def element_or_none(self, using, value):
"""Check if an element in the current element.
Support:
Android iOS Web(WebView)
Args:
using(str): The element location strategy.
value(str): The value of the location strategy.
Returns:
Return Element if the element does exists and return None otherwise.
Raises:
WebDriverException.
"""
try:
return self._execute(Command.FIND_CHILD_ELEMENT, {
'using': using,
'value': value
})
except:
return None
|
[
"Check",
"if",
"an",
"element",
"in",
"the",
"current",
"element",
"."
] |
macacajs/wd.py
|
python
|
https://github.com/macacajs/wd.py/blob/6d3c52060013e01a67cd52b68b5230b387427bad/macaca/webelement.py#L113-L135
|
[
"def",
"element_or_none",
"(",
"self",
",",
"using",
",",
"value",
")",
":",
"try",
":",
"return",
"self",
".",
"_execute",
"(",
"Command",
".",
"FIND_CHILD_ELEMENT",
",",
"{",
"'using'",
":",
"using",
",",
"'value'",
":",
"value",
"}",
")",
"except",
":",
"return",
"None"
] |
6d3c52060013e01a67cd52b68b5230b387427bad
|
valid
|
WebElement.elements
|
find elements in the current element.
Support:
Android iOS Web(WebView)
Args:
using(str): The element location strategy.
value(str): The value of the location strategy.
Returns:
Return a List<Element | None>, if no element matched, the list is empty.
Raises:
WebDriverException.
|
macaca/webelement.py
|
def elements(self, using, value):
"""find elements in the current element.
Support:
Android iOS Web(WebView)
Args:
using(str): The element location strategy.
value(str): The value of the location strategy.
Returns:
Return a List<Element | None>, if no element matched, the list is empty.
Raises:
WebDriverException.
"""
return self._execute(Command.FIND_CHILD_ELEMENTS, {
'using': using,
'value': value
})
|
def elements(self, using, value):
"""find elements in the current element.
Support:
Android iOS Web(WebView)
Args:
using(str): The element location strategy.
value(str): The value of the location strategy.
Returns:
Return a List<Element | None>, if no element matched, the list is empty.
Raises:
WebDriverException.
"""
return self._execute(Command.FIND_CHILD_ELEMENTS, {
'using': using,
'value': value
})
|
[
"find",
"elements",
"in",
"the",
"current",
"element",
"."
] |
macacajs/wd.py
|
python
|
https://github.com/macacajs/wd.py/blob/6d3c52060013e01a67cd52b68b5230b387427bad/macaca/webelement.py#L137-L156
|
[
"def",
"elements",
"(",
"self",
",",
"using",
",",
"value",
")",
":",
"return",
"self",
".",
"_execute",
"(",
"Command",
".",
"FIND_CHILD_ELEMENTS",
",",
"{",
"'using'",
":",
"using",
",",
"'value'",
":",
"value",
"}",
")"
] |
6d3c52060013e01a67cd52b68b5230b387427bad
|
valid
|
WebElement.move_to
|
Deprecated use element.touch('drag', { toX, toY, duration(s) }) instead.
Move the mouse by an offset of the specificed element.
Support:
Android
Args:
x(float): X offset to move to, relative to the
top-left corner of the element.
y(float): Y offset to move to, relative to the
top-left corner of the element.
Returns:
WebElement object.
|
macaca/webelement.py
|
def move_to(self, x=0, y=0):
"""Deprecated use element.touch('drag', { toX, toY, duration(s) }) instead.
Move the mouse by an offset of the specificed element.
Support:
Android
Args:
x(float): X offset to move to, relative to the
top-left corner of the element.
y(float): Y offset to move to, relative to the
top-left corner of the element.
Returns:
WebElement object.
"""
self._driver.move_to(self, x, y)
|
def move_to(self, x=0, y=0):
"""Deprecated use element.touch('drag', { toX, toY, duration(s) }) instead.
Move the mouse by an offset of the specificed element.
Support:
Android
Args:
x(float): X offset to move to, relative to the
top-left corner of the element.
y(float): Y offset to move to, relative to the
top-left corner of the element.
Returns:
WebElement object.
"""
self._driver.move_to(self, x, y)
|
[
"Deprecated",
"use",
"element",
".",
"touch",
"(",
"drag",
"{",
"toX",
"toY",
"duration",
"(",
"s",
")",
"}",
")",
"instead",
".",
"Move",
"the",
"mouse",
"by",
"an",
"offset",
"of",
"the",
"specificed",
"element",
"."
] |
macacajs/wd.py
|
python
|
https://github.com/macacajs/wd.py/blob/6d3c52060013e01a67cd52b68b5230b387427bad/macaca/webelement.py#L424-L440
|
[
"def",
"move_to",
"(",
"self",
",",
"x",
"=",
"0",
",",
"y",
"=",
"0",
")",
":",
"self",
".",
"_driver",
".",
"move_to",
"(",
"self",
",",
"x",
",",
"y",
")"
] |
6d3c52060013e01a67cd52b68b5230b387427bad
|
valid
|
WebElement.flick
|
Deprecated use touch('drag', { fromX, fromY, toX, toY, duration(s) }) instead.
Flick on the touch screen using finger motion events.
This flickcommand starts at a particulat screen location.
Support:
iOS
Args:
x(float}: The x offset in pixels to flick by.
y(float): The y offset in pixels to flick by.
speed(float) The speed in pixels per seconds.
Returns:
WebElement object.
|
macaca/webelement.py
|
def flick(self, x, y, speed):
"""Deprecated use touch('drag', { fromX, fromY, toX, toY, duration(s) }) instead.
Flick on the touch screen using finger motion events.
This flickcommand starts at a particulat screen location.
Support:
iOS
Args:
x(float}: The x offset in pixels to flick by.
y(float): The y offset in pixels to flick by.
speed(float) The speed in pixels per seconds.
Returns:
WebElement object.
"""
self._driver.flick(self, x, y, speed)
|
def flick(self, x, y, speed):
"""Deprecated use touch('drag', { fromX, fromY, toX, toY, duration(s) }) instead.
Flick on the touch screen using finger motion events.
This flickcommand starts at a particulat screen location.
Support:
iOS
Args:
x(float}: The x offset in pixels to flick by.
y(float): The y offset in pixels to flick by.
speed(float) The speed in pixels per seconds.
Returns:
WebElement object.
"""
self._driver.flick(self, x, y, speed)
|
[
"Deprecated",
"use",
"touch",
"(",
"drag",
"{",
"fromX",
"fromY",
"toX",
"toY",
"duration",
"(",
"s",
")",
"}",
")",
"instead",
".",
"Flick",
"on",
"the",
"touch",
"screen",
"using",
"finger",
"motion",
"events",
".",
"This",
"flickcommand",
"starts",
"at",
"a",
"particulat",
"screen",
"location",
"."
] |
macacajs/wd.py
|
python
|
https://github.com/macacajs/wd.py/blob/6d3c52060013e01a67cd52b68b5230b387427bad/macaca/webelement.py#L443-L459
|
[
"def",
"flick",
"(",
"self",
",",
"x",
",",
"y",
",",
"speed",
")",
":",
"self",
".",
"_driver",
".",
"flick",
"(",
"self",
",",
"x",
",",
"y",
",",
"speed",
")"
] |
6d3c52060013e01a67cd52b68b5230b387427bad
|
valid
|
WebElement.touch
|
Apply touch actions on devices. Such as, tap/doubleTap/press/pinch/rotate/drag.
See more on https://github.com/alibaba/macaca/issues/366.
Support:
Android iOS
Args:
name(str): Name of the action
args(dict): Arguments of the action
Returns:
WebDriver Object.
Raises:
WebDriverException.
|
macaca/webelement.py
|
def touch(self, name, args=None):
"""Apply touch actions on devices. Such as, tap/doubleTap/press/pinch/rotate/drag.
See more on https://github.com/alibaba/macaca/issues/366.
Support:
Android iOS
Args:
name(str): Name of the action
args(dict): Arguments of the action
Returns:
WebDriver Object.
Raises:
WebDriverException.
"""
if isinstance(name, list) and not isinstance(name, str):
for obj in name:
obj['element'] = self.element_id
actions = name
elif isinstance(name, str):
if not args:
args = {}
args['type'] = name
args['element'] = self.element_id
actions = [args]
else:
raise TypeError('Invalid parameters.')
self._driver._execute(Command.PERFORM_ACTIONS, {
'actions': actions
})
|
def touch(self, name, args=None):
"""Apply touch actions on devices. Such as, tap/doubleTap/press/pinch/rotate/drag.
See more on https://github.com/alibaba/macaca/issues/366.
Support:
Android iOS
Args:
name(str): Name of the action
args(dict): Arguments of the action
Returns:
WebDriver Object.
Raises:
WebDriverException.
"""
if isinstance(name, list) and not isinstance(name, str):
for obj in name:
obj['element'] = self.element_id
actions = name
elif isinstance(name, str):
if not args:
args = {}
args['type'] = name
args['element'] = self.element_id
actions = [args]
else:
raise TypeError('Invalid parameters.')
self._driver._execute(Command.PERFORM_ACTIONS, {
'actions': actions
})
|
[
"Apply",
"touch",
"actions",
"on",
"devices",
".",
"Such",
"as",
"tap",
"/",
"doubleTap",
"/",
"press",
"/",
"pinch",
"/",
"rotate",
"/",
"drag",
".",
"See",
"more",
"on",
"https",
":",
"//",
"github",
".",
"com",
"/",
"alibaba",
"/",
"macaca",
"/",
"issues",
"/",
"366",
"."
] |
macacajs/wd.py
|
python
|
https://github.com/macacajs/wd.py/blob/6d3c52060013e01a67cd52b68b5230b387427bad/macaca/webelement.py#L517-L548
|
[
"def",
"touch",
"(",
"self",
",",
"name",
",",
"args",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"name",
",",
"list",
")",
"and",
"not",
"isinstance",
"(",
"name",
",",
"str",
")",
":",
"for",
"obj",
"in",
"name",
":",
"obj",
"[",
"'element'",
"]",
"=",
"self",
".",
"element_id",
"actions",
"=",
"name",
"elif",
"isinstance",
"(",
"name",
",",
"str",
")",
":",
"if",
"not",
"args",
":",
"args",
"=",
"{",
"}",
"args",
"[",
"'type'",
"]",
"=",
"name",
"args",
"[",
"'element'",
"]",
"=",
"self",
".",
"element_id",
"actions",
"=",
"[",
"args",
"]",
"else",
":",
"raise",
"TypeError",
"(",
"'Invalid parameters.'",
")",
"self",
".",
"_driver",
".",
"_execute",
"(",
"Command",
".",
"PERFORM_ACTIONS",
",",
"{",
"'actions'",
":",
"actions",
"}",
")"
] |
6d3c52060013e01a67cd52b68b5230b387427bad
|
valid
|
is_displayed
|
Assert whether the target is displayed
Args:
target(WebElement): WebElement Object.
Returns:
Return True if the element is displayed or return False otherwise.
|
macaca/asserters.py
|
def is_displayed(target):
"""Assert whether the target is displayed
Args:
target(WebElement): WebElement Object.
Returns:
Return True if the element is displayed or return False otherwise.
"""
is_displayed = getattr(target, 'is_displayed', None)
if not is_displayed or not callable(is_displayed):
raise TypeError('Target has no attribute \'is_displayed\' or not callable')
if not is_displayed():
raise WebDriverException('element not visible')
|
def is_displayed(target):
"""Assert whether the target is displayed
Args:
target(WebElement): WebElement Object.
Returns:
Return True if the element is displayed or return False otherwise.
"""
is_displayed = getattr(target, 'is_displayed', None)
if not is_displayed or not callable(is_displayed):
raise TypeError('Target has no attribute \'is_displayed\' or not callable')
if not is_displayed():
raise WebDriverException('element not visible')
|
[
"Assert",
"whether",
"the",
"target",
"is",
"displayed"
] |
macacajs/wd.py
|
python
|
https://github.com/macacajs/wd.py/blob/6d3c52060013e01a67cd52b68b5230b387427bad/macaca/asserters.py#L9-L22
|
[
"def",
"is_displayed",
"(",
"target",
")",
":",
"is_displayed",
"=",
"getattr",
"(",
"target",
",",
"'is_displayed'",
",",
"None",
")",
"if",
"not",
"is_displayed",
"or",
"not",
"callable",
"(",
"is_displayed",
")",
":",
"raise",
"TypeError",
"(",
"'Target has no attribute \\'is_displayed\\' or not callable'",
")",
"if",
"not",
"is_displayed",
"(",
")",
":",
"raise",
"WebDriverException",
"(",
"'element not visible'",
")"
] |
6d3c52060013e01a67cd52b68b5230b387427bad
|
valid
|
vController.PlugIn
|
Take next available controller id and plug in to Virtual USB Bus
|
pyxinput/virtual_controller.py
|
def PlugIn(self):
"""Take next available controller id and plug in to Virtual USB Bus"""
ids = self.available_ids()
if len(ids) == 0:
raise MaxInputsReachedError('Max Inputs Reached')
self.id = ids[0]
_xinput.PlugIn(self.id)
while self.id in self.available_ids():
pass
|
def PlugIn(self):
"""Take next available controller id and plug in to Virtual USB Bus"""
ids = self.available_ids()
if len(ids) == 0:
raise MaxInputsReachedError('Max Inputs Reached')
self.id = ids[0]
_xinput.PlugIn(self.id)
while self.id in self.available_ids():
pass
|
[
"Take",
"next",
"available",
"controller",
"id",
"and",
"plug",
"in",
"to",
"Virtual",
"USB",
"Bus"
] |
bayangan1991/PYXInput
|
python
|
https://github.com/bayangan1991/PYXInput/blob/a0bbdecaeccf7947378bde67e7de79433bfbd30e/pyxinput/virtual_controller.py#L60-L70
|
[
"def",
"PlugIn",
"(",
"self",
")",
":",
"ids",
"=",
"self",
".",
"available_ids",
"(",
")",
"if",
"len",
"(",
"ids",
")",
"==",
"0",
":",
"raise",
"MaxInputsReachedError",
"(",
"'Max Inputs Reached'",
")",
"self",
".",
"id",
"=",
"ids",
"[",
"0",
"]",
"_xinput",
".",
"PlugIn",
"(",
"self",
".",
"id",
")",
"while",
"self",
".",
"id",
"in",
"self",
".",
"available_ids",
"(",
")",
":",
"pass"
] |
a0bbdecaeccf7947378bde67e7de79433bfbd30e
|
valid
|
vController.UnPlug
|
Unplug controller from Virtual USB Bus and free up ID
|
pyxinput/virtual_controller.py
|
def UnPlug(self, force=False):
"""Unplug controller from Virtual USB Bus and free up ID"""
if force:
_xinput.UnPlugForce(c_uint(self.id))
else:
_xinput.UnPlug(c_uint(self.id))
while self.id not in self.available_ids():
if self.id == 0:
break
|
def UnPlug(self, force=False):
"""Unplug controller from Virtual USB Bus and free up ID"""
if force:
_xinput.UnPlugForce(c_uint(self.id))
else:
_xinput.UnPlug(c_uint(self.id))
while self.id not in self.available_ids():
if self.id == 0:
break
|
[
"Unplug",
"controller",
"from",
"Virtual",
"USB",
"Bus",
"and",
"free",
"up",
"ID"
] |
bayangan1991/PYXInput
|
python
|
https://github.com/bayangan1991/PYXInput/blob/a0bbdecaeccf7947378bde67e7de79433bfbd30e/pyxinput/virtual_controller.py#L72-L80
|
[
"def",
"UnPlug",
"(",
"self",
",",
"force",
"=",
"False",
")",
":",
"if",
"force",
":",
"_xinput",
".",
"UnPlugForce",
"(",
"c_uint",
"(",
"self",
".",
"id",
")",
")",
"else",
":",
"_xinput",
".",
"UnPlug",
"(",
"c_uint",
"(",
"self",
".",
"id",
")",
")",
"while",
"self",
".",
"id",
"not",
"in",
"self",
".",
"available_ids",
"(",
")",
":",
"if",
"self",
".",
"id",
"==",
"0",
":",
"break"
] |
a0bbdecaeccf7947378bde67e7de79433bfbd30e
|
valid
|
vController.set_value
|
Set a value on the controller
If percent is True all controls will accept a value between -1.0 and 1.0
If not then:
Triggers are 0 to 255
Axis are -32768 to 32767
Control List:
AxisLx , Left Stick X-Axis
AxisLy , Left Stick Y-Axis
AxisRx , Right Stick X-Axis
AxisRy , Right Stick Y-Axis
BtnBack , Menu/Back Button
BtnStart , Start Button
BtnA , A Button
BtnB , B Button
BtnX , X Button
BtnY , Y Button
BtnThumbL , Left Thumbstick Click
BtnThumbR , Right Thumbstick Click
BtnShoulderL , Left Shoulder Button
BtnShoulderR , Right Shoulder Button
Dpad , Set Dpad Value (0 = Off, Use DPAD_### Constants)
TriggerL , Left Trigger
TriggerR , Right Trigger
|
pyxinput/virtual_controller.py
|
def set_value(self, control, value=None):
"""Set a value on the controller
If percent is True all controls will accept a value between -1.0 and 1.0
If not then:
Triggers are 0 to 255
Axis are -32768 to 32767
Control List:
AxisLx , Left Stick X-Axis
AxisLy , Left Stick Y-Axis
AxisRx , Right Stick X-Axis
AxisRy , Right Stick Y-Axis
BtnBack , Menu/Back Button
BtnStart , Start Button
BtnA , A Button
BtnB , B Button
BtnX , X Button
BtnY , Y Button
BtnThumbL , Left Thumbstick Click
BtnThumbR , Right Thumbstick Click
BtnShoulderL , Left Shoulder Button
BtnShoulderR , Right Shoulder Button
Dpad , Set Dpad Value (0 = Off, Use DPAD_### Constants)
TriggerL , Left Trigger
TriggerR , Right Trigger
"""
func = getattr(_xinput, 'Set' + control)
if 'Axis' in control:
target_type = c_short
if self.percent:
target_value = int(32767 * value)
else:
target_value = value
elif 'Btn' in control:
target_type = c_bool
target_value = bool(value)
elif 'Trigger' in control:
target_type = c_byte
if self.percent:
target_value = int(255 * value)
else:
target_value = value
elif 'Dpad' in control:
target_type = c_int
target_value = int(value)
func(c_uint(self.id), target_type(target_value))
|
def set_value(self, control, value=None):
"""Set a value on the controller
If percent is True all controls will accept a value between -1.0 and 1.0
If not then:
Triggers are 0 to 255
Axis are -32768 to 32767
Control List:
AxisLx , Left Stick X-Axis
AxisLy , Left Stick Y-Axis
AxisRx , Right Stick X-Axis
AxisRy , Right Stick Y-Axis
BtnBack , Menu/Back Button
BtnStart , Start Button
BtnA , A Button
BtnB , B Button
BtnX , X Button
BtnY , Y Button
BtnThumbL , Left Thumbstick Click
BtnThumbR , Right Thumbstick Click
BtnShoulderL , Left Shoulder Button
BtnShoulderR , Right Shoulder Button
Dpad , Set Dpad Value (0 = Off, Use DPAD_### Constants)
TriggerL , Left Trigger
TriggerR , Right Trigger
"""
func = getattr(_xinput, 'Set' + control)
if 'Axis' in control:
target_type = c_short
if self.percent:
target_value = int(32767 * value)
else:
target_value = value
elif 'Btn' in control:
target_type = c_bool
target_value = bool(value)
elif 'Trigger' in control:
target_type = c_byte
if self.percent:
target_value = int(255 * value)
else:
target_value = value
elif 'Dpad' in control:
target_type = c_int
target_value = int(value)
func(c_uint(self.id), target_type(target_value))
|
[
"Set",
"a",
"value",
"on",
"the",
"controller",
"If",
"percent",
"is",
"True",
"all",
"controls",
"will",
"accept",
"a",
"value",
"between",
"-",
"1",
".",
"0",
"and",
"1",
".",
"0"
] |
bayangan1991/PYXInput
|
python
|
https://github.com/bayangan1991/PYXInput/blob/a0bbdecaeccf7947378bde67e7de79433bfbd30e/pyxinput/virtual_controller.py#L82-L133
|
[
"def",
"set_value",
"(",
"self",
",",
"control",
",",
"value",
"=",
"None",
")",
":",
"func",
"=",
"getattr",
"(",
"_xinput",
",",
"'Set'",
"+",
"control",
")",
"if",
"'Axis'",
"in",
"control",
":",
"target_type",
"=",
"c_short",
"if",
"self",
".",
"percent",
":",
"target_value",
"=",
"int",
"(",
"32767",
"*",
"value",
")",
"else",
":",
"target_value",
"=",
"value",
"elif",
"'Btn'",
"in",
"control",
":",
"target_type",
"=",
"c_bool",
"target_value",
"=",
"bool",
"(",
"value",
")",
"elif",
"'Trigger'",
"in",
"control",
":",
"target_type",
"=",
"c_byte",
"if",
"self",
".",
"percent",
":",
"target_value",
"=",
"int",
"(",
"255",
"*",
"value",
")",
"else",
":",
"target_value",
"=",
"value",
"elif",
"'Dpad'",
"in",
"control",
":",
"target_type",
"=",
"c_int",
"target_value",
"=",
"int",
"(",
"value",
")",
"func",
"(",
"c_uint",
"(",
"self",
".",
"id",
")",
",",
"target_type",
"(",
"target_value",
")",
")"
] |
a0bbdecaeccf7947378bde67e7de79433bfbd30e
|
valid
|
main
|
Test the functionality of the rController object
|
pyxinput/read_state.py
|
def main():
"""Test the functionality of the rController object"""
import time
print('Testing controller in position 1:')
print('Running 3 x 3 seconds tests')
# Initialise Controller
con = rController(1)
# Loop printing controller state and buttons held
for i in range(3):
print('Waiting...')
time.sleep(2.5)
print('State: ', con.gamepad)
print('Buttons: ', con.buttons)
time.sleep(0.5)
print('Done!')
|
def main():
"""Test the functionality of the rController object"""
import time
print('Testing controller in position 1:')
print('Running 3 x 3 seconds tests')
# Initialise Controller
con = rController(1)
# Loop printing controller state and buttons held
for i in range(3):
print('Waiting...')
time.sleep(2.5)
print('State: ', con.gamepad)
print('Buttons: ', con.buttons)
time.sleep(0.5)
print('Done!')
|
[
"Test",
"the",
"functionality",
"of",
"the",
"rController",
"object"
] |
bayangan1991/PYXInput
|
python
|
https://github.com/bayangan1991/PYXInput/blob/a0bbdecaeccf7947378bde67e7de79433bfbd30e/pyxinput/read_state.py#L93-L111
|
[
"def",
"main",
"(",
")",
":",
"import",
"time",
"print",
"(",
"'Testing controller in position 1:'",
")",
"print",
"(",
"'Running 3 x 3 seconds tests'",
")",
"# Initialise Controller",
"con",
"=",
"rController",
"(",
"1",
")",
"# Loop printing controller state and buttons held",
"for",
"i",
"in",
"range",
"(",
"3",
")",
":",
"print",
"(",
"'Waiting...'",
")",
"time",
".",
"sleep",
"(",
"2.5",
")",
"print",
"(",
"'State: '",
",",
"con",
".",
"gamepad",
")",
"print",
"(",
"'Buttons: '",
",",
"con",
".",
"buttons",
")",
"time",
".",
"sleep",
"(",
"0.5",
")",
"print",
"(",
"'Done!'",
")"
] |
a0bbdecaeccf7947378bde67e7de79433bfbd30e
|
valid
|
rController.gamepad
|
Returns the current gamepad state. Buttons pressed is shown as a raw integer value.
Use rController.buttons for a list of buttons pressed.
|
pyxinput/read_state.py
|
def gamepad(self):
"""Returns the current gamepad state. Buttons pressed is shown as a raw integer value.
Use rController.buttons for a list of buttons pressed.
"""
state = _xinput_state()
_xinput.XInputGetState(self.ControllerID - 1, pointer(state))
self.dwPacketNumber = state.dwPacketNumber
return state.XINPUT_GAMEPAD
|
def gamepad(self):
"""Returns the current gamepad state. Buttons pressed is shown as a raw integer value.
Use rController.buttons for a list of buttons pressed.
"""
state = _xinput_state()
_xinput.XInputGetState(self.ControllerID - 1, pointer(state))
self.dwPacketNumber = state.dwPacketNumber
return state.XINPUT_GAMEPAD
|
[
"Returns",
"the",
"current",
"gamepad",
"state",
".",
"Buttons",
"pressed",
"is",
"shown",
"as",
"a",
"raw",
"integer",
"value",
".",
"Use",
"rController",
".",
"buttons",
"for",
"a",
"list",
"of",
"buttons",
"pressed",
"."
] |
bayangan1991/PYXInput
|
python
|
https://github.com/bayangan1991/PYXInput/blob/a0bbdecaeccf7947378bde67e7de79433bfbd30e/pyxinput/read_state.py#L76-L84
|
[
"def",
"gamepad",
"(",
"self",
")",
":",
"state",
"=",
"_xinput_state",
"(",
")",
"_xinput",
".",
"XInputGetState",
"(",
"self",
".",
"ControllerID",
"-",
"1",
",",
"pointer",
"(",
"state",
")",
")",
"self",
".",
"dwPacketNumber",
"=",
"state",
".",
"dwPacketNumber",
"return",
"state",
".",
"XINPUT_GAMEPAD"
] |
a0bbdecaeccf7947378bde67e7de79433bfbd30e
|
valid
|
rController.buttons
|
Returns a list of buttons currently pressed
|
pyxinput/read_state.py
|
def buttons(self):
"""Returns a list of buttons currently pressed"""
return [name for name, value in rController._buttons.items()
if self.gamepad.wButtons & value == value]
|
def buttons(self):
"""Returns a list of buttons currently pressed"""
return [name for name, value in rController._buttons.items()
if self.gamepad.wButtons & value == value]
|
[
"Returns",
"a",
"list",
"of",
"buttons",
"currently",
"pressed"
] |
bayangan1991/PYXInput
|
python
|
https://github.com/bayangan1991/PYXInput/blob/a0bbdecaeccf7947378bde67e7de79433bfbd30e/pyxinput/read_state.py#L87-L90
|
[
"def",
"buttons",
"(",
"self",
")",
":",
"return",
"[",
"name",
"for",
"name",
",",
"value",
"in",
"rController",
".",
"_buttons",
".",
"items",
"(",
")",
"if",
"self",
".",
"gamepad",
".",
"wButtons",
"&",
"value",
"==",
"value",
"]"
] |
a0bbdecaeccf7947378bde67e7de79433bfbd30e
|
valid
|
maybe_decode_header
|
Decodes an encoded 7-bit ASCII header value into it's actual value.
|
mailviews/previews.py
|
def maybe_decode_header(header):
"""
Decodes an encoded 7-bit ASCII header value into it's actual value.
"""
value, encoding = decode_header(header)[0]
if encoding:
return value.decode(encoding)
else:
return value
|
def maybe_decode_header(header):
"""
Decodes an encoded 7-bit ASCII header value into it's actual value.
"""
value, encoding = decode_header(header)[0]
if encoding:
return value.decode(encoding)
else:
return value
|
[
"Decodes",
"an",
"encoded",
"7",
"-",
"bit",
"ASCII",
"header",
"value",
"into",
"it",
"s",
"actual",
"value",
"."
] |
disqus/django-mailviews
|
python
|
https://github.com/disqus/django-mailviews/blob/9993d5e911d545b3bc038433986c5f6812e7e965/mailviews/previews.py#L38-L46
|
[
"def",
"maybe_decode_header",
"(",
"header",
")",
":",
"value",
",",
"encoding",
"=",
"decode_header",
"(",
"header",
")",
"[",
"0",
"]",
"if",
"encoding",
":",
"return",
"value",
".",
"decode",
"(",
"encoding",
")",
"else",
":",
"return",
"value"
] |
9993d5e911d545b3bc038433986c5f6812e7e965
|
valid
|
autodiscover
|
Imports all available previews classes.
|
mailviews/previews.py
|
def autodiscover():
"""
Imports all available previews classes.
"""
from django.conf import settings
for application in settings.INSTALLED_APPS:
module = import_module(application)
if module_has_submodule(module, 'emails'):
emails = import_module('%s.emails' % application)
try:
import_module('%s.emails.previews' % application)
except ImportError:
# Only raise the exception if this module contains previews and
# there was a problem importing them. (An emails module that
# does not contain previews is not an error.)
if module_has_submodule(emails, 'previews'):
raise
|
def autodiscover():
"""
Imports all available previews classes.
"""
from django.conf import settings
for application in settings.INSTALLED_APPS:
module = import_module(application)
if module_has_submodule(module, 'emails'):
emails = import_module('%s.emails' % application)
try:
import_module('%s.emails.previews' % application)
except ImportError:
# Only raise the exception if this module contains previews and
# there was a problem importing them. (An emails module that
# does not contain previews is not an error.)
if module_has_submodule(emails, 'previews'):
raise
|
[
"Imports",
"all",
"available",
"previews",
"classes",
"."
] |
disqus/django-mailviews
|
python
|
https://github.com/disqus/django-mailviews/blob/9993d5e911d545b3bc038433986c5f6812e7e965/mailviews/previews.py#L216-L233
|
[
"def",
"autodiscover",
"(",
")",
":",
"from",
"django",
".",
"conf",
"import",
"settings",
"for",
"application",
"in",
"settings",
".",
"INSTALLED_APPS",
":",
"module",
"=",
"import_module",
"(",
"application",
")",
"if",
"module_has_submodule",
"(",
"module",
",",
"'emails'",
")",
":",
"emails",
"=",
"import_module",
"(",
"'%s.emails'",
"%",
"application",
")",
"try",
":",
"import_module",
"(",
"'%s.emails.previews'",
"%",
"application",
")",
"except",
"ImportError",
":",
"# Only raise the exception if this module contains previews and",
"# there was a problem importing them. (An emails module that",
"# does not contain previews is not an error.)",
"if",
"module_has_submodule",
"(",
"emails",
",",
"'previews'",
")",
":",
"raise"
] |
9993d5e911d545b3bc038433986c5f6812e7e965
|
valid
|
PreviewSite.register
|
Adds a preview to the index.
|
mailviews/previews.py
|
def register(self, cls):
"""
Adds a preview to the index.
"""
preview = cls(site=self)
logger.debug('Registering %r with %r', preview, self)
index = self.__previews.setdefault(preview.module, {})
index[cls.__name__] = preview
|
def register(self, cls):
"""
Adds a preview to the index.
"""
preview = cls(site=self)
logger.debug('Registering %r with %r', preview, self)
index = self.__previews.setdefault(preview.module, {})
index[cls.__name__] = preview
|
[
"Adds",
"a",
"preview",
"to",
"the",
"index",
"."
] |
disqus/django-mailviews
|
python
|
https://github.com/disqus/django-mailviews/blob/9993d5e911d545b3bc038433986c5f6812e7e965/mailviews/previews.py#L61-L68
|
[
"def",
"register",
"(",
"self",
",",
"cls",
")",
":",
"preview",
"=",
"cls",
"(",
"site",
"=",
"self",
")",
"logger",
".",
"debug",
"(",
"'Registering %r with %r'",
",",
"preview",
",",
"self",
")",
"index",
"=",
"self",
".",
"__previews",
".",
"setdefault",
"(",
"preview",
".",
"module",
",",
"{",
"}",
")",
"index",
"[",
"cls",
".",
"__name__",
"]",
"=",
"preview"
] |
9993d5e911d545b3bc038433986c5f6812e7e965
|
valid
|
PreviewSite.detail_view
|
Looks up a preview in the index, returning a detail view response.
|
mailviews/previews.py
|
def detail_view(self, request, module, preview):
"""
Looks up a preview in the index, returning a detail view response.
"""
try:
preview = self.__previews[module][preview]
except KeyError:
raise Http404 # The provided module/preview does not exist in the index.
return preview.detail_view(request)
|
def detail_view(self, request, module, preview):
"""
Looks up a preview in the index, returning a detail view response.
"""
try:
preview = self.__previews[module][preview]
except KeyError:
raise Http404 # The provided module/preview does not exist in the index.
return preview.detail_view(request)
|
[
"Looks",
"up",
"a",
"preview",
"in",
"the",
"index",
"returning",
"a",
"detail",
"view",
"response",
"."
] |
disqus/django-mailviews
|
python
|
https://github.com/disqus/django-mailviews/blob/9993d5e911d545b3bc038433986c5f6812e7e965/mailviews/previews.py#L104-L112
|
[
"def",
"detail_view",
"(",
"self",
",",
"request",
",",
"module",
",",
"preview",
")",
":",
"try",
":",
"preview",
"=",
"self",
".",
"__previews",
"[",
"module",
"]",
"[",
"preview",
"]",
"except",
"KeyError",
":",
"raise",
"Http404",
"# The provided module/preview does not exist in the index.",
"return",
"preview",
".",
"detail_view",
"(",
"request",
")"
] |
9993d5e911d545b3bc038433986c5f6812e7e965
|
valid
|
Preview.url
|
The URL to access this preview.
|
mailviews/previews.py
|
def url(self):
"""
The URL to access this preview.
"""
return reverse('%s:detail' % URL_NAMESPACE, kwargs={
'module': self.module,
'preview': type(self).__name__,
})
|
def url(self):
"""
The URL to access this preview.
"""
return reverse('%s:detail' % URL_NAMESPACE, kwargs={
'module': self.module,
'preview': type(self).__name__,
})
|
[
"The",
"URL",
"to",
"access",
"this",
"preview",
"."
] |
disqus/django-mailviews
|
python
|
https://github.com/disqus/django-mailviews/blob/9993d5e911d545b3bc038433986c5f6812e7e965/mailviews/previews.py#L155-L162
|
[
"def",
"url",
"(",
"self",
")",
":",
"return",
"reverse",
"(",
"'%s:detail'",
"%",
"URL_NAMESPACE",
",",
"kwargs",
"=",
"{",
"'module'",
":",
"self",
".",
"module",
",",
"'preview'",
":",
"type",
"(",
"self",
")",
".",
"__name__",
",",
"}",
")"
] |
9993d5e911d545b3bc038433986c5f6812e7e965
|
valid
|
Preview.detail_view
|
Renders the message view to a response.
|
mailviews/previews.py
|
def detail_view(self, request):
"""
Renders the message view to a response.
"""
context = {
'preview': self,
}
kwargs = {}
if self.form_class:
if request.GET:
form = self.form_class(data=request.GET)
else:
form = self.form_class()
context['form'] = form
if not form.is_bound or not form.is_valid():
return render(request, 'mailviews/previews/detail.html', context)
kwargs.update(form.get_message_view_kwargs())
message_view = self.get_message_view(request, **kwargs)
message = message_view.render_to_message()
raw = message.message()
headers = OrderedDict((header, maybe_decode_header(raw[header])) for header in self.headers)
context.update({
'message': message,
'subject': message.subject,
'body': message.body,
'headers': headers,
'raw': raw.as_string(),
})
alternatives = getattr(message, 'alternatives', [])
try:
html = next(alternative[0] for alternative in alternatives
if alternative[1] == 'text/html')
context.update({
'html': html,
'escaped_html': b64encode(html.encode('utf-8')),
})
except StopIteration:
pass
return render(request, self.template_name, context)
|
def detail_view(self, request):
"""
Renders the message view to a response.
"""
context = {
'preview': self,
}
kwargs = {}
if self.form_class:
if request.GET:
form = self.form_class(data=request.GET)
else:
form = self.form_class()
context['form'] = form
if not form.is_bound or not form.is_valid():
return render(request, 'mailviews/previews/detail.html', context)
kwargs.update(form.get_message_view_kwargs())
message_view = self.get_message_view(request, **kwargs)
message = message_view.render_to_message()
raw = message.message()
headers = OrderedDict((header, maybe_decode_header(raw[header])) for header in self.headers)
context.update({
'message': message,
'subject': message.subject,
'body': message.body,
'headers': headers,
'raw': raw.as_string(),
})
alternatives = getattr(message, 'alternatives', [])
try:
html = next(alternative[0] for alternative in alternatives
if alternative[1] == 'text/html')
context.update({
'html': html,
'escaped_html': b64encode(html.encode('utf-8')),
})
except StopIteration:
pass
return render(request, self.template_name, context)
|
[
"Renders",
"the",
"message",
"view",
"to",
"a",
"response",
"."
] |
disqus/django-mailviews
|
python
|
https://github.com/disqus/django-mailviews/blob/9993d5e911d545b3bc038433986c5f6812e7e965/mailviews/previews.py#L167-L213
|
[
"def",
"detail_view",
"(",
"self",
",",
"request",
")",
":",
"context",
"=",
"{",
"'preview'",
":",
"self",
",",
"}",
"kwargs",
"=",
"{",
"}",
"if",
"self",
".",
"form_class",
":",
"if",
"request",
".",
"GET",
":",
"form",
"=",
"self",
".",
"form_class",
"(",
"data",
"=",
"request",
".",
"GET",
")",
"else",
":",
"form",
"=",
"self",
".",
"form_class",
"(",
")",
"context",
"[",
"'form'",
"]",
"=",
"form",
"if",
"not",
"form",
".",
"is_bound",
"or",
"not",
"form",
".",
"is_valid",
"(",
")",
":",
"return",
"render",
"(",
"request",
",",
"'mailviews/previews/detail.html'",
",",
"context",
")",
"kwargs",
".",
"update",
"(",
"form",
".",
"get_message_view_kwargs",
"(",
")",
")",
"message_view",
"=",
"self",
".",
"get_message_view",
"(",
"request",
",",
"*",
"*",
"kwargs",
")",
"message",
"=",
"message_view",
".",
"render_to_message",
"(",
")",
"raw",
"=",
"message",
".",
"message",
"(",
")",
"headers",
"=",
"OrderedDict",
"(",
"(",
"header",
",",
"maybe_decode_header",
"(",
"raw",
"[",
"header",
"]",
")",
")",
"for",
"header",
"in",
"self",
".",
"headers",
")",
"context",
".",
"update",
"(",
"{",
"'message'",
":",
"message",
",",
"'subject'",
":",
"message",
".",
"subject",
",",
"'body'",
":",
"message",
".",
"body",
",",
"'headers'",
":",
"headers",
",",
"'raw'",
":",
"raw",
".",
"as_string",
"(",
")",
",",
"}",
")",
"alternatives",
"=",
"getattr",
"(",
"message",
",",
"'alternatives'",
",",
"[",
"]",
")",
"try",
":",
"html",
"=",
"next",
"(",
"alternative",
"[",
"0",
"]",
"for",
"alternative",
"in",
"alternatives",
"if",
"alternative",
"[",
"1",
"]",
"==",
"'text/html'",
")",
"context",
".",
"update",
"(",
"{",
"'html'",
":",
"html",
",",
"'escaped_html'",
":",
"b64encode",
"(",
"html",
".",
"encode",
"(",
"'utf-8'",
")",
")",
",",
"}",
")",
"except",
"StopIteration",
":",
"pass",
"return",
"render",
"(",
"request",
",",
"self",
".",
"template_name",
",",
"context",
")"
] |
9993d5e911d545b3bc038433986c5f6812e7e965
|
valid
|
split_docstring
|
Splits the docstring of the given value into it's summary and body.
:returns: a 2-tuple of the format ``(summary, body)``
|
mailviews/utils.py
|
def split_docstring(value):
"""
Splits the docstring of the given value into it's summary and body.
:returns: a 2-tuple of the format ``(summary, body)``
"""
docstring = textwrap.dedent(getattr(value, '__doc__', ''))
if not docstring:
return None
pieces = docstring.strip().split('\n\n', 1)
try:
body = pieces[1]
except IndexError:
body = None
return Docstring(pieces[0], body)
|
def split_docstring(value):
"""
Splits the docstring of the given value into it's summary and body.
:returns: a 2-tuple of the format ``(summary, body)``
"""
docstring = textwrap.dedent(getattr(value, '__doc__', ''))
if not docstring:
return None
pieces = docstring.strip().split('\n\n', 1)
try:
body = pieces[1]
except IndexError:
body = None
return Docstring(pieces[0], body)
|
[
"Splits",
"the",
"docstring",
"of",
"the",
"given",
"value",
"into",
"it",
"s",
"summary",
"and",
"body",
"."
] |
disqus/django-mailviews
|
python
|
https://github.com/disqus/django-mailviews/blob/9993d5e911d545b3bc038433986c5f6812e7e965/mailviews/utils.py#L10-L26
|
[
"def",
"split_docstring",
"(",
"value",
")",
":",
"docstring",
"=",
"textwrap",
".",
"dedent",
"(",
"getattr",
"(",
"value",
",",
"'__doc__'",
",",
"''",
")",
")",
"if",
"not",
"docstring",
":",
"return",
"None",
"pieces",
"=",
"docstring",
".",
"strip",
"(",
")",
".",
"split",
"(",
"'\\n\\n'",
",",
"1",
")",
"try",
":",
"body",
"=",
"pieces",
"[",
"1",
"]",
"except",
"IndexError",
":",
"body",
"=",
"None",
"return",
"Docstring",
"(",
"pieces",
"[",
"0",
"]",
",",
"body",
")"
] |
9993d5e911d545b3bc038433986c5f6812e7e965
|
valid
|
EmailMessageView.render_to_message
|
Renders and returns an unsent message with the provided context.
Any extra keyword arguments passed will be passed through as keyword
arguments to the message constructor.
:param extra_context: Any additional context to use when rendering the
templated content.
:type extra_context: :class:`dict`
:returns: A message instance.
:rtype: :attr:`.message_class`
|
mailviews/messages.py
|
def render_to_message(self, extra_context=None, **kwargs):
"""
Renders and returns an unsent message with the provided context.
Any extra keyword arguments passed will be passed through as keyword
arguments to the message constructor.
:param extra_context: Any additional context to use when rendering the
templated content.
:type extra_context: :class:`dict`
:returns: A message instance.
:rtype: :attr:`.message_class`
"""
if extra_context is None:
extra_context = {}
# Ensure our custom headers are added to the underlying message class.
kwargs.setdefault('headers', {}).update(self.headers)
context = self.get_context_data(**extra_context)
return self.message_class(
subject=self.render_subject(context),
body=self.render_body(context),
**kwargs)
|
def render_to_message(self, extra_context=None, **kwargs):
"""
Renders and returns an unsent message with the provided context.
Any extra keyword arguments passed will be passed through as keyword
arguments to the message constructor.
:param extra_context: Any additional context to use when rendering the
templated content.
:type extra_context: :class:`dict`
:returns: A message instance.
:rtype: :attr:`.message_class`
"""
if extra_context is None:
extra_context = {}
# Ensure our custom headers are added to the underlying message class.
kwargs.setdefault('headers', {}).update(self.headers)
context = self.get_context_data(**extra_context)
return self.message_class(
subject=self.render_subject(context),
body=self.render_body(context),
**kwargs)
|
[
"Renders",
"and",
"returns",
"an",
"unsent",
"message",
"with",
"the",
"provided",
"context",
"."
] |
disqus/django-mailviews
|
python
|
https://github.com/disqus/django-mailviews/blob/9993d5e911d545b3bc038433986c5f6812e7e965/mailviews/messages.py#L39-L62
|
[
"def",
"render_to_message",
"(",
"self",
",",
"extra_context",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"extra_context",
"is",
"None",
":",
"extra_context",
"=",
"{",
"}",
"# Ensure our custom headers are added to the underlying message class.",
"kwargs",
".",
"setdefault",
"(",
"'headers'",
",",
"{",
"}",
")",
".",
"update",
"(",
"self",
".",
"headers",
")",
"context",
"=",
"self",
".",
"get_context_data",
"(",
"*",
"*",
"extra_context",
")",
"return",
"self",
".",
"message_class",
"(",
"subject",
"=",
"self",
".",
"render_subject",
"(",
"context",
")",
",",
"body",
"=",
"self",
".",
"render_body",
"(",
"context",
")",
",",
"*",
"*",
"kwargs",
")"
] |
9993d5e911d545b3bc038433986c5f6812e7e965
|
valid
|
EmailMessageView.send
|
Renders and sends an email message.
All keyword arguments other than ``extra_context`` are passed through
as keyword arguments when constructing a new :attr:`message_class`
instance for this message.
This method exists primarily for convenience, and the proper
rendering of your message should not depend on the behavior of this
method. To alter how a message is created, override
:meth:``render_to_message`` instead, since that should always be
called, even if a message is not sent.
:param extra_context: Any additional context data that will be used
when rendering this message.
:type extra_context: :class:`dict`
|
mailviews/messages.py
|
def send(self, extra_context=None, **kwargs):
"""
Renders and sends an email message.
All keyword arguments other than ``extra_context`` are passed through
as keyword arguments when constructing a new :attr:`message_class`
instance for this message.
This method exists primarily for convenience, and the proper
rendering of your message should not depend on the behavior of this
method. To alter how a message is created, override
:meth:``render_to_message`` instead, since that should always be
called, even if a message is not sent.
:param extra_context: Any additional context data that will be used
when rendering this message.
:type extra_context: :class:`dict`
"""
message = self.render_to_message(extra_context=extra_context, **kwargs)
return message.send()
|
def send(self, extra_context=None, **kwargs):
"""
Renders and sends an email message.
All keyword arguments other than ``extra_context`` are passed through
as keyword arguments when constructing a new :attr:`message_class`
instance for this message.
This method exists primarily for convenience, and the proper
rendering of your message should not depend on the behavior of this
method. To alter how a message is created, override
:meth:``render_to_message`` instead, since that should always be
called, even if a message is not sent.
:param extra_context: Any additional context data that will be used
when rendering this message.
:type extra_context: :class:`dict`
"""
message = self.render_to_message(extra_context=extra_context, **kwargs)
return message.send()
|
[
"Renders",
"and",
"sends",
"an",
"email",
"message",
"."
] |
disqus/django-mailviews
|
python
|
https://github.com/disqus/django-mailviews/blob/9993d5e911d545b3bc038433986c5f6812e7e965/mailviews/messages.py#L64-L83
|
[
"def",
"send",
"(",
"self",
",",
"extra_context",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"message",
"=",
"self",
".",
"render_to_message",
"(",
"extra_context",
"=",
"extra_context",
",",
"*",
"*",
"kwargs",
")",
"return",
"message",
".",
"send",
"(",
")"
] |
9993d5e911d545b3bc038433986c5f6812e7e965
|
valid
|
TemplatedEmailMessageView.render_subject
|
Renders the message subject for the given context.
The context data is automatically unescaped to avoid rendering HTML
entities in ``text/plain`` content.
:param context: The context to use when rendering the subject template.
:type context: :class:`~django.template.Context`
:returns: A rendered subject.
:rtype: :class:`str`
|
mailviews/messages.py
|
def render_subject(self, context):
"""
Renders the message subject for the given context.
The context data is automatically unescaped to avoid rendering HTML
entities in ``text/plain`` content.
:param context: The context to use when rendering the subject template.
:type context: :class:`~django.template.Context`
:returns: A rendered subject.
:rtype: :class:`str`
"""
rendered = self.subject_template.render(unescape(context))
return rendered.strip()
|
def render_subject(self, context):
"""
Renders the message subject for the given context.
The context data is automatically unescaped to avoid rendering HTML
entities in ``text/plain`` content.
:param context: The context to use when rendering the subject template.
:type context: :class:`~django.template.Context`
:returns: A rendered subject.
:rtype: :class:`str`
"""
rendered = self.subject_template.render(unescape(context))
return rendered.strip()
|
[
"Renders",
"the",
"message",
"subject",
"for",
"the",
"given",
"context",
"."
] |
disqus/django-mailviews
|
python
|
https://github.com/disqus/django-mailviews/blob/9993d5e911d545b3bc038433986c5f6812e7e965/mailviews/messages.py#L149-L162
|
[
"def",
"render_subject",
"(",
"self",
",",
"context",
")",
":",
"rendered",
"=",
"self",
".",
"subject_template",
".",
"render",
"(",
"unescape",
"(",
"context",
")",
")",
"return",
"rendered",
".",
"strip",
"(",
")"
] |
9993d5e911d545b3bc038433986c5f6812e7e965
|
valid
|
TemplatedHTMLEmailMessageView.render_to_message
|
Renders and returns an unsent message with the given context.
Any extra keyword arguments passed will be passed through as keyword
arguments to the message constructor.
:param extra_context: Any additional context to use when rendering
templated content.
:type extra_context: :class:`dict`
:returns: A message instance.
:rtype: :attr:`.message_class`
|
mailviews/messages.py
|
def render_to_message(self, extra_context=None, *args, **kwargs):
"""
Renders and returns an unsent message with the given context.
Any extra keyword arguments passed will be passed through as keyword
arguments to the message constructor.
:param extra_context: Any additional context to use when rendering
templated content.
:type extra_context: :class:`dict`
:returns: A message instance.
:rtype: :attr:`.message_class`
"""
message = super(TemplatedHTMLEmailMessageView, self)\
.render_to_message(extra_context, *args, **kwargs)
if extra_context is None:
extra_context = {}
context = self.get_context_data(**extra_context)
content = self.render_html_body(context)
message.attach_alternative(content, mimetype='text/html')
return message
|
def render_to_message(self, extra_context=None, *args, **kwargs):
"""
Renders and returns an unsent message with the given context.
Any extra keyword arguments passed will be passed through as keyword
arguments to the message constructor.
:param extra_context: Any additional context to use when rendering
templated content.
:type extra_context: :class:`dict`
:returns: A message instance.
:rtype: :attr:`.message_class`
"""
message = super(TemplatedHTMLEmailMessageView, self)\
.render_to_message(extra_context, *args, **kwargs)
if extra_context is None:
extra_context = {}
context = self.get_context_data(**extra_context)
content = self.render_html_body(context)
message.attach_alternative(content, mimetype='text/html')
return message
|
[
"Renders",
"and",
"returns",
"an",
"unsent",
"message",
"with",
"the",
"given",
"context",
"."
] |
disqus/django-mailviews
|
python
|
https://github.com/disqus/django-mailviews/blob/9993d5e911d545b3bc038433986c5f6812e7e965/mailviews/messages.py#L223-L245
|
[
"def",
"render_to_message",
"(",
"self",
",",
"extra_context",
"=",
"None",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"message",
"=",
"super",
"(",
"TemplatedHTMLEmailMessageView",
",",
"self",
")",
".",
"render_to_message",
"(",
"extra_context",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"if",
"extra_context",
"is",
"None",
":",
"extra_context",
"=",
"{",
"}",
"context",
"=",
"self",
".",
"get_context_data",
"(",
"*",
"*",
"extra_context",
")",
"content",
"=",
"self",
".",
"render_html_body",
"(",
"context",
")",
"message",
".",
"attach_alternative",
"(",
"content",
",",
"mimetype",
"=",
"'text/html'",
")",
"return",
"message"
] |
9993d5e911d545b3bc038433986c5f6812e7e965
|
valid
|
timestamp
|
get microseconds since 2000-01-01 00:00
|
pgcopy/copy.py
|
def timestamp(_, dt):
'get microseconds since 2000-01-01 00:00'
# see http://stackoverflow.com/questions/2956886/
dt = util.to_utc(dt)
unix_timestamp = calendar.timegm(dt.timetuple())
# timetuple doesn't maintain microseconds
# see http://stackoverflow.com/a/14369386/519015
val = ((unix_timestamp - psql_epoch) * 1000000) + dt.microsecond
return ('iq', (8, val))
|
def timestamp(_, dt):
'get microseconds since 2000-01-01 00:00'
# see http://stackoverflow.com/questions/2956886/
dt = util.to_utc(dt)
unix_timestamp = calendar.timegm(dt.timetuple())
# timetuple doesn't maintain microseconds
# see http://stackoverflow.com/a/14369386/519015
val = ((unix_timestamp - psql_epoch) * 1000000) + dt.microsecond
return ('iq', (8, val))
|
[
"get",
"microseconds",
"since",
"2000",
"-",
"01",
"-",
"01",
"00",
":",
"00"
] |
altaurog/pgcopy
|
python
|
https://github.com/altaurog/pgcopy/blob/0f97ff1b2940cf27a3e6963749bf3d26efd1608f/pgcopy/copy.py#L40-L48
|
[
"def",
"timestamp",
"(",
"_",
",",
"dt",
")",
":",
"# see http://stackoverflow.com/questions/2956886/",
"dt",
"=",
"util",
".",
"to_utc",
"(",
"dt",
")",
"unix_timestamp",
"=",
"calendar",
".",
"timegm",
"(",
"dt",
".",
"timetuple",
"(",
")",
")",
"# timetuple doesn't maintain microseconds",
"# see http://stackoverflow.com/a/14369386/519015",
"val",
"=",
"(",
"(",
"unix_timestamp",
"-",
"psql_epoch",
")",
"*",
"1000000",
")",
"+",
"dt",
".",
"microsecond",
"return",
"(",
"'iq'",
",",
"(",
"8",
",",
"val",
")",
")"
] |
0f97ff1b2940cf27a3e6963749bf3d26efd1608f
|
valid
|
numeric
|
NBASE = 1000
ndigits = total number of base-NBASE digits
weight = base-NBASE weight of first digit
sign = 0x0000 if positive, 0x4000 if negative, 0xC000 if nan
dscale = decimal digits after decimal place
|
pgcopy/copy.py
|
def numeric(_, n):
"""
NBASE = 1000
ndigits = total number of base-NBASE digits
weight = base-NBASE weight of first digit
sign = 0x0000 if positive, 0x4000 if negative, 0xC000 if nan
dscale = decimal digits after decimal place
"""
try:
nt = n.as_tuple()
except AttributeError:
raise TypeError('numeric field requires Decimal value (got %r)' % n)
digits = []
if isinstance(nt.exponent, str):
# NaN, Inf, -Inf
ndigits = 0
weight = 0
sign = 0xC000
dscale = 0
else:
decdigits = list(reversed(nt.digits + (nt.exponent % 4) * (0,)))
weight = 0
while decdigits:
if any(decdigits[:4]):
break
weight += 1
del decdigits[:4]
while decdigits:
digits.insert(0, ndig(decdigits[:4]))
del decdigits[:4]
ndigits = len(digits)
weight += nt.exponent // 4 + ndigits - 1
sign = nt.sign * 0x4000
dscale = -min(0, nt.exponent)
data = [ndigits, weight, sign, dscale] + digits
return ('ihhHH%dH' % ndigits, [2 * len(data)] + data)
|
def numeric(_, n):
"""
NBASE = 1000
ndigits = total number of base-NBASE digits
weight = base-NBASE weight of first digit
sign = 0x0000 if positive, 0x4000 if negative, 0xC000 if nan
dscale = decimal digits after decimal place
"""
try:
nt = n.as_tuple()
except AttributeError:
raise TypeError('numeric field requires Decimal value (got %r)' % n)
digits = []
if isinstance(nt.exponent, str):
# NaN, Inf, -Inf
ndigits = 0
weight = 0
sign = 0xC000
dscale = 0
else:
decdigits = list(reversed(nt.digits + (nt.exponent % 4) * (0,)))
weight = 0
while decdigits:
if any(decdigits[:4]):
break
weight += 1
del decdigits[:4]
while decdigits:
digits.insert(0, ndig(decdigits[:4]))
del decdigits[:4]
ndigits = len(digits)
weight += nt.exponent // 4 + ndigits - 1
sign = nt.sign * 0x4000
dscale = -min(0, nt.exponent)
data = [ndigits, weight, sign, dscale] + digits
return ('ihhHH%dH' % ndigits, [2 * len(data)] + data)
|
[
"NBASE",
"=",
"1000",
"ndigits",
"=",
"total",
"number",
"of",
"base",
"-",
"NBASE",
"digits",
"weight",
"=",
"base",
"-",
"NBASE",
"weight",
"of",
"first",
"digit",
"sign",
"=",
"0x0000",
"if",
"positive",
"0x4000",
"if",
"negative",
"0xC000",
"if",
"nan",
"dscale",
"=",
"decimal",
"digits",
"after",
"decimal",
"place"
] |
altaurog/pgcopy
|
python
|
https://github.com/altaurog/pgcopy/blob/0f97ff1b2940cf27a3e6963749bf3d26efd1608f/pgcopy/copy.py#L54-L89
|
[
"def",
"numeric",
"(",
"_",
",",
"n",
")",
":",
"try",
":",
"nt",
"=",
"n",
".",
"as_tuple",
"(",
")",
"except",
"AttributeError",
":",
"raise",
"TypeError",
"(",
"'numeric field requires Decimal value (got %r)'",
"%",
"n",
")",
"digits",
"=",
"[",
"]",
"if",
"isinstance",
"(",
"nt",
".",
"exponent",
",",
"str",
")",
":",
"# NaN, Inf, -Inf",
"ndigits",
"=",
"0",
"weight",
"=",
"0",
"sign",
"=",
"0xC000",
"dscale",
"=",
"0",
"else",
":",
"decdigits",
"=",
"list",
"(",
"reversed",
"(",
"nt",
".",
"digits",
"+",
"(",
"nt",
".",
"exponent",
"%",
"4",
")",
"*",
"(",
"0",
",",
")",
")",
")",
"weight",
"=",
"0",
"while",
"decdigits",
":",
"if",
"any",
"(",
"decdigits",
"[",
":",
"4",
"]",
")",
":",
"break",
"weight",
"+=",
"1",
"del",
"decdigits",
"[",
":",
"4",
"]",
"while",
"decdigits",
":",
"digits",
".",
"insert",
"(",
"0",
",",
"ndig",
"(",
"decdigits",
"[",
":",
"4",
"]",
")",
")",
"del",
"decdigits",
"[",
":",
"4",
"]",
"ndigits",
"=",
"len",
"(",
"digits",
")",
"weight",
"+=",
"nt",
".",
"exponent",
"//",
"4",
"+",
"ndigits",
"-",
"1",
"sign",
"=",
"nt",
".",
"sign",
"*",
"0x4000",
"dscale",
"=",
"-",
"min",
"(",
"0",
",",
"nt",
".",
"exponent",
")",
"data",
"=",
"[",
"ndigits",
",",
"weight",
",",
"sign",
",",
"dscale",
"]",
"+",
"digits",
"return",
"(",
"'ihhHH%dH'",
"%",
"ndigits",
",",
"[",
"2",
"*",
"len",
"(",
"data",
")",
"]",
"+",
"data",
")"
] |
0f97ff1b2940cf27a3e6963749bf3d26efd1608f
|
valid
|
set_default_subparser
|
default subparser selection. Call after setup, just before parse_args()
name: is the name of the subparser to call by default
args: if set is the argument list handed to parse_args()
, tested with 2.7, 3.2, 3.3, 3.4
it works with 2.6 assuming argparse is installed
|
simple_monitor_alert/management.py
|
def set_default_subparser(self, name, args=None):
"""default subparser selection. Call after setup, just before parse_args()
name: is the name of the subparser to call by default
args: if set is the argument list handed to parse_args()
, tested with 2.7, 3.2, 3.3, 3.4
it works with 2.6 assuming argparse is installed
"""
subparser_found = False
for arg in sys.argv[1:]:
if arg in ['-h', '--help']: # global help if no subparser
break
else:
for x in self._subparsers._actions:
if not isinstance(x, argparse._SubParsersAction):
continue
for sp_name in x._name_parser_map.keys():
if sp_name in sys.argv[1:]:
subparser_found = True
if not subparser_found:
# insert default in first position, this implies no
# global options without a sub_parsers specified
if args is None:
sys.argv.insert(1, name)
else:
args.insert(0, name)
|
def set_default_subparser(self, name, args=None):
"""default subparser selection. Call after setup, just before parse_args()
name: is the name of the subparser to call by default
args: if set is the argument list handed to parse_args()
, tested with 2.7, 3.2, 3.3, 3.4
it works with 2.6 assuming argparse is installed
"""
subparser_found = False
for arg in sys.argv[1:]:
if arg in ['-h', '--help']: # global help if no subparser
break
else:
for x in self._subparsers._actions:
if not isinstance(x, argparse._SubParsersAction):
continue
for sp_name in x._name_parser_map.keys():
if sp_name in sys.argv[1:]:
subparser_found = True
if not subparser_found:
# insert default in first position, this implies no
# global options without a sub_parsers specified
if args is None:
sys.argv.insert(1, name)
else:
args.insert(0, name)
|
[
"default",
"subparser",
"selection",
".",
"Call",
"after",
"setup",
"just",
"before",
"parse_args",
"()",
"name",
":",
"is",
"the",
"name",
"of",
"the",
"subparser",
"to",
"call",
"by",
"default",
"args",
":",
"if",
"set",
"is",
"the",
"argument",
"list",
"handed",
"to",
"parse_args",
"()"
] |
Nekmo/simple-monitor-alert
|
python
|
https://github.com/Nekmo/simple-monitor-alert/blob/11d6dbd3c0b3b9a210d6435208066f5636f1f44e/simple_monitor_alert/management.py#L36-L61
|
[
"def",
"set_default_subparser",
"(",
"self",
",",
"name",
",",
"args",
"=",
"None",
")",
":",
"subparser_found",
"=",
"False",
"for",
"arg",
"in",
"sys",
".",
"argv",
"[",
"1",
":",
"]",
":",
"if",
"arg",
"in",
"[",
"'-h'",
",",
"'--help'",
"]",
":",
"# global help if no subparser",
"break",
"else",
":",
"for",
"x",
"in",
"self",
".",
"_subparsers",
".",
"_actions",
":",
"if",
"not",
"isinstance",
"(",
"x",
",",
"argparse",
".",
"_SubParsersAction",
")",
":",
"continue",
"for",
"sp_name",
"in",
"x",
".",
"_name_parser_map",
".",
"keys",
"(",
")",
":",
"if",
"sp_name",
"in",
"sys",
".",
"argv",
"[",
"1",
":",
"]",
":",
"subparser_found",
"=",
"True",
"if",
"not",
"subparser_found",
":",
"# insert default in first position, this implies no",
"# global options without a sub_parsers specified",
"if",
"args",
"is",
"None",
":",
"sys",
".",
"argv",
".",
"insert",
"(",
"1",
",",
"name",
")",
"else",
":",
"args",
".",
"insert",
"(",
"0",
",",
"name",
")"
] |
11d6dbd3c0b3b9a210d6435208066f5636f1f44e
|
valid
|
execute_from_command_line
|
A simple method that runs a ManagementUtility.
|
simple_monitor_alert/management.py
|
def execute_from_command_line(argv=None):
"""
A simple method that runs a ManagementUtility.
"""
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--monitors-dir', default=MONITORS_DIR)
parser.add_argument('--alerts-dir', default=ALERTS_DIR)
parser.add_argument('--config', default=SMA_INI_FILE)
parser.add_argument('--warning', help='set logging to warning', action='store_const', dest='loglevel',
const=logging.WARNING, default=logging.INFO)
parser.add_argument('--quiet', help='set logging to ERROR', action='store_const', dest='loglevel',
const=logging.ERROR, default=logging.INFO)
parser.add_argument('--debug', help='set logging to DEBUG',
action='store_const', dest='loglevel',
const=logging.DEBUG, default=logging.INFO)
parser.add_argument('--verbose', help='set logging to COMM',
action='store_const', dest='loglevel',
const=5, default=logging.INFO)
parser.sub = parser.add_subparsers()
parse_service = parser.sub.add_parser('service', help='Run SMA as service (daemon).')
parse_service.set_defaults(which='service')
parse_oneshot = parser.sub.add_parser('one-shot', help='Run SMA once and exit')
parse_oneshot.set_defaults(which='one-shot')
parse_alerts = parser.sub.add_parser('alerts', help='Alerts options.')
parse_alerts.set_defaults(which='alerts')
parse_alerts.add_argument('--test', help = 'Test alert', action='store_true')
parse_alerts.add_argument('alert_section', nargs='?', help='Alert section to see')
parse_results = parser.sub.add_parser('results', help='Monitors results')
parse_results.set_defaults(which='results')
parser.set_default_subparser('one-shot')
args = parser.parse_args(argv[1:])
create_logger('sma', args.loglevel)
if not getattr(args, 'which', None) or args.which == 'one-shot':
sma = SMA(args.monitors_dir, args.alerts_dir, args.config)
sma.evaluate_and_alert()
elif args.which == 'service':
sma = SMAService(args.monitors_dir, args.alerts_dir, args.config)
sma.start()
elif args.which == 'alerts' and args.test:
sma = SMA(args.monitors_dir, args.alerts_dir, args.config)
sma.alerts.test()
elif args.which == 'results':
print(SMA(args.monitors_dir, args.alerts_dir, args.config).results)
|
def execute_from_command_line(argv=None):
"""
A simple method that runs a ManagementUtility.
"""
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--monitors-dir', default=MONITORS_DIR)
parser.add_argument('--alerts-dir', default=ALERTS_DIR)
parser.add_argument('--config', default=SMA_INI_FILE)
parser.add_argument('--warning', help='set logging to warning', action='store_const', dest='loglevel',
const=logging.WARNING, default=logging.INFO)
parser.add_argument('--quiet', help='set logging to ERROR', action='store_const', dest='loglevel',
const=logging.ERROR, default=logging.INFO)
parser.add_argument('--debug', help='set logging to DEBUG',
action='store_const', dest='loglevel',
const=logging.DEBUG, default=logging.INFO)
parser.add_argument('--verbose', help='set logging to COMM',
action='store_const', dest='loglevel',
const=5, default=logging.INFO)
parser.sub = parser.add_subparsers()
parse_service = parser.sub.add_parser('service', help='Run SMA as service (daemon).')
parse_service.set_defaults(which='service')
parse_oneshot = parser.sub.add_parser('one-shot', help='Run SMA once and exit')
parse_oneshot.set_defaults(which='one-shot')
parse_alerts = parser.sub.add_parser('alerts', help='Alerts options.')
parse_alerts.set_defaults(which='alerts')
parse_alerts.add_argument('--test', help = 'Test alert', action='store_true')
parse_alerts.add_argument('alert_section', nargs='?', help='Alert section to see')
parse_results = parser.sub.add_parser('results', help='Monitors results')
parse_results.set_defaults(which='results')
parser.set_default_subparser('one-shot')
args = parser.parse_args(argv[1:])
create_logger('sma', args.loglevel)
if not getattr(args, 'which', None) or args.which == 'one-shot':
sma = SMA(args.monitors_dir, args.alerts_dir, args.config)
sma.evaluate_and_alert()
elif args.which == 'service':
sma = SMAService(args.monitors_dir, args.alerts_dir, args.config)
sma.start()
elif args.which == 'alerts' and args.test:
sma = SMA(args.monitors_dir, args.alerts_dir, args.config)
sma.alerts.test()
elif args.which == 'results':
print(SMA(args.monitors_dir, args.alerts_dir, args.config).results)
|
[
"A",
"simple",
"method",
"that",
"runs",
"a",
"ManagementUtility",
"."
] |
Nekmo/simple-monitor-alert
|
python
|
https://github.com/Nekmo/simple-monitor-alert/blob/11d6dbd3c0b3b9a210d6435208066f5636f1f44e/simple_monitor_alert/management.py#L66-L117
|
[
"def",
"execute_from_command_line",
"(",
"argv",
"=",
"None",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"__doc__",
")",
"parser",
".",
"add_argument",
"(",
"'--monitors-dir'",
",",
"default",
"=",
"MONITORS_DIR",
")",
"parser",
".",
"add_argument",
"(",
"'--alerts-dir'",
",",
"default",
"=",
"ALERTS_DIR",
")",
"parser",
".",
"add_argument",
"(",
"'--config'",
",",
"default",
"=",
"SMA_INI_FILE",
")",
"parser",
".",
"add_argument",
"(",
"'--warning'",
",",
"help",
"=",
"'set logging to warning'",
",",
"action",
"=",
"'store_const'",
",",
"dest",
"=",
"'loglevel'",
",",
"const",
"=",
"logging",
".",
"WARNING",
",",
"default",
"=",
"logging",
".",
"INFO",
")",
"parser",
".",
"add_argument",
"(",
"'--quiet'",
",",
"help",
"=",
"'set logging to ERROR'",
",",
"action",
"=",
"'store_const'",
",",
"dest",
"=",
"'loglevel'",
",",
"const",
"=",
"logging",
".",
"ERROR",
",",
"default",
"=",
"logging",
".",
"INFO",
")",
"parser",
".",
"add_argument",
"(",
"'--debug'",
",",
"help",
"=",
"'set logging to DEBUG'",
",",
"action",
"=",
"'store_const'",
",",
"dest",
"=",
"'loglevel'",
",",
"const",
"=",
"logging",
".",
"DEBUG",
",",
"default",
"=",
"logging",
".",
"INFO",
")",
"parser",
".",
"add_argument",
"(",
"'--verbose'",
",",
"help",
"=",
"'set logging to COMM'",
",",
"action",
"=",
"'store_const'",
",",
"dest",
"=",
"'loglevel'",
",",
"const",
"=",
"5",
",",
"default",
"=",
"logging",
".",
"INFO",
")",
"parser",
".",
"sub",
"=",
"parser",
".",
"add_subparsers",
"(",
")",
"parse_service",
"=",
"parser",
".",
"sub",
".",
"add_parser",
"(",
"'service'",
",",
"help",
"=",
"'Run SMA as service (daemon).'",
")",
"parse_service",
".",
"set_defaults",
"(",
"which",
"=",
"'service'",
")",
"parse_oneshot",
"=",
"parser",
".",
"sub",
".",
"add_parser",
"(",
"'one-shot'",
",",
"help",
"=",
"'Run SMA once and exit'",
")",
"parse_oneshot",
".",
"set_defaults",
"(",
"which",
"=",
"'one-shot'",
")",
"parse_alerts",
"=",
"parser",
".",
"sub",
".",
"add_parser",
"(",
"'alerts'",
",",
"help",
"=",
"'Alerts options.'",
")",
"parse_alerts",
".",
"set_defaults",
"(",
"which",
"=",
"'alerts'",
")",
"parse_alerts",
".",
"add_argument",
"(",
"'--test'",
",",
"help",
"=",
"'Test alert'",
",",
"action",
"=",
"'store_true'",
")",
"parse_alerts",
".",
"add_argument",
"(",
"'alert_section'",
",",
"nargs",
"=",
"'?'",
",",
"help",
"=",
"'Alert section to see'",
")",
"parse_results",
"=",
"parser",
".",
"sub",
".",
"add_parser",
"(",
"'results'",
",",
"help",
"=",
"'Monitors results'",
")",
"parse_results",
".",
"set_defaults",
"(",
"which",
"=",
"'results'",
")",
"parser",
".",
"set_default_subparser",
"(",
"'one-shot'",
")",
"args",
"=",
"parser",
".",
"parse_args",
"(",
"argv",
"[",
"1",
":",
"]",
")",
"create_logger",
"(",
"'sma'",
",",
"args",
".",
"loglevel",
")",
"if",
"not",
"getattr",
"(",
"args",
",",
"'which'",
",",
"None",
")",
"or",
"args",
".",
"which",
"==",
"'one-shot'",
":",
"sma",
"=",
"SMA",
"(",
"args",
".",
"monitors_dir",
",",
"args",
".",
"alerts_dir",
",",
"args",
".",
"config",
")",
"sma",
".",
"evaluate_and_alert",
"(",
")",
"elif",
"args",
".",
"which",
"==",
"'service'",
":",
"sma",
"=",
"SMAService",
"(",
"args",
".",
"monitors_dir",
",",
"args",
".",
"alerts_dir",
",",
"args",
".",
"config",
")",
"sma",
".",
"start",
"(",
")",
"elif",
"args",
".",
"which",
"==",
"'alerts'",
"and",
"args",
".",
"test",
":",
"sma",
"=",
"SMA",
"(",
"args",
".",
"monitors_dir",
",",
"args",
".",
"alerts_dir",
",",
"args",
".",
"config",
")",
"sma",
".",
"alerts",
".",
"test",
"(",
")",
"elif",
"args",
".",
"which",
"==",
"'results'",
":",
"print",
"(",
"SMA",
"(",
"args",
".",
"monitors_dir",
",",
"args",
".",
"alerts_dir",
",",
"args",
".",
"config",
")",
".",
"results",
")"
] |
11d6dbd3c0b3b9a210d6435208066f5636f1f44e
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.