Code stringlengths 103 85.9k | Summary listlengths 0 94 |
|---|---|
Please provide a description of the function:def rename_file(pdf, bibitem):
year = _get_bib_element(bibitem, "year")
author = _get_bib_element(bibitem, "author")
if author:
author = author.split(",")[0]
title = _get_bib_element(bibitem, "title")
l = [i for i in (year, author, title) if ... | [
"Attempt to rename pdf according to bibitem.\n\n "
] |
Please provide a description of the function:def soup_maker(fh):
try:
from bs4 import BeautifulSoup
soup = BeautifulSoup(fh, "lxml")
for tag in soup.find_all():
tag.name = tag.name.lower()
except ImportError:
from BeautifulSoup import BeautifulStoneSoup
s... | [
" Takes a file handler returns BeautifulSoup"
] |
Please provide a description of the function:def parse(self, file_handle):
xbrl_obj = XBRL()
# if no file handle was given create our own
if not hasattr(file_handle, 'read'):
file_handler = open(file_handle)
else:
file_handler = file_handle
# S... | [
"\n parse is the main entry point for an XBRLParser. It takes a file\n handle.\n "
] |
Please provide a description of the function:def parseGAAP(self,
xbrl,
doc_date="",
context="current",
ignore_errors=0):
gaap_obj = GAAP()
if ignore_errors == 2:
logging.basicConfig(filename='/tmp/xbrl.log',
... | [
"\n Parse GAAP from our XBRL soup and return a GAAP object.\n "
] |
Please provide a description of the function:def parseDEI(self,
xbrl,
ignore_errors=0):
dei_obj = DEI()
if ignore_errors == 2:
logging.basicConfig(filename='/tmp/xbrl.log',
level=logging.ERROR,
format='%(asctime)s %(... | [
"\n Parse DEI from our XBRL soup and return a DEI object.\n "
] |
Please provide a description of the function:def parseCustom(self,
xbrl,
ignore_errors=0):
custom_obj = Custom()
custom_data = xbrl.find_all(re.compile('^((?!(us-gaap|dei|xbrll|xbrldi)).)*:\s*',
re.IGNORECASE | re.MULTILINE))
element... | [
"\n Parse company custom entities from XBRL and return an Custom object.\n "
] |
Please provide a description of the function:def trim_decimals(s, precision=-3):
encoded = s.encode('ascii', 'ignore')
str_val = ""
if six.PY3:
str_val = str(encoded, encoding='ascii', errors='ignore')[:precision]
else:
# If precision is 0, this must be h... | [
"\n Convert from scientific notation using precision\n "
] |
Please provide a description of the function:def data_processing(self,
elements,
xbrl,
ignore_errors,
logger,
context_ids=[],
**kwargs):
options = kwargs.get('... | [
"\n Process a XBRL tag object and extract the correct value as\n stated by the context.\n "
] |
Please provide a description of the function:def cli(inputtiles, delimiter):
try:
inputtiles = click.open_file(inputtiles).readlines()
except IOError:
inputtiles = [inputtiles]
for x in xt.xvert(inputtiles, delimiter):
click.echo(x) | [
"\n Automatically onvert a stream of tiles to another format\\n\n \\tz/x/y | z-x-y ==> [x, y, z]\\n\n \\t[x, y, z] ==> z/x/y | z-x-y | z?x?y -d ?\\n\n\n\n NOTES\n ------\n Will always match the last pattern, eg:\n 10-10-10 hi hi 20/20/20.png\n will return [20, 20, 20]\n "
] |
Please provide a description of the function:def by_name(self):
return {key.split(preferences_settings.SECTION_KEY_SEPARATOR)[-1]: value for key, value in self.all().items()} | [
"Return a dictionary with preferences identifiers and values, but without the section name in the identifier"
] |
Please provide a description of the function:def get_cache_key(self, section, name):
if not self.instance:
return 'dynamic_preferences_{0}_{1}_{2}'.format(self.model.__name__, section, name)
return 'dynamic_preferences_{0}_{1}_{2}_{3}'.format(self.model.__name__, self.instance.pk, s... | [
"Return the cache key corresponding to a given preference"
] |
Please provide a description of the function:def from_cache(self, section, name):
cached_value = self.cache.get(
self.get_cache_key(section, name), CachedValueNotFound)
if cached_value is CachedValueNotFound:
raise CachedValueNotFound
if cached_value == prefere... | [
"Return a preference raw_value from cache"
] |
Please provide a description of the function:def many_from_cache(self, preferences):
keys = {
p: self.get_cache_key(p.section.name, p.name)
for p in preferences
}
cached = self.cache.get_many(list(keys.values()))
for k, v in cached.items():
#... | [
"\n Return cached value for given preferences\n missing preferences will be skipped\n "
] |
Please provide a description of the function:def to_cache(self, pref):
key = self.get_cache_key(pref.section, pref.name)
value = pref.raw_value
if value is None or value == '':
# some cache backends refuse to cache None or empty values
# resulting in more DB quer... | [
"\n Update/create the cache value for the given preference model instance\n "
] |
Please provide a description of the function:def get(self, key, no_cache=False):
section, name = self.parse_lookup(key)
preference = self.registry.get(
section=section, name=name, fallback=False)
if no_cache or not preferences_settings.ENABLE_CACHE:
return self.g... | [
"Return the value of a single preference using a dotted path key\n :arg no_cache: if true, the cache is bypassed\n "
] |
Please provide a description of the function:def all(self):
if not preferences_settings.ENABLE_CACHE:
return self.load_from_db()
preferences = self.registry.preferences()
# first we hit the cache once for all existing preferences
a = self.many_from_cache(preference... | [
"Return a dictionary containing all preferences by section\n Loaded from cache or from db in case of cold cache\n "
] |
Please provide a description of the function:def load_from_db(self, cache=False):
a = {}
db_prefs = {p.preference.identifier(): p for p in self.queryset}
for preference in self.registry.preferences():
try:
db_pref = db_prefs[preference.identifier()]
... | [
"Return a dictionary of preferences by section directly from DB"
] |
Please provide a description of the function:def validate_value(self, value):
field = self.instance.preference.setup_field()
value = field.to_python(value)
field.validate(value)
field.run_validators(value)
return value | [
"\n We call validation from the underlying form field\n "
] |
Please provide a description of the function:def to_python(cls, value, **kwargs):
if not value:
return ''
try:
return str(value)
except:
pass
try:
return value.encode('utf-8')
except:
pass
raise cls.exce... | [
"String deserialisation just return the value as a string"
] |
Please provide a description of the function:def enforce_timezone(cls, value):
field_timezone = cls.default_timezone()
if (field_timezone is not None) and not is_aware(value):
return make_aware(value, field_timezone)
elif (field_timezone is None) and is_aware(value):
... | [
"\n When `self.default_timezone` is `None`, always return naive datetimes.\n When `self.default_timezone` is not `None`, always return aware datetimes.\n "
] |
Please provide a description of the function:def identifier(self):
if not self.section.name:
return self.name
return preferences_settings.SECTION_KEY_SEPARATOR.join([self.section.name, self.name]) | [
"\n Return the name and the section of the Preference joined with a separator, with the form `section<separator>name`\n "
] |
Please provide a description of the function:def get_by_instance(self, instance):
# we iterate throught registered preference models in order to get the instance class
# and check if instance is and instance of this class
for model, registry in self.items():
try:
... | [
"Return a preference registry using a model instance"
] |
Please provide a description of the function:def register(self, preference_class):
preference = preference_class(registry=self)
self.section_objects[preference.section.name] = preference.section
try:
self[preference.section.name][preference.name] = preference
excep... | [
"\n Store the given preference class in the registry.\n\n :param preference_class: a :py:class:`prefs.Preference` subclass\n "
] |
Please provide a description of the function:def _fallback(self, section_name, pref_name):
message = (
'Creating a fallback preference with ' +
'section "{}" and name "{}".' +
'This means you have preferences in your database that ' +
'don\'t match any re... | [
"\n Create a fallback preference object,\n This is used when you have model instances that do not match\n any registered preferences, see #41\n "
] |
Please provide a description of the function:def get(self, name, section=None, fallback=False):
# try dotted notation
try:
_section, name = name.split(
preferences_settings.SECTION_KEY_SEPARATOR)
return self[_section][name]
except ValueError:
... | [
"\n Returns a previously registered preference\n\n :param section: The section name under which the preference is registered\n :type section: str.\n :param name: The name of the preference. You can use dotted notation 'section.name' if you want to avoid providing section param\n :... |
Please provide a description of the function:def get_by_name(self, name):
for section in self.values():
for preference in section.values():
if preference.name == name:
return preference
raise NotFoundInRegistry("No such preference in {0} with name... | [
"Get a preference by name only (no section)"
] |
Please provide a description of the function:def manager(self, **kwargs):
return PreferencesManager(registry=self, model=self.preference_model, **kwargs) | [
"Return a preference manager that can be used to retrieve preference values"
] |
Please provide a description of the function:def preferences(self, section=None):
if section is None:
return [self[section][name] for section in self for name in self[section]]
else:
return [self[section][name] for name in self[section]] | [
"\n Return a list of all registered preferences\n or a list of preferences registered for a given section\n\n :param section: The section name under which the preference is registered\n :type section: str.\n :return: a list of :py:class:`prefs.BasePreference` instances\n "
... |
Please provide a description of the function:def user_preference_form_builder(instance, preferences=[], **kwargs):
return preference_form_builder(
UserPreferenceForm,
preferences,
model={'instance': instance},
**kwargs) | [
"\n A shortcut :py:func:`preference_form_builder(UserPreferenceForm, preferences, **kwargs)`\n :param user: a :py:class:`django.contrib.auth.models.User` instance\n "
] |
Please provide a description of the function:def get_queryset(self):
self.init_preferences()
queryset = super(PreferenceViewSet, self).get_queryset()
section = self.request.query_params.get('section')
if section:
queryset = queryset.filter(section=section)
... | [
"\n We just ensure preferences are actually populated before fetching\n from db\n "
] |
Please provide a description of the function:def get_object(self):
queryset = self.filter_queryset(self.get_queryset())
lookup_url_kwarg = self.lookup_url_kwarg or self.lookup_field
identifier = self.kwargs[lookup_url_kwarg]
section, name = self.get_section_and_name(identifier)
... | [
"\n Returns the object the view is displaying.\n You may want to override this if you need to provide non-standard\n queryset lookups. Eg if objects are referenced using multiple\n keyword arguments in the url conf.\n "
] |
Please provide a description of the function:def bulk(self, request, *args, **kwargs):
manager = self.get_manager()
errors = {}
preferences = []
payload = request.data
# first, we check updated preferences actually exists in the registry
try:
for ide... | [
"\n Update multiple preferences at once\n\n this is a long method because we ensure everything is valid\n before actually persisting the changes\n "
] |
Please provide a description of the function:def preference_form_builder(form_base_class, preferences=[], **kwargs):
registry = form_base_class.registry
preferences_obj = []
if len(preferences) > 0:
# Preferences have been selected explicitly
for pref in preferences:
if isin... | [
"\n Return a form class for updating preferences\n :param form_base_class: a Form class used as the base. Must have a ``registry` attribute\n :param preferences: a list of :py:class:\n :param section: a section where the form builder will load preferences\n "
] |
Please provide a description of the function:def set_value(self, value):
self.raw_value = self.preference.serializer.serialize(value) | [
"\n Save serialized self.value to self.raw_value\n "
] |
Please provide a description of the function:def delete_preferences(queryset):
deleted = []
# Iterate through preferences. If an error is raised when accessing preference object, just delete it
for p in queryset:
try:
pref = p.registry.get(section=p.section, name=p.name, fallback=F... | [
"\n Delete preferences objects if they are not present in registry. Return a list of deleted objects\n "
] |
Please provide a description of the function:def create_deletion_handler(preference):
def delete_related_preferences(sender, instance, *args, **kwargs):
queryset = preference.registry.preference_model.objects\
.filter(name=preference.name,
... | [
"\n Will generate a dynamic handler to purge related preference\n on instance deletion\n "
] |
Please provide a description of the function:def get_field_kwargs(self):
kwargs = self.field_kwargs.copy()
kwargs.setdefault('label', self.get('verbose_name'))
kwargs.setdefault('help_text', self.get('help_text'))
kwargs.setdefault('widget', self.get('widget'))
kwargs.se... | [
"\n Return a dict of arguments to use as parameters for the field\n class instianciation.\n\n This will use :py:attr:`field_kwargs` as a starter,\n and use sensible defaults for a few attributes:\n\n - :py:attr:`instance.verbose_name` for the field label\n - :py:attr:`insta... |
Please provide a description of the function:def get_api_field_data(self):
field = self.setup_field()
d = {
'class': field.__class__.__name__,
'widget': {
'class': field.widget.__class__.__name__
}
}
try:
d['input_... | [
"\n Field data to serialize for use on front-end side, for example\n will include choices available for a choice field\n "
] |
Please provide a description of the function:def commiter_factory(config: dict) -> BaseCommitizen:
name: str = config["name"]
try:
_cz = registry[name](config)
except KeyError:
msg_error = (
"The commiter has not been found in the system.\n\n"
f"Try running 'pip ... | [
"Return the correct commitizen existing in the registry."
] |
Please provide a description of the function:def prerelease_generator(current_version: str, prerelease: Optional[str] = None) -> str:
if not prerelease:
return ""
version = Version(current_version)
new_prerelease_number: int = 0
if version.is_prerelease and prerelease.startswith(version.pr... | [
"\n X.YaN # Alpha release\n X.YbN # Beta release\n X.YrcN # Release Candidate\n X.Y # Final\n\n This function might return something like 'alpha1'\n but it will be handled by Version.\n "
] |
Please provide a description of the function:def generate_version(
current_version: str, increment: str, prerelease: Optional[str] = None
) -> Version:
pre_version = prerelease_generator(current_version, prerelease=prerelease)
semver = semver_generator(current_version, increment=increment)
# TODO: ... | [
"Based on the given increment a proper semver will be generated.\n\n For now the rules and versioning scheme is based on\n python's PEP 0440.\n More info: https://www.python.org/dev/peps/pep-0440/\n\n Example:\n PATCH 1.0.0 -> 1.0.1\n MINOR 1.0.0 -> 1.1.0\n MAJOR 1.0.0 -> 2.0.0\n ... |
Please provide a description of the function:def update_version_in_files(current_version: str, new_version: str, files: list):
for filepath in files:
# Read in the file
with open(filepath, "r") as file:
filedata = file.read()
# Replace the target string
filedata = f... | [
"Change old version to the new one in every file given.\n\n Note that this version is not the tag formatted one.\n So for example, your tag could look like `v1.0.0` while your version in\n the package like `1.0.0`.\n "
] |
Please provide a description of the function:def create_tag(version: Union[Version, str], tag_format: Optional[str] = None):
if isinstance(version, str):
version = Version(version)
if not tag_format:
return version.public
major, minor, patch = version.release
prerelease = ""
i... | [
"The tag and the software version might be different.\n\n That's why this function exists.\n\n Example:\n\n | tag | version (PEP 0440) |\n | --- | ------- |\n | v0.9.0 | 0.9.0 |\n | ver1.0.0 | 1.0.0 |\n | ver1.0.0.a0 | 1.0.0a0 |\n\n "
] |
Please provide a description of the function:def read_pyproject_conf(data: str) -> dict:
doc = parse(data)
try:
return doc["tool"]["commitizen"]
except exceptions.NonExistentKey:
return {} | [
"We expect to have a section in pyproject looking like\n\n ```\n [tool.commitizen]\n name = \"cz_conventional_commits\"\n ```\n "
] |
Please provide a description of the function:def read_raw_parser_conf(data: str) -> dict:
config = configparser.ConfigParser(allow_no_value=True)
config.read_string(data)
try:
_data: dict = dict(config["commitizen"])
if "files" in _data:
files = _data["files"]
_f... | [
"We expect to have a section like this\n\n ```\n [commitizen]\n name = cz_jira\n files = [\n \"commitizen/__version__.py\",\n \"pyproject.toml\"\n ] # this tab at the end is important\n ```\n "
] |
Please provide a description of the function:def set_key(key: str, value: str) -> dict:
if not _conf.path:
return {}
if "toml" in _conf.path:
with open(_conf.path, "r") as f:
parser = parse(f.read())
parser["tool"]["commitizen"][key] = value
with open(_conf.path... | [
"Set or update a key in the conf.\n\n For now only strings are supported.\n We use to update the version number.\n "
] |
Please provide a description of the function:def open(self, name, mode='r', compression=None):
if compression == 'use_ext':
self.get_compression_type(name)
else:
self.ctype = compression
if not self.ctype:
self.fp = open(name, mode)
elif sel... | [
"\n Open a file pointer. Note that a file is *always* opened in text\n mode. The method inherits its input parameters from the constructor\n of :class:`FileObject`.\n "
] |
Please provide a description of the function:def close(self):
if self.fp:
self.fp.close()
self.fp = None
if self.fp_extra:
self.fp_extra.close()
self.fp_extra = None
self.ctype = None | [
"\n Close a file pointer.\n "
] |
Please provide a description of the function:def get_compression_type(self, file_name):
ext = os.path.splitext(file_name)[1]
if ext == '.gz':
self.ctype = 'gzip'
elif ext == '.bz2':
self.ctype = 'bzip2'
elif ext in ('.xz', '.lzma'):
self.cty... | [
"\n Determine compression type for a given file using its extension.\n\n :param file_name: a given file name\n :type file_name: str\n "
] |
Please provide a description of the function:def do(to_install):
for solver in to_install:
print('preparing {0}'.format(solver))
download_archive(sources[solver])
extract_archive(sources[solver][-1], solver)
adapt_files(solver)
patch_solver(solver)
compile_solv... | [
"\n Prepare all solvers specified in the command line.\n "
] |
Please provide a description of the function:def download_archive(sources):
# last element is expected to be the local archive name
save_to = sources[-1]
# not downloading the file again if it exists
if os.path.exists(save_to):
print('not downloading {0} since it exists locally'.format(sa... | [
"\n Downloads an archive and saves locally (taken from PySMT).\n "
] |
Please provide a description of the function:def extract_archive(archive, solver, put_inside = False):
print('extracting {0}'.format(archive))
root = os.path.join('solvers', solver if put_inside else '')
if archive.endswith('.tar.gz'):
if os.path.exists(archive[:-7]):
shutil.rmtre... | [
"\n Unzips/untars a previously downloaded archive file.\n "
] |
Please provide a description of the function:def adapt_files(solver):
print("adapting {0}'s files".format(solver))
root = os.path.join('solvers', solver)
for arch in to_extract[solver]:
arch = os.path.join(root, arch)
extract_archive(arch, solver, put_inside=True)
for fnames in t... | [
"\n Rename and remove files whenever necessary.\n "
] |
Please provide a description of the function:def compute(self):
self.setd = []
self.solution = None
self.bb_assumps = [] # backbone assumptions
self.ss_assumps = [] # satisfied soft clause assumptions
if self.oracle.solve():
# hard part is satisfiable => ... | [
"\n Compute and return one solution. This method checks whether the\n hard part of the formula is satisfiable, i.e. an MCS can be\n extracted. If the formula is satisfiable, the model computed by the\n SAT call is used as an *over-approximation* of the MCS in the\n ... |
Please provide a description of the function:def enumerate(self):
done = False
while not done:
mcs = self.compute()
if mcs != None:
yield mcs
else:
done = True | [
"\n This method iterates through MCSes enumerating them until the\n formula has no more MCSes. The method iteratively invokes\n :func:`compute`. Note that the method does not block the MCSes\n computed - this should be explicitly done by a user.\n "
] |
Please provide a description of the function:def block(self, mcs):
self.oracle.add_clause([self.sels[cl_id - 1] for cl_id in mcs]) | [
"\n Block a (previously computed) MCS. The MCS should be given as an\n iterable of integers. Note that this method is not automatically\n invoked from :func:`enumerate` because a user may want to block\n some of the MCSes conditionally depending on the needs. For\n ... |
Please provide a description of the function:def _overapprox(self):
model = self.oracle.get_model()
for sel in self.sels:
if len(model) < sel or model[sel - 1] > 0:
# soft clauses contain positive literals
# so if var is true then the clause is sati... | [
"\n The method extracts a model corresponding to an over-approximation\n of an MCS, i.e. it is the model of the hard part of the formula\n (the corresponding oracle call is made in :func:`compute`).\n\n Here, the set of selectors is divided into two parts:\n ``... |
Please provide a description of the function:def do_cld_check(self, cld):
# adding a selector literal to clause D
# selector literals for clauses D currently
# cannot be reused, but this may change later
self.topv += 1
sel = self.topv
cld.append(-sel)
#... | [
"\n Do the \"clause :math:`D`\" check. This method receives a list of\n literals, which serves a \"clause :math:`D`\" [1]_, and checks\n whether the formula conjoined with :math:`D` is satisfiable.\n\n If clause :math:`D` cannot be satisfied together with the formula,\n ... |
Please provide a description of the function:def _map_extlit(self, l):
v = abs(l)
if v in self.vmap.e2i:
return int(copysign(self.vmap.e2i[v], l))
else:
self.topv += 1
self.vmap.e2i[v] = self.topv
self.vmap.i2e[self.topv] = v
... | [
"\n Map an external variable to an internal one if necessary.\n\n This method is used when new clauses are added to the formula\n incrementally, which may result in introducing new variables\n clashing with the previously used *clause selectors*. The method\n m... |
Please provide a description of the function:def init(self, bootstrap_with):
# formula encoding the sets to hit
formula = WCNF()
# hard clauses
for to_hit in bootstrap_with:
to_hit = list(map(lambda obj: self.idpool.id(obj), to_hit))
formula.append(to_... | [
"\n This method serves for initializing the hitting set solver with a\n given list of sets to hit. Concretely, the hitting set problem is\n encoded into partial MaxSAT as outlined above, which is then fed\n either to a MaxSAT solver or an MCS enumerator.\n\n :p... |
Please provide a description of the function:def get(self):
model = self.oracle.compute()
if model:
if self.htype == 'rc2':
# extracting a hitting set
self.hset = filter(lambda v: v > 0, model)
else:
self.hset = model
... | [
"\n This method computes and returns a hitting set. The hitting set is\n obtained using the underlying oracle operating the MaxSAT problem\n formulation. The computed solution is mapped back to objects of the\n problem domain.\n\n :rtype: list(obj)\n "
] |
Please provide a description of the function:def hit(self, to_hit):
# translating objects to variables
to_hit = list(map(lambda obj: self.idpool.id(obj), to_hit))
# a soft clause should be added for each new object
new_obj = list(filter(lambda vid: vid not in self.oracle.vmap.... | [
"\n This method adds a new set to hit to the hitting set solver. This\n is done by translating the input iterable of objects into a list of\n Boolean variables in the MaxSAT problem formulation.\n\n :param to_hit: a new set to hit\n :type to_hit: iterable(obj)\... |
Please provide a description of the function:def block(self, to_block):
# translating objects to variables
to_block = list(map(lambda obj: self.idpool.id(obj), to_block))
# a soft clause should be added for each new object
new_obj = list(filter(lambda vid: vid not in self.orac... | [
"\n The method serves for imposing a constraint forbidding the hitting\n set solver to compute a given hitting set. Each set to block is\n encoded as a hard clause in the MaxSAT problem formulation, which\n is then added to the underlying oracle.\n\n :param to_... |
Please provide a description of the function:def enumerate(self):
done = False
while not done:
hset = self.get()
if hset != None:
self.block(hset)
yield hset
else:
done = True | [
"\n The method can be used as a simple iterator computing and blocking\n the hitting sets on the fly. It essentially calls :func:`get`\n followed by :func:`block`. Each hitting set is reported as a list\n of objects in the original problem domain, i.e. it is mapped back\n... |
Please provide a description of the function:def atmost(cls, lits, bound=1, top_id=None, encoding=EncType.seqcounter):
if encoding < 0 or encoding > 9:
raise(NoSuchEncodingError(encoding))
if not top_id:
top_id = max(map(lambda x: abs(x), lits))
# we are going... | [
"\n This method can be used for creating a CNF encoding of an AtMostK\n constraint, i.e. of :math:`\\sum_{i=1}^{n}{x_i}\\leq k`. The method\n shares the arguments and the return type with method\n :meth:`CardEnc.atleast`. Please, see it for details.\n "
] |
Please provide a description of the function:def atleast(cls, lits, bound=1, top_id=None, encoding=EncType.seqcounter):
if encoding < 0 or encoding > 9:
raise(NoSuchEncodingError(encoding))
if not top_id:
top_id = max(map(lambda x: abs(x), lits))
# we are goin... | [
"\n This method can be used for creating a CNF encoding of an AtLeastK\n constraint, i.e. of :math:`\\sum_{i=1}^{n}{x_i}\\geq k`. The method\n takes 1 mandatory argument ``lits`` and 3 default arguments can be\n specified: ``bound``, ``top_id``, and ``encoding``.\n\n ... |
Please provide a description of the function:def equals(cls, lits, bound=1, top_id=None, encoding=EncType.seqcounter):
res1 = cls.atleast(lits, bound, top_id, encoding)
res2 = cls.atmost(lits, bound, res1.nv, encoding)
# merging together AtLeast and AtMost constraints
res1.nv ... | [
"\n This method can be used for creating a CNF encoding of an EqualsK\n constraint, i.e. of :math:`\\sum_{i=1}^{n}{x_i}= k`. The method\n makes consecutive calls of both :meth:`CardEnc.atleast` and\n :meth:`CardEnc.atmost`. It shares the arguments and the return type\n ... |
Please provide a description of the function:def new(self, lits=[], ubound=1, top_id=None):
self.lits = list(lits)
self.ubound = ubound
self.top_id = max(map(lambda x: abs(x), self.lits + [top_id if top_id != None else 0]))
# saving default SIGINT handler
def_sigint_ha... | [
"\n The actual constructor of :class:`ITotalizer`. Invoked from\n ``self.__init__()``. Creates an object of :class:`ITotalizer` given\n a list of literals in the sum, the largest potential bound to\n consider, as well as the top variable identifier used so far. See\n ... |
Please provide a description of the function:def delete(self):
if self.tobj:
if not self._merged:
pycard.itot_del(self.tobj)
# otherwise, this totalizer object is merged into a larger one
# therefore, this memory should be freed in its destr... | [
"\n Destroys a previously constructed :class:`ITotalizer` object.\n Internal variables ``self.cnf`` and ``self.rhs`` get cleaned.\n "
] |
Please provide a description of the function:def increase(self, ubound=1, top_id=None):
self.top_id = max(self.top_id, top_id if top_id != None else 0)
# do nothing if the bound is set incorrectly
if ubound <= self.ubound or self.ubound >= len(self.lits):
self.nof_new = 0
... | [
"\n Increases a potential upper bound that can be imposed on the\n literals in the sum of an existing :class:`ITotalizer` object to a\n new value.\n\n :param ubound: a new upper bound.\n :param top_id: a new top variable identifier.\n\n :type ubound:... |
Please provide a description of the function:def extend(self, lits=[], ubound=None, top_id=None):
# preparing a new list of distinct input literals
lits = list(set(lits).difference(set(self.lits)))
if not lits:
# nothing to merge with -> just increase the bound
... | [
"\n Extends the list of literals in the sum and (if needed) increases a\n potential upper bound that can be imposed on the complete list of\n literals in the sum of an existing :class:`ITotalizer` object to a\n new value.\n\n :param lits: additional literals to... |
Please provide a description of the function:def merge_with(self, another, ubound=None, top_id=None):
self.top_id = max(self.top_id, top_id if top_id != None else 0, another.top_id)
self.ubound = max(self.ubound, ubound if ubound != None else 0, another.ubound)
# extending the list of... | [
"\n This method merges a tree of the current :class:`ITotalizer`\n object, with a tree of another object and (if needed) increases a\n potential upper bound that can be imposed on the complete list of\n literals in the sum of an existing :class:`ITotalizer` object to a\n ... |
Please provide a description of the function:def parse_options():
try:
opts, args = getopt.getopt(sys.argv[1:],
'k:n:ht:v',
['kval=',
'size=',
'help',
... | [
"\n Parses command-line options:\n "
] |
Please provide a description of the function:def usage():
print('Usage:', os.path.basename(sys.argv[0]), '[options]')
print('Options:')
print(' -k, --kval=<int> Value k for generating k-PHP')
print(' Available values: [1 .. INT_MAX] (default = 1)')
pr... | [
"\n Prints usage message.\n "
] |
Please provide a description of the function:def add_clause(self, clause, soft=False):
# first, map external literals to internal literals
# introduce new variables if necessary
cl = list(map(lambda l: self._map_extlit(l), clause))
if not soft:
# the clause is hard... | [
"\n The method for adding a new hard of soft clause to the problem\n formula. Although the input formula is to be specified as an\n argument of the constructor of :class:`LBX`, adding clauses may be\n helpful when *enumerating* MCSes of the formula. This way, the\n ... |
Please provide a description of the function:def compute(self):
self.setd = []
self.satc = [False for cl in self.soft] # satisfied clauses
self.solution = None
self.bb_assumps = [] # backbone assumptions
self.ss_assumps = [] # satisfied soft clause assumptions
... | [
"\n Compute and return one solution. This method checks whether the\n hard part of the formula is satisfiable, i.e. an MCS can be\n extracted. If the formula is satisfiable, the model computed by the\n SAT call is used as an *over-approximation* of the MCS in the\n ... |
Please provide a description of the function:def _satisfied(self, cl, model):
for l in cl:
if len(model) < abs(l) or model[abs(l) - 1] == l:
# either literal is unassigned or satisfied by the model
return True
return False | [
"\n Given a clause (as an iterable of integers) and an assignment (as a\n list of integers), this method checks whether or not the assignment\n satisfies the clause. This is done by a simple clause traversal.\n The method is invoked from :func:`_filter_satisfied`.\n\n ... |
Please provide a description of the function:def _filter_satisfied(self, update_setd=False):
model = self.oracle.get_model()
setd = set()
for i, cl in enumerate(self.soft):
if not self.satc[i]:
if self._satisfied(cl, model):
self.satc[i]... | [
"\n This method extracts a model provided by the previous call to a SAT\n oracle and iterates over all soft clauses checking if each of is\n satisfied by the model. Satisfied clauses are marked accordingly\n while the literals of the unsatisfied clauses are kept in a list... |
Please provide a description of the function:def _compute(self):
# unless clause D checks are used, test one literal at a time
# and add it either to satisfied of backbone assumptions
i = 0
while i < len(self.setd):
if self.ucld:
self.do_cld_check(se... | [
"\n The main method of the class, which computes an MCS given its\n over-approximation. The over-approximation is defined by a model\n for the hard part of the formula obtained in :func:`compute`.\n\n The method is essentially a simple loop going over all literals\n ... |
Please provide a description of the function:def do_cld_check(self, cld):
# adding a selector literal to clause D
# selector literals for clauses D currently
# cannot be reused, but this may change later
self.topv += 1
sel = self.topv
cld.append(-sel)
#... | [
"\n Do the \"clause :math:`D`\" check. This method receives a list of\n literals, which serves a \"clause :math:`D`\" [2]_, and checks\n whether the formula conjoined with :math:`D` is satisfiable.\n\n .. [2] Joao Marques-Silva, Federico Heras, Mikolas Janota,\n ... |
Please provide a description of the function:def compute(self):
# cheking whether or not the formula is unsatisfiable
if not self.oracle.solve(assumptions=self.sels):
# get an overapproximation of an MUS
approx = sorted(self.oracle.get_core())
if self.verbo... | [
"\n This is the main method of the :class:`MUSX` class. It computes a\n set of soft clauses belonging to an MUS of the input formula.\n First, the method checks whether the formula is satisfiable. If it\n is, nothing else is done. Otherwise, an *unsatisfiable core* of the... |
Please provide a description of the function:def _compute(self, approx):
i = 0
while i < len(approx):
to_test = approx[:i] + approx[(i + 1):]
sel, clid = approx[i], self.vmap[approx[i]]
if self.verbose > 1:
print('c testing clid: {0}'.forma... | [
"\n Deletion-based MUS extraction. Given an over-approximation of an\n MUS, i.e. an unsatisfiable core previously returned by a SAT\n oracle, the method represents a loop, which at each iteration\n removes a clause from the core and checks whether the remaining\n ... |
Please provide a description of the function:def run(self):
# download and compile solvers
prepare.do(to_install)
# now, do standard build
distutils.command.build.build.run(self) | [
"\n Download, patch and compile SAT solvers before building.\n "
] |
Please provide a description of the function:def add_clause(self, clause, no_return=True):
if self.solver:
res = self.solver.add_clause(clause, no_return)
if not no_return:
return res | [
"\n This method is used to add a single clause to the solver. An\n optional argument ``no_return`` controls whether or not to check\n the formula's satisfiability after adding the new clause.\n\n :param clause: an iterable over literals.\n :param no_return: che... |
Please provide a description of the function:def add_atmost(self, lits, k, no_return=True):
if self.solver:
res = self.solver.add_atmost(lits, k, no_return)
if not no_return:
return res | [
"\n This method is responsible for adding a new *native* AtMostK (see\n :mod:`pysat.card`) constraint into :class:`Minicard`.\n\n **Note that none of the other solvers supports native AtMostK\n constraints**.\n\n An AtMostK constraint is :math:`\\sum_{i=1}^{n}{... |
Please provide a description of the function:def append_formula(self, formula, no_return=True):
if self.solver:
res = self.solver.append_formula(formula, no_return)
if not no_return:
return res | [
"\n This method can be used to add a given list of clauses into the\n solver.\n\n :param formula: a list of clauses.\n :param no_return: check solver's internal formula and return the\n result, if set to ``False``.\n\n :type formula: iterable(ite... |
Please provide a description of the function:def new(self, bootstrap_with=None, use_timer=False, incr=False,
with_proof=False):
assert not incr or not with_proof, 'Incremental mode and proof tracing cannot be set together.'
if not self.glucose:
self.glucose = pysolvers... | [
"\n Actual constructor of the solver.\n "
] |
Please provide a description of the function:def delete(self):
if self.glucose:
pysolvers.glucose3_del(self.glucose)
self.glucose = None
if self.prfile:
self.prfile.close() | [
"\n Destructor.\n "
] |
Please provide a description of the function:def conf_budget(self, budget):
if self.glucose:
pysolvers.glucose3_cbudget(self.glucose, budget) | [
"\n Set limit on the number of conflicts.\n "
] |
Please provide a description of the function:def prop_budget(self, budget):
if self.glucose:
pysolvers.glucose3_pbudget(self.glucose, budget) | [
"\n Set limit on the number of propagations.\n "
] |
Please provide a description of the function:def set_phases(self, literals=[]):
if self.glucose:
pysolvers.glucose3_setphases(self.glucose, literals) | [
"\n Sets polarities of a given list of variables.\n "
] |
Please provide a description of the function:def get_model(self):
if self.glucose and self.status == True:
model = pysolvers.glucose3_model(self.glucose)
return model if model != None else [] | [
"\n Get a model if the formula was previously satisfied.\n "
] |
Please provide a description of the function:def get_core(self):
if self.glucose and self.status == False:
return pysolvers.glucose3_core(self.glucose) | [
"\n Get an unsatisfiable core if the formula was previously\n unsatisfied.\n "
] |
Please provide a description of the function:def get_proof(self):
if self.glucose and self.prfile:
self.prfile.seek(0)
return [line.rstrip() for line in self.prfile.readlines()] | [
"\n Get a proof produced when deciding the formula.\n "
] |
Please provide a description of the function:def add_clause(self, clause, no_return=True):
if self.glucose:
res = pysolvers.glucose3_add_cl(self.glucose, clause)
if res == False:
self.status = False
if not no_return:
return res | [
"\n Add a new clause to solver's internal formula.\n "
] |
Please provide a description of the function:def new(self, bootstrap_with=None, use_timer=False, incr=False,
with_proof=False):
assert not incr or not with_proof, 'Incremental mode and proof tracing cannot be set together.'
if not self.glucose:
self.glucose = pysolvers... | [
"\n Actual constructor of the solver.\n "
] |
Please provide a description of the function:def delete(self):
if self.glucose:
pysolvers.glucose41_del(self.glucose)
self.glucose = None
if self.prfile:
self.prfile.close() | [
"\n Destructor.\n "
] |
Please provide a description of the function:def solve(self, assumptions=[]):
if self.glucose:
if self.use_timer:
start_time = time.clock()
# saving default SIGINT handler
def_sigint_handler = signal.signal(signal.SIGINT, signal.SIG_DFL)
... | [
"\n Solve internal formula.\n "
] |
Please provide a description of the function:def solve_limited(self, assumptions=[]):
if self.glucose:
if self.use_timer:
start_time = time.clock()
# saving default SIGINT handler
def_sigint_handler = signal.signal(signal.SIGINT, signal.SIG_DFL)
... | [
"\n Solve internal formula using given budgets for conflicts and\n propagations.\n "
] |
Please provide a description of the function:def conf_budget(self, budget):
if self.glucose:
pysolvers.glucose41_cbudget(self.glucose, budget) | [
"\n Set limit on the number of conflicts.\n "
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.