Code stringlengths 103 85.9k | Summary listlengths 0 94 |
|---|---|
Please provide a description of the function:def check(self, version): # Ignore PyDocStyleBear
def _compare_spec(spec):
if len(spec) == 1:
spec = ("=", spec[0])
token = Tokens.operators.index(spec[0])
comparison = compare_version(version, spec[1])
... | [
"Check if `version` fits into our dependency specification.\n\n :param version: str\n :return: bool\n "
] |
Please provide a description of the function:def compose_sep(deps, separator):
result = {}
for dep in deps:
if dep.name not in result:
result[dep.name] = separator.join([op + ver for op, ver in dep.spec])
else:
result[dep.name] += separato... | [
"Opposite of parse().\n\n :param deps: list of Dependency()\n :param separator: when joining dependencies, use this separator\n :return: dict of {name: version spec}\n "
] |
Please provide a description of the function:def solve(self, dependencies, graceful=True, all_versions=False): # Ignore PyDocStyleBear
def _compare_version_index_url(v1, v2):
return compare_version(v1[0], v2[0])
solved = {}
for dep in self.dependency_parser.p... | [
"Solve `dependencies` against upstream repository.\n\n :param dependencies: List, List of dependencies in native format\n :param graceful: bool, Print info output to stdout\n :param all_versions: bool, Return all matched versions instead of the latest\n :return: Dict[str, str], Matched v... |
Please provide a description of the function:def pip_compile(*packages: str):
result = None
packages = "\n".join(packages)
with tempfile.TemporaryDirectory() as tmp_dirname, cwd(tmp_dirname):
with open("requirements.in", "w") as requirements_file:
requirements_file.write(packages)
... | [
"Run pip-compile to pin down packages, also resolve their transitive dependencies."
] |
Please provide a description of the function:def _print_version(ctx, _, value):
if not value or ctx.resilient_parsing:
return
click.echo(analyzer_version)
ctx.exit() | [
"Print solver version and exit."
] |
Please provide a description of the function:def cli(ctx=None, verbose=0):
if ctx:
ctx.auto_envvar_prefix = "THOTH_SOLVER"
if verbose:
_LOG.setLevel(logging.DEBUG)
_LOG.debug("Debug mode is on") | [
"Thoth solver command line interface."
] |
Please provide a description of the function:def pypi(
click_ctx,
requirements,
index=None,
python_version=3,
exclude_packages=None,
output=None,
subgraph_check_api=None,
no_transitive=True,
no_pretty=False,
):
requirements = [requirement.strip() for requirement in requireme... | [
"Manipulate with dependency requirements using PyPI."
] |
Please provide a description of the function:def _create_entry(entry: dict, source: Source = None) -> dict:
entry["package_name"] = entry["package"].pop("package_name")
entry["package_version"] = entry["package"].pop("installed_version")
if source:
entry["index_url"] = source.url
entry... | [
"Filter and normalize the output of pipdeptree entry."
] |
Please provide a description of the function:def _get_environment_details(python_bin: str) -> list:
cmd = "{} -m pipdeptree --json".format(python_bin)
output = run_command(cmd, is_json=True).stdout
return [_create_entry(entry) for entry in output] | [
"Get information about packages in environment where packages get installed."
] |
Please provide a description of the function:def _should_resolve_subgraph(subgraph_check_api: str, package_name: str, package_version: str, index_url: str) -> bool:
_LOGGER.info(
"Checking if the given dependency subgraph for package %r in version %r from index %r should be resolved",
package_n... | [
"Ask the given subgraph check API if the given package in the given version should be included in the resolution.\n\n This subgraph resolving avoidence serves two purposes - we don't need to\n resolve dependency subgraphs that were already analyzed and we also avoid\n analyzing of \"core\" packages (like s... |
Please provide a description of the function:def _install_requirement(
python_bin: str, package: str, version: str = None, index_url: str = None, clean: bool = True
) -> None:
previous_version = _pipdeptree(python_bin, package)
try:
cmd = "{} -m pip install --force-reinstall --no-cache-dir --n... | [
"Install requirements specified using suggested pip binary."
] |
Please provide a description of the function:def _pipdeptree(python_bin, package_name: str = None, warn: bool = False) -> typing.Optional[dict]:
cmd = "{} -m pipdeptree --json".format(python_bin)
_LOGGER.debug("Obtaining pip dependency tree using: %r", cmd)
output = run_command(cmd, is_json=True).stdo... | [
"Get pip dependency tree by executing pipdeptree tool."
] |
Please provide a description of the function:def _get_dependency_specification(dep_spec: typing.List[tuple]) -> str:
return ",".join(dep_range[0] + dep_range[1] for dep_range in dep_spec) | [
"Get string representation of dependency specification as provided by PythonDependencyParser."
] |
Please provide a description of the function:def _do_resolve_index(
python_bin: str,
solver: PythonSolver,
*,
all_solvers: typing.List[PythonSolver],
requirements: typing.List[str],
exclude_packages: set = None,
transitive: bool = True,
subgraph_check_api: str = None,
) -> dict:
... | [
"Perform resolution of requirements against the given solver."
] |
Please provide a description of the function:def resolve(
requirements: typing.List[str],
index_urls: list = None,
python_version: int = 3,
exclude_packages: set = None,
transitive: bool = True,
subgraph_check_api: str = None,
) -> dict:
assert python_version in (2, 3), "Unknown Python ... | [
"Resolve given requirements for the given Python version."
] |
Please provide a description of the function:def fetch_releases(self, package_name):
package_name = self.source.normalize_package_name(package_name)
releases = self.source.get_package_versions(package_name)
releases_with_index_url = [(item, self.index_url) for item in releases]
... | [
"Fetch package and index_url for a package_name."
] |
Please provide a description of the function:def parse_python(spec): # Ignore PyDocStyleBear
def _extract_op_version(spec):
# https://www.python.org/dev/peps/pep-0440/#compatible-release
if spec.operator == "~=":
version = spec.version.split(".")
... | [
"Parse PyPI specification of a single dependency.\n\n :param spec: str, for example \"Django>=1.5,<1.8\"\n :return: [Django [[('>=', '1.5'), ('<', '1.8')]]]\n ",
"There is no `specs` field In Pip 8+, take info from `specifier` field."
] |
Please provide a description of the function:def get(obj):
if not isinstance(obj, bytes):
raise TypeError("object type must be bytes")
info = {
"type": dict(),
"extension": dict(),
"mime": dict()
}
stream = " ".join(['{:02X}'.format(byte) for byte in obj])
fo... | [
"\n Determines file format and picks suitable file types, extensions and MIME types\n\n Takes:\n obj (bytes) -> byte sequence (128 bytes are enough)\n\n Returns:\n (<class 'fleep.Info'>) -> Class instance\n "
] |
Please provide a description of the function:def bottleneck_matching(I1, I2, matchidx, D, labels=["dgm1", "dgm2"], ax=None):
plot_diagrams([I1, I2], labels=labels, ax=ax)
cp = np.cos(np.pi / 4)
sp = np.sin(np.pi / 4)
R = np.array([[cp, -sp], [sp, cp]])
if I1.size == 0:
I1 = np.array([... | [
" Visualize bottleneck matching between two diagrams\n\n Parameters\n ===========\n\n I1: array\n A diagram\n I2: array\n A diagram\n matchidx: tuples of matched indices\n if input `matching=True`, then return matching\n D: array\n cross-similarity matrix\n labels: l... |
Please provide a description of the function:def plot_diagrams(
diagrams,
plot_only=None,
title=None,
xy_range=None,
labels=None,
colormap="default",
size=20,
ax_color=np.array([0.0, 0.0, 0.0]),
diagonal=True,
lifetime=False,
legend=True,
show=False,
ax=None
):
... | [
"A helper function to plot persistence diagrams. \n\n Parameters\n ----------\n diagrams: ndarray (n_pairs, 2) or list of diagrams\n A diagram or list of diagrams. If diagram is a list of diagrams, \n then plot all on the same plot using different colors.\n plot_only: list of numeric\n ... |
Please provide a description of the function:def persistent_entropy(
dgms, keep_inf=False, val_inf=None, normalize=False
):
if isinstance(dgms, list) == False:
dgms = [dgms]
# Step 1: Remove infinity bars if keep_inf = False. If keep_inf = True, infinity value is substituted by val_inf.
... | [
"\n Perform the persistent entropy values of a family of persistence barcodes (or persistence diagrams).\n Assumes that the input diagrams are from a determined dimension. If the infinity bars have any meaning\n in your experiment and you want to keep them, remember to give the value you desire to val_Inf.... |
Please provide a description of the function:def evalHeatKernel(dgm1, dgm2, sigma):
kSigma = 0
I1 = np.array(dgm1)
I2 = np.array(dgm2)
for i in range(I1.shape[0]):
p = I1[i, 0:2]
for j in range(I2.shape[0]):
q = I2[j, 0:2]
qc = I2[j, 1::-1]
kSigma... | [
"\n Evaluate the continuous heat-based kernel between dgm1 and dgm2 (more correct than L2 on the discretized version above but may be slower because can't exploit fast matrix multiplication when evaluating many, many kernels)\n "
] |
Please provide a description of the function:def heat(dgm1, dgm2, sigma=0.4):
return np.sqrt(
evalHeatKernel(dgm1, dgm1, sigma)
+ evalHeatKernel(dgm2, dgm2, sigma)
- 2 * evalHeatKernel(dgm1, dgm2, sigma)
) | [
"\n Return the pseudo-metric between two diagrams based on the continuous\n heat kernel as described in \"A Stable Multi-Scale Kernel for Topological Machine Learning\" by Jan Reininghaus, Stefan Huber, Ulrich Bauer, and Roland Kwitt (CVPR 2015)\n\n Parameters\n -----------\n\n dgm1: np.array (m,2)\n... |
Please provide a description of the function:def bottleneck(dgm1, dgm2, matching=False):
return_matching = matching
S = np.array(dgm1)
S = S[np.isfinite(S[:, 1]), :]
T = np.array(dgm2)
T = T[np.isfinite(T[:, 1]), :]
N = S.shape[0]
M = T.shape[0]
# Step 1: Compute CSM between S a... | [
"\n Perform the Bottleneck distance matching between persistence diagrams.\n Assumes first two columns of S and T are the coordinates of the persistence\n points, but allows for other coordinate columns (which are ignored in\n diagonal matching)\n\n Parameters\n -----------\n dgm1: Mx(>=2) \n ... |
Please provide a description of the function:def sliced_wasserstein(PD1, PD2, M=50):
diag_theta = np.array(
[np.cos(0.25 * np.pi), np.sin(0.25 * np.pi)], dtype=np.float32
)
l_theta1 = [np.dot(diag_theta, x) for x in PD1]
l_theta2 = [np.dot(diag_theta, x) for x in PD2]
if (len(l_theta... | [
" Implementation of Sliced Wasserstein distance as described in \n Sliced Wasserstein Kernel for Persistence Diagrams by Mathieu Carriere, Marco Cuturi, Steve Oudot (https://arxiv.org/abs/1706.03358)\n\n\n Parameters\n -----------\n \n PD1: np.array size (m,2)\n Persist... |
Please provide a description of the function:def transform(self, diagrams):
# if diagram is empty, return empty image
if len(diagrams) == 0:
return np.zeros((self.nx, self.ny))
# if first entry of first entry is not iterable, then diagrams is singular and we need to make it ... | [
" Convert diagram or list of diagrams to a persistence image.\n\n Parameters\n -----------\n\n diagrams : list of or singleton diagram, list of pairs. [(birth, death)]\n Persistence diagrams to be converted to persistence images. It is assumed they are in (birth, death) format. Can i... |
Please provide a description of the function:def weighting(self, landscape=None):
# TODO: Implement a logistic function
# TODO: use self.weighting_type to choose function
if landscape is not None:
if len(landscape) > 0:
maxy = np.max(landscape[:, 1])
... | [
" Define a weighting function, \n for stability results to hold, the function must be 0 at y=0. \n ",
" This is the function defined as w_b(t) in the original PI paper\n\n Take b to be maxy/self.ny to effectively zero out the bottom pixel row\n "
] |
Please provide a description of the function:def kernel(self, spread=1):
# TODO: use self.kernel_type to choose function
def gaussian(data, pixel):
return mvn.pdf(data, mean=pixel, cov=spread)
return gaussian | [
" This will return whatever kind of kernel we want to use.\n Must have signature (ndarray size NxM, ndarray size 1xM) -> ndarray size Nx1\n "
] |
Please provide a description of the function:def show(self, imgs, ax=None):
ax = ax or plt.gca()
if type(imgs) is not list:
imgs = [imgs]
for i, img in enumerate(imgs):
ax.imshow(img, cmap=plt.get_cmap("plasma"))
ax.axis("off") | [
" Visualize the persistence image\n\n "
] |
Please provide a description of the function:def resolve_orm_path(model, orm_path):
bits = orm_path.split('__')
endpoint_model = reduce(get_model_at_related_field, [model] + bits[:-1])
if bits[-1] == 'pk':
field = endpoint_model._meta.pk
else:
field = endpoint_model._meta.get_field... | [
"\n Follows the queryset-style query path of ``orm_path`` starting from ``model`` class. If the\n path ends up referring to a bad field name, ``django.db.models.fields.FieldDoesNotExist`` will\n be raised.\n\n "
] |
Please provide a description of the function:def get_model_at_related_field(model, attr):
field = model._meta.get_field(attr)
if hasattr(field, 'related_model'):
return field.related_model
raise ValueError("{model}.{attr} ({klass}) is not a relationship field.".format(**{
'model': mo... | [
"\n Looks up ``attr`` as a field of ``model`` and returns the related model class. If ``attr`` is\n not a relationship field, ``ValueError`` is raised.\n\n "
] |
Please provide a description of the function:def contains_plural_field(model, fields):
source_model = model
for orm_path in fields:
model = source_model
bits = orm_path.lstrip('+-').split('__')
for bit in bits[:-1]:
field = model._meta.get_field(bit)
if field... | [
" Returns a boolean indicating if ``fields`` contains a relationship to multiple items. "
] |
Please provide a description of the function:def get_json_response_object(self, datatable):
# Ensure the object list is calculated.
# Calling get_records() will do this implicitly, but we want simultaneous access to the
# 'total_initial_record_count', and 'unpaged_record_count' values.... | [
"\n Returns the JSON-compatible dictionary that will be serialized for an AJAX response.\n\n The value names are in the form \"s~\" for strings, \"i~\" for integers, and \"a~\" for arrays,\n if you're unfamiliar with the old C-style jargon used in dataTables.js. \"aa~\" means\n \"array ... |
Please provide a description of the function:def serialize_to_json(self, response_data):
indent = None
if settings.DEBUG:
indent = 4
# Serialize to JSON with Django's encoder: Adds date/time, decimal,
# and UUID support.
return json.dumps(response_data, ind... | [
" Returns the JSON string for the compiled data object. "
] |
Please provide a description of the function:def get_ajax(self, request, *args, **kwargs):
response_data = self.get_json_response_object(self._datatable)
response = HttpResponse(self.serialize_to_json(response_data),
content_type="application/json")
ret... | [
" Called when accessed via AJAX on the request method specified by the Datatable. "
] |
Please provide a description of the function:def get_datatable(self, **kwargs):
if hasattr(self, '_datatable'):
return self._datatable
datatable_class = self.get_datatable_class()
if datatable_class is None:
class AutoMeta:
model = self.model or ... | [
" Gathers and returns the final :py:class:`Datatable` instance for processing. "
] |
Please provide a description of the function:def get_active_ajax_datatable(self):
data = getattr(self.request, self.request.method)
datatables_dict = self.get_datatables(only=data['datatable'])
return list(datatables_dict.values())[0] | [
" Returns a single datatable according to the hint GET variable from an AJAX request. "
] |
Please provide a description of the function:def get_datatables(self, only=None):
if not hasattr(self, '_datatables'):
self._datatables = {}
datatable_classes = self.get_datatable_classes()
for name, datatable_class in datatable_classes.items():
if on... | [
" Returns a dict of the datatables served by this view. "
] |
Please provide a description of the function:def get_default_datatable_kwargs(self, **kwargs):
kwargs['view'] = self
# This is provided by default, but if the view is instantiated outside of the request cycle
# (such as for the purposes of embedding that view's datatable elsewhere), t... | [
"\n Builds the default set of kwargs for initializing a Datatable class. Note that by default\n the MultipleDatatableMixin does not support any configuration via the view's class\n attributes, and instead relies completely on the Datatable class itself to declare its\n configuration det... |
Please provide a description of the function:def get_column_for_modelfield(model_field):
# If the field points to another model, we want to get the pk field of that other model and use
# that as the real field. It is possible that a ForeignKey points to a model with table
# inheritance, however, so w... | [
" Return the built-in Column class for a model field class. "
] |
Please provide a description of the function:def get_source_value(self, obj, source, **kwargs):
result = []
for sub_source in self.expand_source(source):
# Call super() to get default logic, but send it the 'sub_source'
sub_result = super(CompoundColumn, self).get_source... | [
"\n Treat ``field`` as a nested sub-Column instance, which explicitly stands in as the object\n to which term coercions and the query type lookup are delegated.\n "
] |
Please provide a description of the function:def _get_flat_db_sources(self, model):
sources = []
for source in self.sources:
for sub_source in self.expand_source(source):
target_field = self.resolve_source(model, sub_source)
if target_field:
... | [
" Return a flattened representation of the individual ``sources`` lists. "
] |
Please provide a description of the function:def get_source_handler(self, model, source):
if isinstance(source, Column):
return source
# Generate a generic handler for the source
modelfield = resolve_orm_path(model, source)
column_class = get_column_for_modelfield(m... | [
" Allow the nested Column source to be its own handler. "
] |
Please provide a description of the function:def dispatch(self, request, *args, **kwargs):
if request.GET.get(self.xeditable_fieldname_param):
return self.get_ajax_xeditable_choices(request, *args, **kwargs)
return super(XEditableMixin, self).dispatch(request, *args, **kwargs) | [
" Introduces the ``ensure_csrf_cookie`` decorator and handles xeditable choices ajax. "
] |
Please provide a description of the function:def get_ajax_xeditable_choices(self, request, *args, **kwargs):
field_name = request.GET.get(self.xeditable_fieldname_param)
if not field_name:
return HttpResponseBadRequest("Field name must be given")
queryset = self.get_queryse... | [
" AJAX GET handler for xeditable queries asking for field choice lists. "
] |
Please provide a description of the function:def post(self, request, *args, **kwargs):
self.object_list = None
form = self.get_xeditable_form(self.get_xeditable_form_class())
if form.is_valid():
obj = self.get_update_object(form)
if obj is None:
d... | [
"\n Builds a dynamic form that targets only the field in question, and saves the modification.\n "
] |
Please provide a description of the function:def get_xeditable_form_kwargs(self):
kwargs = {
'model': self.get_queryset().model,
}
if self.request.method in ('POST', 'PUT'):
kwargs.update({
'data': self.request.POST,
})
return ... | [
" Returns a dict of keyword arguments to be sent to the xeditable form class. "
] |
Please provide a description of the function:def get_update_object(self, form):
pk = form.cleaned_data['pk']
queryset = self.get_queryset()
try:
obj = queryset.get(pk=pk)
except queryset.model.DoesNotExist:
obj = None
return obj | [
"\n Retrieves the target object based on the update form's ``pk`` and the table's queryset.\n "
] |
Please provide a description of the function:def update_object(self, form, obj):
field_name = form.cleaned_data['name']
value = form.cleaned_data['value']
setattr(obj, field_name, value)
save_kwargs = {}
if CAN_UPDATE_FIELDS:
save_kwargs['update_fields'] = [f... | [
" Saves the new value to the target object. "
] |
Please provide a description of the function:def get_field_choices(self, field, field_name):
if self.request.GET.get('select2'):
names = ['id', 'text']
else:
names = ['value', 'text']
choices_getter = getattr(self, 'get_field_%s_choices', None)
if choices... | [
"\n Returns the valid choices for ``field``. The ``field_name`` argument is given for\n convenience.\n "
] |
Please provide a description of the function:def get_declared_columns(bases, attrs, with_base_columns=True):
local_columns = [
(column_name, attrs.pop(column_name)) \
for column_name, obj in list(six.iteritems(attrs)) \
if isinstance(obj, Column)
]
local_columns.... | [
"\n Create a list of form field instances from the passed in 'attrs', plus any\n similar fields on the base classes (in 'bases'). This is used by both the\n Form and ModelForm metclasses.\n\n If 'with_base_columns' is True, all fields from the bases are used.\n Otherwise, only fields in the 'declared... |
Please provide a description of the function:def populate_records(self):
self.object_list = self.get_valuesqueryset(self.object_list)
super(ValuesDatatable, self).populate_records() | [
"\n Switches the original queryset to a ``ValuesQuerySet``, selecting values according to what\n each column has declared in its :py:attr:`~datatableview.columns.Column.sources` list.\n "
] |
Please provide a description of the function:def preload_record_data(self, obj):
data = {}
for orm_path, column_name in self.value_queries.items():
value = obj[orm_path]
if column_name not in data:
data[column_name] = value
else:
... | [
"\n Modifies the ``obj`` values dict to alias the selected values to the column name that asked\n for its selection.\n\n For example, a datatable that declares a column ``'blog'`` which has a related lookup source\n ``'blog__name'`` will ensure that the selected value exists in ``obj`` a... |
Please provide a description of the function:def resolve_virtual_columns(self, *names):
from .views.legacy import get_field_definition
virtual_columns = {}
for name in names:
field = get_field_definition(name)
column = TextColumn(sources=field.fields, label=field... | [
"\n Assume that all ``names`` are legacy-style tuple declarations, and generate modern columns\n instances to match the behavior of the old syntax.\n "
] |
Please provide a description of the function:def set_value_field(self, model, field_name):
fields = fields_for_model(model, fields=[field_name])
self.fields['value'] = fields[field_name] | [
"\n Adds a ``value`` field to this form that uses the appropriate formfield for the named target\n field. This will help to ensure that the value is correctly validated.\n "
] |
Please provide a description of the function:def clean_name(self):
field_name = self.cleaned_data['name']
# get_all_field_names is deprecated in Django 1.8, this also fixes proxied models
if hasattr(self.model._meta, 'get_fields'):
field_names = [field.name for field in self... | [
" Validates that the ``name`` field corresponds to a field on the model. "
] |
Please provide a description of the function:def get_field_definition(field_definition):
if not isinstance(field_definition, (tuple, list)):
field_definition = [field_definition]
else:
field_definition = list(field_definition)
if len(field_definition) == 1:
field = [None, field... | [
" Normalizes a field definition into its component parts, even if some are missing. "
] |
Please provide a description of the function:def _get_datatable_options(self):
if not hasattr(self, '_datatable_options'):
self._datatable_options = self.get_datatable_options()
# Convert sources from list to tuple, so that modern Column tracking dicts can hold the
... | [
" Helps to keep the promise that we only run ``get_datatable_options()`` once. "
] |
Please provide a description of the function:def get_cache_key(datatable_class, view=None, user=None, **kwargs):
datatable_name = datatable_class.__name__
if datatable_name.endswith('_Synthesized'):
datatable_name = datatable_name[:-12]
datatable_id = '%s.%s' % (datatable_class.__module__, dat... | [
"\n Returns a cache key unique to the current table, and (if available) the request user.\n\n The ``view`` argument should be the class reference itself, since it is easily obtainable\n in contexts where the instance is not available.\n "
] |
Please provide a description of the function:def get_cached_data(datatable, **kwargs):
cache_key = '%s%s' % (CACHE_PREFIX, datatable.get_cache_key(**kwargs))
data = cache.get(cache_key)
log.debug("Reading data from cache at %r: %r", cache_key, data)
return data | [
" Returns the cached object list under the appropriate key, or None if not set. "
] |
Please provide a description of the function:def cache_data(datatable, data, **kwargs):
cache_key = '%s%s' % (CACHE_PREFIX, datatable.get_cache_key(**kwargs))
log.debug("Setting data to cache at %r: %r", cache_key, data)
cache.set(cache_key, data) | [
" Stores the object list in the cache under the appropriate key. "
] |
Please provide a description of the function:def keyed_helper(helper):
@wraps(helper)
def wrapper(instance=None, key=None, attr=None, *args, **kwargs):
if set((instance, key, attr)) == {None}:
# helper was called in place with neither important arg
raise ValueError("If call... | [
"\n Decorator for helper functions that operate on direct values instead of model instances.\n\n A keyed helper is one that can be used normally in the view's own custom callbacks, but also\n supports direct access in the column declaration, such as in the example:\n\n datatable_options = {\n ... |
Please provide a description of the function:def link_to_model(instance, text=None, *args, **kwargs):
if not text:
text = kwargs.get('rich_value') or six.text_type(instance)
return u.format(instance.get_absolute_url(), text) | [
"\n Returns HTML in the form::\n\n <a href=\"{{ instance.get_absolute_url }}\">{{ text }}</a>\n\n If ``text`` is provided and isn't empty, it will be used as the hyperlinked text.\n\n If ``text`` isn't available, then ``kwargs['rich_value']`` will be consulted instead.\n\n Failing those checks, t... |
Please provide a description of the function:def make_boolean_checkmark(value, true_value="✔", false_value="✘", *args, **kwargs):
value = kwargs.get('default_value', value)
if value:
return true_value
return false_value | [
"\n Returns a unicode ✔ or ✘, configurable by pre-calling the helper with ``true_value`` and/or\n ``false_value`` arguments, based on the incoming value.\n\n The value at ``kwargs['default_value']`` is checked to see if it casts to a boolean ``True`` or\n ``False``, and returns the appropriate represent... |
Please provide a description of the function:def itemgetter(k, ellipsis=False, key=None):
def helper(instance, *args, **kwargs):
default_value = kwargs.get('default_value')
if default_value is None:
default_value = instance
value = default_value[k]
if ellipsis and is... | [
"\n Looks up ``k`` as an index of the column's value.\n\n If ``k`` is a ``slice`` type object, then ``ellipsis`` can be given as a string to use to\n indicate truncation. Alternatively, ``ellipsis`` can be set to ``True`` to use a default\n ``'...'``.\n\n If a ``key`` is given, it may be a function ... |
Please provide a description of the function:def attrgetter(attr, key=None):
def helper(instance, *args, **kwargs):
value = instance
for bit in attr.split('.'):
value = getattr(value, bit)
if callable(value):
value = value()
return value
if k... | [
"\n Looks up ``attr`` on the target value. If the result is a callable, it will be called in place\n without arguments.\n\n If a ``key`` is given, it may be a function which maps the target value to something else\n before the attribute lookup takes place.\n\n Examples::\n\n # Explicitly selec... |
Please provide a description of the function:def format_date(format_string, localize=False, key=None):
if localize is not False and localtime is None:
raise Exception("Cannot use format_date argument 'localize' with Django < 1.5")
def helper(value, *args, **kwargs):
inner_localize = kwarg... | [
"\n A pre-called helper to supply a date format string ahead of time, so that it can apply to each\n date or datetime that this column represents. With Django >= 1.5, the ``localize=True`` keyword\n argument can be given, or else can be supplied in the column's own declaration for the same\n effect. (... |
Please provide a description of the function:def format(format_string, cast=lambda x: x):
def helper(instance, *args, **kwargs):
value = kwargs.get('default_value')
if value is None:
value = instance
value = cast(value)
return format_string.format(value, obj=instanc... | [
"\n A pre-called helper to supply a modern string format (the kind with {} instead of %s), so that\n it can apply to each value in the column as it is rendered. This can be useful for string\n padding like leading zeroes, or rounding floating point numbers to a certain number of decimal\n places, etc.\... |
Please provide a description of the function:def make_xeditable(instance=None, extra_attrs=[], *args, **kwargs):
if instance is None:
# Preloading kwargs into the helper for deferred execution
helper = partial(make_xeditable, extra_attrs=extra_attrs, *args, **kwargs)
return helper
... | [
"\n Converts the contents of the column into an ``<a>`` tag with the required DOM attributes to\n power the X-Editable UI.\n\n The following keyword arguments are all optional, but may be provided when pre-calling the\n helper, to customize the output of the helper once it is run per object record:\n\n ... |
Please provide a description of the function:def make_processor(func, arg=None):
def helper(instance, *args, **kwargs):
value = kwargs.get('default_value')
if value is None:
value = instance
if arg is not None:
extra_arg = [arg]
else:
extra_ar... | [
"\n A pre-called processor that wraps the execution of the target callable ``func``.\n\n This is useful for when ``func`` is a third party mapping function that can take your column's\n value and return an expected result, but doesn't understand all of the extra kwargs that get\n sent to processor callb... |
Please provide a description of the function:def upload_kitten(client):
'''
Upload a picture of a kitten. We don't ship one, so get creative!
'''
# Here's the metadata for the upload. All of these are optional, including
# this config dict itself.
config = {
'album': album,
'name': 'Catastrophe!',
'title... | [] |
Please provide a description of the function:def _isdst(dt):
if type(dt) == datetime.date:
dt = datetime.datetime.combine(dt, datetime.datetime.min.time())
dtc = dt.replace(year=datetime.datetime.now().year)
if time.localtime(dtc.timestamp()).tm_isdst == 1:
return True
return False | [
"Check if date is in dst.\n "
] |
Please provide a description of the function:def _mktime(time_struct):
try:
return time.mktime(time_struct)
except OverflowError:
dt = datetime.datetime(*time_struct[:6])
ep = datetime.datetime(1970, 1, 1)
diff = dt - ep
ts = diff.days * 24 * 3600 + diff.seconds + ti... | [
"Custom mktime because Windows can't be arsed to properly do pre-Epoch\n dates, probably because it's busy counting all its chromosomes.\n "
] |
Please provide a description of the function:def _strftime(pattern, time_struct=time.localtime()):
try:
return time.strftime(pattern, time_struct)
except OSError:
dt = datetime.datetime.fromtimestamp(_mktime(time_struct))
# This is incredibly hacky and will probably break with leap
... | [
"Custom strftime because Windows is shit again.\n "
] |
Please provide a description of the function:def _gmtime(timestamp):
try:
return time.gmtime(timestamp)
except OSError:
dt = datetime.datetime(1970, 1, 1) + datetime.timedelta(seconds=timestamp)
dst = int(_isdst(dt))
return time.struct_time(dt.timetuple()[:8] + tuple([dst])) | [
"Custom gmtime because yada yada.\n "
] |
Please provide a description of the function:def _dtfromtimestamp(timestamp):
try:
return datetime.datetime.fromtimestamp(timestamp)
except OSError:
timestamp -= time.timezone
dt = datetime.datetime(1970, 1, 1) + datetime.timedelta(seconds=timestamp)
if _isdst(dt):
... | [
"Custom datetime timestamp constructor. because Windows. again.\n "
] |
Please provide a description of the function:def _dfromtimestamp(timestamp):
try:
return datetime.date.fromtimestamp(timestamp)
except OSError:
timestamp -= time.timezone
d = datetime.date(1970, 1, 1) + datetime.timedelta(seconds=timestamp)
if _isdst(d):
timestam... | [
"Custom date timestamp constructor. ditto\n "
] |
Please provide a description of the function:def guesstype(timestr):
timestr_full = " {} ".format(timestr)
if timestr_full.find(" in ") != -1 or timestr_full.find(" ago ") != -1:
return Chronyk(timestr)
comps = ["second", "minute", "hour", "day", "week", "month", "year"]
for comp in comps:... | [
"Tries to guess whether a string represents a time or a time delta and\n returns the appropriate object.\n\n :param timestr (required)\n The string to be analyzed\n "
] |
Please provide a description of the function:def _round(num):
deci = num - math.floor(num)
if deci > 0.8:
return int(math.floor(num) + 1)
else:
return int(math.floor(num)) | [
"A custom rounding function that's a bit more 'strict'.\n "
] |
Please provide a description of the function:def datetime(self, timezone=None):
if timezone is None:
timezone = self.timezone
return _dtfromtimestamp(self.__timestamp__ - timezone) | [
"Returns a datetime object.\n\n This object retains all information, including timezones.\n\n :param timezone = self.timezone\n The timezone (in seconds west of UTC) to return the value in. By\n default, the timezone used when constructing the class is used\n (local on... |
Please provide a description of the function:def date(self, timezone=None):
if timezone is None:
timezone = self.timezone
return _dfromtimestamp(self.__timestamp__ - timezone) | [
"Returns a datetime.date object.\n This object retains all information, including timezones.\n \n :param timezone = self.timezone\n The timezone (in seconds west of UTC) to return the value in. By\n default, the timezone used when constructing the class is used\n ... |
Please provide a description of the function:def timestamp(self, timezone=None):
if timezone is None:
timezone = self.timezone
return self.__timestamp__ - timezone | [
"Returns a timestamp (seconds since the epoch).\n\n :param timezone = self.timezone\n The timezone (in seconds west of UTC) to return the value in. By\n default, the timezone used when constructing the class is used\n (local one by default). To use UTC, use timezone = 0. To u... |
Please provide a description of the function:def ctime(self, timezone=None):
if timezone is None:
timezone = self.timezone
return time.ctime(self.__timestamp__ - timezone) | [
"Returns a ctime string.\n\n :param timezone = self.timezone\n The timezone (in seconds west of UTC) to return the value in. By\n default, the timezone used when constructing the class is used\n (local one by default). To use UTC, use timezone = 0. To use the\n loc... |
Please provide a description of the function:def timestring(self, pattern="%Y-%m-%d %H:%M:%S", timezone=None):
if timezone is None:
timezone = self.timezone
timestamp = self.__timestamp__ - timezone
timestamp -= LOCALTZ
return _strftime(pattern, _gmtime(timestamp)) | [
"Returns a time string.\n\n :param pattern = \"%Y-%m-%d %H:%M:%S\"\n The format used. By default, an ISO-type format is used. The\n syntax here is identical to the one used by time.strftime() and\n time.strptime().\n\n :param timezone = self.timezone\n The t... |
Please provide a description of the function:def relativestring(
self, now=None, minimum=10, maximum=3600 * 24 * 30,
pattern="%Y-%m-%d", timezone=None, maxunits=1):
if now is None:
now = time.time()
if timezone is None:
timezone = self.timezone
... | [
"Returns a relative time string (e.g. \"10 seconds ago\").\n\n :param now = time.time()\n The timestamp to compare this time to. By default, the current\n local time is used.\n\n :param minimum = 10\n Amount in seconds under which \"just now\" is returned instead of a\... |
Please provide a description of the function:def timestring(self, maxunits=3):
try:
assert maxunits >= 1
except:
raise ValueError("Values < 1 for maxunits are not supported.")
values = collections.OrderedDict()
seconds = abs(self.seconds)
valu... | [
"Returns a string representation of this amount of time, like:\n \"2 hours and 30 minutes\" or \"4 days, 2 hours and 40 minutes\"\n\n :param maxunits = 3\n The maximum amount of units to use.\n\n 1: \"2 hours\"\n 4: \"4 days, 2 hours, 5 minuts and 46 seconds\"\n\n ... |
Please provide a description of the function:def get_ticket(self, ticket_id):
url = 'tickets/%d' % ticket_id
ticket = self._api._get(url)
return Ticket(**ticket) | [
"Fetches the ticket for the given ticket ID"
] |
Please provide a description of the function:def create_ticket(self, subject, **kwargs):
url = 'tickets'
status = kwargs.get('status', 2)
priority = kwargs.get('priority', 1)
data = {
'subject': subject,
'status': status,
'priority': priority... | [
"\n Creates a ticket\n To create ticket with attachments,\n pass a key 'attachments' with value as list of fully qualified file paths in string format.\n ex: attachments = ('/path/to/attachment1', '/path/to/attachment2')\n "
] |
Please provide a description of the function:def create_outbound_email(self, subject, description, email, email_config_id, **kwargs):
url = 'tickets/outbound_email'
priority = kwargs.get('priority', 1)
data = {
'subject': subject,
'description': description,
... | [
"Creates an outbound email"
] |
Please provide a description of the function:def update_ticket(self, ticket_id, **kwargs):
url = 'tickets/%d' % ticket_id
ticket = self._api._put(url, data=json.dumps(kwargs))
return Ticket(**ticket) | [
"Updates a ticket from a given ticket ID"
] |
Please provide a description of the function:def list_tickets(self, **kwargs):
filter_name = 'new_and_my_open'
if 'filter_name' in kwargs:
filter_name = kwargs['filter_name']
del kwargs['filter_name']
url = 'tickets'
if filter_name is not None:
... | [
"List all tickets, optionally filtered by a view. Specify filters as\n keyword arguments, such as:\n\n filter_name = one of ['new_and_my_open', 'watching', 'spam', 'deleted',\n None]\n (defaults to 'new_and_my_open')\n Passing None means that no named... |
Please provide a description of the function:def list_contacts(self, **kwargs):
url = 'contacts?'
page = 1 if not 'page' in kwargs else kwargs['page']
per_page = 100 if not 'per_page' in kwargs else kwargs['per_page']
contacts = []
# Skip pagination by looping over ea... | [
"\n List all contacts, optionally filtered by a query. Specify filters as\n query keyword argument, such as:\n\n email=abc@xyz.com,\n mobile=1234567890,\n phone=1234567890,\n\n contacts can be filtered by state and company_id such as:\n\n state=[blocked/deleted/unver... |
Please provide a description of the function:def create_contact(self, *args, **kwargs):
url = 'contacts'
data = {
'view_all_tickets': False,
'description': 'Freshdesk Contact'
}
data.update(kwargs)
return Contact(**self._api._post(url, data=json.d... | [
"Creates a contact"
] |
Please provide a description of the function:def list_agents(self, **kwargs):
url = 'agents?'
page = 1 if not 'page' in kwargs else kwargs['page']
per_page = 100 if not 'per_page' in kwargs else kwargs['per_page']
agents = []
# Skip pagination by looping over each pag... | [
"List all agents, optionally filtered by a view. Specify filters as\n keyword arguments, such as:\n\n {\n email='abc@xyz.com',\n phone=873902,\n mobile=56523,\n state='fulltime'\n }\n\n Passing None means that no named filter will be passed to\... |
Please provide a description of the function:def get_agent(self, agent_id):
url = 'agents/%s' % agent_id
return Agent(**self._api._get(url)) | [
"Fetches the agent for the given agent ID"
] |
Please provide a description of the function:def update_agent(self, agent_id, **kwargs):
url = 'agents/%s' % agent_id
agent = self._api._put(url, data=json.dumps(kwargs))
return Agent(**agent) | [
"Updates an agent"
] |
Please provide a description of the function:def _get(self, url, params={}):
req = self._session.get(self._api_prefix + url, params=params)
return self._action(req) | [
"Wrapper around request.get() to use the API prefix. Returns a JSON response."
] |
Please provide a description of the function:def _post(self, url, data={}, **kwargs):
if 'files' in kwargs:
req = self._session.post(self._api_prefix + url, auth=self._session.auth, data=data, **kwargs)
return self._action(req)
req = self._session.post(self._api_prefix ... | [
"Wrapper around request.post() to use the API prefix. Returns a JSON response."
] |
Please provide a description of the function:def _put(self, url, data={}):
req = self._session.put(self._api_prefix + url, data=data)
return self._action(req) | [
"Wrapper around request.put() to use the API prefix. Returns a JSON response."
] |
Please provide a description of the function:def _delete(self, url):
req = self._session.delete(self._api_prefix + url)
return self._action(req) | [
"Wrapper around request.delete() to use the API prefix. Returns a JSON response."
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.