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 isinstance(value, six.string_types): return value elif (type(value) == datetime.date): return value.strftime(ctx.get_date_format(False)) elif isinstance(value, datetime.time): return value.strftime('%H:%M') elif isinstance(value, datetime.datetime): return value.astimezone(ctx.timezone).strftime(ctx.get_date_format(True)) raise EvaluationError(("Can't convert '%s' to a string" % six.text_type(value)))
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): return value elif (type(value) == datetime.date): return value.strftime(ctx.get_date_format(False)) elif isinstance(value, datetime.time): return value.strftime('%H:%M') elif isinstance(value, datetime.datetime): return value.astimezone(ctx.timezone).strftime(ctx.get_date_format(True)) raise EvaluationError(("Can't convert '%s' to a string" % six.text_type(value)))
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): return value elif (type(value) == datetime.date): return value.strftime(ctx.get_date_format(False)) elif isinstance(value, datetime.time): return value.strftime('%H:%M') elif isinstance(value, datetime.datetime): return value.astimezone(ctx.timezone).strftime(ctx.get_date_format(True)) raise EvaluationError(("Can't convert '%s' to a string" % six.text_type(value)))<|docstring|>Tries conversion of any value to a string<|endoftext|>
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 elif isinstance(value, datetime.datetime): return value.date() raise EvaluationError(("Can't convert '%s' to a date" % six.text_type(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.datetime): return value.date() raise EvaluationError(("Can't convert '%s' to a date" % six.text_type(value)))
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.datetime): return value.date() raise EvaluationError(("Can't convert '%s' to a date" % six.text_type(value)))<|docstring|>Tries conversion of any value to a date<|endoftext|>
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): return ctx.timezone.localize(datetime.datetime.combine(value, datetime.time(0, 0))) elif isinstance(value, datetime.datetime): return value.astimezone(ctx.timezone) raise EvaluationError(("Can't convert '%s' to a datetime" % six.text_type(value)))
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.datetime.combine(value, datetime.time(0, 0))) elif isinstance(value, datetime.datetime): return value.astimezone(ctx.timezone) raise EvaluationError(("Can't convert '%s' to a datetime" % six.text_type(value)))
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.datetime.combine(value, datetime.time(0, 0))) elif isinstance(value, datetime.datetime): return value.astimezone(ctx.timezone) raise EvaluationError(("Can't convert '%s' to a datetime" % six.text_type(value)))<|docstring|>Tries conversion of any value to a datetime<|endoftext|>
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): return value elif isinstance(value, datetime.datetime): return value.astimezone(ctx.timezone) raise EvaluationError(("Can't convert '%s' to a date or datetime" % six.text_type(value)))
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.datetime): return value.astimezone(ctx.timezone) raise EvaluationError(("Can't convert '%s' to a date or datetime" % six.text_type(value)))
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.datetime): return value.astimezone(ctx.timezone) raise EvaluationError(("Can't convert '%s' to a date or datetime" % six.text_type(value)))<|docstring|>Tries conversion of any value to a date or datetime<|endoftext|>
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, datetime.datetime): return value.astimezone(ctx.timezone).time() raise EvaluationError(("Can't convert '%s' to a time" % six.text_type(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 value.astimezone(ctx.timezone).time() raise EvaluationError(("Can't convert '%s' to a time" % six.text_type(value)))
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 value.astimezone(ctx.timezone).time() raise EvaluationError(("Can't convert '%s' to a time" % six.text_type(value)))<|docstring|>Tries conversion of any value to a time<|endoftext|>
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)): return (value1, value2) try: return (to_decimal(value1, ctx), to_decimal(value2, ctx)) except EvaluationError: pass try: (d1, d2) = (to_date_or_datetime(value1, ctx), to_date_or_datetime(value2, ctx)) if (type(value1) != type(value2)): (d1, d2) = (to_datetime(d1, ctx), to_datetime(d2, ctx)) return (d1, d2) except EvaluationError: pass return (to_string(value1, ctx), to_string(value2, ctx))
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)): return (value1, value2) try: return (to_decimal(value1, ctx), to_decimal(value2, ctx)) except EvaluationError: pass try: (d1, d2) = (to_date_or_datetime(value1, ctx), to_date_or_datetime(value2, ctx)) if (type(value1) != type(value2)): (d1, d2) = (to_datetime(d1, ctx), to_datetime(d2, ctx)) return (d1, d2) except EvaluationError: pass return (to_string(value1, ctx), to_string(value2, ctx))
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)): return (value1, value2) try: return (to_decimal(value1, ctx), to_decimal(value2, ctx)) except EvaluationError: pass try: (d1, d2) = (to_date_or_datetime(value1, ctx), to_date_or_datetime(value2, ctx)) if (type(value1) != type(value2)): (d1, d2) = (to_datetime(d1, ctx), to_datetime(d2, ctx)) return (d1, d2) except EvaluationError: pass return (to_string(value1, ctx), to_string(value2, ctx))<|docstring|>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<|endoftext|>
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('"', '""') as_string = ('"%s"' % as_string) return as_string
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|>Converts a value back to its representation form, e.g. x -> "x"<|endoftext|>
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() if (exponent >= 1): normalized = normalized.quantize(1) (sign, digits, exponent) = normalized.as_tuple() int_digits = (len(digits) + exponent) fractional_digits = min(max((10 - int_digits), 0), (- exponent)) normalized = normalized.quantize((Decimal(10) ** (- fractional_digits))) return six.text_type(normalized)
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() if (exponent >= 1): normalized = normalized.quantize(1) (sign, digits, exponent) = normalized.as_tuple() int_digits = (len(digits) + exponent) fractional_digits = min(max((10 - int_digits), 0), (- exponent)) normalized = normalized.quantize((Decimal(10) ** (- fractional_digits))) return six.text_type(normalized)
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() if (exponent >= 1): normalized = normalized.quantize(1) (sign, digits, exponent) = normalized.as_tuple() int_digits = (len(digits) + exponent) fractional_digits = min(max((10 - int_digits), 0), (- exponent)) normalized = normalized.quantize((Decimal(10) ** (- fractional_digits))) return six.text_type(normalized)<|docstring|>Formats a decimal number using the same precision as Excel :param decimal: the decimal value :return: the formatted string value<|endoftext|>
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 token_network in payment_network.tokenidentifiers_to_tokennetworks.values(): for channel_state in token_network.partneraddresses_to_channels.values(): addresses.add(channel_state.partner_state.address) return addresses
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 token_network in payment_network.tokenidentifiers_to_tokennetworks.values(): for channel_state in token_network.partneraddresses_to_channels.values(): addresses.add(channel_state.partner_state.address) return addresses
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 token_network in payment_network.tokenidentifiers_to_tokennetworks.values(): for channel_state in token_network.partneraddresses_to_channels.values(): addresses.add(channel_state.partner_state.address) return addresses<|docstring|>Return the identifiers for all nodes accross all payment networks which have a channel open with this one.<|endoftext|>
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 not None): return [token_network.token_address for token_network in payment_network.tokenidentifiers_to_tokennetworks.values()] return list()
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_network in payment_network.tokenidentifiers_to_tokennetworks.values()] return list()
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_network in payment_network.tokenidentifiers_to_tokennetworks.values()] return list()<|docstring|>Return the list of tokens registered with the given payment network.<|endoftext|>
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) channel_state = None if token_network: channel_state = token_network.partneraddresses_to_channels.get(partner_address) return channel_state
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: channel_state = token_network.partneraddresses_to_channels.get(partner_address) return channel_state
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: channel_state = token_network.partneraddresses_to_channels.get(partner_address) return channel_state<|docstring|>Return the NettingChannelState if it exists, None otherwise.<|endoftext|>
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_address) result = [] for channel_state in token_network.channelidentifiers_to_channels.values(): if channel_state.partner_state.balance_proof: result.append(channel_state) return result
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_address) result = [] for channel_state in token_network.channelidentifiers_to_channels.values(): if channel_state.partner_state.balance_proof: result.append(channel_state) return result
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_address) result = [] for channel_state in token_network.channelidentifiers_to_channels.values(): if channel_state.partner_state.balance_proof: result.append(channel_state) return result<|docstring|>Return the state of channels that had received any transfers in this token network.<|endoftext|>
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) result = [] for channel_state in token_network.channelidentifiers_to_channels.values(): if (channel.get_status(channel_state) == CHANNEL_STATE_OPENED): result.append(channel_state) return result
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.channelidentifiers_to_channels.values(): if (channel.get_status(channel_state) == CHANNEL_STATE_OPENED): result.append(channel_state) return result
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.channelidentifiers_to_channels.values(): if (channel.get_status(channel_state) == CHANNEL_STATE_OPENED): result.append(channel_state) return result<|docstring|>Return the state of open channels in a token network.<|endoftext|>
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_address) result = [] for channel_state in token_network.channelidentifiers_to_channels.values(): if (channel.get_status(channel_state) == CHANNEL_STATE_SETTLED): result.append(channel_state) return result
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_network.channelidentifiers_to_channels.values(): if (channel.get_status(channel_state) == CHANNEL_STATE_SETTLED): result.append(channel_state) return result
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_network.channelidentifiers_to_channels.values(): if (channel.get_status(channel_state) == CHANNEL_STATE_SETTLED): result.append(channel_state) return result<|docstring|>Return the state of open channels in a token network.<|endoftext|>
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 |\n +---+\n | 2 |\n +---+\n | 3 |\n +---+\n | 4 |\n +---+\n | 5 |\n +---+\n | 6 |\n +---+\n | 7 |\n +---+\n | 9 |\n +---+\n >>> sheet.row.select([1,2,3,5])\n >>> sheet\n pyexcel sheet:\n +---+\n | 2 |\n +---+\n | 3 |\n +---+\n | 4 |\n +---+\n | 6 |\n +---+\n\n ' new_indices = [] if compact.is_array_type(indices, str): new_indices = utils.names_to_indices(indices, self._ref.rownames) else: new_indices = indices to_remove = [] for index in self._ref.row_range(): if (index not in new_indices): to_remove.append(index) self._ref.filter(row_indices=to_remove)
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 | +---+ | 7 | +---+ | 9 | +---+ >>> sheet.row.select([1,2,3,5]) >>> sheet pyexcel sheet: +---+ | 2 | +---+ | 3 | +---+ | 4 | +---+ | 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 |\n +---+\n | 2 |\n +---+\n | 3 |\n +---+\n | 4 |\n +---+\n | 5 |\n +---+\n | 6 |\n +---+\n | 7 |\n +---+\n | 9 |\n +---+\n >>> sheet.row.select([1,2,3,5])\n >>> sheet\n pyexcel sheet:\n +---+\n | 2 |\n +---+\n | 3 |\n +---+\n | 4 |\n +---+\n | 6 |\n +---+\n\n ' new_indices = [] if compact.is_array_type(indices, str): new_indices = utils.names_to_indices(indices, self._ref.rownames) else: new_indices = indices to_remove = [] for index in self._ref.row_range(): if (index not in new_indices): to_remove.append(index) self._ref.filter(row_indices=to_remove)
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 |\n +---+\n | 2 |\n +---+\n | 3 |\n +---+\n | 4 |\n +---+\n | 5 |\n +---+\n | 6 |\n +---+\n | 7 |\n +---+\n | 9 |\n +---+\n >>> sheet.row.select([1,2,3,5])\n >>> sheet\n pyexcel sheet:\n +---+\n | 2 |\n +---+\n | 3 |\n +---+\n | 4 |\n +---+\n | 6 |\n +---+\n\n ' new_indices = [] if compact.is_array_type(indices, str): new_indices = utils.names_to_indices(indices, self._ref.rownames) else: new_indices = indices to_remove = [] for index in self._ref.row_range(): if (index not in new_indices): to_remove.append(index) self._ref.filter(row_indices=to_remove)<|docstring|>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 | +---+ | 7 | +---+ | 9 | +---+ >>> sheet.row.select([1,2,3,5]) >>> sheet pyexcel sheet: +---+ | 2 | +---+ | 3 | +---+ | 4 | +---+ | 6 | +---+<|endoftext|>
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 |\n +---+\n | 2 |\n +---+\n | 3 |\n +---+\n | 4 |\n +---+\n | 5 |\n +---+\n | 6 |\n +---+\n | 7 |\n +---+\n | 9 |\n +---+\n >>> del sheet.row[1,2,3,5]\n >>> sheet\n pyexcel sheet:\n +---+\n | 1 |\n +---+\n | 5 |\n +---+\n | 7 |\n +---+\n | 9 |\n +---+\n\n ' if compact.is_string(type(locator)): self._ref.delete_named_row_at(locator) elif compact.is_tuple_consists_of_strings(locator): indices = utils.names_to_indices(list(locator), self._ref.rownames) self._ref.delete_rows(indices) elif isinstance(locator, slice): my_range = utils.analyse_slice(locator, self._ref.number_of_rows()) self._ref.delete_rows(my_range) elif isinstance(locator, tuple): self._ref.filter(row_indices=list(locator)) elif isinstance(locator, list): self._ref.filter(row_indices=locator) elif isinstance(locator, types.LambdaType): self._delete_rows_by_content(locator) elif isinstance(locator, types.FunctionType): self._delete_rows_by_content(locator) else: self._ref.delete_rows([locator])
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 | +---+ | 7 | +---+ | 9 | +---+ >>> del sheet.row[1,2,3,5] >>> sheet pyexcel sheet: +---+ | 1 | +---+ | 5 | +---+ | 7 | +---+ | 9 | +---+
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 |\n +---+\n | 2 |\n +---+\n | 3 |\n +---+\n | 4 |\n +---+\n | 5 |\n +---+\n | 6 |\n +---+\n | 7 |\n +---+\n | 9 |\n +---+\n >>> del sheet.row[1,2,3,5]\n >>> sheet\n pyexcel sheet:\n +---+\n | 1 |\n +---+\n | 5 |\n +---+\n | 7 |\n +---+\n | 9 |\n +---+\n\n ' if compact.is_string(type(locator)): self._ref.delete_named_row_at(locator) elif compact.is_tuple_consists_of_strings(locator): indices = utils.names_to_indices(list(locator), self._ref.rownames) self._ref.delete_rows(indices) elif isinstance(locator, slice): my_range = utils.analyse_slice(locator, self._ref.number_of_rows()) self._ref.delete_rows(my_range) elif isinstance(locator, tuple): self._ref.filter(row_indices=list(locator)) elif isinstance(locator, list): self._ref.filter(row_indices=locator) elif isinstance(locator, types.LambdaType): self._delete_rows_by_content(locator) elif isinstance(locator, types.FunctionType): self._delete_rows_by_content(locator) else: self._ref.delete_rows([locator])
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 |\n +---+\n | 2 |\n +---+\n | 3 |\n +---+\n | 4 |\n +---+\n | 5 |\n +---+\n | 6 |\n +---+\n | 7 |\n +---+\n | 9 |\n +---+\n >>> del sheet.row[1,2,3,5]\n >>> sheet\n pyexcel sheet:\n +---+\n | 1 |\n +---+\n | 5 |\n +---+\n | 7 |\n +---+\n | 9 |\n +---+\n\n ' if compact.is_string(type(locator)): self._ref.delete_named_row_at(locator) elif compact.is_tuple_consists_of_strings(locator): indices = utils.names_to_indices(list(locator), self._ref.rownames) self._ref.delete_rows(indices) elif isinstance(locator, slice): my_range = utils.analyse_slice(locator, self._ref.number_of_rows()) self._ref.delete_rows(my_range) elif isinstance(locator, tuple): self._ref.filter(row_indices=list(locator)) elif isinstance(locator, list): self._ref.filter(row_indices=locator) elif isinstance(locator, types.LambdaType): self._delete_rows_by_content(locator) elif isinstance(locator, types.FunctionType): self._delete_rows_by_content(locator) else: self._ref.delete_rows([locator])<|docstring|>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 | +---+ | 7 | +---+ | 9 | +---+ >>> del sheet.row[1,2,3,5] >>> sheet pyexcel sheet: +---+ | 1 | +---+ | 5 | +---+ | 7 | +---+ | 9 | +---+<|endoftext|>
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.named_row_at(the_attr)
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)<|docstring|>Refer to sheet.row.name<|endoftext|>
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: self._ref.set_row_at(i, a_row) else: self._ref.set_row_at(aslice, a_row)
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) else: self._ref.set_row_at(aslice, a_row)
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) else: self._ref.set_row_at(aslice, a_row)<|docstring|>Override the operator to set items<|endoftext|>
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.number_of_rows()) results = [] for i in my_range: results.append(self._ref.row_at(i)) return results if (abs(index) in self._ref.row_range()): return self._ref.row_at(index) else: raise IndexError
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.number_of_rows()) results = [] for i in my_range: results.append(self._ref.row_at(i)) return results if (abs(index) in self._ref.row_range()): return self._ref.row_at(index) else: raise IndexError
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.number_of_rows()) results = [] for i in my_range: results.append(self._ref.row_at(i)) return results if (abs(index) in self._ref.row_range()): return self._ref.row_at(index) else: raise IndexError<|docstring|>By default, this class recognize from top to bottom from left to right<|endoftext|>
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'): self._ref.extend_rows(copy.deepcopy(other.get_internal_array())) else: raise TypeError return self
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'): self._ref.extend_rows(copy.deepcopy(other.get_internal_array())) else: raise TypeError return self
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'): self._ref.extend_rows(copy.deepcopy(other.get_internal_array())) else: raise TypeError return self<|docstring|>Overload += sign :return: self<|endoftext|>
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)) elif hasattr(other, 'get_internal_array'): new_instance.extend_rows(copy.deepcopy(other.get_internal_array())) else: raise TypeError return new_instance
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)) elif hasattr(other, 'get_internal_array'): new_instance.extend_rows(copy.deepcopy(other.get_internal_array())) else: raise TypeError return new_instance
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)) elif hasattr(other, 'get_internal_array'): new_instance.extend_rows(copy.deepcopy(other.get_internal_array())) else: raise TypeError return new_instance<|docstring|>Overload + sign :return: new instance<|endoftext|>
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): result_dict = {'packit_id': propose_downstream_results.id, 'status': propose_downstream_results.status, 'submitted_time': optional_timestamp(propose_downstream_results.submitted_time), 'status_per_downstream_pr': {pr.branch: pr.status for pr in propose_downstream_results.propose_downstream_targets}, 'packit_id_per_downstream_pr': {pr.branch: pr.id for pr in propose_downstream_results.propose_downstream_targets}, 'pr_id': propose_downstream_results.get_pr_id(), 'issue_id': propose_downstream_results.get_issue_id(), 'release': propose_downstream_results.get_release_tag()} project = propose_downstream_results.get_project() result_dict['repo_namespace'] = project.namespace result_dict['repo_name'] = project.repo_name result_dict['project_url'] = project.project_url result.append(result_dict) resp = response_maker(result, status=HTTPStatus.PARTIAL_CONTENT.value) resp.headers['Content-Range'] = f'propose-downstreams {(first + 1)}-{last}/*' return resp
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_downstream_results.id, 'status': propose_downstream_results.status, 'submitted_time': optional_timestamp(propose_downstream_results.submitted_time), 'status_per_downstream_pr': {pr.branch: pr.status for pr in propose_downstream_results.propose_downstream_targets}, 'packit_id_per_downstream_pr': {pr.branch: pr.id for pr in propose_downstream_results.propose_downstream_targets}, 'pr_id': propose_downstream_results.get_pr_id(), 'issue_id': propose_downstream_results.get_issue_id(), 'release': propose_downstream_results.get_release_tag()} project = propose_downstream_results.get_project() result_dict['repo_namespace'] = project.namespace result_dict['repo_name'] = project.repo_name result_dict['project_url'] = project.project_url result.append(result_dict) resp = response_maker(result, status=HTTPStatus.PARTIAL_CONTENT.value) resp.headers['Content-Range'] = f'propose-downstreams {(first + 1)}-{last}/*' return resp
@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_downstream_results.id, 'status': propose_downstream_results.status, 'submitted_time': optional_timestamp(propose_downstream_results.submitted_time), 'status_per_downstream_pr': {pr.branch: pr.status for pr in propose_downstream_results.propose_downstream_targets}, 'packit_id_per_downstream_pr': {pr.branch: pr.id for pr in propose_downstream_results.propose_downstream_targets}, 'pr_id': propose_downstream_results.get_pr_id(), 'issue_id': propose_downstream_results.get_issue_id(), 'release': propose_downstream_results.get_release_tag()} project = propose_downstream_results.get_project() result_dict['repo_namespace'] = project.namespace result_dict['repo_name'] = project.repo_name result_dict['project_url'] = project.project_url result.append(result_dict) resp = response_maker(result, status=HTTPStatus.PARTIAL_CONTENT.value) resp.headers['Content-Range'] = f'propose-downstreams {(first + 1)}-{last}/*' return resp<|docstring|>List of all Propose Downstreams results.<|endoftext|>
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)) if (not dowstream_pr): return response_maker({'error': 'No info about propose downstream target stored in DB'}, status=HTTPStatus.NOT_FOUND.value) job_result_dict = {'status': dowstream_pr.status, 'branch': dowstream_pr.branch, 'downstream_pr_url': dowstream_pr.downstream_pr_url, 'submitted_time': optional_timestamp(dowstream_pr.submitted_time), 'start_time': optional_timestamp(dowstream_pr.start_time), 'finished_time': optional_timestamp(dowstream_pr.finished_time), 'logs': dowstream_pr.logs} job_result_dict.update(get_project_info_from_build(dowstream_pr.propose_downstream)) return response_maker(job_result_dict)
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 response_maker({'error': 'No info about propose downstream target stored in DB'}, status=HTTPStatus.NOT_FOUND.value) job_result_dict = {'status': dowstream_pr.status, 'branch': dowstream_pr.branch, 'downstream_pr_url': dowstream_pr.downstream_pr_url, 'submitted_time': optional_timestamp(dowstream_pr.submitted_time), 'start_time': optional_timestamp(dowstream_pr.start_time), 'finished_time': optional_timestamp(dowstream_pr.finished_time), 'logs': dowstream_pr.logs} job_result_dict.update(get_project_info_from_build(dowstream_pr.propose_downstream)) return response_maker(job_result_dict)
@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 response_maker({'error': 'No info about propose downstream target stored in DB'}, status=HTTPStatus.NOT_FOUND.value) job_result_dict = {'status': dowstream_pr.status, 'branch': dowstream_pr.branch, 'downstream_pr_url': dowstream_pr.downstream_pr_url, 'submitted_time': optional_timestamp(dowstream_pr.submitted_time), 'start_time': optional_timestamp(dowstream_pr.start_time), 'finished_time': optional_timestamp(dowstream_pr.finished_time), 'logs': dowstream_pr.logs} job_result_dict.update(get_project_info_from_build(dowstream_pr.propose_downstream)) return response_maker(job_result_dict)<|docstring|>A specific propose-downstream job details<|endoftext|>
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 ValueError('n must be a positive value') if ((p <= 0) or (p >= 1)): raise ValueError('p must be greater than 0 and less than 1') self.n = round(n) self.p = float(p) else: if (type(data) is not list): raise TypeError('data must be a list') if (len(data) < 2): raise ValueError('data must contain multiple values') mean = float((sum(data) / len(data))) var = 0 for i in data: var += ((mean - i) ** 2) var = (var / len(data)) p = (1 - (var / mean)) self.n = round((mean / p)) self.p = float((mean / self.n))
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 ValueError('n must be a positive value') if ((p <= 0) or (p >= 1)): raise ValueError('p must be greater than 0 and less than 1') self.n = round(n) self.p = float(p) else: if (type(data) is not list): raise TypeError('data must be a list') if (len(data) < 2): raise ValueError('data must contain multiple values') mean = float((sum(data) / len(data))) var = 0 for i in data: var += ((mean - i) ** 2) var = (var / len(data)) p = (1 - (var / mean)) self.n = round((mean / p)) self.p = float((mean / self.n))
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 ValueError('n must be a positive value') if ((p <= 0) or (p >= 1)): raise ValueError('p must be greater than 0 and less than 1') self.n = round(n) self.p = float(p) else: if (type(data) is not list): raise TypeError('data must be a list') if (len(data) < 2): raise ValueError('data must contain multiple values') mean = float((sum(data) / len(data))) var = 0 for i in data: var += ((mean - i) ** 2) var = (var / len(data)) p = (1 - (var / mean)) self.n = round((mean / p)) self.p = float((mean / self.n))<|docstring|>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”<|endoftext|>
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 - self.p) ** (self.n - k)))
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 - self.p) ** (self.n - k)))
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 - self.p) ** (self.n - k)))<|docstring|>Probability mass function Calculates the value of the PMF for a given number of “successes” k is the number of “successes”<|endoftext|>
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) return acumulated
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) return acumulated
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) return acumulated<|docstring|>Cumulative distribution function Calculates the value of the CDF for a given number of “successes” k is the number of “successes”<|endoftext|>
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 tqsdk import TqApi, TqAccount, TqMultiAccount\n\n account1 = TqAccount("H海通期货", "123456", "123456")\n account2 = TqAccount("H宏源期货", "654321", "123456")\n api = TqApi(TqMultiAccount([account1, account2]), auth=TqAuth("信易账户", "账户密码"))\n # 分别获取账户资金信息\n order1 = api.insert_order(symbol="DCE.m2101", direction="BUY", offset="OPEN", volume=3, account=account1)\n order2 = api.insert_order(symbol="SHFE.au2012C308", direction="BUY", offset="OPEN", volume=3, limit_price=78.0, account=account2)\n while order1.status != "FINISHED" or order2.status != "FINISHED":\n api.wait_update()\n # 分别获取账户资金信息\n account_info1 = account1.get_account()\n account_info2 = account2.get_account()\n api.close()\n\n Example2::\n\n # 多账户模式下使用 TargetPosTask\n from tqsdk import TqApi, TqAccount, TqMultiAccount, TqAuth, TargetPosTask\n\n account1 = TqAccount("H海通期货", "123456", "123456")\n account2 = TqAccount("H宏源期货", "654321", "123456")\n api = TqApi(TqMultiAccount([account1, account2]), auth=TqAuth("信易账户", "账户密码"))\n symbol1 = "DCE.m2105"\n symbol2 = "DCE.i2101"\n position1 = account1.get_position(symbol1)\n position2 = account2.get_position(symbol2)\n # 多账户模式下, 调仓工具需要指定账户实例\n target_pos1 = TargetPosTask(api, symbol1, account=account1)\n target_pos2 = TargetPosTask(api, symbol2, account=account2)\n target_pos1.set_target_volume(30)\n target_pos2.set_target_volume(80)\n while position1.volume_long != 30 or position2.volume_long != 80:\n api.wait_update()\n\n api.close()\n\n ' self._account_list = (accounts if accounts else [TqSim()]) self._has_tq_account = any([True for a in self._account_list if isinstance(a, BaseOtg)]) self._map_conn_id = {} if self._has_duplicate_account(): raise Exception('多账户列表中不允许使用重复的账户实例.')
创建 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") api = TqApi(TqMultiAccount([account1, account2]), auth=TqAuth("信易账户", "账户密码")) # 分别获取账户资金信息 order1 = api.insert_order(symbol="DCE.m2101", direction="BUY", offset="OPEN", volume=3, account=account1) order2 = api.insert_order(symbol="SHFE.au2012C308", direction="BUY", offset="OPEN", volume=3, limit_price=78.0, account=account2) while order1.status != "FINISHED" or order2.status != "FINISHED": api.wait_update() # 分别获取账户资金信息 account_info1 = account1.get_account() account_info2 = account2.get_account() api.close() Example2:: # 多账户模式下使用 TargetPosTask from tqsdk import TqApi, TqAccount, TqMultiAccount, TqAuth, TargetPosTask account1 = TqAccount("H海通期货", "123456", "123456") account2 = TqAccount("H宏源期货", "654321", "123456") api = TqApi(TqMultiAccount([account1, account2]), auth=TqAuth("信易账户", "账户密码")) symbol1 = "DCE.m2105" symbol2 = "DCE.i2101" position1 = account1.get_position(symbol1) position2 = account2.get_position(symbol2) # 多账户模式下, 调仓工具需要指定账户实例 target_pos1 = TargetPosTask(api, symbol1, account=account1) target_pos2 = TargetPosTask(api, symbol2, account=account2) target_pos1.set_target_volume(30) target_pos2.set_target_volume(80) while position1.volume_long != 30 or position2.volume_long != 80: api.wait_update() api.close()
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 tqsdk import TqApi, TqAccount, TqMultiAccount\n\n account1 = TqAccount("H海通期货", "123456", "123456")\n account2 = TqAccount("H宏源期货", "654321", "123456")\n api = TqApi(TqMultiAccount([account1, account2]), auth=TqAuth("信易账户", "账户密码"))\n # 分别获取账户资金信息\n order1 = api.insert_order(symbol="DCE.m2101", direction="BUY", offset="OPEN", volume=3, account=account1)\n order2 = api.insert_order(symbol="SHFE.au2012C308", direction="BUY", offset="OPEN", volume=3, limit_price=78.0, account=account2)\n while order1.status != "FINISHED" or order2.status != "FINISHED":\n api.wait_update()\n # 分别获取账户资金信息\n account_info1 = account1.get_account()\n account_info2 = account2.get_account()\n api.close()\n\n Example2::\n\n # 多账户模式下使用 TargetPosTask\n from tqsdk import TqApi, TqAccount, TqMultiAccount, TqAuth, TargetPosTask\n\n account1 = TqAccount("H海通期货", "123456", "123456")\n account2 = TqAccount("H宏源期货", "654321", "123456")\n api = TqApi(TqMultiAccount([account1, account2]), auth=TqAuth("信易账户", "账户密码"))\n symbol1 = "DCE.m2105"\n symbol2 = "DCE.i2101"\n position1 = account1.get_position(symbol1)\n position2 = account2.get_position(symbol2)\n # 多账户模式下, 调仓工具需要指定账户实例\n target_pos1 = TargetPosTask(api, symbol1, account=account1)\n target_pos2 = TargetPosTask(api, symbol2, account=account2)\n target_pos1.set_target_volume(30)\n target_pos2.set_target_volume(80)\n while position1.volume_long != 30 or position2.volume_long != 80:\n api.wait_update()\n\n api.close()\n\n ' self._account_list = (accounts if accounts else [TqSim()]) self._has_tq_account = any([True for a in self._account_list if isinstance(a, BaseOtg)]) self._map_conn_id = {} if self._has_duplicate_account(): raise Exception('多账户列表中不允许使用重复的账户实例.')
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 tqsdk import TqApi, TqAccount, TqMultiAccount\n\n account1 = TqAccount("H海通期货", "123456", "123456")\n account2 = TqAccount("H宏源期货", "654321", "123456")\n api = TqApi(TqMultiAccount([account1, account2]), auth=TqAuth("信易账户", "账户密码"))\n # 分别获取账户资金信息\n order1 = api.insert_order(symbol="DCE.m2101", direction="BUY", offset="OPEN", volume=3, account=account1)\n order2 = api.insert_order(symbol="SHFE.au2012C308", direction="BUY", offset="OPEN", volume=3, limit_price=78.0, account=account2)\n while order1.status != "FINISHED" or order2.status != "FINISHED":\n api.wait_update()\n # 分别获取账户资金信息\n account_info1 = account1.get_account()\n account_info2 = account2.get_account()\n api.close()\n\n Example2::\n\n # 多账户模式下使用 TargetPosTask\n from tqsdk import TqApi, TqAccount, TqMultiAccount, TqAuth, TargetPosTask\n\n account1 = TqAccount("H海通期货", "123456", "123456")\n account2 = TqAccount("H宏源期货", "654321", "123456")\n api = TqApi(TqMultiAccount([account1, account2]), auth=TqAuth("信易账户", "账户密码"))\n symbol1 = "DCE.m2105"\n symbol2 = "DCE.i2101"\n position1 = account1.get_position(symbol1)\n position2 = account2.get_position(symbol2)\n # 多账户模式下, 调仓工具需要指定账户实例\n target_pos1 = TargetPosTask(api, symbol1, account=account1)\n target_pos2 = TargetPosTask(api, symbol2, account=account2)\n target_pos1.set_target_volume(30)\n target_pos2.set_target_volume(80)\n while position1.volume_long != 30 or position2.volume_long != 80:\n api.wait_update()\n\n api.close()\n\n ' self._account_list = (accounts if accounts else [TqSim()]) self._has_tq_account = any([True for a in self._account_list if isinstance(a, BaseOtg)]) self._map_conn_id = {} if self._has_duplicate_account(): raise Exception('多账户列表中不允许使用重复的账户实例.')<|docstring|>创建 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") api = TqApi(TqMultiAccount([account1, account2]), auth=TqAuth("信易账户", "账户密码")) # 分别获取账户资金信息 order1 = api.insert_order(symbol="DCE.m2101", direction="BUY", offset="OPEN", volume=3, account=account1) order2 = api.insert_order(symbol="SHFE.au2012C308", direction="BUY", offset="OPEN", volume=3, limit_price=78.0, account=account2) while order1.status != "FINISHED" or order2.status != "FINISHED": api.wait_update() # 分别获取账户资金信息 account_info1 = account1.get_account() account_info2 = account2.get_account() api.close() Example2:: # 多账户模式下使用 TargetPosTask from tqsdk import TqApi, TqAccount, TqMultiAccount, TqAuth, TargetPosTask account1 = TqAccount("H海通期货", "123456", "123456") account2 = TqAccount("H宏源期货", "654321", "123456") api = TqApi(TqMultiAccount([account1, account2]), auth=TqAuth("信易账户", "账户密码")) symbol1 = "DCE.m2105" symbol2 = "DCE.i2101" position1 = account1.get_position(symbol1) position2 = account2.get_position(symbol2) # 多账户模式下, 调仓工具需要指定账户实例 target_pos1 = TargetPosTask(api, symbol1, account=account1) target_pos2 = TargetPosTask(api, symbol2, account=account2) target_pos1.set_target_volume(30) target_pos2.set_target_volume(80) while position1.volume_long != 30 or position2.volume_long != 80: api.wait_update() api.close()<|endoftext|>
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 == account)] return (selected_list[0] if selected_list else None) elif (account is None): return (self._account_list[0] if (len(self._account_list) == 1) else None) else: return (account if (account in self._account_list) else None)
查询委托、成交、资产、委托时, 需要指定账户实例 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 == account)] return (selected_list[0] if selected_list else None) elif (account is None): return (self._account_list[0] if (len(self._account_list) == 1) else None) else: return (account if (account in self._account_list) else None)
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 == account)] return (selected_list[0] if selected_list else None) elif (account is None): return (self._account_list[0] if (len(self._account_list) == 1) else None) else: return (account if (account in self._account_list) else None)<|docstring|>查询委托、成交、资产、委托时, 需要指定账户实例 account: 类型 str 表示 account_key,其他为账户类型或者 None<|endoftext|>
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_datas.append(trade_more_data) return any(trade_more_datas)
获取业务信息截面 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) return any(trade_more_datas)
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) return any(trade_more_datas)<|docstring|>获取业务信息截面 trade_more_data 标识,当且仅当所有账户的标识置为 false 时,业务信息截面就绪<|endoftext|>
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 RHS @param t time in ODE @param y variables in ODE @param arg1 parameter for the ODE @returns the RHS of the ODE<|endoftext|>
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\n ' raise NotImplementedError('A problem class should implement member function f_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\n ' raise NotImplementedError('A problem class should implement member function f_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\n ' raise NotImplementedError('A problem class should implement member function f_tangent')<|docstring|>! 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<|endoftext|>
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,\zeta $ to $R,Z, arphi $) @param coords1 the coordinates to convert @returns the converted coordinates<|endoftext|>
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), 'T': (10 ** 12), 'P': (10 ** 15), 'E': (10 ** 18), 'Z': (10 ** 21), 'Y': (10 ** 24)} (arg,) = list(element.clauses) exp = func.trim(arg) def apply_multiplier(text, multiplier): return func.cast((_squash_to_numeric(text) * multiplier), sqlalchemy.UnicodeText) exp = sqlalchemy.case(*[(exp.endswith(abrev), apply_multiplier(exp, number_abbreviations[abrev])) for abrev in number_abbreviations], else_=exp) return compiler.process(exp, **kw)
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,) = list(element.clauses) exp = func.trim(arg) def apply_multiplier(text, multiplier): return func.cast((_squash_to_numeric(text) * multiplier), sqlalchemy.UnicodeText) exp = sqlalchemy.case(*[(exp.endswith(abrev), apply_multiplier(exp, number_abbreviations[abrev])) for abrev in number_abbreviations], else_=exp) return compiler.process(exp, **kw)
@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,) = list(element.clauses) exp = func.trim(arg) def apply_multiplier(text, multiplier): return func.cast((_squash_to_numeric(text) * multiplier), sqlalchemy.UnicodeText) exp = sqlalchemy.case(*[(exp.endswith(abrev), apply_multiplier(exp, number_abbreviations[abrev])) for abrev in number_abbreviations], else_=exp) return compiler.process(exp, **kw)<|docstring|>Turn common number formatting into a number. use metric abbreviations, remove stuff like $, etc.<|endoftext|>
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, '([+\\-]?(\\d+\\.?\\d*[Ee][+\\-]?\\d+))'), func.nullif(func.regexp_replace(text, '[^0-9\\.\\+\\-]+', '', 'g'), '')) return compiler.process(sql_only_numeric(arg), **kw)
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\\.\\+\\-]+', , 'g'), )) return compiler.process(sql_only_numeric(arg), **kw)
@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\\.\\+\\-]+', , 'g'), )) return compiler.process(sql_only_numeric(arg), **kw)<|docstring|>Turn common number formatting into a number. use metric abbreviations, remove stuff like $, etc.<|endoftext|>
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.Integer), **kw)
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, remove stuff like $, etc.<|endoftext|>
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)), sqlalchemy.Integer), **kw)
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 abbreviations, remove stuff like $, etc.<|endoftext|>
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 compiler.process((basic_safe_divide if (divide_by_zero_value is None) else func.coalesce(basic_safe_divide, divide_by_zero_value)))
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 func.coalesce(basic_safe_divide, divide_by_zero_value)))
@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 func.coalesce(basic_safe_divide, divide_by_zero_value)))<|docstring|>Divides numerator by denominator, returning NULL if the denominator is 0.<|endoftext|>
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(wrapped, '__annotations__', {}).get(STATE, State) if (ENV == ENVIRONMENT.LOCAL): for output_state in execute_message(func, state, read_message()): logger.info(output_state)
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(wrapped, '__annotations__', {}).get(STATE, State) if (ENV == ENVIRONMENT.LOCAL): for output_state in execute_message(func, state, read_message()): logger.info(output_state)
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(wrapped, '__annotations__', {}).get(STATE, State) if (ENV == ENVIRONMENT.LOCAL): for output_state in execute_message(func, state, read_message()): logger.info(output_state)<|docstring|>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.<|endoftext|>
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 as default\n\n Returns:\n (str) target string with keyword highlighted\n\n ' return re.sub(keyword, ((color + '\\g<0>') + Style.RESET_ALL), target)
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 as default\n\n Returns:\n (str) target string with keyword highlighted\n\n ' return re.sub(keyword, ((color + '\\g<0>') + Style.RESET_ALL), target)
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 as default\n\n Returns:\n (str) target string with keyword highlighted\n\n ' return re.sub(keyword, ((color + '\\g<0>') + Style.RESET_ALL), target)<|docstring|>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<|endoftext|>
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 = {} for (k, v) in param_dict.items(): if re.search(key, k): find_result[k] = v if isinstance(v, dict): res = find_key(v, key) if res: find_result[k] = res return 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 = {} for (k, v) in param_dict.items(): if re.search(key, k): find_result[k] = v if isinstance(v, dict): res = find_key(v, key) if res: find_result[k] = res return 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 = {} for (k, v) in param_dict.items(): if re.search(key, k): find_result[k] = v if isinstance(v, dict): res = find_key(v, key) if res: find_result[k] = res return find_result<|docstring|>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}<|endoftext|>
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): diff_result[k] = v elif (dst[k] != v): if isinstance(v, dict): diff_result[k] = diff_dict(v, dst[k]) else: diff_result[k] = v return diff_result
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): diff_result[k] = v elif (dst[k] != v): if isinstance(v, dict): diff_result[k] = diff_dict(v, dst[k]) else: diff_result[k] = v return diff_result
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): diff_result[k] = v elif (dst[k] != v): if isinstance(v, dict): diff_result[k] = diff_dict(v, dst[k]) else: diff_result[k] = v return diff_result<|docstring|>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<|endoftext|>
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(original) replacement_type = type(replacement) if (replacement_type == original_type): return replacement def conditional_cast(from_type, to_type): if ((replacement_type == from_type) and (original_type == to_type)): return (True, to_type(replacement)) else: return (False, None) casts = [(tuple, list), (list, tuple)] try: casts.append((str, unicode)) except Exception: pass for (from_type, to_type) in casts: (converted, converted_value) = conditional_cast(from_type, to_type) if converted: return converted_value raise ValueError('Type mismatch ({} vs. {}) with values ({} vs. {}) for config key: {}'.format(original_type, replacement_type, original, replacement, full_key))
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(original) replacement_type = type(replacement) if (replacement_type == original_type): return replacement def conditional_cast(from_type, to_type): if ((replacement_type == from_type) and (original_type == to_type)): return (True, to_type(replacement)) else: return (False, None) casts = [(tuple, list), (list, tuple)] try: casts.append((str, unicode)) except Exception: pass for (from_type, to_type) in casts: (converted, converted_value) = conditional_cast(from_type, to_type) if converted: return converted_value raise ValueError('Type mismatch ({} vs. {}) with values ({} vs. {}) for config key: {}'.format(original_type, replacement_type, original, replacement, full_key))
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(original) replacement_type = type(replacement) if (replacement_type == original_type): return replacement def conditional_cast(from_type, to_type): if ((replacement_type == from_type) and (original_type == to_type)): return (True, to_type(replacement)) else: return (False, None) casts = [(tuple, list), (list, tuple)] try: casts.append((str, unicode)) except Exception: pass for (from_type, to_type) in casts: (converted, converted_value) = conditional_cast(from_type, to_type) if converted: return converted_value raise ValueError('Type mismatch ({} vs. {}) with values ({} vs. {}) for config key: {}'.format(original_type, replacement_type, original, replacement, full_key))<|docstring|>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.<|endoftext|>
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_location = os.path.join(file_location, '__init__.py') spec = importlib.util.spec_from_file_location(spec_name, module_location) logger.debug('Trying to import {}'.format(module_location)) nextmodule = _get_module(spec) if (nextmodule is None): module_location = (file_location + '.py') spec = importlib.util.spec_from_file_location(spec_name, module_location) logger.debug('Trying to import {}'.format(module_location)) nextmodule = _get_module(spec) if nextmodule: (module, n) = (nextmodule, (n + 1)) else: break if module: object = module else: object = builtins for part in parts[n:]: try: object = getattr(object, part) except AttributeError: return None return object
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 = importlib.util.spec_from_file_location(spec_name, module_location) logger.debug('Trying to import {}'.format(module_location)) nextmodule = _get_module(spec) if (nextmodule is None): module_location = (file_location + '.py') spec = importlib.util.spec_from_file_location(spec_name, module_location) logger.debug('Trying to import {}'.format(module_location)) nextmodule = _get_module(spec) if nextmodule: (module, n) = (nextmodule, (n + 1)) else: break if module: object = module else: object = builtins for part in parts[n:]: try: object = getattr(object, part) except AttributeError: return None return object
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 = importlib.util.spec_from_file_location(spec_name, module_location) logger.debug('Trying to import {}'.format(module_location)) nextmodule = _get_module(spec) if (nextmodule is None): module_location = (file_location + '.py') spec = importlib.util.spec_from_file_location(spec_name, module_location) logger.debug('Trying to import {}'.format(module_location)) nextmodule = _get_module(spec) if nextmodule: (module, n) = (nextmodule, (n + 1)) else: break if module: object = module else: object = builtins for part in parts[n:]: try: object = getattr(object, part) except AttributeError: return None return object<|docstring|>Locate an object by name or dotted path, importing as necessary.<|endoftext|>
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 execution of the module raises exception.\n ' spec = importlib.util.spec_from_file_location(dotted_path, filepath) module = importlib.util.module_from_spec(spec) spec.loader.exec_module(module) return module
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 execution of the module raises exception.\n ' spec = importlib.util.spec_from_file_location(dotted_path, filepath) module = importlib.util.module_from_spec(spec) spec.loader.exec_module(module) return module
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 execution of the module raises exception.\n ' spec = importlib.util.spec_from_file_location(dotted_path, filepath) module = importlib.util.module_from_spec(spec) spec.loader.exec_module(module) return module<|docstring|>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.<|endoftext|>
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 ((len(split) > 1) and (split[0] not in sys.modules)): root = split[0] sys.modules[root] = types.ModuleType(root) sys.modules[dotted_path] = module_obj
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 ((len(split) > 1) and (split[0] not in sys.modules)): root = split[0] sys.modules[root] = types.ModuleType(root) sys.modules[dotted_path] = module_obj
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 ((len(split) > 1) and (split[0] not in sys.modules)): root = split[0] sys.modules[root] = types.ModuleType(root) sys.modules[dotted_path] = module_obj<|docstring|>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<|endoftext|>
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 :param author_name: the name of the author of the item to load.\n :param directory: the component directory.\n :return: the module associated to the Python package of the component.\n ' item_type_plural = (item_type + 's') dotted_path = 'packages.{}.{}.{}'.format(author_name, item_type_plural, item_name) filepath = (Path(directory) / '__init__.py') return load_module(dotted_path, filepath)
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 to the Python package of the component.
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 :param author_name: the name of the author of the item to load.\n :param directory: the component directory.\n :return: the module associated to the Python package of the component.\n ' item_type_plural = (item_type + 's') dotted_path = 'packages.{}.{}.{}'.format(author_name, item_type_plural, item_name) filepath = (Path(directory) / '__init__.py') return load_module(dotted_path, filepath)
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 :param author_name: the name of the author of the item to load.\n :param directory: the component directory.\n :return: the module associated to the Python package of the component.\n ' item_type_plural = (item_type + 's') dotted_path = 'packages.{}.{}.{}'.format(author_name, item_type_plural, item_name) filepath = (Path(directory) / '__init__.py') return load_module(dotted_path, filepath)<|docstring|>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 to the Python package of the component.<|endoftext|>
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 :param author_name: the name of the author of the item to load.\n :param module_obj: the module object. It is assumed it has been already executed.\n :return:\n ' item_type_plural = (item_type + 's') dotted_path = 'packages.{}.{}.{}'.format(author_name, item_type_plural, item_name) import_module(dotted_path, module_obj)
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. :return:
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 :param author_name: the name of the author of the item to load.\n :param module_obj: the module object. It is assumed it has been already executed.\n :return:\n ' item_type_plural = (item_type + 's') dotted_path = 'packages.{}.{}.{}'.format(author_name, item_type_plural, item_name) import_module(dotted_path, module_obj)
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 :param author_name: the name of the author of the item to load.\n :param module_obj: the module object. It is assumed it has been already executed.\n :return:\n ' item_type_plural = (item_type + 's') dotted_path = 'packages.{}.{}.{}'.format(author_name, item_type_plural, item_name) import_module(dotted_path, module_obj)<|docstring|>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. :return:<|endoftext|>
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: Enable the developer to generate two different fingerprints for the same package.\n (Can be used with different configuration)\n ' import hashlib if (nonce is not None): string_for_hash = ''.join([author, package_name, version, str(nonce)]) else: string_for_hash = ''.join([author, package_name, version]) m_hash = hashlib.sha3_256() m_hash.update(string_for_hash.encode()) encoded_str = m_hash.digest().hex() return encoded_str
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: Enable the developer to generate two different fingerprints for the same package.\n (Can be used with different configuration)\n ' import hashlib if (nonce is not None): string_for_hash = .join([author, package_name, version, str(nonce)]) else: string_for_hash = .join([author, package_name, version]) m_hash = hashlib.sha3_256() m_hash.update(string_for_hash.encode()) encoded_str = m_hash.digest().hex() return encoded_str
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: Enable the developer to generate two different fingerprints for the same package.\n (Can be used with different configuration)\n ' import hashlib if (nonce is not None): string_for_hash = .join([author, package_name, version, str(nonce)]) else: string_for_hash = .join([author, package_name, version]) m_hash = hashlib.sha3_256() m_hash.update(string_for_hash.encode()) encoded_str = m_hash.digest().hex() return encoded_str<|docstring|>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)<|endoftext|>
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) self._update_selector_and_sink_socket(base_tree) self.log.debug('Copy all blocks/connections from radio program to meta radio program') old_uhd_usrp_source_id = [] old_blocks_socket_pdu_id = [] proto_trees = [] proto_vars = [] proto_usrp_src_dicts = [] coord_y_offsets = (250, 500) for (protocol_it, proto_prefix) in enumerate(self.radio_programs): proto_xfile = self.radio_programs[proto_prefix] ptree = etree.parse(proto_xfile) proto_trees.append(ptree) proto_vars.append(self._rename_all_variables(proto_prefix, proto_trees[protocol_it], coord_y_offsets[protocol_it])) proto_usrp_src_dicts.append(self._copy_usrp_src_cfg(proto_trees[protocol_it].getroot(), proto_vars[protocol_it])) for proto_block in proto_trees[protocol_it].getroot().findall('block'): block_key = proto_block.find('key') if (block_key.text == 'uhd_usrp_source'): for param in proto_block.findall('param'): param_val = param.find('value') param_key = param.find('key') if (param_key.text == 'id'): old_uhd_usrp_source_id.append(param_val.text) elif (block_key.text == 'blocks_socket_pdu'): for param in proto_block.findall('param'): param_val = param.find('value') param_key = param.find('key') if (param_key.text == 'id'): old_blocks_socket_pdu_id.append(param_val.text) elif (block_key.text == 'options'): found = False for param in proto_block.findall('param'): param_val = param.find('value') param_key = param.find('key') if ((param_key.text == 'id') and (param_val.text == (proto_prefix + 'top_block'))): found = True if (not found): new_root.append(proto_block) else: new_root.append(proto_block) self.log.debug('Init session variable') for base_block in new_root.findall('block'): init_session_value = '[0' for field in self.usrp_source_fields: init_session_value = ((init_session_value + ',') + proto_usrp_src_dicts[0][field]) init_session_value = (init_session_value + ']') block_key = base_block.find('key') if (block_key.text == 'variable'): found = False for param in base_block.findall('param'): param_val = param.find('value') param_key = param.find('key') if ((param_key.text == 'id') and (param_val.text == 'session_var')): found = True if found: for param in base_block.findall('param'): param_val = param.find('value') param_key = param.find('key') if (param_key.text == 'value'): param_val.text = init_session_value self.log.debug('Configure node connections ...') self.log.debug('... copy from template') for base_conn in base_tree.getroot().findall('connection'): new_root.append(base_conn) self.log.debug('... copy from each radio program & reconnect to selector/common sink') for protocol_it in range(self._get_num_protocols()): for proto_conn in proto_trees[protocol_it].getroot().findall('connection'): if (proto_conn.find('source_block_id').text == old_uhd_usrp_source_id[protocol_it]): proto_conn.find('source_block_id').text = self.common_selector_id proto_conn.find('source_key').text = str(protocol_it) if (proto_conn.find('sink_block_id').text == old_blocks_socket_pdu_id[protocol_it]): proto_conn.find('sink_block_id').text = self.common_blocks_socket_pdu_id new_root.append(proto_conn) self.log.info('Serialize combined grc file') new_tree = etree.ElementTree(new_root) new_tree.write(os.path.join(self.gr_radio_programs_path, self.gen_grc_fname)) fout = open(os.path.join(self.gr_radio_programs_path, self.gen_proto_dict_fname), 'w') fout.write(str(proto_usrp_src_dicts)) fout.close() fout = open(os.path.join(self.gr_radio_programs_path, self.gen_proto_fields_fname), 'w') fout.write(str(self.usrp_source_fields)) fout.close() return self.gen_grc_fname
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_and_sink_socket(base_tree) self.log.debug('Copy all blocks/connections from radio program to meta radio program') old_uhd_usrp_source_id = [] old_blocks_socket_pdu_id = [] proto_trees = [] proto_vars = [] proto_usrp_src_dicts = [] coord_y_offsets = (250, 500) for (protocol_it, proto_prefix) in enumerate(self.radio_programs): proto_xfile = self.radio_programs[proto_prefix] ptree = etree.parse(proto_xfile) proto_trees.append(ptree) proto_vars.append(self._rename_all_variables(proto_prefix, proto_trees[protocol_it], coord_y_offsets[protocol_it])) proto_usrp_src_dicts.append(self._copy_usrp_src_cfg(proto_trees[protocol_it].getroot(), proto_vars[protocol_it])) for proto_block in proto_trees[protocol_it].getroot().findall('block'): block_key = proto_block.find('key') if (block_key.text == 'uhd_usrp_source'): for param in proto_block.findall('param'): param_val = param.find('value') param_key = param.find('key') if (param_key.text == 'id'): old_uhd_usrp_source_id.append(param_val.text) elif (block_key.text == 'blocks_socket_pdu'): for param in proto_block.findall('param'): param_val = param.find('value') param_key = param.find('key') if (param_key.text == 'id'): old_blocks_socket_pdu_id.append(param_val.text) elif (block_key.text == 'options'): found = False for param in proto_block.findall('param'): param_val = param.find('value') param_key = param.find('key') if ((param_key.text == 'id') and (param_val.text == (proto_prefix + 'top_block'))): found = True if (not found): new_root.append(proto_block) else: new_root.append(proto_block) self.log.debug('Init session variable') for base_block in new_root.findall('block'): init_session_value = '[0' for field in self.usrp_source_fields: init_session_value = ((init_session_value + ',') + proto_usrp_src_dicts[0][field]) init_session_value = (init_session_value + ']') block_key = base_block.find('key') if (block_key.text == 'variable'): found = False for param in base_block.findall('param'): param_val = param.find('value') param_key = param.find('key') if ((param_key.text == 'id') and (param_val.text == 'session_var')): found = True if found: for param in base_block.findall('param'): param_val = param.find('value') param_key = param.find('key') if (param_key.text == 'value'): param_val.text = init_session_value self.log.debug('Configure node connections ...') self.log.debug('... copy from template') for base_conn in base_tree.getroot().findall('connection'): new_root.append(base_conn) self.log.debug('... copy from each radio program & reconnect to selector/common sink') for protocol_it in range(self._get_num_protocols()): for proto_conn in proto_trees[protocol_it].getroot().findall('connection'): if (proto_conn.find('source_block_id').text == old_uhd_usrp_source_id[protocol_it]): proto_conn.find('source_block_id').text = self.common_selector_id proto_conn.find('source_key').text = str(protocol_it) if (proto_conn.find('sink_block_id').text == old_blocks_socket_pdu_id[protocol_it]): proto_conn.find('sink_block_id').text = self.common_blocks_socket_pdu_id new_root.append(proto_conn) self.log.info('Serialize combined grc file') new_tree = etree.ElementTree(new_root) new_tree.write(os.path.join(self.gr_radio_programs_path, self.gen_grc_fname)) fout = open(os.path.join(self.gr_radio_programs_path, self.gen_proto_dict_fname), 'w') fout.write(str(proto_usrp_src_dicts)) fout.close() fout = open(os.path.join(self.gr_radio_programs_path, self.gen_proto_fields_fname), 'w') fout.write(str(self.usrp_source_fields)) fout.close() return self.gen_grc_fname
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_and_sink_socket(base_tree) self.log.debug('Copy all blocks/connections from radio program to meta radio program') old_uhd_usrp_source_id = [] old_blocks_socket_pdu_id = [] proto_trees = [] proto_vars = [] proto_usrp_src_dicts = [] coord_y_offsets = (250, 500) for (protocol_it, proto_prefix) in enumerate(self.radio_programs): proto_xfile = self.radio_programs[proto_prefix] ptree = etree.parse(proto_xfile) proto_trees.append(ptree) proto_vars.append(self._rename_all_variables(proto_prefix, proto_trees[protocol_it], coord_y_offsets[protocol_it])) proto_usrp_src_dicts.append(self._copy_usrp_src_cfg(proto_trees[protocol_it].getroot(), proto_vars[protocol_it])) for proto_block in proto_trees[protocol_it].getroot().findall('block'): block_key = proto_block.find('key') if (block_key.text == 'uhd_usrp_source'): for param in proto_block.findall('param'): param_val = param.find('value') param_key = param.find('key') if (param_key.text == 'id'): old_uhd_usrp_source_id.append(param_val.text) elif (block_key.text == 'blocks_socket_pdu'): for param in proto_block.findall('param'): param_val = param.find('value') param_key = param.find('key') if (param_key.text == 'id'): old_blocks_socket_pdu_id.append(param_val.text) elif (block_key.text == 'options'): found = False for param in proto_block.findall('param'): param_val = param.find('value') param_key = param.find('key') if ((param_key.text == 'id') and (param_val.text == (proto_prefix + 'top_block'))): found = True if (not found): new_root.append(proto_block) else: new_root.append(proto_block) self.log.debug('Init session variable') for base_block in new_root.findall('block'): init_session_value = '[0' for field in self.usrp_source_fields: init_session_value = ((init_session_value + ',') + proto_usrp_src_dicts[0][field]) init_session_value = (init_session_value + ']') block_key = base_block.find('key') if (block_key.text == 'variable'): found = False for param in base_block.findall('param'): param_val = param.find('value') param_key = param.find('key') if ((param_key.text == 'id') and (param_val.text == 'session_var')): found = True if found: for param in base_block.findall('param'): param_val = param.find('value') param_key = param.find('key') if (param_key.text == 'value'): param_val.text = init_session_value self.log.debug('Configure node connections ...') self.log.debug('... copy from template') for base_conn in base_tree.getroot().findall('connection'): new_root.append(base_conn) self.log.debug('... copy from each radio program & reconnect to selector/common sink') for protocol_it in range(self._get_num_protocols()): for proto_conn in proto_trees[protocol_it].getroot().findall('connection'): if (proto_conn.find('source_block_id').text == old_uhd_usrp_source_id[protocol_it]): proto_conn.find('source_block_id').text = self.common_selector_id proto_conn.find('source_key').text = str(protocol_it) if (proto_conn.find('sink_block_id').text == old_blocks_socket_pdu_id[protocol_it]): proto_conn.find('sink_block_id').text = self.common_blocks_socket_pdu_id new_root.append(proto_conn) self.log.info('Serialize combined grc file') new_tree = etree.ElementTree(new_root) new_tree.write(os.path.join(self.gr_radio_programs_path, self.gen_grc_fname)) fout = open(os.path.join(self.gr_radio_programs_path, self.gen_proto_dict_fname), 'w') fout.write(str(proto_usrp_src_dicts)) fout.close() fout = open(os.path.join(self.gr_radio_programs_path, self.gen_proto_fields_fname), 'w') fout.write(str(self.usrp_source_fields)) fout.close() return self.gen_grc_fname<|docstring|>generate meta radio program<|endoftext|>
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(response):\n >>> pprint(response)\n >>>\n >>> thread = api.list_admins(callback=callback_function)\n\n :param callback function: The callback function\n for asynchronous request. (optional)\n :param str filter: The filter to be used for query.\n :param list[str] ids: A comma-separated list of resource IDs. This cannot be provided together with the name or names query parameters.\n :param int limit: limit, should be >= 0\n :param list[str] names: A comma-separated list of resource names. This cannot be provided together with the ids query parameters.\n :param str sort: The way to order the results.\n :param int start: start\n :param str token: token\n :param bool expose: Display the unmasked API token. This is only valid when listing your own token.\n :return: AdminResponse\n If the method is called asynchronously,\n returns the request thread.\n ' kwargs['_return_http_data_only'] = True if kwargs.get('callback'): return self.list_admins_with_http_info(**kwargs) else: data = self.list_admins_with_http_info(**kwargs) return data
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_function) :param callback function: The callback function for asynchronous request. (optional) :param str filter: The filter to be used for query. :param list[str] ids: A comma-separated list of resource IDs. This cannot be provided together with the name or names query parameters. :param int limit: limit, should be >= 0 :param list[str] names: A comma-separated list of resource names. This cannot be provided together with the ids query parameters. :param str sort: The way to order the results. :param int start: start :param str token: token :param bool expose: Display the unmasked API token. This is only valid when listing your own token. :return: AdminResponse If the method is called asynchronously, returns the request thread.
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(response):\n >>> pprint(response)\n >>>\n >>> thread = api.list_admins(callback=callback_function)\n\n :param callback function: The callback function\n for asynchronous request. (optional)\n :param str filter: The filter to be used for query.\n :param list[str] ids: A comma-separated list of resource IDs. This cannot be provided together with the name or names query parameters.\n :param int limit: limit, should be >= 0\n :param list[str] names: A comma-separated list of resource names. This cannot be provided together with the ids query parameters.\n :param str sort: The way to order the results.\n :param int start: start\n :param str token: token\n :param bool expose: Display the unmasked API token. This is only valid when listing your own token.\n :return: AdminResponse\n If the method is called asynchronously,\n returns the request thread.\n ' kwargs['_return_http_data_only'] = True if kwargs.get('callback'): return self.list_admins_with_http_info(**kwargs) else: data = self.list_admins_with_http_info(**kwargs) return data
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(response):\n >>> pprint(response)\n >>>\n >>> thread = api.list_admins(callback=callback_function)\n\n :param callback function: The callback function\n for asynchronous request. (optional)\n :param str filter: The filter to be used for query.\n :param list[str] ids: A comma-separated list of resource IDs. This cannot be provided together with the name or names query parameters.\n :param int limit: limit, should be >= 0\n :param list[str] names: A comma-separated list of resource names. This cannot be provided together with the ids query parameters.\n :param str sort: The way to order the results.\n :param int start: start\n :param str token: token\n :param bool expose: Display the unmasked API token. This is only valid when listing your own token.\n :return: AdminResponse\n If the method is called asynchronously,\n returns the request thread.\n ' kwargs['_return_http_data_only'] = True if kwargs.get('callback'): return self.list_admins_with_http_info(**kwargs) else: data = self.list_admins_with_http_info(**kwargs) return data<|docstring|>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_function) :param callback function: The callback function for asynchronous request. (optional) :param str filter: The filter to be used for query. :param list[str] ids: A comma-separated list of resource IDs. This cannot be provided together with the name or names query parameters. :param int limit: limit, should be >= 0 :param list[str] names: A comma-separated list of resource names. This cannot be provided together with the ids query parameters. :param str sort: The way to order the results. :param int start: start :param str token: token :param bool expose: Display the unmasked API token. This is only valid when listing your own token. :return: AdminResponse If the method is called asynchronously, returns the request thread.<|endoftext|>
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 callback_function(response):\n >>> pprint(response)\n >>>\n >>> thread = api.list_admins_with_http_info(callback=callback_function)\n\n :param callback function: The callback function\n for asynchronous request. (optional)\n :param str filter: The filter to be used for query.\n :param list[str] ids: A comma-separated list of resource IDs. This cannot be provided together with the name or names query parameters.\n :param int limit: limit, should be >= 0\n :param list[str] names: A comma-separated list of resource names. This cannot be provided together with the ids query parameters.\n :param str sort: The way to order the results.\n :param int start: start\n :param str token: token\n :param bool expose: Display the unmasked API token. This is only valid when listing your own token.\n :return: AdminResponse\n If the method is called asynchronously,\n returns the request thread.\n ' all_params = ['filter', 'ids', 'limit', 'names', 'sort', 'start', 'token', 'expose'] all_params.append('callback') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() for (key, val) in iteritems(params['kwargs']): if (key not in all_params): raise TypeError(("Got an unexpected keyword argument '%s' to method list_admins" % key)) params[key] = val del params['kwargs'] collection_formats = {} path_params = {} query_params = [] if ('filter' in params): query_params.append(('filter', params['filter'])) if ('ids' in params): query_params.append(('ids', params['ids'])) collection_formats['ids'] = 'csv' if ('limit' in params): query_params.append(('limit', params['limit'])) if ('names' in params): query_params.append(('names', params['names'])) collection_formats['names'] = 'csv' if ('sort' in params): query_params.append(('sort', params['sort'])) if ('start' in params): query_params.append(('start', params['start'])) if ('token' in params): query_params.append(('token', params['token'])) if ('expose' in params): query_params.append(('expose', params['expose'])) header_params = {} form_params = [] local_var_files = {} body_params = None header_params['Accept'] = self.api_client.select_header_accept(['application/json']) header_params['Content-Type'] = self.api_client.select_header_content_type(['application/json']) auth_settings = ['AuthTokenHeader'] return self.api_client.call_api('/1.9/admins', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='AdminResponse', auth_settings=auth_settings, callback=params.get('callback'), _return_http_data_only=params.get('_return_http_data_only'), _preload_content=params.get('_preload_content', True), _request_timeout=params.get('_request_timeout'), collection_formats=collection_formats)
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(callback=callback_function) :param callback function: The callback function for asynchronous request. (optional) :param str filter: The filter to be used for query. :param list[str] ids: A comma-separated list of resource IDs. This cannot be provided together with the name or names query parameters. :param int limit: limit, should be >= 0 :param list[str] names: A comma-separated list of resource names. This cannot be provided together with the ids query parameters. :param str sort: The way to order the results. :param int start: start :param str token: token :param bool expose: Display the unmasked API token. This is only valid when listing your own token. :return: AdminResponse If the method is called asynchronously, returns the request thread.
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 callback_function(response):\n >>> pprint(response)\n >>>\n >>> thread = api.list_admins_with_http_info(callback=callback_function)\n\n :param callback function: The callback function\n for asynchronous request. (optional)\n :param str filter: The filter to be used for query.\n :param list[str] ids: A comma-separated list of resource IDs. This cannot be provided together with the name or names query parameters.\n :param int limit: limit, should be >= 0\n :param list[str] names: A comma-separated list of resource names. This cannot be provided together with the ids query parameters.\n :param str sort: The way to order the results.\n :param int start: start\n :param str token: token\n :param bool expose: Display the unmasked API token. This is only valid when listing your own token.\n :return: AdminResponse\n If the method is called asynchronously,\n returns the request thread.\n ' all_params = ['filter', 'ids', 'limit', 'names', 'sort', 'start', 'token', 'expose'] all_params.append('callback') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() for (key, val) in iteritems(params['kwargs']): if (key not in all_params): raise TypeError(("Got an unexpected keyword argument '%s' to method list_admins" % key)) params[key] = val del params['kwargs'] collection_formats = {} path_params = {} query_params = [] if ('filter' in params): query_params.append(('filter', params['filter'])) if ('ids' in params): query_params.append(('ids', params['ids'])) collection_formats['ids'] = 'csv' if ('limit' in params): query_params.append(('limit', params['limit'])) if ('names' in params): query_params.append(('names', params['names'])) collection_formats['names'] = 'csv' if ('sort' in params): query_params.append(('sort', params['sort'])) if ('start' in params): query_params.append(('start', params['start'])) if ('token' in params): query_params.append(('token', params['token'])) if ('expose' in params): query_params.append(('expose', params['expose'])) header_params = {} form_params = [] local_var_files = {} body_params = None header_params['Accept'] = self.api_client.select_header_accept(['application/json']) header_params['Content-Type'] = self.api_client.select_header_content_type(['application/json']) auth_settings = ['AuthTokenHeader'] return self.api_client.call_api('/1.9/admins', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='AdminResponse', auth_settings=auth_settings, callback=params.get('callback'), _return_http_data_only=params.get('_return_http_data_only'), _preload_content=params.get('_preload_content', True), _request_timeout=params.get('_request_timeout'), collection_formats=collection_formats)
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 callback_function(response):\n >>> pprint(response)\n >>>\n >>> thread = api.list_admins_with_http_info(callback=callback_function)\n\n :param callback function: The callback function\n for asynchronous request. (optional)\n :param str filter: The filter to be used for query.\n :param list[str] ids: A comma-separated list of resource IDs. This cannot be provided together with the name or names query parameters.\n :param int limit: limit, should be >= 0\n :param list[str] names: A comma-separated list of resource names. This cannot be provided together with the ids query parameters.\n :param str sort: The way to order the results.\n :param int start: start\n :param str token: token\n :param bool expose: Display the unmasked API token. This is only valid when listing your own token.\n :return: AdminResponse\n If the method is called asynchronously,\n returns the request thread.\n ' all_params = ['filter', 'ids', 'limit', 'names', 'sort', 'start', 'token', 'expose'] all_params.append('callback') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() for (key, val) in iteritems(params['kwargs']): if (key not in all_params): raise TypeError(("Got an unexpected keyword argument '%s' to method list_admins" % key)) params[key] = val del params['kwargs'] collection_formats = {} path_params = {} query_params = [] if ('filter' in params): query_params.append(('filter', params['filter'])) if ('ids' in params): query_params.append(('ids', params['ids'])) collection_formats['ids'] = 'csv' if ('limit' in params): query_params.append(('limit', params['limit'])) if ('names' in params): query_params.append(('names', params['names'])) collection_formats['names'] = 'csv' if ('sort' in params): query_params.append(('sort', params['sort'])) if ('start' in params): query_params.append(('start', params['start'])) if ('token' in params): query_params.append(('token', params['token'])) if ('expose' in params): query_params.append(('expose', params['expose'])) header_params = {} form_params = [] local_var_files = {} body_params = None header_params['Accept'] = self.api_client.select_header_accept(['application/json']) header_params['Content-Type'] = self.api_client.select_header_content_type(['application/json']) auth_settings = ['AuthTokenHeader'] return self.api_client.call_api('/1.9/admins', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='AdminResponse', auth_settings=auth_settings, callback=params.get('callback'), _return_http_data_only=params.get('_return_http_data_only'), _preload_content=params.get('_preload_content', True), _request_timeout=params.get('_request_timeout'), collection_formats=collection_formats)<|docstring|>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(callback=callback_function) :param callback function: The callback function for asynchronous request. (optional) :param str filter: The filter to be used for query. :param list[str] ids: A comma-separated list of resource IDs. This cannot be provided together with the name or names query parameters. :param int limit: limit, should be >= 0 :param list[str] names: A comma-separated list of resource names. This cannot be provided together with the ids query parameters. :param str sort: The way to order the results. :param int start: start :param str token: token :param bool expose: Display the unmasked API token. This is only valid when listing your own token. :return: AdminResponse If the method is called asynchronously, returns the request thread.<|endoftext|>
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 callback_function(response):\n >>> pprint(response)\n >>>\n >>> thread = api.update_admins(admin, callback=callback_function)\n\n :param callback function: The callback function\n for asynchronous request. (optional)\n :param Admin admin: (required)\n :param list[str] ids: A comma-separated list of resource IDs. This cannot be provided together with the name or names query parameters.\n :param list[str] names: A comma-separated list of resource names. This cannot be provided together with the ids query parameters.\n :return: AdminResponse\n If the method is called asynchronously,\n returns the request thread.\n ' kwargs['_return_http_data_only'] = True if kwargs.get('callback'): return self.update_admins_with_http_info(admin, **kwargs) else: data = self.update_admins_with_http_info(admin, **kwargs) return data
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, callback=callback_function) :param callback function: The callback function for asynchronous request. (optional) :param Admin admin: (required) :param list[str] ids: A comma-separated list of resource IDs. This cannot be provided together with the name or names query parameters. :param list[str] names: A comma-separated list of resource names. This cannot be provided together with the ids query parameters. :return: AdminResponse If the method is called asynchronously, returns the request thread.
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 callback_function(response):\n >>> pprint(response)\n >>>\n >>> thread = api.update_admins(admin, callback=callback_function)\n\n :param callback function: The callback function\n for asynchronous request. (optional)\n :param Admin admin: (required)\n :param list[str] ids: A comma-separated list of resource IDs. This cannot be provided together with the name or names query parameters.\n :param list[str] names: A comma-separated list of resource names. This cannot be provided together with the ids query parameters.\n :return: AdminResponse\n If the method is called asynchronously,\n returns the request thread.\n ' kwargs['_return_http_data_only'] = True if kwargs.get('callback'): return self.update_admins_with_http_info(admin, **kwargs) else: data = self.update_admins_with_http_info(admin, **kwargs) return data
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 callback_function(response):\n >>> pprint(response)\n >>>\n >>> thread = api.update_admins(admin, callback=callback_function)\n\n :param callback function: The callback function\n for asynchronous request. (optional)\n :param Admin admin: (required)\n :param list[str] ids: A comma-separated list of resource IDs. This cannot be provided together with the name or names query parameters.\n :param list[str] names: A comma-separated list of resource names. This cannot be provided together with the ids query parameters.\n :return: AdminResponse\n If the method is called asynchronously,\n returns the request thread.\n ' kwargs['_return_http_data_only'] = True if kwargs.get('callback'): return self.update_admins_with_http_info(admin, **kwargs) else: data = self.update_admins_with_http_info(admin, **kwargs) return data<|docstring|>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, callback=callback_function) :param callback function: The callback function for asynchronous request. (optional) :param Admin admin: (required) :param list[str] ids: A comma-separated list of resource IDs. This cannot be provided together with the name or names query parameters. :param list[str] names: A comma-separated list of resource names. This cannot be provided together with the ids query parameters. :return: AdminResponse If the method is called asynchronously, returns the request thread.<|endoftext|>
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 >>> def callback_function(response):\n >>> pprint(response)\n >>>\n >>> thread = api.update_admins_with_http_info(admin, callback=callback_function)\n\n :param callback function: The callback function\n for asynchronous request. (optional)\n :param Admin admin: (required)\n :param list[str] ids: A comma-separated list of resource IDs. This cannot be provided together with the name or names query parameters.\n :param list[str] names: A comma-separated list of resource names. This cannot be provided together with the ids query parameters.\n :return: AdminResponse\n If the method is called asynchronously,\n returns the request thread.\n ' all_params = ['admin', 'ids', 'names'] all_params.append('callback') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() for (key, val) in iteritems(params['kwargs']): if (key not in all_params): raise TypeError(("Got an unexpected keyword argument '%s' to method update_admins" % key)) params[key] = val del params['kwargs'] if (('admin' not in params) or (params['admin'] is None)): raise ValueError('Missing the required parameter `admin` when calling `update_admins`') collection_formats = {} path_params = {} query_params = [] if ('ids' in params): query_params.append(('ids', params['ids'])) collection_formats['ids'] = 'csv' if ('names' in params): query_params.append(('names', params['names'])) collection_formats['names'] = 'csv' header_params = {} form_params = [] local_var_files = {} body_params = None if ('admin' in params): body_params = params['admin'] header_params['Accept'] = self.api_client.select_header_accept(['application/json']) header_params['Content-Type'] = self.api_client.select_header_content_type(['application/json']) auth_settings = ['AuthTokenHeader'] return self.api_client.call_api('/1.9/admins', 'PATCH', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='AdminResponse', auth_settings=auth_settings, callback=params.get('callback'), _return_http_data_only=params.get('_return_http_data_only'), _preload_content=params.get('_preload_content', True), _request_timeout=params.get('_request_timeout'), collection_formats=collection_formats)
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_http_info(admin, callback=callback_function) :param callback function: The callback function for asynchronous request. (optional) :param Admin admin: (required) :param list[str] ids: A comma-separated list of resource IDs. This cannot be provided together with the name or names query parameters. :param list[str] names: A comma-separated list of resource names. This cannot be provided together with the ids query parameters. :return: AdminResponse If the method is called asynchronously, returns the request thread.
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 callback_function(response):\n >>> pprint(response)\n >>>\n >>> thread = api.update_admins_with_http_info(admin, callback=callback_function)\n\n :param callback function: The callback function\n for asynchronous request. (optional)\n :param Admin admin: (required)\n :param list[str] ids: A comma-separated list of resource IDs. This cannot be provided together with the name or names query parameters.\n :param list[str] names: A comma-separated list of resource names. This cannot be provided together with the ids query parameters.\n :return: AdminResponse\n If the method is called asynchronously,\n returns the request thread.\n ' all_params = ['admin', 'ids', 'names'] all_params.append('callback') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() for (key, val) in iteritems(params['kwargs']): if (key not in all_params): raise TypeError(("Got an unexpected keyword argument '%s' to method update_admins" % key)) params[key] = val del params['kwargs'] if (('admin' not in params) or (params['admin'] is None)): raise ValueError('Missing the required parameter `admin` when calling `update_admins`') collection_formats = {} path_params = {} query_params = [] if ('ids' in params): query_params.append(('ids', params['ids'])) collection_formats['ids'] = 'csv' if ('names' in params): query_params.append(('names', params['names'])) collection_formats['names'] = 'csv' header_params = {} form_params = [] local_var_files = {} body_params = None if ('admin' in params): body_params = params['admin'] header_params['Accept'] = self.api_client.select_header_accept(['application/json']) header_params['Content-Type'] = self.api_client.select_header_content_type(['application/json']) auth_settings = ['AuthTokenHeader'] return self.api_client.call_api('/1.9/admins', 'PATCH', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='AdminResponse', auth_settings=auth_settings, callback=params.get('callback'), _return_http_data_only=params.get('_return_http_data_only'), _preload_content=params.get('_preload_content', True), _request_timeout=params.get('_request_timeout'), collection_formats=collection_formats)
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 callback_function(response):\n >>> pprint(response)\n >>>\n >>> thread = api.update_admins_with_http_info(admin, callback=callback_function)\n\n :param callback function: The callback function\n for asynchronous request. (optional)\n :param Admin admin: (required)\n :param list[str] ids: A comma-separated list of resource IDs. This cannot be provided together with the name or names query parameters.\n :param list[str] names: A comma-separated list of resource names. This cannot be provided together with the ids query parameters.\n :return: AdminResponse\n If the method is called asynchronously,\n returns the request thread.\n ' all_params = ['admin', 'ids', 'names'] all_params.append('callback') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() for (key, val) in iteritems(params['kwargs']): if (key not in all_params): raise TypeError(("Got an unexpected keyword argument '%s' to method update_admins" % key)) params[key] = val del params['kwargs'] if (('admin' not in params) or (params['admin'] is None)): raise ValueError('Missing the required parameter `admin` when calling `update_admins`') collection_formats = {} path_params = {} query_params = [] if ('ids' in params): query_params.append(('ids', params['ids'])) collection_formats['ids'] = 'csv' if ('names' in params): query_params.append(('names', params['names'])) collection_formats['names'] = 'csv' header_params = {} form_params = [] local_var_files = {} body_params = None if ('admin' in params): body_params = params['admin'] header_params['Accept'] = self.api_client.select_header_accept(['application/json']) header_params['Content-Type'] = self.api_client.select_header_content_type(['application/json']) auth_settings = ['AuthTokenHeader'] return self.api_client.call_api('/1.9/admins', 'PATCH', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='AdminResponse', auth_settings=auth_settings, callback=params.get('callback'), _return_http_data_only=params.get('_return_http_data_only'), _preload_content=params.get('_preload_content', True), _request_timeout=params.get('_request_timeout'), collection_formats=collection_formats)<|docstring|>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_http_info(admin, callback=callback_function) :param callback function: The callback function for asynchronous request. (optional) :param Admin admin: (required) :param list[str] ids: A comma-separated list of resource IDs. This cannot be provided together with the name or names query parameters. :param list[str] names: A comma-separated list of resource names. This cannot be provided together with the ids query parameters. :return: AdminResponse If the method is called asynchronously, returns the request thread.<|endoftext|>
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_from, nodes_to) in og.items(): for node_to in nodes_to: if (node_to[0] in ig): ig[node_to[0]].append(node_from) else: ig[node_to[0]] = [node_from] return ig
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_from, nodes_to) in og.items(): for node_to in nodes_to: if (node_to[0] in ig): ig[node_to[0]].append(node_from) else: ig[node_to[0]] = [node_from] return ig
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_from, nodes_to) in og.items(): for node_to in nodes_to: if (node_to[0] in ig): ig[node_to[0]].append(node_from) else: ig[node_to[0]] = [node_from] return ig<|docstring|>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.<|endoftext|>
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: n = in_set.popleft() sorted_nodes.append(n) if (n not in graph): print('Your graph is missing node', n) children = graph[n] for child in children: child_id = child[0] ig[child_id].remove(n) if (not ig[child_id]): in_set.append(child_id) print('sorting done') return sorted_nodes
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: n = in_set.popleft() sorted_nodes.append(n) if (n not in graph): print('Your graph is missing node', n) children = graph[n] for child in children: child_id = child[0] ig[child_id].remove(n) if (not ig[child_id]): in_set.append(child_id) print('sorting done') return sorted_nodes
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: n = in_set.popleft() sorted_nodes.append(n) if (n not in graph): print('Your graph is missing node', n) children = graph[n] for child in children: child_id = child[0] ig[child_id].remove(n) if (not ig[child_id]): in_set.append(child_id) print('sorting done') return sorted_nodes<|docstring|>Summary Args: graph (TYPE): Description start_node (TYPE): Description Returns: TYPE: Description<|endoftext|>
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 Returns:\n list(int): shortest path\n ' N = len(S) if (N > len(graph)): print('ERROR: More sorted nodes than in the graph') if (N < len(graph)): print('ERROR: Less sorted nodes than in the graph') dist = dict() p = dict() for (node_id, children) in graph.items(): dist[node_id] = math.inf p[node_id] = None dist[S[0]] = 0 for el in S: u = el children = graph[u] for child in children: v = child[0] w = child[1] if (dist[v] > (dist[u] + w)): dist[v] = (dist[u] + w) p[v] = u path = [] par_id = S[(- 1)] path.append(par_id) while par_id: par_id = p[par_id] path.append(par_id) return path
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 Returns:\n list(int): shortest path\n ' N = len(S) if (N > len(graph)): print('ERROR: More sorted nodes than in the graph') if (N < len(graph)): print('ERROR: Less sorted nodes than in the graph') dist = dict() p = dict() for (node_id, children) in graph.items(): dist[node_id] = math.inf p[node_id] = None dist[S[0]] = 0 for el in S: u = el children = graph[u] for child in children: v = child[0] w = child[1] if (dist[v] > (dist[u] + w)): dist[v] = (dist[u] + w) p[v] = u path = [] par_id = S[(- 1)] path.append(par_id) while par_id: par_id = p[par_id] path.append(par_id) return path
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 Returns:\n list(int): shortest path\n ' N = len(S) if (N > len(graph)): print('ERROR: More sorted nodes than in the graph') if (N < len(graph)): print('ERROR: Less sorted nodes than in the graph') dist = dict() p = dict() for (node_id, children) in graph.items(): dist[node_id] = math.inf p[node_id] = None dist[S[0]] = 0 for el in S: u = el children = graph[u] for child in children: v = child[0] w = child[1] if (dist[v] > (dist[u] + w)): dist[v] = (dist[u] + w) p[v] = u path = [] par_id = S[(- 1)] path.append(par_id) while par_id: par_id = p[par_id] path.append(par_id) return path<|docstring|>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<|endoftext|>
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'.format(func[0]))
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]))<|docstring|>test func dostrings<|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|>
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.assertIsNotNone(HBNBCommand.do_show.__doc__) self.assertIsNotNone(HBNBCommand.do_destroy.__doc__) self.assertIsNotNone(HBNBCommand.do_all.__doc__) self.assertIsNotNone(HBNBCommand.do_update.__doc__) self.assertIsNotNone(HBNBCommand.default.__doc__)
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(HBNBCommand.do_show.__doc__) self.assertIsNotNone(HBNBCommand.do_destroy.__doc__) self.assertIsNotNone(HBNBCommand.do_all.__doc__) self.assertIsNotNone(HBNBCommand.do_update.__doc__) self.assertIsNotNone(HBNBCommand.default.__doc__)
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(HBNBCommand.do_show.__doc__) self.assertIsNotNone(HBNBCommand.do_destroy.__doc__) self.assertIsNotNone(HBNBCommand.do_all.__doc__) self.assertIsNotNone(HBNBCommand.do_update.__doc__) self.assertIsNotNone(HBNBCommand.default.__doc__)<|docstring|>testing docstings<|endoftext|>
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.assertEqual("** class doesn't exist **\n", f.getvalue()) with patch('sys.stdout', new=StringIO()) as f: HBNBCommand().onecmd('create BaseModel') HBNBCommand().onecmd('create User') with patch('sys.stdout', new=StringIO()) as f: HBNBCommand().onecmd('all User') self.assertEqual('[[User]', f.getvalue()[:7]) with patch('sys.stdout', new=StringIO()) as f: HBNBCommand().onecmd('create BaseModel') self.assertRegex(f.getvalue(), '^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$') with patch('sys.stdout', new=StringIO()) as f: HBNBCommand().onecmd('create User') self.assertRegex(f.getvalue(), '^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$')
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("** class doesn't exist **\n", f.getvalue()) with patch('sys.stdout', new=StringIO()) as f: HBNBCommand().onecmd('create BaseModel') HBNBCommand().onecmd('create User') with patch('sys.stdout', new=StringIO()) as f: HBNBCommand().onecmd('all User') self.assertEqual('[[User]', f.getvalue()[:7]) with patch('sys.stdout', new=StringIO()) as f: HBNBCommand().onecmd('create BaseModel') self.assertRegex(f.getvalue(), '^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$') with patch('sys.stdout', new=StringIO()) as f: HBNBCommand().onecmd('create User') self.assertRegex(f.getvalue(), '^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$')
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("** class doesn't exist **\n", f.getvalue()) with patch('sys.stdout', new=StringIO()) as f: HBNBCommand().onecmd('create BaseModel') HBNBCommand().onecmd('create User') with patch('sys.stdout', new=StringIO()) as f: HBNBCommand().onecmd('all User') self.assertEqual('[[User]', f.getvalue()[:7]) with patch('sys.stdout', new=StringIO()) as f: HBNBCommand().onecmd('create BaseModel') self.assertRegex(f.getvalue(), '^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$') with patch('sys.stdout', new=StringIO()) as f: HBNBCommand().onecmd('create User') self.assertRegex(f.getvalue(), '^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$')<|docstring|>testing creat input<|endoftext|>
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 self.assertRaises(TrainingProgress.DoesNotExist): self.progress.refresh_from_db()
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.DoesNotExist): self.progress.refresh_from_db()
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.DoesNotExist): self.progress.refresh_from_db()<|docstring|>Regression test for issue #1085.<|endoftext|>
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('%(message)s') sh.setFormatter(sh_formatter) logging.getLogger().addHandler(sh)
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_formatter) logging.getLogger().addHandler(sh)
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_formatter) logging.getLogger().addHandler(sh)<|docstring|>log setup along with log file and level.<|endoftext|>
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.\n demo : :class:`bool`, optional\n Whether to simulate a connection to the equipment by opening\n a connection in demo mode.\n ' if (record.connection.backend == Backend.PyVISA): pop_or_get = record.connection.properties.pop else: pop_or_get = record.connection.properties.get clear = pop_or_get('clear', False) reset = pop_or_get('reset', False) super(DMM, self).__init__(app, record, demo=demo) self.ignore_attributes(['fetched', 'config_changed']) if clear: self.clear() if reset: self.reset()
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 connection in demo mode.
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.\n demo : :class:`bool`, optional\n Whether to simulate a connection to the equipment by opening\n a connection in demo mode.\n ' if (record.connection.backend == Backend.PyVISA): pop_or_get = record.connection.properties.pop else: pop_or_get = record.connection.properties.get clear = pop_or_get('clear', False) reset = pop_or_get('reset', False) super(DMM, self).__init__(app, record, demo=demo) self.ignore_attributes(['fetched', 'config_changed']) if clear: self.clear() if reset: self.reset()
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.\n demo : :class:`bool`, optional\n Whether to simulate a connection to the equipment by opening\n a connection in demo mode.\n ' if (record.connection.backend == Backend.PyVISA): pop_or_get = record.connection.properties.pop else: pop_or_get = record.connection.properties.get clear = pop_or_get('clear', False) reset = pop_or_get('reset', False) super(DMM, self).__init__(app, record, demo=demo) self.ignore_attributes(['fetched', 'config_changed']) if clear: self.clear() if reset: self.reset()<|docstring|>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 connection in demo mode.<|endoftext|>
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.\n :class:`float`\n The standard deviation.\n " if initiate: self.logger.info(f'send INIT to {self.alias!r}') self.connection.write('INIT') samples = self.connection.query('FETCH?').rstrip() return self._average_and_emit(samples)
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.\n :class:`float`\n The standard deviation.\n " if initiate: self.logger.info(f'send INIT to {self.alias!r}') self.connection.write('INIT') samples = self.connection.query('FETCH?').rstrip() return self._average_and_emit(samples)
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.\n :class:`float`\n The standard deviation.\n " if initiate: self.logger.info(f'send INIT to {self.alias!r}') self.connection.write('INIT') samples = self.connection.query('FETCH?').rstrip() return self._average_and_emit(samples)<|docstring|>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.<|endoftext|>
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 will be automatically retrieved.\n line_freq : :class:`float`, optional\n The line frequency, in Hz.\n\n Returns\n -------\n :class:`float`\n The number of seconds.\n ' if (not info): info = self.info() duration = (((info['nsamples'] * info['trigger_count']) * info['nplc']) / line_freq) if (info['auto_zero'] == 'ON'): duration *= 2.0 return duration
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:`float` The number of seconds.
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 will be automatically retrieved.\n line_freq : :class:`float`, optional\n The line frequency, in Hz.\n\n Returns\n -------\n :class:`float`\n The number of seconds.\n ' if (not info): info = self.info() duration = (((info['nsamples'] * info['trigger_count']) * info['nplc']) / line_freq) if (info['auto_zero'] == 'ON'): duration *= 2.0 return duration
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 will be automatically retrieved.\n line_freq : :class:`float`, optional\n The line frequency, in Hz.\n\n Returns\n -------\n :class:`float`\n The number of seconds.\n ' if (not info): info = self.info() duration = (((info['nsamples'] * info['trigger_count']) * info['nplc']) / line_freq) if (info['auto_zero'] == 'ON'): duration *= 2.0 return duration<|docstring|>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:`float` The number of seconds.<|endoftext|>
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. Can be any key in :attr:`.DMM.FUNCTIONS` (case insensitive).\n range : :class:`float` or :class:`str`, optional\n The range to use for the measurement. Can be any key in :attr:`.DMM.RANGES`.\n nsamples : :class:`int`, optional\n The number of samples to acquire after receiving a trigger.\n nplc : :class:`float`, optional\n The number of power line cycles.\n auto_zero : :class:`bool` or :class:`str`, optional\n The auto-zero mode. Can be any key in :attr:`.DMM.AUTO_ZEROS`.\n trigger : :class:`str`, optional\n The trigger mode. Can be any key in :attr:`.DMM.TRIGGERS` (case insensitive).\n edge : :class:`str` or :attr:`.DMM.TriggerEdge`, optional\n The edge to trigger on. Can be any key in :attr:`.DMM.EDGES` (case insensitive).\n ntriggers : :class:`int`, optional\n The number of triggers that are accepted by the digital multimeter\n before returning to the *wait-for-trigger* state.\n delay : :class:`float` or :data:`None`, optional\n The trigger delay in seconds. If :data:`None` then enables the auto-delay\n feature where the digital multimeter automatically determines the delay\n based on the function, range and NPLC.\n\n Returns\n -------\n :class:`dict`\n The result of :meth:`.info` after the settings have been written.\n ' raise NotImplementedError
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 : :class:`int`, optional The number of samples to acquire after receiving a trigger. nplc : :class:`float`, optional The number of power line cycles. auto_zero : :class:`bool` or :class:`str`, optional The auto-zero mode. Can be any key in :attr:`.DMM.AUTO_ZEROS`. trigger : :class:`str`, optional The trigger mode. Can be any key in :attr:`.DMM.TRIGGERS` (case insensitive). edge : :class:`str` or :attr:`.DMM.TriggerEdge`, optional The edge to trigger on. Can be any key in :attr:`.DMM.EDGES` (case insensitive). ntriggers : :class:`int`, optional The number of triggers that are accepted by the digital multimeter before returning to the *wait-for-trigger* state. delay : :class:`float` or :data:`None`, optional The trigger delay in seconds. If :data:`None` then enables the auto-delay feature where the digital multimeter automatically determines the delay based on the function, range and NPLC. Returns ------- :class:`dict` The result of :meth:`.info` after the settings have been written.
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. Can be any key in :attr:`.DMM.FUNCTIONS` (case insensitive).\n range : :class:`float` or :class:`str`, optional\n The range to use for the measurement. Can be any key in :attr:`.DMM.RANGES`.\n nsamples : :class:`int`, optional\n The number of samples to acquire after receiving a trigger.\n nplc : :class:`float`, optional\n The number of power line cycles.\n auto_zero : :class:`bool` or :class:`str`, optional\n The auto-zero mode. Can be any key in :attr:`.DMM.AUTO_ZEROS`.\n trigger : :class:`str`, optional\n The trigger mode. Can be any key in :attr:`.DMM.TRIGGERS` (case insensitive).\n edge : :class:`str` or :attr:`.DMM.TriggerEdge`, optional\n The edge to trigger on. Can be any key in :attr:`.DMM.EDGES` (case insensitive).\n ntriggers : :class:`int`, optional\n The number of triggers that are accepted by the digital multimeter\n before returning to the *wait-for-trigger* state.\n delay : :class:`float` or :data:`None`, optional\n The trigger delay in seconds. If :data:`None` then enables the auto-delay\n feature where the digital multimeter automatically determines the delay\n based on the function, range and NPLC.\n\n Returns\n -------\n :class:`dict`\n The result of :meth:`.info` after the settings have been written.\n ' raise NotImplementedError
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. Can be any key in :attr:`.DMM.FUNCTIONS` (case insensitive).\n range : :class:`float` or :class:`str`, optional\n The range to use for the measurement. Can be any key in :attr:`.DMM.RANGES`.\n nsamples : :class:`int`, optional\n The number of samples to acquire after receiving a trigger.\n nplc : :class:`float`, optional\n The number of power line cycles.\n auto_zero : :class:`bool` or :class:`str`, optional\n The auto-zero mode. Can be any key in :attr:`.DMM.AUTO_ZEROS`.\n trigger : :class:`str`, optional\n The trigger mode. Can be any key in :attr:`.DMM.TRIGGERS` (case insensitive).\n edge : :class:`str` or :attr:`.DMM.TriggerEdge`, optional\n The edge to trigger on. Can be any key in :attr:`.DMM.EDGES` (case insensitive).\n ntriggers : :class:`int`, optional\n The number of triggers that are accepted by the digital multimeter\n before returning to the *wait-for-trigger* state.\n delay : :class:`float` or :data:`None`, optional\n The trigger delay in seconds. If :data:`None` then enables the auto-delay\n feature where the digital multimeter automatically determines the delay\n based on the function, range and NPLC.\n\n Returns\n -------\n :class:`dict`\n The result of :meth:`.info` after the settings have been written.\n ' raise NotImplementedError<|docstring|>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 : :class:`int`, optional The number of samples to acquire after receiving a trigger. nplc : :class:`float`, optional The number of power line cycles. auto_zero : :class:`bool` or :class:`str`, optional The auto-zero mode. Can be any key in :attr:`.DMM.AUTO_ZEROS`. trigger : :class:`str`, optional The trigger mode. Can be any key in :attr:`.DMM.TRIGGERS` (case insensitive). edge : :class:`str` or :attr:`.DMM.TriggerEdge`, optional The edge to trigger on. Can be any key in :attr:`.DMM.EDGES` (case insensitive). ntriggers : :class:`int`, optional The number of triggers that are accepted by the digital multimeter before returning to the *wait-for-trigger* state. delay : :class:`float` or :data:`None`, optional The trigger delay in seconds. If :data:`None` then enables the auto-delay feature where the digital multimeter automatically determines the delay based on the function, range and NPLC. Returns ------- :class:`dict` The result of :meth:`.info` after the settings have been written.<|endoftext|>
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'{command!r} did not return "1"'
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'{command!r} did not return "1"'
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'{command!r} did not return "1"'<|docstring|>Appends ``'*OPC?'`` to the end of a command. The *OPC? command guarantees that command's that were previously sent to the device have completed.<|endoftext|>
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 The average value.\n :class:`float`\n The standard deviation.\n ' if isinstance(samples, str): samples = samples.split(',') samples = [float(val) for val in samples] self.logger.info(f'fetch {self.alias!r} {samples}') (ave, stdev) = ave_std(np.asarray(samples)) if (abs(ave) > 1e+30): (ave, stdev) = (np.NaN, np.NaN) self.fetched.emit(ave, stdev) self.emit_notification(ave, stdev) return (ave, stdev)
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 The average value.\n :class:`float`\n The standard deviation.\n ' if isinstance(samples, str): samples = samples.split(',') samples = [float(val) for val in samples] self.logger.info(f'fetch {self.alias!r} {samples}') (ave, stdev) = ave_std(np.asarray(samples)) if (abs(ave) > 1e+30): (ave, stdev) = (np.NaN, np.NaN) self.fetched.emit(ave, stdev) self.emit_notification(ave, stdev) return (ave, stdev)
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 The average value.\n :class:`float`\n The standard deviation.\n ' if isinstance(samples, str): samples = samples.split(',') samples = [float(val) for val in samples] self.logger.info(f'fetch {self.alias!r} {samples}') (ave, stdev) = ave_std(np.asarray(samples)) if (abs(ave) > 1e+30): (ave, stdev) = (np.NaN, np.NaN) self.fetched.emit(ave, stdev) self.emit_notification(ave, stdev) return (ave, stdev)<|docstring|>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.<|endoftext|>
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(): classic.init_app(cls.app)
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|>Instantiate an app for use with a SQLite database.<|endoftext|>
cb9cfc17065933bd686e8019d37bd0b6b84cb1c04f9d3fa1786b9a2f3add5c56
@mock.patch(f'{core.__name__}.StreamPublisher', mock.MagicMock()) def setUp(self): 'Create, and complete the submission.' self.submitter = domain.agent.User(1234, email='[email protected]', forename='Jane', surname='User', endorsements=['cs.DL', 'cs.IR']) self.defaults = {'creator': self.submitter} with self.app.app_context(): classic.create_all() self.title = 'the best title' self.doi = '10.01234/56789' (self.submission, self.events) = save(domain.event.CreateSubmission(**self.defaults), domain.event.ConfirmContactInformation(**self.defaults), domain.event.ConfirmAuthorship(**self.defaults), domain.event.ConfirmPolicy(**self.defaults), domain.event.SetTitle(title=self.title, **self.defaults), domain.event.SetLicense(license_uri=CCO, license_name='CC0 1.0', **self.defaults), domain.event.SetPrimaryClassification(category='cs.DL', **self.defaults), domain.event.SetUploadPackage(checksum='a9s9k342900ks03330029', source_format=domain.submission.SubmissionContent.Format('tex'), identifier=123, uncompressed_size=593992, compressed_size=593992, **self.defaults), domain.event.SetAbstract(abstract=('Very abstract ' * 20), **self.defaults), domain.event.SetComments(comments=('Fine indeed ' * 10), **self.defaults), domain.event.SetJournalReference(journal_ref='Foo 1992', **self.defaults), domain.event.SetDOI(doi=self.doi, **self.defaults), domain.event.SetAuthors(authors_display='Robert Paulson (FC)', **self.defaults), domain.event.FinalizeSubmission(**self.defaults)) with self.app.app_context(): session = classic.current_session() db_row = session.query(classic.models.Submission).first() db_row.status = classic.models.Submission.ON_HOLD session.add(db_row) session.commit()
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='[email protected]', forename='Jane', surname='User', endorsements=['cs.DL', 'cs.IR']) self.defaults = {'creator': self.submitter} with self.app.app_context(): classic.create_all() self.title = 'the best title' self.doi = '10.01234/56789' (self.submission, self.events) = save(domain.event.CreateSubmission(**self.defaults), domain.event.ConfirmContactInformation(**self.defaults), domain.event.ConfirmAuthorship(**self.defaults), domain.event.ConfirmPolicy(**self.defaults), domain.event.SetTitle(title=self.title, **self.defaults), domain.event.SetLicense(license_uri=CCO, license_name='CC0 1.0', **self.defaults), domain.event.SetPrimaryClassification(category='cs.DL', **self.defaults), domain.event.SetUploadPackage(checksum='a9s9k342900ks03330029', source_format=domain.submission.SubmissionContent.Format('tex'), identifier=123, uncompressed_size=593992, compressed_size=593992, **self.defaults), domain.event.SetAbstract(abstract=('Very abstract ' * 20), **self.defaults), domain.event.SetComments(comments=('Fine indeed ' * 10), **self.defaults), domain.event.SetJournalReference(journal_ref='Foo 1992', **self.defaults), domain.event.SetDOI(doi=self.doi, **self.defaults), domain.event.SetAuthors(authors_display='Robert Paulson (FC)', **self.defaults), domain.event.FinalizeSubmission(**self.defaults)) with self.app.app_context(): session = classic.current_session() db_row = session.query(classic.models.Submission).first() db_row.status = classic.models.Submission.ON_HOLD session.add(db_row) session.commit()
@mock.patch(f'{core.__name__}.StreamPublisher', mock.MagicMock()) def setUp(self): self.submitter = domain.agent.User(1234, email='[email protected]', forename='Jane', surname='User', endorsements=['cs.DL', 'cs.IR']) self.defaults = {'creator': self.submitter} with self.app.app_context(): classic.create_all() self.title = 'the best title' self.doi = '10.01234/56789' (self.submission, self.events) = save(domain.event.CreateSubmission(**self.defaults), domain.event.ConfirmContactInformation(**self.defaults), domain.event.ConfirmAuthorship(**self.defaults), domain.event.ConfirmPolicy(**self.defaults), domain.event.SetTitle(title=self.title, **self.defaults), domain.event.SetLicense(license_uri=CCO, license_name='CC0 1.0', **self.defaults), domain.event.SetPrimaryClassification(category='cs.DL', **self.defaults), domain.event.SetUploadPackage(checksum='a9s9k342900ks03330029', source_format=domain.submission.SubmissionContent.Format('tex'), identifier=123, uncompressed_size=593992, compressed_size=593992, **self.defaults), domain.event.SetAbstract(abstract=('Very abstract ' * 20), **self.defaults), domain.event.SetComments(comments=('Fine indeed ' * 10), **self.defaults), domain.event.SetJournalReference(journal_ref='Foo 1992', **self.defaults), domain.event.SetDOI(doi=self.doi, **self.defaults), domain.event.SetAuthors(authors_display='Robert Paulson (FC)', **self.defaults), domain.event.FinalizeSubmission(**self.defaults)) with self.app.app_context(): session = classic.current_session() db_row = session.query(classic.models.Submission).first() db_row.status = classic.models.Submission.ON_HOLD session.add(db_row) session.commit()<|docstring|>Create, and complete the submission.<|endoftext|>
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') self.assertEqual(len(submission.versions), 0, 'There are no announced versions') with self.app.app_context(): submission = load_fast(self.submission.submission_id) self.assertTrue(submission.is_on_hold, 'The submission is on hold') self.assertEqual(len(submission.versions), 0, 'There are no announced versions') with self.app.app_context(): session = classic.current_session() db_rows = session.query(classic.models.Submission).all() self.assertEqual(len(db_rows), 1, 'There is one row in the submission table') row = db_rows[0] self.assertEqual(row.type, classic.models.Submission.NEW_SUBMISSION, "The classic submission has type 'new'") self.assertEqual(row.status, classic.models.Submission.ON_HOLD, 'The classic submission is in the ON_HOLD state')
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(submission.versions), 0, 'There are no announced versions') with self.app.app_context(): submission = load_fast(self.submission.submission_id) self.assertTrue(submission.is_on_hold, 'The submission is on hold') self.assertEqual(len(submission.versions), 0, 'There are no announced versions') with self.app.app_context(): session = classic.current_session() db_rows = session.query(classic.models.Submission).all() self.assertEqual(len(db_rows), 1, 'There is one row in the submission table') row = db_rows[0] self.assertEqual(row.type, classic.models.Submission.NEW_SUBMISSION, "The classic submission has type 'new'") self.assertEqual(row.status, classic.models.Submission.ON_HOLD, 'The classic submission is in the ON_HOLD state')
@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(submission.versions), 0, 'There are no announced versions') with self.app.app_context(): submission = load_fast(self.submission.submission_id) self.assertTrue(submission.is_on_hold, 'The submission is on hold') self.assertEqual(len(submission.versions), 0, 'There are no announced versions') with self.app.app_context(): session = classic.current_session() db_rows = session.query(classic.models.Submission).all() self.assertEqual(len(db_rows), 1, 'There is one row in the submission table') row = db_rows[0] self.assertEqual(row.type, classic.models.Submission.NEW_SUBMISSION, "The classic submission has type 'new'") self.assertEqual(row.status, classic.models.Submission.ON_HOLD, 'The classic submission is in the ON_HOLD state')<|docstring|>The submission is now on hold.<|endoftext|>
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 results in an exception.'): save(domain.event.CreateSubmissionVersion(**self.defaults), submission_id=self.submission.submission_id) self.test_is_in_submitted_state()
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.CreateSubmissionVersion(**self.defaults), submission_id=self.submission.submission_id) self.test_is_in_submitted_state()
@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.CreateSubmissionVersion(**self.defaults), submission_id=self.submission.submission_id) self.test_is_in_submitted_state()<|docstring|>The submission cannot be replaced: it hasn't yet been announced.<|endoftext|>
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 in an exception.'): save(domain.event.RequestWithdrawal(reason='the best reason', **self.defaults), submission_id=self.submission.submission_id) self.test_is_in_submitted_state()
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(reason='the best reason', **self.defaults), submission_id=self.submission.submission_id) self.test_is_in_submitted_state()
@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(reason='the best reason', **self.defaults), submission_id=self.submission.submission_id) self.test_is_in_submitted_state()<|docstring|>The submission cannot be withdrawn: it hasn't yet been announced.<|endoftext|>
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.'): save(domain.event.SetTitle(title='A better title', **self.defaults), submission_id=self.submission.submission_id) with self.assertRaises(exceptions.InvalidEvent, msg='Creating a SetDOI command results in an exception.'): save(domain.event.SetDOI(doi='10.1000/182', **self.defaults), submission_id=self.submission.submission_id) self.test_is_in_submitted_state()
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', **self.defaults), submission_id=self.submission.submission_id) with self.assertRaises(exceptions.InvalidEvent, msg='Creating a SetDOI command results in an exception.'): save(domain.event.SetDOI(doi='10.1000/182', **self.defaults), submission_id=self.submission.submission_id) self.test_is_in_submitted_state()
@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', **self.defaults), submission_id=self.submission.submission_id) with self.assertRaises(exceptions.InvalidEvent, msg='Creating a SetDOI command results in an exception.'): save(domain.event.SetDOI(doi='10.1000/182', **self.defaults), submission_id=self.submission.submission_id) self.test_is_in_submitted_state()<|docstring|>The submission cannot be changed: it hasn't yet been announced.<|endoftext|>
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(): (submission, events) = load(self.submission.submission_id) self.assertEqual(submission.status, domain.submission.Submission.WORKING, 'The submission is in the working state') self.assertEqual(len(submission.versions), 0, 'There are no announced versions') with self.app.app_context(): submission = load_fast(self.submission.submission_id) self.assertEqual(submission.status, domain.submission.Submission.WORKING, 'The submission is in the working state') self.assertEqual(len(submission.versions), 0, 'There are no announced versions') with self.app.app_context(): session = classic.current_session() db_rows = session.query(classic.models.Submission).all() self.assertEqual(len(db_rows), 1, 'There is one row in the submission table') row = db_rows[0] self.assertEqual(row.type, classic.models.Submission.NEW_SUBMISSION, "The classic submission has type 'new'") self.assertEqual(row.status, classic.models.Submission.NOT_SUBMITTED, 'The classic submission is in the not submitted state') self.assertEqual(row.sticky_status, classic.models.Submission.ON_HOLD, 'The hold is preserved as a sticky status')
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(self.submission.submission_id) self.assertEqual(submission.status, domain.submission.Submission.WORKING, 'The submission is in the working state') self.assertEqual(len(submission.versions), 0, 'There are no announced versions') with self.app.app_context(): submission = load_fast(self.submission.submission_id) self.assertEqual(submission.status, domain.submission.Submission.WORKING, 'The submission is in the working state') self.assertEqual(len(submission.versions), 0, 'There are no announced versions') with self.app.app_context(): session = classic.current_session() db_rows = session.query(classic.models.Submission).all() self.assertEqual(len(db_rows), 1, 'There is one row in the submission table') row = db_rows[0] self.assertEqual(row.type, classic.models.Submission.NEW_SUBMISSION, "The classic submission has type 'new'") self.assertEqual(row.status, classic.models.Submission.NOT_SUBMITTED, 'The classic submission is in the not submitted state') self.assertEqual(row.sticky_status, classic.models.Submission.ON_HOLD, 'The hold is preserved as a sticky status')
@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(self.submission.submission_id) self.assertEqual(submission.status, domain.submission.Submission.WORKING, 'The submission is in the working state') self.assertEqual(len(submission.versions), 0, 'There are no announced versions') with self.app.app_context(): submission = load_fast(self.submission.submission_id) self.assertEqual(submission.status, domain.submission.Submission.WORKING, 'The submission is in the working state') self.assertEqual(len(submission.versions), 0, 'There are no announced versions') with self.app.app_context(): session = classic.current_session() db_rows = session.query(classic.models.Submission).all() self.assertEqual(len(db_rows), 1, 'There is one row in the submission table') row = db_rows[0] self.assertEqual(row.type, classic.models.Submission.NEW_SUBMISSION, "The classic submission has type 'new'") self.assertEqual(row.status, classic.models.Submission.NOT_SUBMITTED, 'The classic submission is in the not submitted state') self.assertEqual(row.sticky_status, classic.models.Submission.ON_HOLD, 'The hold is preserved as a sticky status')<|docstring|>The submission can be unfinalized.<|endoftext|>
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.shape), N))) (U, S, V) = linalg.svd(h) hx = [((- U[(:, n)]) * np.sqrt(S[n])) for n in range(N)] hy = [((- V[(n, :)]) * np.sqrt(S[n])) for n in range(N)] return np.array(list(zip(hx, hy)))
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.shape), N))) (U, S, V) = linalg.svd(h) hx = [((- U[(:, n)]) * np.sqrt(S[n])) for n in range(N)] hy = [((- V[(n, :)]) * np.sqrt(S[n])) for n in range(N)] return np.array(list(zip(hx, hy)))
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.shape), N))) (U, S, V) = linalg.svd(h) hx = [((- U[(:, n)]) * np.sqrt(S[n])) for n in range(N)] hy = [((- V[(n, :)]) * np.sqrt(S[n])) for n in range(N)] return np.array(list(zip(hx, hy)))<|docstring|>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])<|endoftext|>