code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
formula = variable.get_formula(period)
if formula is None:
return None
if self.trace:
parameters_at = self.trace_parameters_at_instant
else:
parameters_at = self.tax_benefit_system.get_parameters_at_instant
if formula.__code__.co_ar... | def _run_formula(self, variable, population, period) | Find the ``variable`` formula for the given ``period`` if it exists, and apply it to ``population``. | 4.719534 | 4.53387 | 1.04095 |
if variable.definition_period == periods.ETERNITY:
return # For variables which values are constant in time, all periods are accepted
if variable.definition_period == periods.MONTH and period.unit != periods.MONTH:
raise ValueError("Unable to compute variable '{0}' for... | def _check_period_consistency(self, period, variable) | Check that a period matches the variable definition_period | 3.566988 | 3.332418 | 1.07039 |
previous_periods = [_period for (_name, _period) in self.computation_stack if _name == variable.name]
self.computation_stack.append((variable.name, str(period)))
if str(period) in previous_periods:
raise CycleError("Circular definition detected on formula {}@{}".format(varia... | def _check_for_cycle(self, variable, period) | Raise an exception in the case of a circular definition, where evaluating a variable for
a given period loops around to evaluating the same variable/period pair. Also guards, as
a heuristic, against "quasicircles", where the evaluation of a variable at a period involves
the same variable at a di... | 5.119574 | 4.3459 | 1.178024 |
if period is not None and not isinstance(period, periods.Period):
period = periods.period(period)
return self.get_holder(variable_name).get_array(period) | def get_array(self, variable_name, period) | Return the value of ``variable_name`` for ``period``, if this value is alreay in the cache (if it has been set as an input or previously calculated).
Unlike :any:`calculate`, this method *does not* trigger calculations and *does not* use any formula. | 4.193646 | 4.819505 | 0.87014 |
result = dict(
total_nb_bytes = 0,
by_variable = {}
)
for entity in self.populations.values():
entity_memory_usage = entity.get_memory_usage(variables = variables)
result['total_nb_bytes'] += entity_memory_usage['total_nb_bytes']
... | def get_memory_usage(self, variables = None) | Get data about the virtual memory usage of the simulation | 2.624452 | 2.73519 | 0.959513 |
variable = self.tax_benefit_system.get_variable(variable_name, check_existence = True)
period = periods.period(period)
if ((variable.end is not None) and (period.start.date > variable.end)):
return
self.get_holder(variable_name).set_input(period, value) | def set_input(self, variable_name, period, value) | Set a variable's value for a given period
:param variable: the variable to be set
:param value: the input value for the variable
:param period: the period for which the value is setted
Example:
>>> from openfisca_country_template import CountryTaxBenefitSyst... | 6.545506 | 6.990523 | 0.93634 |
new = empty_clone(self)
new_dict = new.__dict__
for key, value in self.__dict__.items():
if key not in ('debug', 'trace', 'tracer'):
new_dict[key] = value
new.persons = self.persons.clone(new)
setattr(new, new.persons.entity.key, new.persons... | def clone(self, debug = False, trace = False) | Copy the simulation just enough to be able to run the copy without modifying the original simulation | 5.408191 | 5.04224 | 1.072577 |
array = holder._to_array(array)
period_size = period.size
period_unit = period.unit
if holder.variable.definition_period == MONTH:
cached_period_unit = periods.MONTH
elif holder.variable.definition_period == YEAR:
cached_period_unit = periods.YEAR
else:
raise Value... | def set_input_dispatch_by_period(holder, period, array) | This function can be declared as a ``set_input`` attribute of a variable.
In this case, the variable will accept inputs on larger periods that its definition period, and the value for the larger period will be applied to all its subperiods.
To read more about ``set_input`` attributes, check the `docum... | 5.063384 | 5.132115 | 0.986608 |
if not isinstance(array, np.ndarray):
array = np.array(array)
period_size = period.size
period_unit = period.unit
if holder.variable.definition_period == MONTH:
cached_period_unit = periods.MONTH
elif holder.variable.definition_period == YEAR:
cached_period_unit = perio... | def set_input_divide_by_period(holder, period, array) | This function can be declared as a ``set_input`` attribute of a variable.
In this case, the variable will accept inputs on larger periods that its definition period, and the value for the larger period will be divided between its subperiods.
To read more about ``set_input`` attributes, check the `docu... | 3.929582 | 3.756859 | 1.045975 |
new = empty_clone(self)
new_dict = new.__dict__
for key, value in self.__dict__.items():
if key not in ('population', 'formula', 'simulation'):
new_dict[key] = value
new_dict['population'] = population
new_dict['simulation'] = population.sim... | def clone(self, population) | Copy the holder just enough to be able to run a new simulation without modifying the original simulation. | 3.905843 | 3.556308 | 1.098286 |
self._memory_storage.delete(period)
if self._disk_storage:
self._disk_storage.delete(period) | def delete_arrays(self, period = None) | If ``period`` is ``None``, remove all known values of the variable.
If ``period`` is not ``None``, only remove all values for any period included in period (e.g. if period is "2017", values for "2017-01", "2017-07", etc. would be removed) | 5.882196 | 6.775712 | 0.86813 |
if self.variable.is_neutralized:
return self.default_array()
value = self._memory_storage.get(period)
if value is not None:
return value
if self._disk_storage:
return self._disk_storage.get(period) | def get_array(self, period) | Get the value of the variable for the given period.
If the value is not known, return ``None``. | 5.843446 | 5.638116 | 1.036418 |
usage = dict(
nb_cells_by_array = self.population.count,
dtype = self.variable.dtype,
)
usage.update(self._memory_storage.get_memory_usage())
if self.simulation.trace:
usage_stats = self.simulation.tracer.usage_stats[self.variable.name]... | def get_memory_usage(self) | Get data about the virtual memory usage of the holder.
:returns: Memory usage data
:rtype: dict
Example:
>>> holder.get_memory_usage()
>>> {
>>> 'nb_arrays': 12, # The holder contains the variable values for 12 different periods
... | 5.349366 | 3.964686 | 1.349253 |
return list(self._memory_storage.get_known_periods()) + list((
self._disk_storage.get_known_periods() if self._disk_storage else [])) | def get_known_periods(self) | Get the list of periods the variable value is known for. | 7.448284 | 5.991274 | 1.243189 |
period = periods.period(period)
if period.unit == ETERNITY and self.variable.definition_period != ETERNITY:
error_message = os.linesep.join([
'Unable to set a value for variable {0} for ETERNITY.',
'{0} is only defined for {1}s. Please adapt your inp... | def set_input(self, period, array) | Set a variable's value (``array``) for a given period (``period``)
:param array: the input value for the variable
:param period: the period at which the value is setted
Example :
>>> holder.set_input([12, 14], '2018-04')
>>> holder.get_array('2018-04')
... | 4.312027 | 4.074654 | 1.058256 |
parent_directory = os.path.abspath(os.path.join(directory, os.pardir))
if not os.path.isdir(parent_directory): # To deal with reforms
os.mkdir(parent_directory)
if not os.path.isdir(directory):
os.mkdir(directory)
if os.listdir(directory):
raise ValueError("Directory '{}' ... | def dump_simulation(simulation, directory) | Write simulation data to directory, so that it can be restored later. | 3.275902 | 3.244575 | 1.009655 |
simulation = Simulation(tax_benefit_system, tax_benefit_system.instantiate_entities())
entities_dump_dir = os.path.join(directory, "__entities__")
for population in simulation.populations.values():
if population.entity.is_person:
continue
person_count = _restore_entity(popu... | def restore_simulation(directory, tax_benefit_system, **kwargs) | Restore simulation from directory | 3.607428 | 3.591386 | 1.004467 |
for form in six.itervalues(forms):
if not form.is_valid():
return False
return True | def are_forms_valid(self, forms) | Check if all forms defined in `form_classes` are valid. | 3.038974 | 3.01503 | 1.007942 |
context = {}
if 'forms' not in kwargs:
context['forms'] = self.get_forms()
else:
context['forms'] = kwargs['forms']
return context | def get_context_data(self, **kwargs) | Add forms into the context dictionary. | 3.161291 | 2.558217 | 1.23574 |
kwargs = {}
for key in six.iterkeys(self.form_classes):
if self.request.method in ('POST', 'PUT'):
kwargs[key] = {
'data': self.request.POST,
'files': self.request.FILES,
}
else:
kwa... | def get_form_kwargs(self) | Build the keyword arguments required to instantiate the form. | 2.43088 | 2.211565 | 1.099167 |
initial = super(MultiFormView, self).get_initial()
for key in six.iterkeys(self.form_classes):
initial[key] = {}
return initial | def get_initial(self) | Returns a copy of `initial` with empty initial data dictionaries for each form. | 4.470978 | 2.926559 | 1.527725 |
forms = self.get_forms()
if self.are_forms_valid(forms):
return self.forms_valid(forms)
else:
return self.forms_invalid(forms) | def post(self, request, **kwargs) | Uses `are_forms_valid()` to call either `forms_valid()` or * `forms_invalid()`. | 2.726805 | 1.700599 | 1.603438 |
for form in six.itervalues(forms):
form.save()
return super(MultiModelFormView, self).forms_valid(forms) | def forms_valid(self, forms) | Calls `save()` on each form. | 4.100028 | 3.796421 | 1.079972 |
forms = {}
objects = self.get_objects()
initial = self.get_initial()
form_kwargs = self.get_form_kwargs()
for key, form_class in six.iteritems(self.form_classes):
forms[key] = form_class(instance=objects[key], initial=initial[key], **form_kwargs[key])
... | def get_forms(self) | Initializes the forms defined in `form_classes` with initial data from `get_initial()`,
kwargs from get_form_kwargs() and form instance object from `get_objects()`. | 2.590129 | 1.875725 | 1.380868 |
objects = {}
for key in six.iterkeys(self.form_classes):
objects[key] = None
return objects | def get_objects(self) | Returns dictionary with the instance objects for each form. Keys should match the
corresponding form. | 7.24137 | 4.450043 | 1.627258 |
ratio_total = sum(ratios)
divided_value = amount / ratio_total
values = []
for ratio in ratios:
value = divided_value * ratio
values.append(value)
# Now round the values, keeping track of the bits we cut off
rounded = [v.quantize(Decimal("0.01")) for v in values]
remain... | def ratio_split(amount, ratios) | Split in_value according to the ratios specified in `ratios`
This is special in that it ensures the returned values always sum to
in_value (i.e. we avoid losses or gains due to rounding errors). As a
result, this method returns a list of `Decimal` values with length equal
to that of `ratios`.
Exam... | 3.663036 | 3.893636 | 0.940775 |
reader = self._get_csv_reader()
headings = six.next(reader)
try:
examples = six.next(reader)
except StopIteration:
examples = []
found_fields = set()
for i, value in enumerate(headings):
if i >= 20:
break
... | def create_columns(self) | For each column in file create a TransactionCsvImportColumn | 3.627826 | 3.123989 | 1.16128 |
return StatementLine.objects.filter(
date=obj.date, amount=obj.amount, description=obj.description
).count() | def _get_num_similar_objects(self, obj) | Get any statement lines which would be considered a duplicate of obj | 8.900664 | 5.210718 | 1.708145 |
return len(list(filter(lambda r: row == r, self.dataset[:until]))) | def _get_num_similar_rows(self, row, until=None) | Get the number of rows similar to row which precede the index `until` | 8.182794 | 7.195442 | 1.137219 |
response = requests.get(
url="https://api.teller.io/accounts/{}/transactions".format(account_uuid),
headers={"Authorization": "Bearer {}".format(token)},
)
response.raise_for_status()
data = response.json()
statement_import = StatementImport.objects.create(
source="tell... | def do_import(token, account_uuid, bank_account, since=None) | Import data from teller.io
Returns the created StatementImport | 2.503397 | 2.341889 | 1.068965 |
balances = [account.balance(raw=True) for account in Account.objects.root_nodes()]
if sum(balances, Balance()) != 0:
raise exceptions.AccountingEquationViolationError(
"Account balances do not sum to zero. They sum to {}".format(sum(balances))
) | def validate_accounting_equation(cls) | Check that all accounts sum to 0 | 6.62928 | 5.574651 | 1.189183 |
return -1 if self.type in (Account.TYPES.asset, Account.TYPES.expense) else 1 | def sign(self) | Returns 1 if a credit should increase the value of the
account, or -1 if a credit should decrease the value of the
account.
This is based on the account type as is standard accounting practice.
The signs can be derrived from the following expanded form of the
accounting equation... | 11.640173 | 9.217738 | 1.262801 |
balances = [
account.simple_balance(as_of=as_of, raw=raw, leg_query=leg_query, **kwargs)
for account in self.get_descendants(include_self=True)
]
return sum(balances, Balance()) | def balance(self, as_of=None, raw=False, leg_query=None, **kwargs) | Get the balance for this account, including child accounts
Args:
as_of (Date): Only include transactions on or before this date
raw (bool): If true the returned balance should not have its sign
adjusted for display purposes.
kwargs (dict): Will be use... | 3.271827 | 3.77789 | 0.866046 |
legs = self.legs
if as_of:
legs = legs.filter(transaction__date__lte=as_of)
if leg_query or kwargs:
leg_query = leg_query or models.Q()
legs = legs.filter(leg_query, **kwargs)
return legs.sum_to_balance() * (1 if raw else self.sign) + self._... | def simple_balance(self, as_of=None, raw=False, leg_query=None, **kwargs) | Get the balance for this account, ignoring all child accounts
Args:
as_of (Date): Only include transactions on or before this date
raw (bool): If true the returned balance should not have its sign
adjusted for display purposes.
leg_query (models.Q): D... | 4.051908 | 3.751316 | 1.08013 |
if not isinstance(amount, Money):
raise TypeError("amount must be of type Money")
if to_account.sign == 1 and to_account.type != self.TYPES.trading:
# Transferring from two positive-signed accounts implies that
# the caller wants to reduce the first account ... | def transfer_to(self, to_account, amount, **transaction_kwargs) | Create a transaction which transfers amount to to_account
This is a shortcut utility method which simplifies the process of
transferring between accounts.
This method attempts to perform the transaction in an intuitive manner.
For example:
* Transferring income -> income wil... | 6.312053 | 5.923965 | 1.065511 |
result = self.values("amount_currency").annotate(total=models.Sum("amount"))
return Balance([Money(r["total"], r["amount_currency"]) for r in result]) | def sum_to_balance(self) | Sum the Legs of the QuerySet to get a `Balance`_ object | 9.019047 | 5.289071 | 1.705223 |
# TODO: Consider moving to annotation, particularly once we can count on Django 1.11's subquery support
transaction_date = self.transaction.date
return self.account.balance(
leg_query=(
models.Q(transaction__date__lt=transaction_date)
| (
... | def account_balance_after(self) | Get the balance of the account associated with this leg following the transaction | 6.87747 | 6.174884 | 1.113781 |
# TODO: Consider moving to annotation, particularly once we can count on Django 1.11's subquery support
transaction_date = self.transaction.date
return self.account.balance(
leg_query=(
models.Q(transaction__date__lt=transaction_date)
| (
... | def account_balance_before(self) | Get the balance of the account associated with this leg before the transaction | 6.806076 | 6.030135 | 1.128677 |
from_account = self.statement_import.bank_account
transaction = Transaction.objects.create()
Leg.objects.create(
transaction=transaction, account=from_account, amount=+(self.amount * -1)
)
Leg.objects.create(transaction=transaction, account=to_account, amoun... | def create_transaction(self, to_account) | Create a transaction for this statement amount and account, into to_account
This will also set this StatementLine's ``transaction`` attribute to the newly
created transaction.
Args:
to_account (Account): The account the transaction is into / out of.
Returns:
Tr... | 3.488601 | 3.745734 | 0.931353 |
if not self.is_supported(defaults.INTERNAL_CURRENCY):
logger.info('Tried to cache unsupported currency "{}". Ignoring.'.format(currency))
else:
cache.set(_cache_key(currency, date), str(rate), _cache_timeout(date)) | def cache_rate(self, currency, date, rate) | Cache a rate for future use | 6.339973 | 6.191514 | 1.023978 |
if str(currency) == defaults.INTERNAL_CURRENCY:
return Decimal(1)
cached = cache.get(_cache_key(currency, date))
if cached:
return Decimal(cached)
else:
# Expect self._get_rate() to implement caching
return Decimal(self._get_rate(... | def get_rate(self, currency, date) | Get the exchange rate for ``currency`` against ``_INTERNAL_CURRENCY``
If implementing your own backend, you should probably override :meth:`_get_rate()`
rather than this. | 5.339559 | 4.44827 | 1.200367 |
if str(money.currency) == str(to_currency):
return copy.copy(money)
return Money(
amount=money.amount
* self.rate(money.currency, to_currency, date or datetime.date.today()),
currency=to_currency,
) | def convert(self, money, to_currency, date=None) | Convert the given ``money`` to ``to_currency`` using exchange rate on ``date``
If ``date`` is omitted then the date given by ``money.date`` will be used. | 3.382687 | 3.53788 | 0.956134 |
return (1 / self.backend.get_rate(from_currency, date)) * self.backend.get_rate(
to_currency, date
) | def rate(self, from_currency, to_currency, date) | Get the exchange rate between the specified currencies | 4.039919 | 4.151794 | 0.973054 |
return [m.currency.code for m in self.monies() if m.amount] | def currencies(self) | Get all currencies with non-zero values | 11.613664 | 8.032403 | 1.445852 |
out = Money(currency=to_currency)
for money in self._money_obs:
out += converter.convert(money, to_currency)
return Balance([out]) | def normalise(self, to_currency) | Normalise this balance into a single currency
Args:
to_currency (str): Destination currency
Returns:
(Balance): A new balance object containing a single Money value in the specified currency | 11.221937 | 13.321078 | 0.84242 |
grace = getattr(settings, 'HITCOUNT_KEEP_HIT_ACTIVE', {'days': 7})
period = timezone.now() - timedelta(**grace)
return self.filter(created__gte=period).filter(*args, **kwargs) | def filter_active(self, *args, **kwargs) | Return only the 'active' hits.
How you count a hit/view will depend on personal choice: Should the
same user/visitor *ever* be counted twice? After a week, or a month,
or a year, should their view be counted again?
The defaulf is to consider a visitor's hit still 'active' if they
... | 6.68665 | 4.185881 | 1.59743 |
if not save_hitcount:
instance.hitcount.decrease() | def delete_hit_count_handler(sender, instance, save_hitcount=False, **kwargs) | Custom callback for the Hit.delete() method.
Hit.delete(): removes the hit from the associated HitCount object.
Hit.delete(save_hitcount=True): preserves the hit for the associated
HitCount object. | 6.239772 | 8.958432 | 0.696525 |
"Brutally deleting all entries for this model..."
MyModel = apps.get_model("blog", "Post")
MyModel.objects.all().delete() | def unload_fixture(apps, schema_editor) | Brutally deleting all entries for this model... | 10.390308 | 3.4233 | 3.035173 |
# if neither header contain a value, just use local loopback
ip_address = request.META.get('HTTP_X_FORWARDED_FOR',
request.META.get('REMOTE_ADDR', '127.0.0.1'))
if ip_address:
# make sure we have one and only one IP
try:
ip_address = IP_RE.... | def get_ip(request) | Retrieves the remote IP address from the request data. If the user is
behind a proxy, they may have a comma-separated list of IP addresses, so
we need to account for that. In such a case, only the first IP in the
list will be retrieved. Also, some hosts that use a proxy will put the
REMOTE_ADDR into ... | 3.530253 | 3.62898 | 0.972795 |
warnings.warn(
"hitcount.views._update_hit_count is deprecated. "
"Use hitcount.views.HitCountMixin.hit_count() instead.",
RemovedInHitCount13Warning
)
return HitCountMixin.hit_count(request, hitcount) | def _update_hit_count(request, hitcount) | Deprecated in 1.2. Use hitcount.views.Hit CountMixin.hit_count() instead. | 3.231615 | 2.437828 | 1.325612 |
warnings.warn(
"hitcount.views.update_hit_count_ajax is deprecated. "
"Use hitcount.views.HitCountJSONView instead.",
RemovedInHitCount13Warning
)
view = HitCountJSONView.as_view()
return view(request, *args, **kwargs) | def update_hit_count_ajax(request, *args, **kwargs) | Deprecated in 1.2. Use hitcount.views.HitCountJSONView instead. | 2.804015 | 2.059475 | 1.361519 |
UpdateHitCountResponse = namedtuple(
'UpdateHitCountResponse', 'hit_counted hit_message')
# as of Django 1.8.4 empty sessions are not being saved
# https://code.djangoproject.com/ticket/25489
if request.session.session_key is None:
request.session.save()... | def hit_count(self, request, hitcount) | Called with a HttpRequest and HitCount object it will return a
namedtuple:
UpdateHitCountResponse(hit_counted=Boolean, hit_message='Message').
`hit_counted` will be True if the hit was counted and False if it was
not. `'hit_message` will indicate by what means the Hit was either
... | 2.983228 | 2.907278 | 1.026124 |
error_to_raise = template.TemplateSyntaxError(
"'%(a)s' requires a valid individual model variable "
"in the form of '%(a)s for [model_obj]'.\n"
"Got: %(b)s" % {'a': tag_name, 'b': obj_variable}
)
try:
obj = obj_variable.resolve(context)
except template.VariableDoes... | def get_hit_count_from_obj_variable(context, obj_variable, tag_name) | Helper function to return a HitCount for a given template object variable.
Raises TemplateSyntaxError if the passed object variable cannot be parsed. | 3.181222 | 3.053303 | 1.041895 |
period = {}
if arg[0] == '"' and arg[-1] == '"':
opt = arg[1:-1] # remove quotes
else:
opt = arg
for o in opt.split(","):
key, value = o.split("=")
period[str(key)] = int(value)
return period | def return_period_from_string(arg) | Takes a string such as "days=1,seconds=30" and strips the quotes
and returns a dictionary with the key/value pairs | 3.034732 | 2.692044 | 1.127297 |
params = self._translate(self._options)
self._resp = self._r_session.get(self._url, params=params, stream=True)
self._resp.raise_for_status()
self._lines = self._resp.iter_lines(self._chunk_size) | def _start(self) | Starts streaming the feed using the provided session and feed options. | 3.98192 | 3.374889 | 1.179867 |
translation = dict()
for key, val in iteritems_(options):
self._validate(key, val, feed_arg_types(self._source))
try:
if isinstance(val, STRTYPE):
translation[key] = val
elif not isinstance(val, NONETYPE):
... | def _translate(self, options) | Perform translation of feed options passed in as keyword
arguments to CouchDB/Cloudant equivalent. | 5.848848 | 5.083802 | 1.150487 |
if key in arg_types:
arg_type = arg_types[key]
else:
if ANY_ARG not in arg_types:
raise CloudantArgumentError(116, key)
arg_type = arg_types[ANY_ARG]
if arg_type == ANY_TYPE:
return
if (not isinstance(val, arg_type... | def _validate(self, key, val, arg_types) | Ensures that the key and the value are valid arguments to be used with
the feed. | 2.995178 | 2.9105 | 1.029094 |
while True:
if not self._resp:
self._start()
if self._stop:
raise StopIteration
skip, data = self._process_data(next_(self._lines))
if not skip:
break
return data | def next(self) | Handles the iteration by pulling the next line out of the stream,
attempting to convert the response to JSON if necessary.
:returns: Data representing what was seen in the feed | 7.765347 | 8.948165 | 0.867815 |
skip = False
if self._raw_data:
return skip, line
line = unicode_(line)
if not line:
if (self._options.get('heartbeat', False) and
self._options.get('feed') in ('continuous', 'longpoll') and
not self._last_seq):
... | def _process_data(self, line) | Validates and processes the line passed in and converts it to a
Python object if necessary. | 4.023092 | 4.043548 | 0.994941 |
if key == 'feed' and val != 'continuous':
raise CloudantArgumentError(121, val)
super(InfiniteFeed, self)._validate(key, val, arg_types) | def _validate(self, key, val, arg_types) | Ensures that the key and the value are valid arguments to be used with
the feed. | 8.656448 | 7.614131 | 1.136892 |
while True:
if self._source == 'CouchDB':
raise CloudantFeedException(101)
if self._last_seq:
self._options.update({'since': self._last_seq})
self._resp = None
self._last_seq = None
if not self._resp:
... | def next(self) | Handles the iteration by pulling the next line out of the stream and
converting the response to JSON.
:returns: Data representing what was seen in the feed | 6.485205 | 6.580914 | 0.985457 |
if self._features is None:
metadata = self.metadata()
if "features" in metadata:
self._features = metadata["features"]
else:
self._features = []
return self._features | def features(self) | lazy fetch and cache features | 2.835981 | 2.337445 | 1.213283 |
if self.r_session:
self.session_logout()
if self.admin_party:
self._use_iam = False
self.r_session = ClientSession(
timeout=self._timeout
)
elif self._use_basic_auth:
self._use_iam = False
self.r_se... | def connect(self) | Starts up an authentication session for the client using cookie
authentication if necessary. | 3.199691 | 3.125883 | 1.023612 |
if self.r_session:
self.session_logout()
self.r_session = None
self.clear() | def disconnect(self) | Ends a client authentication session, performs a logout and a clean up. | 10.048057 | 6.959862 | 1.443715 |
self.change_credentials(user=user, auth_token=passwd) | def session_login(self, user=None, passwd=None) | Performs a session login by posting the auth information
to the _session endpoint.
:param str user: Username used to connect to server.
:param str auth_token: Authentication token used to connect to server. | 12.96558 | 12.543313 | 1.033665 |
self.r_session.set_credentials(user, auth_token)
self.r_session.login() | def change_credentials(self, user=None, auth_token=None) | Change login credentials.
:param str user: Username used to connect to server.
:param str auth_token: Authentication token used to connect to server. | 5.276984 | 5.968721 | 0.884106 |
url = '/'.join((self.server_url, '_all_dbs'))
resp = self.r_session.get(url)
resp.raise_for_status()
return response_to_json_dict(resp) | def all_dbs(self) | Retrieves a list of all database names for the current client.
:returns: List of database names for the client | 3.84959 | 4.505674 | 0.854387 |
new_db = self._DATABASE_CLASS(self, dbname, partitioned=partitioned)
try:
new_db.create(kwargs.get('throw_on_exists', False))
except CloudantDatabaseException as ex:
if ex.status_code == 412:
raise CloudantClientException(412, dbname)
supe... | def create_database(self, dbname, partitioned=False, **kwargs) | Creates a new database on the remote server with the name provided
and adds the new database object to the client's locally cached
dictionary before returning it to the caller. The method will
optionally throw a CloudantClientException if the database
exists remotely.
:param st... | 3.728062 | 3.502403 | 1.06443 |
db = self._DATABASE_CLASS(self, dbname)
if not db.exists():
raise CloudantClientException(404, dbname)
db.delete()
if dbname in list(self.keys()):
super(CouchDB, self).__delitem__(dbname) | def delete_database(self, dbname) | Removes the named database remotely and locally. The method will throw
a CloudantClientException if the database does not exist.
:param str dbname: Name of the database to delete. | 4.783059 | 4.641901 | 1.030409 |
resp = self.r_session.get(self.server_url)
resp.raise_for_status()
return response_to_json_dict(resp) | def metadata(self) | Retrieves the remote server metadata dictionary.
:returns: Dictionary containing server metadata details | 5.710254 | 5.011628 | 1.139401 |
if not remote:
return list(super(CouchDB, self).keys())
return self.all_dbs() | def keys(self, remote=False) | Returns the database names for this client. Default is
to return only the locally cached database names, specify
``remote=True`` to make a remote request to include all databases.
:param bool remote: Dictates whether the list of locally cached
database names are returned or a remote... | 7.381831 | 9.434666 | 0.782416 |
if not remote:
return super(CouchDB, self).get(key, default)
db = self._DATABASE_CLASS(self, key)
if db.exists():
super(CouchDB, self).__setitem__(key, db)
return db
return default | def get(self, key, default=None, remote=False) | Overrides dictionary get behavior to retrieve database objects with
support for returning a default. If remote=True then a remote
request is made to retrieve the database from the remote server,
otherwise the client's locally cached database object is returned.
:param str key: Database... | 3.746464 | 4.529299 | 0.827162 |
err = False
if year is None and month is None:
resp = self.r_session.get(endpoint)
else:
try:
if int(year) > 0 and int(month) in range(1, 13):
resp = self.r_session.get(
'/'.join((endpoint, str(int(year)... | def _usage_endpoint(self, endpoint, year=None, month=None) | Common helper for getting usage and billing reports with
optional year and month URL elements.
:param str endpoint: Cloudant usage endpoint.
:param int year: Year to query against. Optional parameter.
Defaults to None. If used, it must be accompanied by ``month``.
:param i... | 2.854637 | 2.761357 | 1.033781 |
endpoint = '/'.join((self.server_url, '_api', 'v2', 'bill'))
return self._usage_endpoint(endpoint, year, month) | def bill(self, year=None, month=None) | Retrieves Cloudant billing data, optionally for a given year and month.
:param int year: Year to query against, for example 2014.
Optional parameter. Defaults to None. If used, it must be
accompanied by ``month``.
:param int month: Month to query against that must be an intege... | 7.999214 | 8.617381 | 0.928265 |
endpoint = '/'.join((
self.server_url, '_api', 'v2', 'usage', 'data_volume'))
return self._usage_endpoint(endpoint, year, month) | def volume_usage(self, year=None, month=None) | Retrieves Cloudant volume usage data, optionally for a given
year and month.
:param int year: Year to query against, for example 2014.
Optional parameter. Defaults to None. If used, it must be
accompanied by ``month``.
:param int month: Month to query against that must... | 7.290697 | 8.232539 | 0.885595 |
endpoint = '/'.join((
self.server_url, '_api', 'v2', 'usage', 'requests'))
return self._usage_endpoint(endpoint, year, month) | def requests_usage(self, year=None, month=None) | Retrieves Cloudant requests usage data, optionally for a given
year and month.
:param int year: Year to query against, for example 2014.
Optional parameter. Defaults to None. If used, it must be
accompanied by ``month``.
:param int month: Month to query against that mu... | 6.29994 | 7.282393 | 0.865092 |
endpoint = '/'.join((
self.server_url, '_api', 'v2', 'user', 'shared_databases'))
resp = self.r_session.get(endpoint)
resp.raise_for_status()
data = response_to_json_dict(resp)
return data.get('shared_databases', []) | def shared_databases(self) | Retrieves a list containing the names of databases shared
with this account.
:returns: List of database names | 4.172422 | 4.305021 | 0.969199 |
endpoint = '/'.join((self.server_url, '_api', 'v2', 'api_keys'))
resp = self.r_session.post(endpoint)
resp.raise_for_status()
return response_to_json_dict(resp) | def generate_api_key(self) | Creates and returns a new API Key/pass pair.
:returns: API key/pass pair in JSON format | 4.697658 | 4.785566 | 0.981631 |
endpoint = '/'.join((
self.server_url, '_api', 'v2', 'user', 'config', 'cors'))
resp = self.r_session.get(endpoint)
resp.raise_for_status()
return response_to_json_dict(resp) | def cors_configuration(self) | Retrieves the current CORS configuration.
:returns: CORS data in JSON format | 5.049613 | 5.01861 | 1.006178 |
return self.update_cors_configuration(
enable_cors=False,
allow_credentials=False,
origins=[],
overwrite_origins=True
) | def disable_cors(self) | Switches CORS off.
:returns: CORS status in JSON format | 7.453164 | 9.662965 | 0.771312 |
if origins is None:
origins = []
cors_config = {
'enable_cors': enable_cors,
'allow_credentials': allow_credentials,
'origins': origins
}
if overwrite_origins:
return self._write_cors_configuration(cors_config)
... | def update_cors_configuration(
self,
enable_cors=True,
allow_credentials=True,
origins=None,
overwrite_origins=False) | Merges existing CORS configuration with updated values.
:param bool enable_cors: Enables/disables CORS. Defaults to True.
:param bool allow_credentials: Allows authentication credentials.
Defaults to True.
:param list origins: List of allowed CORS origin(s). Special cases are
... | 1.865351 | 2.071929 | 0.900297 |
endpoint = '/'.join((
self.server_url, '_api', 'v2', 'user', 'config', 'cors'))
resp = self.r_session.put(
endpoint,
data=json.dumps(config, cls=self.encoder),
headers={'Content-Type': 'application/json'}
)
resp.raise_for_status()
... | def _write_cors_configuration(self, config) | Overwrites the entire CORS config with the values updated in
update_cors_configuration.
:param dict config: Dictionary containing the updated CORS
configuration.
:returns: CORS configuration update status in JSON format | 3.614901 | 3.804459 | 0.950175 |
service_name = service_name or 'cloudantNoSQLDB' # default service
try:
service = CloudFoundryService(vcap_services,
instance_name=instance_name,
service_name=service_name)
except CloudantEx... | def bluemix(cls, vcap_services, instance_name=None, service_name=None, **kwargs) | Create a Cloudant session using a VCAP_SERVICES environment variable.
:param vcap_services: VCAP_SERVICES environment variable
:type vcap_services: dict or str
:param str instance_name: Optional Bluemix instance name. Only required
if multiple Cloudant instances are available.
... | 3.054297 | 3.329583 | 0.917321 |
return cls(None,
api_key,
account=account_name,
auto_renew=kwargs.get('auto_renew', True),
use_iam=True,
**kwargs) | def iam(cls, account_name, api_key, **kwargs) | Create a Cloudant client that uses IAM authentication.
:param account_name: Cloudant account name.
:param api_key: IAM authentication API key. | 4.372282 | 5.027872 | 0.869609 |
if self._partition_key:
base_url = self._database.database_partition_url(
self._partition_key)
else:
base_url = self._database.database_url
return base_url + '/_find' | def url(self) | Constructs and returns the Query URL.
:returns: Query URL | 5.572506 | 5.826323 | 0.956436 |
resp = self._r_session.get('/'.join([self._scheduler, 'docs', '_replicator', doc_id]))
resp.raise_for_status()
return response_to_json_dict(resp) | def get_doc(self, doc_id) | Get replication document state for a given replication document ID. | 6.90869 | 5.408696 | 1.27733 |
params = dict()
if limit is not None:
params["limit"] = limit
if skip is not None:
params["skip"] = skip
resp = self._r_session.get('/'.join([self._scheduler, 'jobs']), params=params)
resp.raise_for_status()
return response_to_json_dict(re... | def list_jobs(self, limit=None, skip=None) | Lists replication jobs. Includes replications created via
/_replicate endpoint as well as those created from replication
documents. Does not include replications which have completed
or have failed to start because replication documents were
malformed. Each job description will include s... | 3.009472 | 3.505907 | 0.8584 |
return '/'.join((
self._database.database_partition_url(partition_key),
'_design',
url_quote_plus(self['_id'][8:], safe='')
)) | def document_partition_url(self, partition_key) | Retrieve the design document partition URL.
:param str partition_key: Partition key.
:return: Design document partition URL.
:rtype: str | 10.543917 | 10.865597 | 0.970395 |
if self.get_view(view_name) is not None:
raise CloudantArgumentError(107, view_name)
if self.get('language', None) == QUERY_LANGUAGE:
raise CloudantDesignDocumentException(101)
view = View(self, view_name, map_func, reduce_func, **kwargs)
self.views.__se... | def add_view(self, view_name, map_func, reduce_func=None, **kwargs) | Appends a MapReduce view to the locally cached DesignDocument View
dictionary. To create a JSON query index use
:func:`~cloudant.database.CloudantDatabase.create_query_index` instead.
A CloudantException is raised if an attempt to add a QueryIndexView
(JSON query index) using this metho... | 4.179354 | 4.303431 | 0.971168 |
if self.get_show_function(show_name) is not None:
raise CloudantArgumentError(110, show_name)
self.shows.__setitem__(show_name, show_func) | def add_show_function(self, show_name, show_func) | Appends a show function to the locally cached DesignDocument
shows dictionary.
:param show_name: Name used to identify the show function.
:param show_func: Javascript show function. | 4.500899 | 5.089806 | 0.884297 |
view = self.get_view(view_name)
if view is None:
raise CloudantArgumentError(111, view_name)
if isinstance(view, QueryIndexView):
raise CloudantDesignDocumentException(102)
view = View(self, view_name, map_func, reduce_func, **kwargs)
self.views.... | def update_view(self, view_name, map_func, reduce_func=None, **kwargs) | Modifies/overwrites an existing MapReduce view definition in the
locally cached DesignDocument View dictionary. To update a JSON
query index use
:func:`~cloudant.database.CloudantDatabase.delete_query_index` followed
by :func:`~cloudant.database.CloudantDatabase.create_query_index`
... | 3.900041 | 3.528565 | 1.105277 |
search = self.get_index(index_name)
if search is None:
raise CloudantArgumentError(112, index_name)
if analyzer is not None:
search = {'index': codify(search_func), 'analyzer': analyzer}
else:
search = {'index': codify(search_func)}
s... | def update_search_index(self, index_name, search_func, analyzer=None) | Modifies/overwrites an existing Cloudant search index in the
locally cached DesignDocument indexes dictionary.
:param str index_name: Name used to identify the search index.
:param str search_func: Javascript search index function.
:param analyzer: Optional analyzer for this search inde... | 4.169258 | 4.001568 | 1.041906 |
if self.get_list_function(list_name) is None:
raise CloudantArgumentError(113, list_name)
self.lists.__setitem__(list_name, codify(list_func)) | def update_list_function(self, list_name, list_func) | Modifies/overwrites an existing list function in the
locally cached DesignDocument indexes dictionary.
:param str list_name: Name used to identify the list function.
:param str list_func: Javascript list function. | 6.395953 | 6.746141 | 0.948091 |
if self.get_show_function(show_name) is None:
raise CloudantArgumentError(114, show_name)
self.shows.__setitem__(show_name, show_func) | def update_show_function(self, show_name, show_func) | Modifies/overwrites an existing show function in the
locally cached DesignDocument shows dictionary.
:param show_name: Name used to identify the show function.
:param show_func: Javascript show function. | 5.30912 | 5.757956 | 0.922049 |
view = self.get_view(view_name)
if view is None:
return
if isinstance(view, QueryIndexView):
raise CloudantDesignDocumentException(103)
self.views.__delitem__(view_name) | def delete_view(self, view_name) | Removes an existing MapReduce view definition from the locally cached
DesignDocument View dictionary. To delete a JSON query index
use :func:`~cloudant.database.CloudantDatabase.delete_query_index`
instead. A CloudantException is raised if an attempt to delete a
QueryIndexView (JSON qu... | 5.90935 | 4.215044 | 1.401967 |
index = self.get_index(index_name)
if index is None:
return
self.indexes.__delitem__(index_name) | def delete_index(self, index_name) | Removes an existing index in the locally cached DesignDocument
indexes dictionary.
:param str index_name: Name used to identify the index. | 3.51881 | 4.24882 | 0.828185 |
if self.get_show_function(show_name) is None:
return
self.shows.__delitem__(show_name) | def delete_show_function(self, show_name) | Removes an existing show function in the locally cached DesignDocument
shows dictionary.
:param show_name: Name used to identify the list. | 4.233796 | 5.14014 | 0.823673 |
super(DesignDocument, self).fetch()
if self.views:
for view_name, view_def in iteritems_(self.get('views', dict())):
if self.get('language', None) != QUERY_LANGUAGE:
self['views'][view_name] = View(
self,
... | def fetch(self) | Retrieves the remote design document content and populates the locally
cached DesignDocument dictionary. View content is stored either as
View or QueryIndexView objects which are extensions of the ``dict``
type. All other design document data are stored directly as
``dict`` types. | 3.760549 | 2.977308 | 1.26307 |
if self.views:
if self.get('language', None) != QUERY_LANGUAGE:
for view_name, view in self.iterviews():
if isinstance(view, QueryIndexView):
raise CloudantDesignDocumentException(104, view_name)
else:
f... | def save(self) | Saves changes made to the locally cached DesignDocument object's data
structures to the remote database. If the design document does not
exist remotely then it is created in the remote database. If the object
does exist remotely then the design document is updated remotely. In
either ... | 4.014184 | 3.618502 | 1.109349 |
ddoc_info = self.r_session.get(
'/'.join([self.document_url, '_info']))
ddoc_info.raise_for_status()
return response_to_json_dict(ddoc_info) | def info(self) | Retrieves the design document view information data, returns dictionary
GET databasename/_design/{ddoc}/_info | 5.152862 | 3.655666 | 1.409555 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.