body_hash stringlengths 64 64 | body stringlengths 23 109k | docstring stringlengths 1 57k | path stringlengths 4 198 | name stringlengths 1 115 | repository_name stringlengths 7 111 | repository_stars float64 0 191k | lang stringclasses 1
value | body_without_docstring stringlengths 14 108k | unified stringlengths 45 133k |
|---|---|---|---|---|---|---|---|---|---|
dfdded0c2431ff6b2797ea08d16db4a679c69ea09c2ed198c63a9746f08c1d3a | def to_string(value, ctx):
'\n Tries conversion of any value to a string\n '
if isinstance(value, bool):
return ('TRUE' if value else 'FALSE')
elif isinstance(value, int):
return six.text_type(value)
elif isinstance(value, Decimal):
return format_decimal(value)
elif isi... | Tries conversion of any value to a string | python/temba_expressions/conversions.py | to_string | greatnonprofits-nfp/ccl-expressions | 0 | python | def to_string(value, ctx):
'\n \n '
if isinstance(value, bool):
return ('TRUE' if value else 'FALSE')
elif isinstance(value, int):
return six.text_type(value)
elif isinstance(value, Decimal):
return format_decimal(value)
elif isinstance(value, six.string_types):
... | def to_string(value, ctx):
'\n \n '
if isinstance(value, bool):
return ('TRUE' if value else 'FALSE')
elif isinstance(value, int):
return six.text_type(value)
elif isinstance(value, Decimal):
return format_decimal(value)
elif isinstance(value, six.string_types):
... |
7ff02344c56aa3f1b0ea803debccbccd9ace540f6ad4aafec8a4136b47808388 | def to_date(value, ctx):
'\n Tries conversion of any value to a date\n '
if isinstance(value, six.string_types):
temporal = ctx.get_date_parser().auto(value)
if (temporal is not None):
return to_date(temporal, ctx)
elif (type(value) == datetime.date):
return value
... | Tries conversion of any value to a date | python/temba_expressions/conversions.py | to_date | greatnonprofits-nfp/ccl-expressions | 0 | python | def to_date(value, ctx):
'\n \n '
if isinstance(value, six.string_types):
temporal = ctx.get_date_parser().auto(value)
if (temporal is not None):
return to_date(temporal, ctx)
elif (type(value) == datetime.date):
return value
elif isinstance(value, datetime.date... | def to_date(value, ctx):
'\n \n '
if isinstance(value, six.string_types):
temporal = ctx.get_date_parser().auto(value)
if (temporal is not None):
return to_date(temporal, ctx)
elif (type(value) == datetime.date):
return value
elif isinstance(value, datetime.date... |
790f30171f2c5fab47310d5d5a2853cf127dab69e1986f8d641867f09571d462 | def to_datetime(value, ctx):
'\n Tries conversion of any value to a datetime\n '
if isinstance(value, six.string_types):
temporal = ctx.get_date_parser().auto(value)
if (temporal is not None):
return to_datetime(temporal, ctx)
elif (type(value) == datetime.date):
re... | Tries conversion of any value to a datetime | python/temba_expressions/conversions.py | to_datetime | greatnonprofits-nfp/ccl-expressions | 0 | python | def to_datetime(value, ctx):
'\n \n '
if isinstance(value, six.string_types):
temporal = ctx.get_date_parser().auto(value)
if (temporal is not None):
return to_datetime(temporal, ctx)
elif (type(value) == datetime.date):
return ctx.timezone.localize(datetime.datetim... | def to_datetime(value, ctx):
'\n \n '
if isinstance(value, six.string_types):
temporal = ctx.get_date_parser().auto(value)
if (temporal is not None):
return to_datetime(temporal, ctx)
elif (type(value) == datetime.date):
return ctx.timezone.localize(datetime.datetim... |
be48ab62a0c133091dfdd015f7ecbedfbc0e1f039ddd34743bbfbbcbe97488c8 | def to_date_or_datetime(value, ctx):
'\n Tries conversion of any value to a date or datetime\n '
if isinstance(value, six.string_types):
temporal = ctx.get_date_parser().auto(value)
if (temporal is not None):
return temporal
elif (type(value) == datetime.date):
retu... | Tries conversion of any value to a date or datetime | python/temba_expressions/conversions.py | to_date_or_datetime | greatnonprofits-nfp/ccl-expressions | 0 | python | def to_date_or_datetime(value, ctx):
'\n \n '
if isinstance(value, six.string_types):
temporal = ctx.get_date_parser().auto(value)
if (temporal is not None):
return temporal
elif (type(value) == datetime.date):
return value
elif isinstance(value, datetime.dateti... | def to_date_or_datetime(value, ctx):
'\n \n '
if isinstance(value, six.string_types):
temporal = ctx.get_date_parser().auto(value)
if (temporal is not None):
return temporal
elif (type(value) == datetime.date):
return value
elif isinstance(value, datetime.dateti... |
75930e54ae2f4850c25f5c5d88c7006f2411f75bf7087d24f521a3d8f50bd377 | def to_time(value, ctx):
'\n Tries conversion of any value to a time\n '
if isinstance(value, six.string_types):
time = ctx.get_date_parser().time(value)
if (time is not None):
return time
elif isinstance(value, datetime.time):
return value
elif isinstance(value... | Tries conversion of any value to a time | python/temba_expressions/conversions.py | to_time | greatnonprofits-nfp/ccl-expressions | 0 | python | def to_time(value, ctx):
'\n \n '
if isinstance(value, six.string_types):
time = ctx.get_date_parser().time(value)
if (time is not None):
return time
elif isinstance(value, datetime.time):
return value
elif isinstance(value, datetime.datetime):
return va... | def to_time(value, ctx):
'\n \n '
if isinstance(value, six.string_types):
time = ctx.get_date_parser().time(value)
if (time is not None):
return time
elif isinstance(value, datetime.time):
return value
elif isinstance(value, datetime.datetime):
return va... |
9035a51117fdbd5bab055d0c3f4c58dd813fffecf1b26b70634d54795fce7459 | def to_same(value1, value2, ctx):
"\n Converts a pair of arguments to their most-likely types. This deviates from Excel which doesn't auto convert values\n but is necessary for us to intuitively handle contact fields which don't use the correct value type\n "
if (type(value1) == type(value2)):
... | Converts a pair of arguments to their most-likely types. This deviates from Excel which doesn't auto convert values
but is necessary for us to intuitively handle contact fields which don't use the correct value type | python/temba_expressions/conversions.py | to_same | greatnonprofits-nfp/ccl-expressions | 0 | python | def to_same(value1, value2, ctx):
"\n Converts a pair of arguments to their most-likely types. This deviates from Excel which doesn't auto convert values\n but is necessary for us to intuitively handle contact fields which don't use the correct value type\n "
if (type(value1) == type(value2)):
... | def to_same(value1, value2, ctx):
"\n Converts a pair of arguments to their most-likely types. This deviates from Excel which doesn't auto convert values\n but is necessary for us to intuitively handle contact fields which don't use the correct value type\n "
if (type(value1) == type(value2)):
... |
9d90f8effab24cd992db03e5847d5a28efc665960002a4b99ec50b8b345f9b31 | def to_repr(value, ctx):
'\n Converts a value back to its representation form, e.g. x -> "x"\n '
as_string = to_string(value, ctx)
if (isinstance(value, six.string_types) or isinstance(value, datetime.date) or isinstance(value, datetime.time)):
as_string = as_string.replace('"', '""')
... | Converts a value back to its representation form, e.g. x -> "x" | python/temba_expressions/conversions.py | to_repr | greatnonprofits-nfp/ccl-expressions | 0 | python | def to_repr(value, ctx):
'\n \n '
as_string = to_string(value, ctx)
if (isinstance(value, six.string_types) or isinstance(value, datetime.date) or isinstance(value, datetime.time)):
as_string = as_string.replace('"', '')
as_string = ('"%s"' % as_string)
return as_string | def to_repr(value, ctx):
'\n \n '
as_string = to_string(value, ctx)
if (isinstance(value, six.string_types) or isinstance(value, datetime.date) or isinstance(value, datetime.time)):
as_string = as_string.replace('"', '')
as_string = ('"%s"' % as_string)
return as_string<|docstring|... |
2fd125b8d2ba7b5f01685c23d0e86bbabcce3a48bb58541b1c125aaa8765b451 | def format_decimal(decimal):
'\n Formats a decimal number using the same precision as Excel\n :param decimal: the decimal value\n :return: the formatted string value\n '
getcontext().rounding = ROUND_HALF_UP
normalized = decimal.normalize()
(sign, digits, exponent) = normalized.as_tuple()
... | Formats a decimal number using the same precision as Excel
:param decimal: the decimal value
:return: the formatted string value | python/temba_expressions/conversions.py | format_decimal | greatnonprofits-nfp/ccl-expressions | 0 | python | def format_decimal(decimal):
'\n Formats a decimal number using the same precision as Excel\n :param decimal: the decimal value\n :return: the formatted string value\n '
getcontext().rounding = ROUND_HALF_UP
normalized = decimal.normalize()
(sign, digits, exponent) = normalized.as_tuple()
... | def format_decimal(decimal):
'\n Formats a decimal number using the same precision as Excel\n :param decimal: the decimal value\n :return: the formatted string value\n '
getcontext().rounding = ROUND_HALF_UP
normalized = decimal.normalize()
(sign, digits, exponent) = normalized.as_tuple()
... |
54ae4fd58bb008d20f9859d94898fef2ac9796067b0da0521b2e8f05dad63595 | def all_neighbour_nodes(node_state: NodeState) -> typing.Set[typing.Address]:
' Return the identifiers for all nodes accross all payment networks which\n have a channel open with this one.\n '
addresses = set()
for payment_network in node_state.identifiers_to_paymentnetworks.values():
for toke... | Return the identifiers for all nodes accross all payment networks which
have a channel open with this one. | raiden/transfer/views.py | all_neighbour_nodes | gcarq/raiden | 0 | python | def all_neighbour_nodes(node_state: NodeState) -> typing.Set[typing.Address]:
' Return the identifiers for all nodes accross all payment networks which\n have a channel open with this one.\n '
addresses = set()
for payment_network in node_state.identifiers_to_paymentnetworks.values():
for toke... | def all_neighbour_nodes(node_state: NodeState) -> typing.Set[typing.Address]:
' Return the identifiers for all nodes accross all payment networks which\n have a channel open with this one.\n '
addresses = set()
for payment_network in node_state.identifiers_to_paymentnetworks.values():
for toke... |
c30006639209368a763e1ced6775897b37dda7a3a21d3bdc9ae46e24ea8f42d7 | def get_token_network_addresses_for(node_state: NodeState, payment_network_id: typing.Address) -> typing.List[typing.Address]:
' Return the list of tokens registered with the given payment network. '
payment_network = node_state.identifiers_to_paymentnetworks.get(payment_network_id)
if (payment_network is n... | Return the list of tokens registered with the given payment network. | raiden/transfer/views.py | get_token_network_addresses_for | gcarq/raiden | 0 | python | def get_token_network_addresses_for(node_state: NodeState, payment_network_id: typing.Address) -> typing.List[typing.Address]:
' '
payment_network = node_state.identifiers_to_paymentnetworks.get(payment_network_id)
if (payment_network is not None):
return [token_network.token_address for token_netw... | def get_token_network_addresses_for(node_state: NodeState, payment_network_id: typing.Address) -> typing.List[typing.Address]:
' '
payment_network = node_state.identifiers_to_paymentnetworks.get(payment_network_id)
if (payment_network is not None):
return [token_network.token_address for token_netw... |
8bebc61085c34e5bea46a681d03259fd2d9ee71a171a15218875fcd5c856f9f7 | def get_channelstate_for(node_state: NodeState, payment_network_id: typing.Address, token_address: typing.Address, partner_address: typing.Address):
' Return the NettingChannelState if it exists, None otherwise. '
token_network = get_token_network_by_token_address(node_state, payment_network_id, token_address)
... | Return the NettingChannelState if it exists, None otherwise. | raiden/transfer/views.py | get_channelstate_for | gcarq/raiden | 0 | python | def get_channelstate_for(node_state: NodeState, payment_network_id: typing.Address, token_address: typing.Address, partner_address: typing.Address):
' '
token_network = get_token_network_by_token_address(node_state, payment_network_id, token_address)
channel_state = None
if token_network:
chann... | def get_channelstate_for(node_state: NodeState, payment_network_id: typing.Address, token_address: typing.Address, partner_address: typing.Address):
' '
token_network = get_token_network_by_token_address(node_state, payment_network_id, token_address)
channel_state = None
if token_network:
chann... |
0c76ff16e4c291cde83784b38e8faf32ed7bc6b655e3ced476029bf9eb22d5e9 | def get_channestate_for_receiving(node_state: NodeState, payment_network_id: typing.Address, token_address: typing.Address):
'Return the state of channels that had received any transfers in this\n token network.\n '
token_network = get_token_network_by_token_address(node_state, payment_network_id, token_a... | Return the state of channels that had received any transfers in this
token network. | raiden/transfer/views.py | get_channestate_for_receiving | gcarq/raiden | 0 | python | def get_channestate_for_receiving(node_state: NodeState, payment_network_id: typing.Address, token_address: typing.Address):
'Return the state of channels that had received any transfers in this\n token network.\n '
token_network = get_token_network_by_token_address(node_state, payment_network_id, token_a... | def get_channestate_for_receiving(node_state: NodeState, payment_network_id: typing.Address, token_address: typing.Address):
'Return the state of channels that had received any transfers in this\n token network.\n '
token_network = get_token_network_by_token_address(node_state, payment_network_id, token_a... |
d5d1a0c9f82ac3b382e5dd17b447b7fdb5494fc73eff3fa786168669491bf62d | def get_channelstate_open(node_state: NodeState, payment_network_id: typing.Address, token_address: typing.Address) -> typing.List['NettingChannelState']:
'Return the state of open channels in a token network.'
token_network = get_token_network_by_token_address(node_state, payment_network_id, token_address)
... | Return the state of open channels in a token network. | raiden/transfer/views.py | get_channelstate_open | gcarq/raiden | 0 | python | def get_channelstate_open(node_state: NodeState, payment_network_id: typing.Address, token_address: typing.Address) -> typing.List['NettingChannelState']:
token_network = get_token_network_by_token_address(node_state, payment_network_id, token_address)
result = []
for channel_state in token_network.cha... | def get_channelstate_open(node_state: NodeState, payment_network_id: typing.Address, token_address: typing.Address) -> typing.List['NettingChannelState']:
token_network = get_token_network_by_token_address(node_state, payment_network_id, token_address)
result = []
for channel_state in token_network.cha... |
8cf9a3ff6da0273efaf0363c6e7c99b513d7f11a9eca649f46573ada9b02783b | def get_channelstate_not_settled(node_state: NodeState, payment_network_id: typing.Address, token_address: typing.Address) -> typing.List['NettingChannelState']:
'Return the state of open channels in a token network.'
token_network = get_token_network_by_token_address(node_state, payment_network_id, token_addre... | Return the state of open channels in a token network. | raiden/transfer/views.py | get_channelstate_not_settled | gcarq/raiden | 0 | python | def get_channelstate_not_settled(node_state: NodeState, payment_network_id: typing.Address, token_address: typing.Address) -> typing.List['NettingChannelState']:
token_network = get_token_network_by_token_address(node_state, payment_network_id, token_address)
result = []
for channel_state in token_netw... | def get_channelstate_not_settled(node_state: NodeState, payment_network_id: typing.Address, token_address: typing.Address) -> typing.List['NettingChannelState']:
token_network = get_token_network_by_token_address(node_state, payment_network_id, token_address)
result = []
for channel_state in token_netw... |
c312f773787eddadcd27c3eef9c06c285a68994ad210062eaa6d576615f0e58f | def select(self, indices):
'Delete row indices other than specified\n\n Examples:\n\n >>> import pyexcel as pe\n >>> data = [[1],[2],[3],[4],[5],[6],[7],[9]]\n >>> sheet = pe.Sheet(data)\n >>> sheet\n pyexcel sheet:\n +---+\n | 1 |\... | Delete row indices other than specified
Examples:
>>> import pyexcel as pe
>>> data = [[1],[2],[3],[4],[5],[6],[7],[9]]
>>> sheet = pe.Sheet(data)
>>> sheet
pyexcel sheet:
+---+
| 1 |
+---+
| 2 |
+---+
| 3 |
+---+
| 4 |
+---+
| 5 |
+---+
| 6 |
+-... | pyexcel/internal/sheets/row.py | select | wesleyacheng/pyexcel | 1,045 | python | def select(self, indices):
'Delete row indices other than specified\n\n Examples:\n\n >>> import pyexcel as pe\n >>> data = [[1],[2],[3],[4],[5],[6],[7],[9]]\n >>> sheet = pe.Sheet(data)\n >>> sheet\n pyexcel sheet:\n +---+\n | 1 |\... | def select(self, indices):
'Delete row indices other than specified\n\n Examples:\n\n >>> import pyexcel as pe\n >>> data = [[1],[2],[3],[4],[5],[6],[7],[9]]\n >>> sheet = pe.Sheet(data)\n >>> sheet\n pyexcel sheet:\n +---+\n | 1 |\... |
caffe05f54eab0f1df852726a45e518a7fb29fac6bebab405c13c82f7d639341 | def __delitem__(self, locator):
'Override the operator to delete items\n\n Examples:\n\n >>> import pyexcel as pe\n >>> data = [[1],[2],[3],[4],[5],[6],[7],[9]]\n >>> sheet = pe.Sheet(data)\n >>> sheet\n pyexcel sheet:\n +---+\n | 1... | Override the operator to delete items
Examples:
>>> import pyexcel as pe
>>> data = [[1],[2],[3],[4],[5],[6],[7],[9]]
>>> sheet = pe.Sheet(data)
>>> sheet
pyexcel sheet:
+---+
| 1 |
+---+
| 2 |
+---+
| 3 |
+---+
| 4 |
+---+
| 5 |
+---+
| 6 |
+---... | pyexcel/internal/sheets/row.py | __delitem__ | wesleyacheng/pyexcel | 1,045 | python | def __delitem__(self, locator):
'Override the operator to delete items\n\n Examples:\n\n >>> import pyexcel as pe\n >>> data = [[1],[2],[3],[4],[5],[6],[7],[9]]\n >>> sheet = pe.Sheet(data)\n >>> sheet\n pyexcel sheet:\n +---+\n | 1... | def __delitem__(self, locator):
'Override the operator to delete items\n\n Examples:\n\n >>> import pyexcel as pe\n >>> data = [[1],[2],[3],[4],[5],[6],[7],[9]]\n >>> sheet = pe.Sheet(data)\n >>> sheet\n pyexcel sheet:\n +---+\n | 1... |
b2747a3e6accd985d6a88bf8dc64db8d5a4c24719edbdb6a3b9cb5ea89f07d4d | def __getattr__(self, attr):
'\n Refer to sheet.row.name\n '
the_attr = attr
if (attr not in self._ref.rownames):
the_attr = the_attr.replace('_', ' ')
if (the_attr not in self._ref.rownames):
raise AttributeError(('%s is not found' % attr))
return self._ref.nam... | Refer to sheet.row.name | pyexcel/internal/sheets/row.py | __getattr__ | wesleyacheng/pyexcel | 1,045 | python | def __getattr__(self, attr):
'\n \n '
the_attr = attr
if (attr not in self._ref.rownames):
the_attr = the_attr.replace('_', ' ')
if (the_attr not in self._ref.rownames):
raise AttributeError(('%s is not found' % attr))
return self._ref.named_row_at(the_attr) | def __getattr__(self, attr):
'\n \n '
the_attr = attr
if (attr not in self._ref.rownames):
the_attr = the_attr.replace('_', ' ')
if (the_attr not in self._ref.rownames):
raise AttributeError(('%s is not found' % attr))
return self._ref.named_row_at(the_attr)<|do... |
7f58c2b4362ab07a415ddf664eac3f93f05d844e0d6f7ea152eb92adffdfb64c | def __setitem__(self, aslice, a_row):
'Override the operator to set items'
if compact.is_string(type(aslice)):
self._ref.set_named_row_at(aslice, a_row)
elif isinstance(aslice, slice):
my_range = utils.analyse_slice(aslice, self._ref.number_of_rows())
for i in my_range:
s... | Override the operator to set items | pyexcel/internal/sheets/row.py | __setitem__ | wesleyacheng/pyexcel | 1,045 | python | def __setitem__(self, aslice, a_row):
if compact.is_string(type(aslice)):
self._ref.set_named_row_at(aslice, a_row)
elif isinstance(aslice, slice):
my_range = utils.analyse_slice(aslice, self._ref.number_of_rows())
for i in my_range:
self._ref.set_row_at(i, a_row)
el... | def __setitem__(self, aslice, a_row):
if compact.is_string(type(aslice)):
self._ref.set_named_row_at(aslice, a_row)
elif isinstance(aslice, slice):
my_range = utils.analyse_slice(aslice, self._ref.number_of_rows())
for i in my_range:
self._ref.set_row_at(i, a_row)
el... |
65acab6b5aa9e536ee2af08e6612ac27bddf6ba9064f4c34750704a98dd3c9f8 | def __getitem__(self, aslice):
'By default, this class recognize from top to bottom\n from left to right'
index = aslice
if compact.is_string(type(aslice)):
return self._ref.named_row_at(aslice)
elif isinstance(aslice, slice):
my_range = utils.analyse_slice(aslice, self._ref.numbe... | By default, this class recognize from top to bottom
from left to right | pyexcel/internal/sheets/row.py | __getitem__ | wesleyacheng/pyexcel | 1,045 | python | def __getitem__(self, aslice):
'By default, this class recognize from top to bottom\n from left to right'
index = aslice
if compact.is_string(type(aslice)):
return self._ref.named_row_at(aslice)
elif isinstance(aslice, slice):
my_range = utils.analyse_slice(aslice, self._ref.numbe... | def __getitem__(self, aslice):
'By default, this class recognize from top to bottom\n from left to right'
index = aslice
if compact.is_string(type(aslice)):
return self._ref.named_row_at(aslice)
elif isinstance(aslice, slice):
my_range = utils.analyse_slice(aslice, self._ref.numbe... |
0a9a4e1e40bd5dc82d84e943c4cea32d1550efe2fc413b6ffb97916cbb4d99f7 | def __iadd__(self, other):
'Overload += sign\n\n :return: self\n '
if isinstance(other, compact.OrderedDict):
self._ref.extend_rows(copy.deepcopy(other))
elif isinstance(other, list):
self._ref.extend_rows(copy.deepcopy(other))
elif hasattr(other, 'get_internal_array'):
... | Overload += sign
:return: self | pyexcel/internal/sheets/row.py | __iadd__ | wesleyacheng/pyexcel | 1,045 | python | def __iadd__(self, other):
'Overload += sign\n\n :return: self\n '
if isinstance(other, compact.OrderedDict):
self._ref.extend_rows(copy.deepcopy(other))
elif isinstance(other, list):
self._ref.extend_rows(copy.deepcopy(other))
elif hasattr(other, 'get_internal_array'):
... | def __iadd__(self, other):
'Overload += sign\n\n :return: self\n '
if isinstance(other, compact.OrderedDict):
self._ref.extend_rows(copy.deepcopy(other))
elif isinstance(other, list):
self._ref.extend_rows(copy.deepcopy(other))
elif hasattr(other, 'get_internal_array'):
... |
f77af52a56f79d1c4167680850edfa6926d6650256601e6d51a8a395fab4defd | def __add__(self, other):
'Overload + sign\n\n :return: new instance\n '
new_instance = self._ref.clone()
if isinstance(other, compact.OrderedDict):
new_instance.extend_rows(copy.deepcopy(other))
elif isinstance(other, list):
new_instance.extend_rows(copy.deepcopy(other))
... | Overload + sign
:return: new instance | pyexcel/internal/sheets/row.py | __add__ | wesleyacheng/pyexcel | 1,045 | python | def __add__(self, other):
'Overload + sign\n\n :return: new instance\n '
new_instance = self._ref.clone()
if isinstance(other, compact.OrderedDict):
new_instance.extend_rows(copy.deepcopy(other))
elif isinstance(other, list):
new_instance.extend_rows(copy.deepcopy(other))
... | def __add__(self, other):
'Overload + sign\n\n :return: new instance\n '
new_instance = self._ref.clone()
if isinstance(other, compact.OrderedDict):
new_instance.extend_rows(copy.deepcopy(other))
elif isinstance(other, list):
new_instance.extend_rows(copy.deepcopy(other))
... |
971521d0fc937e9d5497aa7df7ea507149003761ca5909782f1a6e91165988a3 | def format(self, row_index=None, formatter=None, format_specs=None):
'Format a row'
if (row_index is not None):
self._handle_one_formatter(row_index, formatter)
elif format_specs:
for spec in format_specs:
self._handle_one_formatter(spec[0], spec[1]) | Format a row | pyexcel/internal/sheets/row.py | format | wesleyacheng/pyexcel | 1,045 | python | def format(self, row_index=None, formatter=None, format_specs=None):
if (row_index is not None):
self._handle_one_formatter(row_index, formatter)
elif format_specs:
for spec in format_specs:
self._handle_one_formatter(spec[0], spec[1]) | def format(self, row_index=None, formatter=None, format_specs=None):
if (row_index is not None):
self._handle_one_formatter(row_index, formatter)
elif format_specs:
for spec in format_specs:
self._handle_one_formatter(spec[0], spec[1])<|docstring|>Format a row<|endoftext|> |
6f6f761192afcd349cf607dbdb06783bb1d8e2eaaef64c40f9432375f6073166 | @ns.expect(pagination_arguments)
@ns.response(HTTPStatus.PARTIAL_CONTENT.value, 'Propose Downstreams results follow')
def get(self):
'List of all Propose Downstreams results.'
result = []
(first, last) = indices()
for propose_downstream_results in ProposeDownstreamModel.get_range(first, last):
r... | List of all Propose Downstreams results. | packit_service/service/api/propose_downstream.py | get | majamassarini/packit-service | 20 | python | @ns.expect(pagination_arguments)
@ns.response(HTTPStatus.PARTIAL_CONTENT.value, 'Propose Downstreams results follow')
def get(self):
result = []
(first, last) = indices()
for propose_downstream_results in ProposeDownstreamModel.get_range(first, last):
result_dict = {'packit_id': propose_downstr... | @ns.expect(pagination_arguments)
@ns.response(HTTPStatus.PARTIAL_CONTENT.value, 'Propose Downstreams results follow')
def get(self):
result = []
(first, last) = indices()
for propose_downstream_results in ProposeDownstreamModel.get_range(first, last):
result_dict = {'packit_id': propose_downstr... |
2beeeb4512137375d6d4cc1c76b839f75f9731c9679277f343ff5f129e2f3c0b | @ns.response(HTTPStatus.OK.value, 'OK, propose downstream target details will follow')
@ns.response(HTTPStatus.NOT_FOUND.value, 'No info about propose downstream target stored in DB')
def get(self, id):
'A specific propose-downstream job details'
dowstream_pr = ProposeDownstreamTargetModel.get_by_id(id_=int(id)... | A specific propose-downstream job details | packit_service/service/api/propose_downstream.py | get | majamassarini/packit-service | 20 | python | @ns.response(HTTPStatus.OK.value, 'OK, propose downstream target details will follow')
@ns.response(HTTPStatus.NOT_FOUND.value, 'No info about propose downstream target stored in DB')
def get(self, id):
dowstream_pr = ProposeDownstreamTargetModel.get_by_id(id_=int(id))
if (not dowstream_pr):
return... | @ns.response(HTTPStatus.OK.value, 'OK, propose downstream target details will follow')
@ns.response(HTTPStatus.NOT_FOUND.value, 'No info about propose downstream target stored in DB')
def get(self, id):
dowstream_pr = ProposeDownstreamTargetModel.get_by_id(id_=int(id))
if (not dowstream_pr):
return... |
0a7cebbe754ef441e89b42849f48b6f3e58974471bb371adb68cf7f4ede76c5f | def __init__(self, data=None, n=1, p=0.5):
'\n Binomial Constructor\n data is a list of the data to be used to estimate the distribution\n n is the number of Bernoulli trials\n p is the probability of a “success”\n '
if (data is None):
if (n <= 0):
raise Va... | Binomial Constructor
data is a list of the data to be used to estimate the distribution
n is the number of Bernoulli trials
p is the probability of a “success” | math/0x03-probability/binomial.py | __init__ | kyeeh/holbertonschool-machine_learning | 0 | python | def __init__(self, data=None, n=1, p=0.5):
'\n Binomial Constructor\n data is a list of the data to be used to estimate the distribution\n n is the number of Bernoulli trials\n p is the probability of a “success”\n '
if (data is None):
if (n <= 0):
raise Va... | def __init__(self, data=None, n=1, p=0.5):
'\n Binomial Constructor\n data is a list of the data to be used to estimate the distribution\n n is the number of Bernoulli trials\n p is the probability of a “success”\n '
if (data is None):
if (n <= 0):
raise Va... |
7c781cce8c361576edf7e77525629ff28216b825e63e9d4fa126604aa6013a23 | @staticmethod
def factorial(n):
'\n Calculates the factorial of n\n '
fn = 1
for i in range(2, (n + 1)):
fn *= i
return fn | Calculates the factorial of n | math/0x03-probability/binomial.py | factorial | kyeeh/holbertonschool-machine_learning | 0 | python | @staticmethod
def factorial(n):
'\n \n '
fn = 1
for i in range(2, (n + 1)):
fn *= i
return fn | @staticmethod
def factorial(n):
'\n \n '
fn = 1
for i in range(2, (n + 1)):
fn *= i
return fn<|docstring|>Calculates the factorial of n<|endoftext|> |
8d3eb8f1d5623f0897f94cb94b77fa461918ad58f570fe564797bb6d0b7403fc | @staticmethod
def combinatory(n, r):
'\n Calculates combinatory of n in r.\n '
return (Binomial.factorial(n) / (Binomial.factorial(r) * Binomial.factorial((n - r)))) | Calculates combinatory of n in r. | math/0x03-probability/binomial.py | combinatory | kyeeh/holbertonschool-machine_learning | 0 | python | @staticmethod
def combinatory(n, r):
'\n \n '
return (Binomial.factorial(n) / (Binomial.factorial(r) * Binomial.factorial((n - r)))) | @staticmethod
def combinatory(n, r):
'\n \n '
return (Binomial.factorial(n) / (Binomial.factorial(r) * Binomial.factorial((n - r))))<|docstring|>Calculates combinatory of n in r.<|endoftext|> |
9169007c2af817c4e68296d44087f096048fc1fd988c04e6e12a3bf84d65add3 | def pmf(self, k):
'\n Probability mass function\n Calculates the value of the PMF for a given number of “successes”\n k is the number of “successes”\n '
k = int(k)
if (k < 0):
return 0
cnk = Binomial.combinatory(self.n, k)
return ((cnk * (self.p ** k)) * ((1 - sel... | Probability mass function
Calculates the value of the PMF for a given number of “successes”
k is the number of “successes” | math/0x03-probability/binomial.py | pmf | kyeeh/holbertonschool-machine_learning | 0 | python | def pmf(self, k):
'\n Probability mass function\n Calculates the value of the PMF for a given number of “successes”\n k is the number of “successes”\n '
k = int(k)
if (k < 0):
return 0
cnk = Binomial.combinatory(self.n, k)
return ((cnk * (self.p ** k)) * ((1 - sel... | def pmf(self, k):
'\n Probability mass function\n Calculates the value of the PMF for a given number of “successes”\n k is the number of “successes”\n '
k = int(k)
if (k < 0):
return 0
cnk = Binomial.combinatory(self.n, k)
return ((cnk * (self.p ** k)) * ((1 - sel... |
36205a0965c0777fd4da791c3b791c15bbf5683e045d5ea0987929ac009e3232 | def cdf(self, k):
'\n Cumulative distribution function\n Calculates the value of the CDF for a given number of “successes”\n k is the number of “successes”\n '
k = int(k)
if (k < 0):
return 0
acumulated = 0
for i in range((k + 1)):
acumulated += self.pmf(i... | Cumulative distribution function
Calculates the value of the CDF for a given number of “successes”
k is the number of “successes” | math/0x03-probability/binomial.py | cdf | kyeeh/holbertonschool-machine_learning | 0 | python | def cdf(self, k):
'\n Cumulative distribution function\n Calculates the value of the CDF for a given number of “successes”\n k is the number of “successes”\n '
k = int(k)
if (k < 0):
return 0
acumulated = 0
for i in range((k + 1)):
acumulated += self.pmf(i... | def cdf(self, k):
'\n Cumulative distribution function\n Calculates the value of the CDF for a given number of “successes”\n k is the number of “successes”\n '
k = int(k)
if (k < 0):
return 0
acumulated = 0
for i in range((k + 1)):
acumulated += self.pmf(i... |
fa7dfdcfb2504588bb76a19a0ad9752ed5771385f86d4fc47b8d0f60a6542471 | def __init__(self, accounts: Optional[List[Union[(TqAccount, TqKq, TqKqStock, TqSim, TqSimStock)]]]=None):
'\n 创建 TqMultiAccount 实例\n\n Args:\n accounts (List[Union[TqAccount, TqKq, TqKqStock, TqSim, TqSimStock]]): [可选] 多账户列表, 若未指定任何账户, 则为 [TqSim()]\n\n Example1::\n\n from... | 创建 TqMultiAccount 实例
Args:
accounts (List[Union[TqAccount, TqKq, TqKqStock, TqSim, TqSimStock]]): [可选] 多账户列表, 若未指定任何账户, 则为 [TqSim()]
Example1::
from tqsdk import TqApi, TqAccount, TqMultiAccount
account1 = TqAccount("H海通期货", "123456", "123456")
account2 = TqAccount("H宏源期货", "654321", "123456")
a... | tqsdk/multiaccount.py | __init__ | contropist/tqsdk-python | 8 | python | def __init__(self, accounts: Optional[List[Union[(TqAccount, TqKq, TqKqStock, TqSim, TqSimStock)]]]=None):
'\n 创建 TqMultiAccount 实例\n\n Args:\n accounts (List[Union[TqAccount, TqKq, TqKqStock, TqSim, TqSimStock]]): [可选] 多账户列表, 若未指定任何账户, 则为 [TqSim()]\n\n Example1::\n\n from... | def __init__(self, accounts: Optional[List[Union[(TqAccount, TqKq, TqKqStock, TqSim, TqSimStock)]]]=None):
'\n 创建 TqMultiAccount 实例\n\n Args:\n accounts (List[Union[TqAccount, TqKq, TqKqStock, TqSim, TqSimStock]]): [可选] 多账户列表, 若未指定任何账户, 则为 [TqSim()]\n\n Example1::\n\n from... |
38f0bafb9b3dd582351a2aec52d9daf9de8c152966c1fcd09f37f947c5e0f7f6 | def _check_valid(self, account: Union[(str, TqAccount, TqKq, TqKqStock, TqSim, TqSimStock, None)]):
'\n 查询委托、成交、资产、委托时, 需要指定账户实例\n account: 类型 str 表示 account_key,其他为账户类型或者 None\n '
if isinstance(account, str):
selected_list = [a for a in self._account_list if (a._account_key == acco... | 查询委托、成交、资产、委托时, 需要指定账户实例
account: 类型 str 表示 account_key,其他为账户类型或者 None | tqsdk/multiaccount.py | _check_valid | contropist/tqsdk-python | 8 | python | def _check_valid(self, account: Union[(str, TqAccount, TqKq, TqKqStock, TqSim, TqSimStock, None)]):
'\n 查询委托、成交、资产、委托时, 需要指定账户实例\n account: 类型 str 表示 account_key,其他为账户类型或者 None\n '
if isinstance(account, str):
selected_list = [a for a in self._account_list if (a._account_key == acco... | def _check_valid(self, account: Union[(str, TqAccount, TqKq, TqKqStock, TqSim, TqSimStock, None)]):
'\n 查询委托、成交、资产、委托时, 需要指定账户实例\n account: 类型 str 表示 account_key,其他为账户类型或者 None\n '
if isinstance(account, str):
selected_list = [a for a in self._account_list if (a._account_key == acco... |
2be960d747065a5fe00aaa76e69ac00a8d1cd8a6f2c8eb3837eea7e42dd7c465 | def _get_account_id(self, account):
' 获取指定账户实例的账户属性 '
acc = self._check_valid(account)
return (acc._account_id if acc else None) | 获取指定账户实例的账户属性 | tqsdk/multiaccount.py | _get_account_id | contropist/tqsdk-python | 8 | python | def _get_account_id(self, account):
' '
acc = self._check_valid(account)
return (acc._account_id if acc else None) | def _get_account_id(self, account):
' '
acc = self._check_valid(account)
return (acc._account_id if acc else None)<|docstring|>获取指定账户实例的账户属性<|endoftext|> |
1cb3e40e40a518e0347d873152344c49703cb274df922f4883861f89da056597 | def _get_account_key(self, account):
' 获取指定账户实例的账户属性 '
acc = self._check_valid(account)
return (acc._account_key if acc else None) | 获取指定账户实例的账户属性 | tqsdk/multiaccount.py | _get_account_key | contropist/tqsdk-python | 8 | python | def _get_account_key(self, account):
' '
acc = self._check_valid(account)
return (acc._account_key if acc else None) | def _get_account_key(self, account):
' '
acc = self._check_valid(account)
return (acc._account_key if acc else None)<|docstring|>获取指定账户实例的账户属性<|endoftext|> |
7c9032c962e8a26361bdb64d183a3859b3a30203a62fe4233d7afd165570266e | def _is_stock_type(self, account_or_account_key):
' 判断账户类型是否为股票账户 '
acc = self._check_valid(account_or_account_key)
return isinstance(acc, StockMixin) | 判断账户类型是否为股票账户 | tqsdk/multiaccount.py | _is_stock_type | contropist/tqsdk-python | 8 | python | def _is_stock_type(self, account_or_account_key):
' '
acc = self._check_valid(account_or_account_key)
return isinstance(acc, StockMixin) | def _is_stock_type(self, account_or_account_key):
' '
acc = self._check_valid(account_or_account_key)
return isinstance(acc, StockMixin)<|docstring|>判断账户类型是否为股票账户<|endoftext|> |
77b523dc1fb61bfce1304422e39feb8d2b3e25f8aea807e1348af38135063ad4 | def _get_trade_more_data_and_order_id(self, data):
' 获取业务信息截面 trade_more_data 标识,当且仅当所有账户的标识置为 false 时,业务信息截面就绪 '
trade_more_datas = []
for account in self._account_list:
trade_node = data.get('trade', {}).get(account._account_key, {})
trade_more_data = trade_node.get('trade_more_data', True... | 获取业务信息截面 trade_more_data 标识,当且仅当所有账户的标识置为 false 时,业务信息截面就绪 | tqsdk/multiaccount.py | _get_trade_more_data_and_order_id | contropist/tqsdk-python | 8 | python | def _get_trade_more_data_and_order_id(self, data):
' '
trade_more_datas = []
for account in self._account_list:
trade_node = data.get('trade', {}).get(account._account_key, {})
trade_more_data = trade_node.get('trade_more_data', True)
trade_more_datas.append(trade_more_data)
ret... | def _get_trade_more_data_and_order_id(self, data):
' '
trade_more_datas = []
for account in self._account_list:
trade_node = data.get('trade', {}).get(account._account_key, {})
trade_more_data = trade_node.get('trade_more_data', True)
trade_more_datas.append(trade_more_data)
ret... |
c234f435d0fcf6b81127860ab9e29417d5d1667483cd974760207fb31f5c434d | def f(self, t, y, args=None):
'! Returns ODE RHS\n @param t time in ODE\n @param y variables in ODE\n @param arg1 parameter for the ODE\n @returns the RHS of the ODE\n '
raise NotImplementedError('A problem class should implement member function f') | ! Returns ODE RHS
@param t time in ODE
@param y variables in ODE
@param arg1 parameter for the ODE
@returns the RHS of the ODE | pyoculus/problems/base_problem.py | f | mbkumar/pyoculus | 4 | python | def f(self, t, y, args=None):
'! Returns ODE RHS\n @param t time in ODE\n @param y variables in ODE\n @param arg1 parameter for the ODE\n @returns the RHS of the ODE\n '
raise NotImplementedError('A problem class should implement member function f') | def f(self, t, y, args=None):
'! Returns ODE RHS\n @param t time in ODE\n @param y variables in ODE\n @param arg1 parameter for the ODE\n @returns the RHS of the ODE\n '
raise NotImplementedError('A problem class should implement member function f')<|docstring|>! Returns ODE R... |
bccc873fe89a6bfc78f1a5b32ad15631382c73c7e578c7c48ee4985f27826de3 | def f_tangent(self, t, y, args=None):
'! Returns ODE RHS, with tangent\n @param t time in ODE\n @param y \x0c$\x08f y\x0c$ variables in ODE and \x0c$\\Delta \\mathbf{y}_1\x0c$, \x0c$\\Delta \\mathbf{y}_2\x0c$\n @param arg1 parameter for the ODE\n @returns the RHS of the ODE, with tangent... | ! Returns ODE RHS, with tangent
@param t time in ODE
@param y $f y$ variables in ODE and $\Delta \mathbf{y}_1$, $\Delta \mathbf{y}_2$
@param arg1 parameter for the ODE
@returns the RHS of the ODE, with tangent | pyoculus/problems/base_problem.py | f_tangent | mbkumar/pyoculus | 4 | python | def f_tangent(self, t, y, args=None):
'! Returns ODE RHS, with tangent\n @param t time in ODE\n @param y \x0c$\x08f y\x0c$ variables in ODE and \x0c$\\Delta \\mathbf{y}_1\x0c$, \x0c$\\Delta \\mathbf{y}_2\x0c$\n @param arg1 parameter for the ODE\n @returns the RHS of the ODE, with tangent... | def f_tangent(self, t, y, args=None):
'! Returns ODE RHS, with tangent\n @param t time in ODE\n @param y \x0c$\x08f y\x0c$ variables in ODE and \x0c$\\Delta \\mathbf{y}_1\x0c$, \x0c$\\Delta \\mathbf{y}_2\x0c$\n @param arg1 parameter for the ODE\n @returns the RHS of the ODE, with tangent... |
febd4a2549367c2a04019715ecf824b047718ba14f15801b5fb01bdb81ec084f | def convert_coords(self, coord1):
'! Converts coordinates (for example \x0c$s,\theta,\\zeta\x0c$ to \x0c$R,Z,\x0barphi\x0c$)\n @param coords1 the coordinates to convert\n @returns the converted coordinates\n '
return coord1 | ! Converts coordinates (for example $s, heta,\zeta$ to $R,Z,arphi$)
@param coords1 the coordinates to convert
@returns the converted coordinates | pyoculus/problems/base_problem.py | convert_coords | mbkumar/pyoculus | 4 | python | def convert_coords(self, coord1):
'! Converts coordinates (for example \x0c$s,\theta,\\zeta\x0c$ to \x0c$R,Z,\x0barphi\x0c$)\n @param coords1 the coordinates to convert\n @returns the converted coordinates\n '
return coord1 | def convert_coords(self, coord1):
'! Converts coordinates (for example \x0c$s,\theta,\\zeta\x0c$ to \x0c$R,Z,\x0barphi\x0c$)\n @param coords1 the coordinates to convert\n @returns the converted coordinates\n '
return coord1<|docstring|>! Converts coordinates (for example $s, heta,\z... |
1f1485c44ecfe65902b82baa00b75123a34ffaf39afe006752be1aa1b370fb8a | @compiles(sql_metric_multiply)
def compile_sql_metric_multiply(element, compiler, **kw):
'\n Turn common number formatting into a number. use metric abbreviations, remove stuff like $, etc.\n '
number_abbreviations = {'D': 10, 'H': (10 ** 2), 'K': (10 ** 3), 'M': (10 ** 6), 'B': (10 ** 9), 'G': (10 ** 9),... | Turn common number formatting into a number. use metric abbreviations, remove stuff like $, etc. | plaidcloud/utilities/sqlalchemy_functions.py | compile_sql_metric_multiply | PlaidCloud/public-utilities | 0 | python | @compiles(sql_metric_multiply)
def compile_sql_metric_multiply(element, compiler, **kw):
'\n \n '
number_abbreviations = {'D': 10, 'H': (10 ** 2), 'K': (10 ** 3), 'M': (10 ** 6), 'B': (10 ** 9), 'G': (10 ** 9), 'T': (10 ** 12), 'P': (10 ** 15), 'E': (10 ** 18), 'Z': (10 ** 21), 'Y': (10 ** 24)}
(arg,)... | @compiles(sql_metric_multiply)
def compile_sql_metric_multiply(element, compiler, **kw):
'\n \n '
number_abbreviations = {'D': 10, 'H': (10 ** 2), 'K': (10 ** 3), 'M': (10 ** 6), 'B': (10 ** 9), 'G': (10 ** 9), 'T': (10 ** 12), 'P': (10 ** 15), 'E': (10 ** 18), 'Z': (10 ** 21), 'Y': (10 ** 24)}
(arg,)... |
4cfb037bb65c4328b0451d704f6010802acda22ce14d9a728259e7bfa429cca7 | @compiles(sql_numericize)
def compile_sql_numericize(element, compiler, **kw):
'\n Turn common number formatting into a number. use metric abbreviations, remove stuff like $, etc.\n '
(arg,) = list(element.clauses)
def sql_only_numeric(text):
return func.coalesce(func.substring(text, '([+\\-]... | Turn common number formatting into a number. use metric abbreviations, remove stuff like $, etc. | plaidcloud/utilities/sqlalchemy_functions.py | compile_sql_numericize | PlaidCloud/public-utilities | 0 | python | @compiles(sql_numericize)
def compile_sql_numericize(element, compiler, **kw):
'\n \n '
(arg,) = list(element.clauses)
def sql_only_numeric(text):
return func.coalesce(func.substring(text, '([+\\-]?(\\d+\\.?\\d*[Ee][+\\-]?\\d+))'), func.nullif(func.regexp_replace(text, '[^0-9\\.\\+\\-]+', , '... | @compiles(sql_numericize)
def compile_sql_numericize(element, compiler, **kw):
'\n \n '
(arg,) = list(element.clauses)
def sql_only_numeric(text):
return func.coalesce(func.substring(text, '([+\\-]?(\\d+\\.?\\d*[Ee][+\\-]?\\d+))'), func.nullif(func.regexp_replace(text, '[^0-9\\.\\+\\-]+', , '... |
5f6e9b11d715e0b9c73ea07cda24c037206d9dab56de647a06acd77edb4db52e | @compiles(sql_integerize_round)
def compile_sql_integerize_round(element, compiler, **kw):
'\n Turn common number formatting into a number. use metric abbreviations, remove stuff like $, etc.\n '
(arg,) = list(element.clauses)
return compiler.process(func.cast(_squash_to_numeric(arg), sqlalchemy.Integ... | Turn common number formatting into a number. use metric abbreviations, remove stuff like $, etc. | plaidcloud/utilities/sqlalchemy_functions.py | compile_sql_integerize_round | PlaidCloud/public-utilities | 0 | python | @compiles(sql_integerize_round)
def compile_sql_integerize_round(element, compiler, **kw):
'\n \n '
(arg,) = list(element.clauses)
return compiler.process(func.cast(_squash_to_numeric(arg), sqlalchemy.Integer), **kw) | @compiles(sql_integerize_round)
def compile_sql_integerize_round(element, compiler, **kw):
'\n \n '
(arg,) = list(element.clauses)
return compiler.process(func.cast(_squash_to_numeric(arg), sqlalchemy.Integer), **kw)<|docstring|>Turn common number formatting into a number. use metric abbreviations, re... |
84d9e3088ba3da1ec4e95c4a3263dd1b74b5e11197d09201cb12760027419d54 | @compiles(sql_integerize_truncate)
def compile_sql_integerize_truncate(element, compiler, **kw):
'\n Turn common number formatting into a number. use metric abbreviations, remove stuff like $, etc.\n '
(arg,) = list(element.clauses)
return compiler.process(func.cast(func.trunc(_squash_to_numeric(arg))... | Turn common number formatting into a number. use metric abbreviations, remove stuff like $, etc. | plaidcloud/utilities/sqlalchemy_functions.py | compile_sql_integerize_truncate | PlaidCloud/public-utilities | 0 | python | @compiles(sql_integerize_truncate)
def compile_sql_integerize_truncate(element, compiler, **kw):
'\n \n '
(arg,) = list(element.clauses)
return compiler.process(func.cast(func.trunc(_squash_to_numeric(arg)), sqlalchemy.Integer), **kw) | @compiles(sql_integerize_truncate)
def compile_sql_integerize_truncate(element, compiler, **kw):
'\n \n '
(arg,) = list(element.clauses)
return compiler.process(func.cast(func.trunc(_squash_to_numeric(arg)), sqlalchemy.Integer), **kw)<|docstring|>Turn common number formatting into a number. use metric... |
dc37048337aceeb36a8f21ebc46239ecdf9347aa0e4f976e555867ae592c17fc | @compiles(sql_safe_divide)
def compile_safe_divide(element, compiler, **kw):
'Divides numerator by denominator, returning NULL if the denominator is 0.\n '
(numerator, denominator, divide_by_zero_value) = list(element.clauses)
basic_safe_divide = (numerator / func.nullif(denominator, 0))
return compi... | Divides numerator by denominator, returning NULL if the denominator is 0. | plaidcloud/utilities/sqlalchemy_functions.py | compile_safe_divide | PlaidCloud/public-utilities | 0 | python | @compiles(sql_safe_divide)
def compile_safe_divide(element, compiler, **kw):
'\n '
(numerator, denominator, divide_by_zero_value) = list(element.clauses)
basic_safe_divide = (numerator / func.nullif(denominator, 0))
return compiler.process((basic_safe_divide if (divide_by_zero_value is None) else fun... | @compiles(sql_safe_divide)
def compile_safe_divide(element, compiler, **kw):
'\n '
(numerator, denominator, divide_by_zero_value) = list(element.clauses)
basic_safe_divide = (numerator / func.nullif(denominator, 0))
return compiler.process((basic_safe_divide if (divide_by_zero_value is None) else fun... |
931e3e3687a191b9a5cc01da21ecf0c0474ff2d620d821d98ea45f6ca1b33b09 | def run(func):
'\n The run function can be extended to execute computation across a distributed system,\n for example by reading JSON messages from a queue or responding to a JSON service post.\n '
func = getattr(func, MAIN, func)
wrapped = getattr(func, '__wrapped__', func)
state = getattr(wra... | The run function can be extended to execute computation across a distributed system,
for example by reading JSON messages from a queue or responding to a JSON service post. | athena/exec.py | run | jordanrule/athena | 1 | python | def run(func):
'\n The run function can be extended to execute computation across a distributed system,\n for example by reading JSON messages from a queue or responding to a JSON service post.\n '
func = getattr(func, MAIN, func)
wrapped = getattr(func, '__wrapped__', func)
state = getattr(wra... | def run(func):
'\n The run function can be extended to execute computation across a distributed system,\n for example by reading JSON messages from a queue or responding to a JSON service post.\n '
func = getattr(func, MAIN, func)
wrapped = getattr(func, '__wrapped__', func)
state = getattr(wra... |
0642e90c675f6330101e9a71b116f8b23e698ff972a5721c7b9c4d3a060eeb5a | def highlight(keyword, target, color=(Fore.BLACK + Back.YELLOW)):
'\n use given color to highlight keyword in target string\n\n Args:\n keyword(str): highlight string\n target(str): target string\n color(str): string represent the color, use black foreground\n and yellow background... | use given color to highlight keyword in target string
Args:
keyword(str): highlight string
target(str): target string
color(str): string represent the color, use black foreground
and yellow background as default
Returns:
(str) target string with keyword highlighted | cvpods/configs/config_helper.py | highlight | StevenGrove/LearnableTreeFilterV2 | 81 | python | def highlight(keyword, target, color=(Fore.BLACK + Back.YELLOW)):
'\n use given color to highlight keyword in target string\n\n Args:\n keyword(str): highlight string\n target(str): target string\n color(str): string represent the color, use black foreground\n and yellow background... | def highlight(keyword, target, color=(Fore.BLACK + Back.YELLOW)):
'\n use given color to highlight keyword in target string\n\n Args:\n keyword(str): highlight string\n target(str): target string\n color(str): string represent the color, use black foreground\n and yellow background... |
4de1a7f9c7972c27e4f4f18b662b5c80f4a7a0fab93fec1c8e7a6c79a8634fec | def find_key(param_dict: dict, key: str) -> dict:
'\n find key in dict\n\n Args:\n param_dict(dict):\n key(str):\n\n Returns:\n (dict)\n\n Examples::\n >>> d = dict(abc=2, ab=4, c=4)\n >>> find_key(d, "ab")\n {\'abc\': 2, \'ab\':4}\n\n '
find_result = {}
... | find key in dict
Args:
param_dict(dict):
key(str):
Returns:
(dict)
Examples::
>>> d = dict(abc=2, ab=4, c=4)
>>> find_key(d, "ab")
{'abc': 2, 'ab':4} | cvpods/configs/config_helper.py | find_key | StevenGrove/LearnableTreeFilterV2 | 81 | python | def find_key(param_dict: dict, key: str) -> dict:
'\n find key in dict\n\n Args:\n param_dict(dict):\n key(str):\n\n Returns:\n (dict)\n\n Examples::\n >>> d = dict(abc=2, ab=4, c=4)\n >>> find_key(d, "ab")\n {\'abc\': 2, \'ab\':4}\n\n '
find_result = {}
... | def find_key(param_dict: dict, key: str) -> dict:
'\n find key in dict\n\n Args:\n param_dict(dict):\n key(str):\n\n Returns:\n (dict)\n\n Examples::\n >>> d = dict(abc=2, ab=4, c=4)\n >>> find_key(d, "ab")\n {\'abc\': 2, \'ab\':4}\n\n '
find_result = {}
... |
694bcac37b6b5049e3274ed99ba042040f5c3cdf5ced9be94f03ab65b076d9a9 | def diff_dict(src, dst):
'\n find difference between src dict and dst dict\n\n Args:\n src(dict): src dict\n dst(dict): dst dict\n\n Returns:\n (dict) dict contains all the difference key\n\n '
diff_result = {}
for (k, v) in src.items():
if (k not in dst):
... | find difference between src dict and dst dict
Args:
src(dict): src dict
dst(dict): dst dict
Returns:
(dict) dict contains all the difference key | cvpods/configs/config_helper.py | diff_dict | StevenGrove/LearnableTreeFilterV2 | 81 | python | def diff_dict(src, dst):
'\n find difference between src dict and dst dict\n\n Args:\n src(dict): src dict\n dst(dict): dst dict\n\n Returns:\n (dict) dict contains all the difference key\n\n '
diff_result = {}
for (k, v) in src.items():
if (k not in dst):
... | def diff_dict(src, dst):
'\n find difference between src dict and dst dict\n\n Args:\n src(dict): src dict\n dst(dict): dst dict\n\n Returns:\n (dict) dict contains all the difference key\n\n '
diff_result = {}
for (k, v) in src.items():
if (k not in dst):
... |
b5005cab1f20831ce1cb5f68c4718402315513b1023f7cb6ce55b85daaf56db1 | def _check_and_coerce_cfg_value_type(replacement, original, full_key):
'\n Checks that `replacement`, which is intended to replace `original` is of\n the right type. The type is correct if it matches exactly or is one of a few\n cases in which the type can be easily coerced.\n '
original_type = type... | Checks that `replacement`, which is intended to replace `original` is of
the right type. The type is correct if it matches exactly or is one of a few
cases in which the type can be easily coerced. | cvpods/configs/config_helper.py | _check_and_coerce_cfg_value_type | StevenGrove/LearnableTreeFilterV2 | 81 | python | def _check_and_coerce_cfg_value_type(replacement, original, full_key):
'\n Checks that `replacement`, which is intended to replace `original` is of\n the right type. The type is correct if it matches exactly or is one of a few\n cases in which the type can be easily coerced.\n '
original_type = type... | def _check_and_coerce_cfg_value_type(replacement, original, full_key):
'\n Checks that `replacement`, which is intended to replace `original` is of\n the right type. The type is correct if it matches exactly or is one of a few\n cases in which the type can be easily coerced.\n '
original_type = type... |
146dc7b6f8c25444265dfb80481616bdf327a0dbf720ee19a36151eb460fdd9e | def _get_module(spec):
'Try to execute a module. Return None if the attempt fail.'
try:
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module
except Exception:
return None | Try to execute a module. Return None if the attempt fail. | aea/helpers/base.py | _get_module | cyenyxe/agents-aea | 0 | python | def _get_module(spec):
try:
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module
except Exception:
return None | def _get_module(spec):
try:
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module
except Exception:
return None<|docstring|>Try to execute a module. Return None if the attempt fail.<|endoftext|> |
e313b7fce5770c19325a0c9dd848d9acaf7c88394921c3d81909bc8e7e394467 | def locate(path):
'Locate an object by name or dotted path, importing as necessary.'
parts = [part for part in path.split('.') if part]
(module, n) = (None, 0)
while (n < len(parts)):
file_location = os.path.join(*parts[:(n + 1)])
spec_name = '.'.join(parts[:(n + 1)])
module_loca... | Locate an object by name or dotted path, importing as necessary. | aea/helpers/base.py | locate | cyenyxe/agents-aea | 0 | python | def locate(path):
parts = [part for part in path.split('.') if part]
(module, n) = (None, 0)
while (n < len(parts)):
file_location = os.path.join(*parts[:(n + 1)])
spec_name = '.'.join(parts[:(n + 1)])
module_location = os.path.join(file_location, '__init__.py')
spec = i... | def locate(path):
parts = [part for part in path.split('.') if part]
(module, n) = (None, 0)
while (n < len(parts)):
file_location = os.path.join(*parts[:(n + 1)])
spec_name = '.'.join(parts[:(n + 1)])
module_location = os.path.join(file_location, '__init__.py')
spec = i... |
682adf7203e8c7fce0cc8a1ad0027fca104a5edea0a7fe538c8ff668de6e94e0 | def load_module(dotted_path: str, filepath: os.PathLike):
'\n Load a module.\n\n :param dotted_path: the dotted path of the package/module.\n :param filepath: the file to the package/module.\n :return: None\n :raises ValueError: if the filepath provided is not a module.\n :raises Exception: if the... | Load a module.
:param dotted_path: the dotted path of the package/module.
:param filepath: the file to the package/module.
:return: None
:raises ValueError: if the filepath provided is not a module.
:raises Exception: if the execution of the module raises exception. | aea/helpers/base.py | load_module | cyenyxe/agents-aea | 0 | python | def load_module(dotted_path: str, filepath: os.PathLike):
'\n Load a module.\n\n :param dotted_path: the dotted path of the package/module.\n :param filepath: the file to the package/module.\n :return: None\n :raises ValueError: if the filepath provided is not a module.\n :raises Exception: if the... | def load_module(dotted_path: str, filepath: os.PathLike):
'\n Load a module.\n\n :param dotted_path: the dotted path of the package/module.\n :param filepath: the file to the package/module.\n :return: None\n :raises ValueError: if the filepath provided is not a module.\n :raises Exception: if the... |
88ef3de44dec512167c194e9113c79d4ace4a693d048ce49bb8bcab37eba5870 | def import_module(dotted_path: str, module_obj) -> None:
'\n Add module to sys.modules.\n\n :param dotted_path: the dotted path to be used in the imports.\n :param module_obj: the module object. It is assumed it has been already executed.\n :return: None\n '
split = dotted_path.split('.')
if ... | Add module to sys.modules.
:param dotted_path: the dotted path to be used in the imports.
:param module_obj: the module object. It is assumed it has been already executed.
:return: None | aea/helpers/base.py | import_module | cyenyxe/agents-aea | 0 | python | def import_module(dotted_path: str, module_obj) -> None:
'\n Add module to sys.modules.\n\n :param dotted_path: the dotted path to be used in the imports.\n :param module_obj: the module object. It is assumed it has been already executed.\n :return: None\n '
split = dotted_path.split('.')
if ... | def import_module(dotted_path: str, module_obj) -> None:
'\n Add module to sys.modules.\n\n :param dotted_path: the dotted path to be used in the imports.\n :param module_obj: the module object. It is assumed it has been already executed.\n :return: None\n '
split = dotted_path.split('.')
if ... |
d2c0512d472c0569c541ea1cda6354b8170420a15d406a03527a087da7101ac5 | def load_agent_component_package(item_type: str, item_name: str, author_name: str, directory: os.PathLike):
'\n Load a Python package associated to a component..\n\n :param item_type: the type of the item. One of "protocol", "connection", "skill".\n :param item_name: the name of the item to load.\n :par... | Load a Python package associated to a component..
:param item_type: the type of the item. One of "protocol", "connection", "skill".
:param item_name: the name of the item to load.
:param author_name: the name of the author of the item to load.
:param directory: the component directory.
:return: the module associated t... | aea/helpers/base.py | load_agent_component_package | cyenyxe/agents-aea | 0 | python | def load_agent_component_package(item_type: str, item_name: str, author_name: str, directory: os.PathLike):
'\n Load a Python package associated to a component..\n\n :param item_type: the type of the item. One of "protocol", "connection", "skill".\n :param item_name: the name of the item to load.\n :par... | def load_agent_component_package(item_type: str, item_name: str, author_name: str, directory: os.PathLike):
'\n Load a Python package associated to a component..\n\n :param item_type: the type of the item. One of "protocol", "connection", "skill".\n :param item_name: the name of the item to load.\n :par... |
c38a01f4621dfbc8a76adf8abbb0c24fee798033c96d5fe0015665a938165923 | def add_agent_component_module_to_sys_modules(item_type: str, item_name: str, author_name: str, module_obj) -> None:
'\n Add an agent component module to sys.modules.\n\n :param item_type: the type of the item. One of "protocol", "connection", "skill"\n :param item_name: the name of the item to load\n :... | Add an agent component module to sys.modules.
:param item_type: the type of the item. One of "protocol", "connection", "skill"
:param item_name: the name of the item to load
:param author_name: the name of the author of the item to load.
:param module_obj: the module object. It is assumed it has been already executed.... | aea/helpers/base.py | add_agent_component_module_to_sys_modules | cyenyxe/agents-aea | 0 | python | def add_agent_component_module_to_sys_modules(item_type: str, item_name: str, author_name: str, module_obj) -> None:
'\n Add an agent component module to sys.modules.\n\n :param item_type: the type of the item. One of "protocol", "connection", "skill"\n :param item_name: the name of the item to load\n :... | def add_agent_component_module_to_sys_modules(item_type: str, item_name: str, author_name: str, module_obj) -> None:
'\n Add an agent component module to sys.modules.\n\n :param item_type: the type of the item. One of "protocol", "connection", "skill"\n :param item_name: the name of the item to load\n :... |
90d38ba5f6e67a5c0862daa8925159a2455917dcfc207de389d1b27d74d99c4d | def generate_fingerprint(author: str, package_name: str, version: str, nonce: Optional[int]=None) -> str:
'Generate a unique id for the package.\n\n :param author: The author of the package.\n :param package_name: The name of the package\n :param version: The version of the package.\n :param nonce: Enab... | Generate a unique id for the package.
:param author: The author of the package.
:param package_name: The name of the package
:param version: The version of the package.
:param nonce: Enable the developer to generate two different fingerprints for the same package.
(Can be used with different configuration) | aea/helpers/base.py | generate_fingerprint | cyenyxe/agents-aea | 0 | python | def generate_fingerprint(author: str, package_name: str, version: str, nonce: Optional[int]=None) -> str:
'Generate a unique id for the package.\n\n :param author: The author of the package.\n :param package_name: The name of the package\n :param version: The version of the package.\n :param nonce: Enab... | def generate_fingerprint(author: str, package_name: str, version: str, nonce: Optional[int]=None) -> str:
'Generate a unique id for the package.\n\n :param author: The author of the package.\n :param package_name: The name of the package\n :param version: The version of the package.\n :param nonce: Enab... |
4e8d7d10dcf1a9fc81c74fce864c12729b564201ab6d624cbe0d223a69e2cf86 | def generate(self):
' generate meta radio program '
new_root = etree.Element('flow_graph')
self.log.info('Load base config ...')
base_xfile = 'generator/gen_stub.grc'
base_tree = etree.parse(base_xfile)
for base_block in base_tree.getroot().findall('block'):
new_root.append(base_block)
... | generate meta radio program | wishful_module_gnuradio/generator/rp_combiner.py | generate | wishful-project/module_gnuradio | 0 | python | def generate(self):
' '
new_root = etree.Element('flow_graph')
self.log.info('Load base config ...')
base_xfile = 'generator/gen_stub.grc'
base_tree = etree.parse(base_xfile)
for base_block in base_tree.getroot().findall('block'):
new_root.append(base_block)
self._update_selector_an... | def generate(self):
' '
new_root = etree.Element('flow_graph')
self.log.info('Load base config ...')
base_xfile = 'generator/gen_stub.grc'
base_tree = etree.parse(base_xfile)
for base_block in base_tree.getroot().findall('block'):
new_root.append(base_block)
self._update_selector_an... |
aea0ceefcf3f8c22691c351088225437d27a1fd7eb0d9947d6f61de935fcac82 | def list_admins(self, **kwargs):
'\n List all administrative accounts.\n This method makes a synchronous HTTP request by default. To make an\n asynchronous HTTP request, please define a `callback` function\n to be invoked when receiving the response.\n >>> def callback_function(re... | List all administrative accounts.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.list_admins(callback=callback... | purity_fb/purity_fb_1dot9/apis/admins_api.py | list_admins | 2vcps/purity_fb_python_client | 0 | python | def list_admins(self, **kwargs):
'\n List all administrative accounts.\n This method makes a synchronous HTTP request by default. To make an\n asynchronous HTTP request, please define a `callback` function\n to be invoked when receiving the response.\n >>> def callback_function(re... | def list_admins(self, **kwargs):
'\n List all administrative accounts.\n This method makes a synchronous HTTP request by default. To make an\n asynchronous HTTP request, please define a `callback` function\n to be invoked when receiving the response.\n >>> def callback_function(re... |
3cd97aca9f8daabfd8b3304212aaab4c2f393b8d642da03111051d472713387d | def list_admins_with_http_info(self, **kwargs):
'\n List all administrative accounts.\n This method makes a synchronous HTTP request by default. To make an\n asynchronous HTTP request, please define a `callback` function\n to be invoked when receiving the response.\n >>> def callb... | List all administrative accounts.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.list_admins_with_http_info(ca... | purity_fb/purity_fb_1dot9/apis/admins_api.py | list_admins_with_http_info | 2vcps/purity_fb_python_client | 0 | python | def list_admins_with_http_info(self, **kwargs):
'\n List all administrative accounts.\n This method makes a synchronous HTTP request by default. To make an\n asynchronous HTTP request, please define a `callback` function\n to be invoked when receiving the response.\n >>> def callb... | def list_admins_with_http_info(self, **kwargs):
'\n List all administrative accounts.\n This method makes a synchronous HTTP request by default. To make an\n asynchronous HTTP request, please define a `callback` function\n to be invoked when receiving the response.\n >>> def callb... |
9871ed2e255e51a5045a08222785b76b3004b82ab1c729ac0c1f27575f944ec9 | def update_admins(self, admin, **kwargs):
'\n Update administrative account attributes.\n This method makes a synchronous HTTP request by default. To make an\n asynchronous HTTP request, please define a `callback` function\n to be invoked when receiving the response.\n >>> def cal... | Update administrative account attributes.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.update_admins(admin, ... | purity_fb/purity_fb_1dot9/apis/admins_api.py | update_admins | 2vcps/purity_fb_python_client | 0 | python | def update_admins(self, admin, **kwargs):
'\n Update administrative account attributes.\n This method makes a synchronous HTTP request by default. To make an\n asynchronous HTTP request, please define a `callback` function\n to be invoked when receiving the response.\n >>> def cal... | def update_admins(self, admin, **kwargs):
'\n Update administrative account attributes.\n This method makes a synchronous HTTP request by default. To make an\n asynchronous HTTP request, please define a `callback` function\n to be invoked when receiving the response.\n >>> def cal... |
946be69a9f7b4cf34c569b8741487886dd11bd425a35306166f44deb6179e020 | def update_admins_with_http_info(self, admin, **kwargs):
'\n Update administrative account attributes.\n This method makes a synchronous HTTP request by default. To make an\n asynchronous HTTP request, please define a `callback` function\n to be invoked when receiving the response.\n ... | Update administrative account attributes.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.update_admins_with_ht... | purity_fb/purity_fb_1dot9/apis/admins_api.py | update_admins_with_http_info | 2vcps/purity_fb_python_client | 0 | python | def update_admins_with_http_info(self, admin, **kwargs):
'\n Update administrative account attributes.\n This method makes a synchronous HTTP request by default. To make an\n asynchronous HTTP request, please define a `callback` function\n to be invoked when receiving the response.\n ... | def update_admins_with_http_info(self, admin, **kwargs):
'\n Update administrative account attributes.\n This method makes a synchronous HTTP request by default. To make an\n asynchronous HTTP request, please define a `callback` function\n to be invoked when receiving the response.\n ... |
c8e903bdccd43f12e1346a818698e1be390f6da128eee4590dbb0fb00cb8db73 | def constructIncomingGraph(og):
'Construct the graph.\n\n No weights preserved. Return grapg ig, where ig[i] = j, there is an edge\n from node j to node i.\n\n Args:\n og (dict): Graph with ougoing edges.\n\n Returns:\n dict: Graph with incoming edges.\n '
ig = dict()
for (node_... | Construct the graph.
No weights preserved. Return grapg ig, where ig[i] = j, there is an edge
from node j to node i.
Args:
og (dict): Graph with ougoing edges.
Returns:
dict: Graph with incoming edges. | src/topological_sorting.py | constructIncomingGraph | ovysotska/image_sequence_matcher | 8 | python | def constructIncomingGraph(og):
'Construct the graph.\n\n No weights preserved. Return grapg ig, where ig[i] = j, there is an edge\n from node j to node i.\n\n Args:\n og (dict): Graph with ougoing edges.\n\n Returns:\n dict: Graph with incoming edges.\n '
ig = dict()
for (node_... | def constructIncomingGraph(og):
'Construct the graph.\n\n No weights preserved. Return grapg ig, where ig[i] = j, there is an edge\n from node j to node i.\n\n Args:\n og (dict): Graph with ougoing edges.\n\n Returns:\n dict: Graph with incoming edges.\n '
ig = dict()
for (node_... |
8cf951d23488e4c83cf476455c0a44f1cd33d25a2672e9bc7572b42d190ad8b9 | def topologicalSorting(graph, start_node):
'Summary\n\n Args:\n graph (TYPE): Description\n start_node (TYPE): Description\n\n Returns:\n TYPE: Description\n '
ig = constructIncomingGraph(graph)
sorted_nodes = deque([])
in_set = deque([start_node])
while in_set:
... | Summary
Args:
graph (TYPE): Description
start_node (TYPE): Description
Returns:
TYPE: Description | src/topological_sorting.py | topologicalSorting | ovysotska/image_sequence_matcher | 8 | python | def topologicalSorting(graph, start_node):
'Summary\n\n Args:\n graph (TYPE): Description\n start_node (TYPE): Description\n\n Returns:\n TYPE: Description\n '
ig = constructIncomingGraph(graph)
sorted_nodes = deque([])
in_set = deque([start_node])
while in_set:
... | def topologicalSorting(graph, start_node):
'Summary\n\n Args:\n graph (TYPE): Description\n start_node (TYPE): Description\n\n Returns:\n TYPE: Description\n '
ig = constructIncomingGraph(graph)
sorted_nodes = deque([])
in_set = deque([start_node])
while in_set:
... |
8b22869c842b8e29e6331352f54364a7f58ed8b931e16b000a6fa33d069e938a | def shortestPath(graph, S):
' Computes the shortest path\n Only computes the path in the topologically sorted graph\n The result is the list of graph node ids that are in the shortest path\n Args:\n graph (dict): constructed graph\n S (deque): topological sorting of the node ids\n\n Retur... | Computes the shortest path
Only computes the path in the topologically sorted graph
The result is the list of graph node ids that are in the shortest path
Args:
graph (dict): constructed graph
S (deque): topological sorting of the node ids
Returns:
list(int): shortest path | src/topological_sorting.py | shortestPath | ovysotska/image_sequence_matcher | 8 | python | def shortestPath(graph, S):
' Computes the shortest path\n Only computes the path in the topologically sorted graph\n The result is the list of graph node ids that are in the shortest path\n Args:\n graph (dict): constructed graph\n S (deque): topological sorting of the node ids\n\n Retur... | def shortestPath(graph, S):
' Computes the shortest path\n Only computes the path in the topologically sorted graph\n The result is the list of graph node ids that are in the shortest path\n Args:\n graph (dict): constructed graph\n S (deque): topological sorting of the node ids\n\n Retur... |
920e2d7048423d163d2073b64205cabea64766f61b72844834400162cace1f2b | def test_pep8_conformance_console(self):
'Test that console.py conforms to PEP8.'
pep8s = pep8.StyleGuide(quiet=True)
result = pep8s.check_files(['console.py'])
self.assertEqual(result.total_errors, 0, 'Found code style errors (and warnings).') | Test that console.py conforms to PEP8. | tests/test_console.py | test_pep8_conformance_console | Joshua-Enrico/AirBnB_clone_v4 | 0 | python | def test_pep8_conformance_console(self):
pep8s = pep8.StyleGuide(quiet=True)
result = pep8s.check_files(['console.py'])
self.assertEqual(result.total_errors, 0, 'Found code style errors (and warnings).') | def test_pep8_conformance_console(self):
pep8s = pep8.StyleGuide(quiet=True)
result = pep8s.check_files(['console.py'])
self.assertEqual(result.total_errors, 0, 'Found code style errors (and warnings).')<|docstring|>Test that console.py conforms to PEP8.<|endoftext|> |
9e9208205792c807a54077558ed067d1e9bfc7ff1afa606c4c04284dc875de23 | def test_pep8_conformance_test_console(self):
'Test that tests/test_console.py conforms to PEP8.'
pep8s = pep8.StyleGuide(quiet=True)
result = pep8s.check_files(['tests/test_console.py'])
self.assertEqual(result.total_errors, 0, 'Found code style errors (and warnings).') | Test that tests/test_console.py conforms to PEP8. | tests/test_console.py | test_pep8_conformance_test_console | Joshua-Enrico/AirBnB_clone_v4 | 0 | python | def test_pep8_conformance_test_console(self):
pep8s = pep8.StyleGuide(quiet=True)
result = pep8s.check_files(['tests/test_console.py'])
self.assertEqual(result.total_errors, 0, 'Found code style errors (and warnings).') | def test_pep8_conformance_test_console(self):
pep8s = pep8.StyleGuide(quiet=True)
result = pep8s.check_files(['tests/test_console.py'])
self.assertEqual(result.total_errors, 0, 'Found code style errors (and warnings).')<|docstring|>Test that tests/test_console.py conforms to PEP8.<|endoftext|> |
7c21329dd1074bbdb57ec47be7cc439b9c620e0baf16cc750ccba32a780368eb | def test_console_module_docstring(self):
'Test for the console.py module docstring'
self.assertIsNot(console.__doc__, None, 'console.py needs a docstring')
self.assertTrue((len(console.__doc__) >= 1), 'console.py needs a docstring') | Test for the console.py module docstring | tests/test_console.py | test_console_module_docstring | Joshua-Enrico/AirBnB_clone_v4 | 0 | python | def test_console_module_docstring(self):
self.assertIsNot(console.__doc__, None, 'console.py needs a docstring')
self.assertTrue((len(console.__doc__) >= 1), 'console.py needs a docstring') | def test_console_module_docstring(self):
self.assertIsNot(console.__doc__, None, 'console.py needs a docstring')
self.assertTrue((len(console.__doc__) >= 1), 'console.py needs a docstring')<|docstring|>Test for the console.py module docstring<|endoftext|> |
88787cf7e054c0d57d96b12504c9ef64aff68b4c5d7469a6b5960a74105d9c44 | def test_HBNBCommand_class_docstring(self):
'Test for the HBNBCommand class docstring'
self.assertIsNot(HBNBCommand.__doc__, None, 'HBNBCommand class needs a docstring')
self.assertTrue((len(HBNBCommand.__doc__) >= 1), 'HBNBCommand class needs a docstring') | Test for the HBNBCommand class docstring | tests/test_console.py | test_HBNBCommand_class_docstring | Joshua-Enrico/AirBnB_clone_v4 | 0 | python | def test_HBNBCommand_class_docstring(self):
self.assertIsNot(HBNBCommand.__doc__, None, 'HBNBCommand class needs a docstring')
self.assertTrue((len(HBNBCommand.__doc__) >= 1), 'HBNBCommand class needs a docstring') | def test_HBNBCommand_class_docstring(self):
self.assertIsNot(HBNBCommand.__doc__, None, 'HBNBCommand class needs a docstring')
self.assertTrue((len(HBNBCommand.__doc__) >= 1), 'HBNBCommand class needs a docstring')<|docstring|>Test for the HBNBCommand class docstring<|endoftext|> |
ec2d01898a58bf7b23de10543ade1858c9a638cbc869958c10b4831d13efa15d | @classmethod
def setUpClass(self):
'setting up tests'
self.base_funcs = inspect.getmembers(BaseModel, inspect.isfunction) | setting up tests | tests/test_console.py | setUpClass | Joshua-Enrico/AirBnB_clone_v4 | 0 | python | @classmethod
def setUpClass(self):
self.base_funcs = inspect.getmembers(BaseModel, inspect.isfunction) | @classmethod
def setUpClass(self):
self.base_funcs = inspect.getmembers(BaseModel, inspect.isfunction)<|docstring|>setting up tests<|endoftext|> |
421b40c3ce20fb272b347fb022a7d4f771183648977fe5ce4e2e7c4f8fc2bb02 | def test_pep8(self):
'Testing pep8'
for path in [path1, path2]:
with self.subTest(path=path):
errors = pycodestyle.Checker(path).check_all()
self.assertEqual(errors, 0) | Testing pep8 | tests/test_console.py | test_pep8 | Joshua-Enrico/AirBnB_clone_v4 | 0 | python | def test_pep8(self):
for path in [path1, path2]:
with self.subTest(path=path):
errors = pycodestyle.Checker(path).check_all()
self.assertEqual(errors, 0) | def test_pep8(self):
for path in [path1, path2]:
with self.subTest(path=path):
errors = pycodestyle.Checker(path).check_all()
self.assertEqual(errors, 0)<|docstring|>Testing pep8<|endoftext|> |
5b7aaa10d198cbc88c185c122908abae8a9086b9615784c4c28261237391038c | def test_module_docstring(self):
'Test module docstring'
self.assertIsNot(module_doc, None, 'base_model.py needs a docstring')
self.assertTrue((len(module_doc) > 1), 'base_model.py needs a docstring') | Test module docstring | tests/test_console.py | test_module_docstring | Joshua-Enrico/AirBnB_clone_v4 | 0 | python | def test_module_docstring(self):
self.assertIsNot(module_doc, None, 'base_model.py needs a docstring')
self.assertTrue((len(module_doc) > 1), 'base_model.py needs a docstring') | def test_module_docstring(self):
self.assertIsNot(module_doc, None, 'base_model.py needs a docstring')
self.assertTrue((len(module_doc) > 1), 'base_model.py needs a docstring')<|docstring|>Test module docstring<|endoftext|> |
a5200740f8ba8154f5ff014b0a01cb7a26d8a9424c145cedb021fb1749ffbd8f | def test_class_docstring(self):
'Test classes doctring'
self.assertIsNot(BaseModel.__doc__, None, 'BaseModel class needs a docstring')
self.assertTrue((len(BaseModel.__doc__) >= 1), 'BaseModel class needs a docstring') | Test classes doctring | tests/test_console.py | test_class_docstring | Joshua-Enrico/AirBnB_clone_v4 | 0 | python | def test_class_docstring(self):
self.assertIsNot(BaseModel.__doc__, None, 'BaseModel class needs a docstring')
self.assertTrue((len(BaseModel.__doc__) >= 1), 'BaseModel class needs a docstring') | def test_class_docstring(self):
self.assertIsNot(BaseModel.__doc__, None, 'BaseModel class needs a docstring')
self.assertTrue((len(BaseModel.__doc__) >= 1), 'BaseModel class needs a docstring')<|docstring|>Test classes doctring<|endoftext|> |
4f4e2b7a690858c86ff3d94b01a3ec2888831e6acb5905cb9eb8d1fd3031c729 | def test_func_docstrings(self):
'test func dostrings'
for func in self.base_funcs:
with self.subTest(function=func):
self.assertIsNot(func[1].__doc__, None, '{:s} method needs a docstring'.format(func[0]))
self.assertTrue((len(func[1].__doc__) > 1), '{:s} method needs a docstring... | test func dostrings | tests/test_console.py | test_func_docstrings | Joshua-Enrico/AirBnB_clone_v4 | 0 | python | def test_func_docstrings(self):
for func in self.base_funcs:
with self.subTest(function=func):
self.assertIsNot(func[1].__doc__, None, '{:s} method needs a docstring'.format(func[0]))
self.assertTrue((len(func[1].__doc__) > 1), '{:s} method needs a docstring'.format(func[0])) | def test_func_docstrings(self):
for func in self.base_funcs:
with self.subTest(function=func):
self.assertIsNot(func[1].__doc__, None, '{:s} method needs a docstring'.format(func[0]))
self.assertTrue((len(func[1].__doc__) > 1), '{:s} method needs a docstring'.format(func[0]))<|d... |
86c7ed9662f8354b01c99a7d705c059d8ba52622931e5cf42b357723b50549e9 | @classmethod
def setUpClass(self):
'setting class up'
self.console = HBNBCommand() | setting class up | tests/test_console.py | setUpClass | Joshua-Enrico/AirBnB_clone_v4 | 0 | python | @classmethod
def setUpClass(self):
self.console = HBNBCommand() | @classmethod
def setUpClass(self):
self.console = HBNBCommand()<|docstring|>setting class up<|endoftext|> |
f6b1275197079b3b29646c6fbc4505de604b65dcceae979001d0e8511c886c6a | def test_docstrings(self):
'testing docstings'
self.assertIsNotNone(console.__doc__)
self.assertIsNotNone(HBNBCommand.emptyline.__doc__)
self.assertIsNotNone(HBNBCommand.do_quit.__doc__)
self.assertIsNotNone(HBNBCommand.do_EOF.__doc__)
self.assertIsNotNone(HBNBCommand.do_create.__doc__)
self... | testing docstings | tests/test_console.py | test_docstrings | Joshua-Enrico/AirBnB_clone_v4 | 0 | python | def test_docstrings(self):
self.assertIsNotNone(console.__doc__)
self.assertIsNotNone(HBNBCommand.emptyline.__doc__)
self.assertIsNotNone(HBNBCommand.do_quit.__doc__)
self.assertIsNotNone(HBNBCommand.do_EOF.__doc__)
self.assertIsNotNone(HBNBCommand.do_create.__doc__)
self.assertIsNotNone(HB... | def test_docstrings(self):
self.assertIsNotNone(console.__doc__)
self.assertIsNotNone(HBNBCommand.emptyline.__doc__)
self.assertIsNotNone(HBNBCommand.do_quit.__doc__)
self.assertIsNotNone(HBNBCommand.do_EOF.__doc__)
self.assertIsNotNone(HBNBCommand.do_create.__doc__)
self.assertIsNotNone(HB... |
894eaeb6220ab2987ba8d5a7cc48b4c97e9cebeb109720545a65d3369c6d146e | def test_non_exist_command(self):
"testing a command that doesn't exist like goku"
with patch('sys.stdout', new=StringIO()) as f:
HBNBCommand().onecmd('goku')
self.assertEqual(('*** Unknown syntax: goku\n' or ''), f.getvalue()) | testing a command that doesn't exist like goku | tests/test_console.py | test_non_exist_command | Joshua-Enrico/AirBnB_clone_v4 | 0 | python | def test_non_exist_command(self):
with patch('sys.stdout', new=StringIO()) as f:
HBNBCommand().onecmd('goku')
self.assertEqual(('*** Unknown syntax: goku\n' or ), f.getvalue()) | def test_non_exist_command(self):
with patch('sys.stdout', new=StringIO()) as f:
HBNBCommand().onecmd('goku')
self.assertEqual(('*** Unknown syntax: goku\n' or ), f.getvalue())<|docstring|>testing a command that doesn't exist like goku<|endoftext|> |
1387e4099ba06a1c6f3e3a81314a3cc7370338e6c0d520f9359375760fe72f5e | def test_empty_line(self):
'testing empty input'
with patch('sys.stdout', new=StringIO()) as f:
HBNBCommand().onecmd('\n')
self.assertEqual('', f.getvalue()) | testing empty input | tests/test_console.py | test_empty_line | Joshua-Enrico/AirBnB_clone_v4 | 0 | python | def test_empty_line(self):
with patch('sys.stdout', new=StringIO()) as f:
HBNBCommand().onecmd('\n')
self.assertEqual(, f.getvalue()) | def test_empty_line(self):
with patch('sys.stdout', new=StringIO()) as f:
HBNBCommand().onecmd('\n')
self.assertEqual(, f.getvalue())<|docstring|>testing empty input<|endoftext|> |
86c7ed9662f8354b01c99a7d705c059d8ba52622931e5cf42b357723b50549e9 | @classmethod
def setUpClass(self):
'setting class up'
self.console = HBNBCommand() | setting class up | tests/test_console.py | setUpClass | Joshua-Enrico/AirBnB_clone_v4 | 0 | python | @classmethod
def setUpClass(self):
self.console = HBNBCommand() | @classmethod
def setUpClass(self):
self.console = HBNBCommand()<|docstring|>setting class up<|endoftext|> |
83669967c4ee0e856e7f229edc86dda420a9604bc3cc2721b9417702f9e26888 | def test_create(self):
'testing creat input'
with patch('sys.stdout', new=StringIO()) as f:
HBNBCommand().onecmd('create')
self.assertEqual('** class name missing **\n', f.getvalue())
with patch('sys.stdout', new=StringIO()) as f:
HBNBCommand().onecmd('create holbieees')
self... | testing creat input | tests/test_console.py | test_create | Joshua-Enrico/AirBnB_clone_v4 | 0 | python | def test_create(self):
with patch('sys.stdout', new=StringIO()) as f:
HBNBCommand().onecmd('create')
self.assertEqual('** class name missing **\n', f.getvalue())
with patch('sys.stdout', new=StringIO()) as f:
HBNBCommand().onecmd('create holbieees')
self.assertEqual("** clas... | def test_create(self):
with patch('sys.stdout', new=StringIO()) as f:
HBNBCommand().onecmd('create')
self.assertEqual('** class name missing **\n', f.getvalue())
with patch('sys.stdout', new=StringIO()) as f:
HBNBCommand().onecmd('create holbieees')
self.assertEqual("** clas... |
8f4e3ce659b2044b30427b76cf42f4c97a388e4fbfeda5ac36f231c5f099b9d6 | def test_delete_trainingprogress_from_edit_view(self):
'Regression test for issue #1085.'
trainingprogress_edit = self.app.get(reverse('trainingprogress_edit', args=[self.progress.pk]), user='admin')
self.assertRedirects(trainingprogress_edit.forms['delete-form'].submit(), reverse('all_trainees'))
with ... | Regression test for issue #1085. | workshops/test/test_training_progress.py | test_delete_trainingprogress_from_edit_view | askingalot/amy | 0 | python | def test_delete_trainingprogress_from_edit_view(self):
trainingprogress_edit = self.app.get(reverse('trainingprogress_edit', args=[self.progress.pk]), user='admin')
self.assertRedirects(trainingprogress_edit.forms['delete-form'].submit(), reverse('all_trainees'))
with self.assertRaises(TrainingProgress... | def test_delete_trainingprogress_from_edit_view(self):
trainingprogress_edit = self.app.get(reverse('trainingprogress_edit', args=[self.progress.pk]), user='admin')
self.assertRedirects(trainingprogress_edit.forms['delete-form'].submit(), reverse('all_trainees'))
with self.assertRaises(TrainingProgress... |
9e6a99b92ed126cd05988039f8caba9926acb4779b22a62704c0cc48e8cfbc5f | def log_setup(log_file='default.log', log_level=logging.INFO):
' \n log setup along with log file and level.\n '
logging.basicConfig(filename=log_file, level=log_level, format='[%(levelname)s] %(name)s %(funcName)s(): %(message)s')
sh = logging.StreamHandler()
sh_formatter = logging.Formatter('%(m... | log setup along with log file and level. | python/log_config.py | log_setup | rich-ehrhardt/openshift-bare-metal | 0 | python | def log_setup(log_file='default.log', log_level=logging.INFO):
' \n \n '
logging.basicConfig(filename=log_file, level=log_level, format='[%(levelname)s] %(name)s %(funcName)s(): %(message)s')
sh = logging.StreamHandler()
sh_formatter = logging.Formatter('%(message)s')
sh.setFormatter(sh_format... | def log_setup(log_file='default.log', log_level=logging.INFO):
' \n \n '
logging.basicConfig(filename=log_file, level=log_level, format='[%(levelname)s] %(name)s %(funcName)s(): %(message)s')
sh = logging.StreamHandler()
sh_formatter = logging.Formatter('%(message)s')
sh.setFormatter(sh_format... |
cd680a4fd8e1678e011be3ae0c98f8a01ed1f848054b4406c04b068768cf0515 | def __init__(self, app, record, *, demo=None):
'Base class for a digital multimeter.\n\n Parameters\n ----------\n app : :class:`photons.App`\n The main application entry point.\n record : :class:`~msl.equipment.record_types.EquipmentRecord`\n The equipment record.\... | Base class for a digital multimeter.
Parameters
----------
app : :class:`photons.App`
The main application entry point.
record : :class:`~msl.equipment.record_types.EquipmentRecord`
The equipment record.
demo : :class:`bool`, optional
Whether to simulate a connection to the equipment by opening
a conne... | photons/equipment/dmm.py | __init__ | MSLNZ/pr-single-photons | 0 | python | def __init__(self, app, record, *, demo=None):
'Base class for a digital multimeter.\n\n Parameters\n ----------\n app : :class:`photons.App`\n The main application entry point.\n record : :class:`~msl.equipment.record_types.EquipmentRecord`\n The equipment record.\... | def __init__(self, app, record, *, demo=None):
'Base class for a digital multimeter.\n\n Parameters\n ----------\n app : :class:`photons.App`\n The main application entry point.\n record : :class:`~msl.equipment.record_types.EquipmentRecord`\n The equipment record.\... |
47a2e0a3452f95e698305e91640d23e6878efcada5567bcd10bf2b4c3ceb55f2 | def reset(self) -> None:
'Resets device to factory default state.'
self.logger.info(f'reset {self.alias!r}')
self._send_command_with_opc('*RST') | Resets device to factory default state. | photons/equipment/dmm.py | reset | MSLNZ/pr-single-photons | 0 | python | def reset(self) -> None:
self.logger.info(f'reset {self.alias!r}')
self._send_command_with_opc('*RST') | def reset(self) -> None:
self.logger.info(f'reset {self.alias!r}')
self._send_command_with_opc('*RST')<|docstring|>Resets device to factory default state.<|endoftext|> |
0ca28e197ce20d2900679dd78c4ab0ba0277b2caf188bae24a0f01cc3f64ad9a | def clear(self) -> None:
'Clears the event registers in all register groups and the error queue.'
self.logger.info(f'clear {self.alias!r}')
self._send_command_with_opc('*CLS') | Clears the event registers in all register groups and the error queue. | photons/equipment/dmm.py | clear | MSLNZ/pr-single-photons | 0 | python | def clear(self) -> None:
self.logger.info(f'clear {self.alias!r}')
self._send_command_with_opc('*CLS') | def clear(self) -> None:
self.logger.info(f'clear {self.alias!r}')
self._send_command_with_opc('*CLS')<|docstring|>Clears the event registers in all register groups and the error queue.<|endoftext|> |
0203c0458243cb9b45a77140599ae2f13e2c4225146a50787b3be67d046781b5 | def bus_trigger(self) -> None:
'Send a software trigger.'
self.logger.info(f'software trigger {self.alias!r}')
self.write('INIT;*TRG') | Send a software trigger. | photons/equipment/dmm.py | bus_trigger | MSLNZ/pr-single-photons | 0 | python | def bus_trigger(self) -> None:
self.logger.info(f'software trigger {self.alias!r}')
self.write('INIT;*TRG') | def bus_trigger(self) -> None:
self.logger.info(f'software trigger {self.alias!r}')
self.write('INIT;*TRG')<|docstring|>Send a software trigger.<|endoftext|> |
ab28c1af2aac6335fdd07e037df3d38e09d718892c718f91095bc5457922e70c | def fetch(self, initiate: bool=False) -> tuple:
"Fetch the samples.\n\n Parameters\n ----------\n initiate : :class:`bool`\n Whether to send the ``'INIT'`` command before sending ``'FETCH?'``.\n\n Returns\n -------\n :class:`float`\n The average value.\... | Fetch the samples.
Parameters
----------
initiate : :class:`bool`
Whether to send the ``'INIT'`` command before sending ``'FETCH?'``.
Returns
-------
:class:`float`
The average value.
:class:`float`
The standard deviation. | photons/equipment/dmm.py | fetch | MSLNZ/pr-single-photons | 0 | python | def fetch(self, initiate: bool=False) -> tuple:
"Fetch the samples.\n\n Parameters\n ----------\n initiate : :class:`bool`\n Whether to send the ``'INIT'`` command before sending ``'FETCH?'``.\n\n Returns\n -------\n :class:`float`\n The average value.\... | def fetch(self, initiate: bool=False) -> tuple:
"Fetch the samples.\n\n Parameters\n ----------\n initiate : :class:`bool`\n Whether to send the ``'INIT'`` command before sending ``'FETCH?'``.\n\n Returns\n -------\n :class:`float`\n The average value.\... |
20b57c938a15d4cf4a6e139ff28fccf5c8b6d1d8c7c82b1c2c57698b6510e144 | def acquisition_time(self, *, info: dict=None, line_freq: float=50.0) -> float:
'Get the approximate number of seconds it takes to acquire the data.\n\n Parameters\n ----------\n info : :class:`dict`, optional\n The value returned by :meth:`.info`. If not specified then it\n ... | Get the approximate number of seconds it takes to acquire the data.
Parameters
----------
info : :class:`dict`, optional
The value returned by :meth:`.info`. If not specified then it
will be automatically retrieved.
line_freq : :class:`float`, optional
The line frequency, in Hz.
Returns
-------
:class:`fl... | photons/equipment/dmm.py | acquisition_time | MSLNZ/pr-single-photons | 0 | python | def acquisition_time(self, *, info: dict=None, line_freq: float=50.0) -> float:
'Get the approximate number of seconds it takes to acquire the data.\n\n Parameters\n ----------\n info : :class:`dict`, optional\n The value returned by :meth:`.info`. If not specified then it\n ... | def acquisition_time(self, *, info: dict=None, line_freq: float=50.0) -> float:
'Get the approximate number of seconds it takes to acquire the data.\n\n Parameters\n ----------\n info : :class:`dict`, optional\n The value returned by :meth:`.info`. If not specified then it\n ... |
ac1241569f8dda1f3ad00e4b913774aa6cd9dbfb54d0004947dccb4c1a325eac | def check_errors(self):
'Query the digital multimeter’s error queue.\n\n If there is an error then raise an exception.\n '
raise NotImplementedError | Query the digital multimeter’s error queue.
If there is an error then raise an exception. | photons/equipment/dmm.py | check_errors | MSLNZ/pr-single-photons | 0 | python | def check_errors(self):
'Query the digital multimeter’s error queue.\n\n If there is an error then raise an exception.\n '
raise NotImplementedError | def check_errors(self):
'Query the digital multimeter’s error queue.\n\n If there is an error then raise an exception.\n '
raise NotImplementedError<|docstring|>Query the digital multimeter’s error queue.
If there is an error then raise an exception.<|endoftext|> |
6aa67b5571d227e65d749f41aac3404bbd3bcec14f52344a04890d0a9120d4aa | def info(self) -> dict:
'Get the configuration information of the digital multimeter.'
raise NotImplementedError | Get the configuration information of the digital multimeter. | photons/equipment/dmm.py | info | MSLNZ/pr-single-photons | 0 | python | def info(self) -> dict:
raise NotImplementedError | def info(self) -> dict:
raise NotImplementedError<|docstring|>Get the configuration information of the digital multimeter.<|endoftext|> |
65f2c375bbe06123436810eff94818905ab1cc05c6b0d153b6d6ddcf1bddb8fb | def configure(self, *, function='voltage', range=10, nsamples=10, nplc=10, auto_zero=True, trigger='bus', edge='falling', ntriggers=1, delay=None) -> dict:
'Configure the digital multimeter.\n\n Parameters\n ----------\n function : :class:`str`, optional\n The function to measure. Ca... | Configure the digital multimeter.
Parameters
----------
function : :class:`str`, optional
The function to measure. Can be any key in :attr:`.DMM.FUNCTIONS` (case insensitive).
range : :class:`float` or :class:`str`, optional
The range to use for the measurement. Can be any key in :attr:`.DMM.RANGES`.
nsamples ... | photons/equipment/dmm.py | configure | MSLNZ/pr-single-photons | 0 | python | def configure(self, *, function='voltage', range=10, nsamples=10, nplc=10, auto_zero=True, trigger='bus', edge='falling', ntriggers=1, delay=None) -> dict:
'Configure the digital multimeter.\n\n Parameters\n ----------\n function : :class:`str`, optional\n The function to measure. Ca... | def configure(self, *, function='voltage', range=10, nsamples=10, nplc=10, auto_zero=True, trigger='bus', edge='falling', ntriggers=1, delay=None) -> dict:
'Configure the digital multimeter.\n\n Parameters\n ----------\n function : :class:`str`, optional\n The function to measure. Ca... |
eb501472589ad95568476e7b822af04c438ce10fba31b7b2a95dbdc6c07e8362 | def _send_command_with_opc(self, command: str):
"Appends ``'*OPC?'`` to the end of a command.\n\n The *OPC? command guarantees that command's that were previously sent\n to the device have completed.\n "
command += ';*OPC?'
assert self.connection.query(command).startswith('1'), f'{comma... | Appends ``'*OPC?'`` to the end of a command.
The *OPC? command guarantees that command's that were previously sent
to the device have completed. | photons/equipment/dmm.py | _send_command_with_opc | MSLNZ/pr-single-photons | 0 | python | def _send_command_with_opc(self, command: str):
"Appends ``'*OPC?'`` to the end of a command.\n\n The *OPC? command guarantees that command's that were previously sent\n to the device have completed.\n "
command += ';*OPC?'
assert self.connection.query(command).startswith('1'), f'{comma... | def _send_command_with_opc(self, command: str):
"Appends ``'*OPC?'`` to the end of a command.\n\n The *OPC? command guarantees that command's that were previously sent\n to the device have completed.\n "
command += ';*OPC?'
assert self.connection.query(command).startswith('1'), f'{comma... |
af5cd252ade4bca90d2db780439728232b1a595cca2be17df3b7feab3c039cfa | def _average_and_emit(self, samples) -> tuple:
'Compute the average and emit the value.\n\n Parameters\n ----------\n samples : :class:`str` or :class:`list`\n A comma-separated string of readings or a list of readings.\n\n Returns\n -------\n :class:`float`\n ... | Compute the average and emit the value.
Parameters
----------
samples : :class:`str` or :class:`list`
A comma-separated string of readings or a list of readings.
Returns
-------
:class:`float`
The average value.
:class:`float`
The standard deviation. | photons/equipment/dmm.py | _average_and_emit | MSLNZ/pr-single-photons | 0 | python | def _average_and_emit(self, samples) -> tuple:
'Compute the average and emit the value.\n\n Parameters\n ----------\n samples : :class:`str` or :class:`list`\n A comma-separated string of readings or a list of readings.\n\n Returns\n -------\n :class:`float`\n ... | def _average_and_emit(self, samples) -> tuple:
'Compute the average and emit the value.\n\n Parameters\n ----------\n samples : :class:`str` or :class:`list`\n A comma-separated string of readings or a list of readings.\n\n Returns\n -------\n :class:`float`\n ... |
a2eacdc6cf43ef00447cef2f3b1dd94a1f386dd27f337197b075d0cd7aaa1458 | @classmethod
def setUpClass(cls):
'Instantiate an app for use with a SQLite database.'
(_, db) = tempfile.mkstemp(suffix='.sqlite')
cls.app = Flask('foo')
cls.app.config['CLASSIC_DATABASE_URI'] = f'sqlite:///{db}'
cls.app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
with cls.app.app_context(... | Instantiate an app for use with a SQLite database. | core/arxiv/submission/tests/examples/test_03_on_hold_submission.py | setUpClass | NeolithEra/arxiv-submission-core | 14 | python | @classmethod
def setUpClass(cls):
(_, db) = tempfile.mkstemp(suffix='.sqlite')
cls.app = Flask('foo')
cls.app.config['CLASSIC_DATABASE_URI'] = f'sqlite:///{db}'
cls.app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
with cls.app.app_context():
classic.init_app(cls.app) | @classmethod
def setUpClass(cls):
(_, db) = tempfile.mkstemp(suffix='.sqlite')
cls.app = Flask('foo')
cls.app.config['CLASSIC_DATABASE_URI'] = f'sqlite:///{db}'
cls.app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
with cls.app.app_context():
classic.init_app(cls.app)<|docstring|>Ins... |
cb9cfc17065933bd686e8019d37bd0b6b84cb1c04f9d3fa1786b9a2f3add5c56 | @mock.patch(f'{core.__name__}.StreamPublisher', mock.MagicMock())
def setUp(self):
'Create, and complete the submission.'
self.submitter = domain.agent.User(1234, email='example@example.com', forename='Jane', surname='User', endorsements=['cs.DL', 'cs.IR'])
self.defaults = {'creator': self.submitter}
wi... | Create, and complete the submission. | core/arxiv/submission/tests/examples/test_03_on_hold_submission.py | setUp | NeolithEra/arxiv-submission-core | 14 | python | @mock.patch(f'{core.__name__}.StreamPublisher', mock.MagicMock())
def setUp(self):
self.submitter = domain.agent.User(1234, email='example@example.com', forename='Jane', surname='User', endorsements=['cs.DL', 'cs.IR'])
self.defaults = {'creator': self.submitter}
with self.app.app_context():
cla... | @mock.patch(f'{core.__name__}.StreamPublisher', mock.MagicMock())
def setUp(self):
self.submitter = domain.agent.User(1234, email='example@example.com', forename='Jane', surname='User', endorsements=['cs.DL', 'cs.IR'])
self.defaults = {'creator': self.submitter}
with self.app.app_context():
cla... |
e35215a5b4bd3cd8197ff24db5a5f7edf3b33a619bd7de29fefaf03b8a5ea7b4 | def tearDown(self):
'Clear the database after each test.'
with self.app.app_context():
classic.drop_all() | Clear the database after each test. | core/arxiv/submission/tests/examples/test_03_on_hold_submission.py | tearDown | NeolithEra/arxiv-submission-core | 14 | python | def tearDown(self):
with self.app.app_context():
classic.drop_all() | def tearDown(self):
with self.app.app_context():
classic.drop_all()<|docstring|>Clear the database after each test.<|endoftext|> |
feb1b19d4be3016beea55d072f2ec6695f0050bce634bcae4e9aee7481006c86 | @mock.patch(f'{core.__name__}.StreamPublisher', mock.MagicMock())
def test_is_in_submitted_state(self):
'The submission is now on hold.'
with self.app.app_context():
(submission, events) = load(self.submission.submission_id)
self.assertTrue(submission.is_on_hold, 'The submission is on hold')
... | The submission is now on hold. | core/arxiv/submission/tests/examples/test_03_on_hold_submission.py | test_is_in_submitted_state | NeolithEra/arxiv-submission-core | 14 | python | @mock.patch(f'{core.__name__}.StreamPublisher', mock.MagicMock())
def test_is_in_submitted_state(self):
with self.app.app_context():
(submission, events) = load(self.submission.submission_id)
self.assertTrue(submission.is_on_hold, 'The submission is on hold')
self.assertEqual(len(submis... | @mock.patch(f'{core.__name__}.StreamPublisher', mock.MagicMock())
def test_is_in_submitted_state(self):
with self.app.app_context():
(submission, events) = load(self.submission.submission_id)
self.assertTrue(submission.is_on_hold, 'The submission is on hold')
self.assertEqual(len(submis... |
997e90969f2d2393d18cb70610ebd219592359722adcf2336cf574f5276671ec | @mock.patch(f'{core.__name__}.StreamPublisher', mock.MagicMock())
def test_cannot_replace_submission(self):
"The submission cannot be replaced: it hasn't yet been announced."
with self.app.app_context():
with self.assertRaises(exceptions.InvalidEvent, msg='Creating a CreateSubmissionVersion command resu... | The submission cannot be replaced: it hasn't yet been announced. | core/arxiv/submission/tests/examples/test_03_on_hold_submission.py | test_cannot_replace_submission | NeolithEra/arxiv-submission-core | 14 | python | @mock.patch(f'{core.__name__}.StreamPublisher', mock.MagicMock())
def test_cannot_replace_submission(self):
with self.app.app_context():
with self.assertRaises(exceptions.InvalidEvent, msg='Creating a CreateSubmissionVersion command results in an exception.'):
save(domain.event.CreateSubmis... | @mock.patch(f'{core.__name__}.StreamPublisher', mock.MagicMock())
def test_cannot_replace_submission(self):
with self.app.app_context():
with self.assertRaises(exceptions.InvalidEvent, msg='Creating a CreateSubmissionVersion command results in an exception.'):
save(domain.event.CreateSubmis... |
0b7d98ab5967f1f1836db9320f10589d1ae63a121f749e97c415f1266af066ee | @mock.patch(f'{core.__name__}.StreamPublisher', mock.MagicMock())
def test_cannot_withdraw_submission(self):
"The submission cannot be withdrawn: it hasn't yet been announced."
with self.app.app_context():
with self.assertRaises(exceptions.InvalidEvent, msg='Creating a RequestWithdrawal command results ... | The submission cannot be withdrawn: it hasn't yet been announced. | core/arxiv/submission/tests/examples/test_03_on_hold_submission.py | test_cannot_withdraw_submission | NeolithEra/arxiv-submission-core | 14 | python | @mock.patch(f'{core.__name__}.StreamPublisher', mock.MagicMock())
def test_cannot_withdraw_submission(self):
with self.app.app_context():
with self.assertRaises(exceptions.InvalidEvent, msg='Creating a RequestWithdrawal command results in an exception.'):
save(domain.event.RequestWithdrawal... | @mock.patch(f'{core.__name__}.StreamPublisher', mock.MagicMock())
def test_cannot_withdraw_submission(self):
with self.app.app_context():
with self.assertRaises(exceptions.InvalidEvent, msg='Creating a RequestWithdrawal command results in an exception.'):
save(domain.event.RequestWithdrawal... |
f4a0ce7d7d74294700e2c51c2ac91b2ca67086ce8e19e0e1f24f109a9212f4b0 | @mock.patch(f'{core.__name__}.StreamPublisher', mock.MagicMock())
def test_cannot_edit_submission(self):
"The submission cannot be changed: it hasn't yet been announced."
with self.app.app_context():
with self.assertRaises(exceptions.InvalidEvent, msg='Creating a SetTitle command results in an exception... | The submission cannot be changed: it hasn't yet been announced. | core/arxiv/submission/tests/examples/test_03_on_hold_submission.py | test_cannot_edit_submission | NeolithEra/arxiv-submission-core | 14 | python | @mock.patch(f'{core.__name__}.StreamPublisher', mock.MagicMock())
def test_cannot_edit_submission(self):
with self.app.app_context():
with self.assertRaises(exceptions.InvalidEvent, msg='Creating a SetTitle command results in an exception.'):
save(domain.event.SetTitle(title='A better title... | @mock.patch(f'{core.__name__}.StreamPublisher', mock.MagicMock())
def test_cannot_edit_submission(self):
with self.app.app_context():
with self.assertRaises(exceptions.InvalidEvent, msg='Creating a SetTitle command results in an exception.'):
save(domain.event.SetTitle(title='A better title... |
87d8088ed2907b4a68b819e9ace5dcc8b527994fcc6875702b87c95a6ba88085 | @mock.patch(f'{core.__name__}.StreamPublisher', mock.MagicMock())
def test_can_be_unfinalized(self):
'The submission can be unfinalized.'
with self.app.app_context():
save(domain.event.UnFinalizeSubmission(**self.defaults), submission_id=self.submission.submission_id)
with self.app.app_context():
... | The submission can be unfinalized. | core/arxiv/submission/tests/examples/test_03_on_hold_submission.py | test_can_be_unfinalized | NeolithEra/arxiv-submission-core | 14 | python | @mock.patch(f'{core.__name__}.StreamPublisher', mock.MagicMock())
def test_can_be_unfinalized(self):
with self.app.app_context():
save(domain.event.UnFinalizeSubmission(**self.defaults), submission_id=self.submission.submission_id)
with self.app.app_context():
(submission, events) = load(se... | @mock.patch(f'{core.__name__}.StreamPublisher', mock.MagicMock())
def test_can_be_unfinalized(self):
with self.app.app_context():
save(domain.event.UnFinalizeSubmission(**self.defaults), submission_id=self.submission.submission_id)
with self.app.app_context():
(submission, events) = load(se... |
0924cfd6b4d9a6ca8a6ffd7f80a49e90a58e500cac4f9cc34fccedc1de6a0c7e | def _separable_series2(h, N=1):
' finds separable approximations to the 2d function 2d h\n\n returns res = (hx, hy)[N]\n s.t. h \x07pprox sum_i outer(res[i,0],res[i,1])\n '
if (min(h.shape) < N):
raise ValueError(('smallest dimension of h is smaller than approximation order! (%s < %s)' % (min(h... | finds separable approximations to the 2d function 2d h
returns res = (hx, hy)[N]
s.t. h pprox sum_i outer(res[i,0],res[i,1]) | gputools/separable/separable_approx.py | _separable_series2 | tlambert03/gputools | 89 | python | def _separable_series2(h, N=1):
' finds separable approximations to the 2d function 2d h\n\n returns res = (hx, hy)[N]\n s.t. h \x07pprox sum_i outer(res[i,0],res[i,1])\n '
if (min(h.shape) < N):
raise ValueError(('smallest dimension of h is smaller than approximation order! (%s < %s)' % (min(h... | def _separable_series2(h, N=1):
' finds separable approximations to the 2d function 2d h\n\n returns res = (hx, hy)[N]\n s.t. h \x07pprox sum_i outer(res[i,0],res[i,1])\n '
if (min(h.shape) < N):
raise ValueError(('smallest dimension of h is smaller than approximation order! (%s < %s)' % (min(h... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.