_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 31 13.1k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q258300 | AxisGraph.null | validation | def null(self):
"""Zero crossing value."""
if not self.option.axis:
return -1
| python | {
"resource": ""
} |
q258301 | KBinXML.mem_size | validation | def mem_size(self):
'''used when allocating memory ingame'''
data_len = self._data_mem_size
node_count = len(list(self.xml_doc.iter(tag=etree.Element)))
if self.compressed:
size = 52 * node_count + data_len + 630
else:
tags_len = 0
for e in self.xml_doc.iter(tag=etree.Element):
e_len = max(len(e.tag), 8)
e_len = (e_len + 3) & ~3
| python | {
"resource": ""
} |
q258302 | _load_class | validation | def _load_class(class_path, default):
""" Loads the class from the class_path string """
if class_path is None:
return default
component = class_path.rsplit('.', 1)
result_processor = getattr(
| python | {
"resource": ""
} |
q258303 | _process_pagination_values | validation | def _process_pagination_values(request):
""" process pagination requests from request parameter """
size = 20
page = 0
from_ = 0
if "page_size" in request.POST:
size = int(request.POST["page_size"])
max_page_size = getattr(settings, "SEARCH_MAX_PAGE_SIZE", 100)
# The parens below are superfluous, but make it much clearer to the reader what is going on
if | python | {
"resource": ""
} |
q258304 | _process_field_values | validation | def _process_field_values(request):
""" Create separate dictionary of supported filter values provided """
return {
field_key: request.POST[field_key]
| python | {
"resource": ""
} |
q258305 | do_search | validation | def do_search(request, course_id=None):
"""
Search view for http requests
Args:
request (required) - django request object
course_id (optional) - course_id within which to restrict search
Returns:
http json response with the following fields
"took" - how many seconds the operation took
"total" - how many results were found
"max_score" - maximum score from these results
"results" - json array of result documents
or
"error" - displayable information about an error that occured on the server
POST Params:
"search_string" (required) - text upon which to search
"page_size" (optional)- how many results to return per page (defaults to 20, with maximum cutoff at 100)
"page_index" (optional) - for which page (zero-indexed) to include results (defaults to 0)
"""
# Setup search environment
SearchInitializer.set_search_enviroment(request=request, course_id=course_id)
results = {
"error": _("Nothing to search")
}
status_code = 500
search_term = request.POST.get("search_string", None)
try:
if not search_term:
raise ValueError(_('No search term provided for search'))
size, from_, page = _process_pagination_values(request)
# Analytics - log search request
track.emit(
'edx.course.search.initiated',
{
"search_term": search_term,
"page_size": size,
"page_number": page,
}
)
results = perform_search(
search_term,
user=request.user,
size=size,
from_=from_,
course_id=course_id
)
status_code = 200
# Analytics - log search results before sending to browser
track.emit(
| python | {
"resource": ""
} |
q258306 | course_discovery | validation | def course_discovery(request):
"""
Search for courses
Args:
request (required) - django request object
Returns:
http json response with the following fields
"took" - how many seconds the operation took
"total" - how many results were found
"max_score" - maximum score from these resutls
"results" - json array of result documents
or
"error" - displayable information about an error that occured on the server
POST Params:
"search_string" (optional) - text with which to search for courses
"page_size" (optional)- how many results to return per page (defaults to 20, with maximum cutoff at 100)
"page_index" (optional) - for which page (zero-indexed) to include results (defaults to 0)
"""
results = {
"error": _("Nothing to search")
}
status_code = 500
search_term = request.POST.get("search_string", None)
try:
size, from_, page = _process_pagination_values(request)
field_dictionary = _process_field_values(request)
# Analytics - log search request
track.emit(
'edx.course_discovery.search.initiated',
{
"search_term": search_term,
"page_size": size,
"page_number": page,
}
)
results = course_discovery_search(
search_term=search_term,
size=size,
from_=from_,
field_dictionary=field_dictionary,
)
# Analytics - log search results before sending to browser
track.emit(
'edx.course_discovery.search.results_displayed',
{
"search_term": search_term,
"page_size": size,
| python | {
"resource": ""
} |
q258307 | _translate_hits | validation | def _translate_hits(es_response):
""" Provide resultset in our desired format from elasticsearch results """
def translate_result(result):
""" Any conversion from ES result syntax into our search engine syntax """
translated_result = copy.copy(result)
data = translated_result.pop("_source")
translated_result.update({
"data": data,
"score": translated_result["_score"]
})
return translated_result
def translate_facet(result):
""" Any conversion from ES facet syntax into our search engine sytax """
terms = {term["term"]: term["count"] for term in result["terms"]}
return {
"terms": terms,
| python | {
"resource": ""
} |
q258308 | _get_filter_field | validation | def _get_filter_field(field_name, field_value):
""" Return field to apply into filter, if an array then use a range, otherwise look for a term match """
filter_field = None
if isinstance(field_value, ValueRange):
range_values = {}
if field_value.lower:
range_values.update({"gte": field_value.lower_string})
if field_value.upper:
range_values.update({"lte": field_value.upper_string})
filter_field = {
"range": {
field_name: range_values
| python | {
"resource": ""
} |
q258309 | _process_field_queries | validation | def _process_field_queries(field_dictionary):
"""
We have a field_dictionary - we want to match the values for an elasticsearch "match" query
This is only potentially useful when trying to tune certain search operations
"""
def field_item(field):
""" format field match as "match" item for elasticsearch query """
| python | {
"resource": ""
} |
q258310 | _process_filters | validation | def _process_filters(filter_dictionary):
"""
We have a filter_dictionary - this means that if the field is included
and matches, then we can include, OR if the field is undefined, then we
assume it is safe to include
"""
def filter_item(field):
""" format elasticsearch filter to pass if value matches OR field is not included """
| python | {
"resource": ""
} |
q258311 | _process_exclude_dictionary | validation | def _process_exclude_dictionary(exclude_dictionary):
"""
Based on values in the exclude_dictionary generate a list of term queries that
will filter out unwanted results.
"""
# not_properties will hold the generated term queries.
not_properties = []
for exclude_property in exclude_dictionary:
exclude_values = exclude_dictionary[exclude_property]
if not isinstance(exclude_values, list):
exclude_values = [exclude_values]
not_properties.extend([{"term": | python | {
"resource": ""
} |
q258312 | _process_facet_terms | validation | def _process_facet_terms(facet_terms):
""" We have a list of terms with which we return facets """
elastic_facets = {}
for facet in facet_terms:
facet_term = {"field": facet}
if facet_terms[facet]:
for facet_option in facet_terms[facet]:
| python | {
"resource": ""
} |
q258313 | ElasticSearchEngine.get_mappings | validation | def get_mappings(cls, index_name, doc_type):
""" fetch mapped-items structure from cache """
| python | {
"resource": ""
} |
q258314 | ElasticSearchEngine.set_mappings | validation | def set_mappings(cls, index_name, doc_type, mappings):
""" set new mapped-items structure into cache """
| python | {
"resource": ""
} |
q258315 | ElasticSearchEngine.log_indexing_error | validation | def log_indexing_error(cls, indexing_errors):
""" Logs indexing errors and raises a general ElasticSearch Exception"""
indexing_errors_log = []
for indexing_error in indexing_errors:
| python | {
"resource": ""
} |
q258316 | ElasticSearchEngine._get_mappings | validation | def _get_mappings(self, doc_type):
"""
Interfaces with the elasticsearch mappings for the index
prevents multiple loading of the same mappings from ES when called more than once
Mappings format in elasticsearch is as follows:
{
"doc_type": {
"properties": {
"nested_property": {
"properties": {
"an_analysed_property": {
"type": "string"
},
"another_analysed_property": {
"type": "string"
}
}
},
"a_not_analysed_property": {
"type": "string",
"index": "not_analyzed"
},
"a_date_property": {
"type": "date"
}
}
| python | {
"resource": ""
} |
q258317 | ElasticSearchEngine.index | validation | def index(self, doc_type, sources, **kwargs):
"""
Implements call to add documents to the ES index
Note the call to _check_mappings which will setup fields with the desired mappings
"""
try:
actions = []
for source in sources:
self._check_mappings(doc_type, source)
id_ = source['id'] if 'id' in source else None
log.debug("indexing %s object with id %s", doc_type, id_)
action = {
"_index": self.index_name,
"_type": doc_type,
"_id": id_,
"_source": source
}
actions.append(action)
# bulk() returns a tuple with summary information
# number of successfully executed actions and number of errors if stats_only is | python | {
"resource": ""
} |
q258318 | ElasticSearchEngine.remove | validation | def remove(self, doc_type, doc_ids, **kwargs):
""" Implements call to remove the documents from the index """
try:
# ignore is flagged as an unexpected-keyword-arg; ES python client documents that it can be used
# pylint: disable=unexpected-keyword-arg
actions = []
for doc_id in doc_ids:
log.debug("Removing document of type %s and index %s", doc_type, doc_id)
action = {
'_op_type': 'delete',
"_index": self.index_name,
"_type": doc_type,
"_id": doc_id
}
| python | {
"resource": ""
} |
q258319 | ElasticSearchEngine.search | validation | def search(self,
query_string=None,
field_dictionary=None,
filter_dictionary=None,
exclude_dictionary=None,
facet_terms=None,
exclude_ids=None,
use_field_match=False,
**kwargs): # pylint: disable=too-many-arguments, too-many-locals, too-many-branches, arguments-differ
"""
Implements call to search the index for the desired content.
Args:
query_string (str): the string of values upon which to search within the
content of the objects within the index
field_dictionary (dict): dictionary of values which _must_ exist and
_must_ match in order for the documents to be included in the results
filter_dictionary (dict): dictionary of values which _must_ match if the
field exists in order for the documents to be included in the results;
documents for which the field does not exist may be included in the
results if they are not otherwise filtered out
exclude_dictionary(dict): dictionary of values all of which which must
not match in order for the documents to be included in the results;
documents which have any of these fields and for which the value matches
one of the specified values shall be filtered out of the result set
facet_terms (dict): dictionary of terms to include within search
facets list - key is the term desired to facet upon, and the value is a
dictionary of extended information to include. Supported right now is a
size specification for a cap upon how many facet results to return (can
be an empty dictionary to use default size for underlying engine):
e.g.
{
"org": {"size": 10}, # only show top 10 organizations
"modes": {}
}
use_field_match (bool): flag to indicate whether to use elastic
filtering or elastic matching for field matches - this is nothing but a
potential performance tune for certain queries
(deprecated) exclude_ids (list): list of id values to exclude from the results -
useful for finding maches that aren't "one of these"
Returns:
dict object with results in the desired format
{
"took": 3,
"total": 4,
"max_score": 2.0123,
"results": [
{
"score": 2.0123,
"data": {
...
}
},
{
"score": 0.0983,
| python | {
"resource": ""
} |
q258320 | perform_search | validation | def perform_search(
search_term,
user=None,
size=10,
from_=0,
course_id=None):
""" Call the search engine with the appropriate parameters """
# field_, filter_ and exclude_dictionary(s) can be overridden by calling application
# field_dictionary includes course if course_id provided
(field_dictionary, filter_dictionary, exclude_dictionary) = SearchFilterGenerator.generate_field_filters(
user=user,
course_id=course_id
)
searcher = SearchEngine.get_search_engine(getattr(settings, "COURSEWARE_INDEX_NAME", "courseware_index"))
if not searcher:
raise NoSearchEngineError("No search engine specified in settings.SEARCH_ENGINE")
results = searcher.search_string(
search_term,
field_dictionary=field_dictionary,
filter_dictionary=filter_dictionary,
exclude_dictionary=exclude_dictionary,
| python | {
"resource": ""
} |
q258321 | course_discovery_search | validation | def course_discovery_search(search_term=None, size=20, from_=0, field_dictionary=None):
"""
Course Discovery activities against the search engine index of course details
"""
# We'll ignore the course-enrollemnt informaiton in field and filter
# dictionary, and use our own logic upon enrollment dates for these
use_search_fields = ["org"]
(search_fields, _, exclude_dictionary) = SearchFilterGenerator.generate_field_filters()
use_field_dictionary = {}
use_field_dictionary.update({field: search_fields[field] for field in search_fields if field in use_search_fields})
if field_dictionary:
use_field_dictionary.update(field_dictionary)
| python | {
"resource": ""
} |
q258322 | SearchResultProcessor.strings_in_dictionary | validation | def strings_in_dictionary(dictionary):
""" Used by default implementation for finding excerpt """
strings = [value for value in six.itervalues(dictionary) if not isinstance(value, dict)]
for child_dict in [dv for dv | python | {
"resource": ""
} |
q258323 | SearchResultProcessor.find_matches | validation | def find_matches(strings, words, length_hoped):
""" Used by default property excerpt """
lower_words = [w.lower() for w in words]
def has_match(string):
""" Do any of the words match within the string """
lower_string = string.lower()
for test_word in lower_words:
if test_word in lower_string:
return True
return False
shortened_strings = [textwrap.wrap(s) for s in strings]
short_string_list = list(chain.from_iterable(shortened_strings))
matches = | python | {
"resource": ""
} |
q258324 | SearchResultProcessor.decorate_matches | validation | def decorate_matches(match_in, match_word):
""" decorate the matches within the excerpt """
matches = re.finditer(match_word, match_in, re.IGNORECASE)
for matched_string in set([match.group() for match in matches]):
match_in = match_in.replace(
| python | {
"resource": ""
} |
q258325 | SearchResultProcessor.add_properties | validation | def add_properties(self):
"""
Called during post processing of result
Any properties defined in your subclass will get exposed as members of the | python | {
"resource": ""
} |
q258326 | SearchResultProcessor.process_result | validation | def process_result(cls, dictionary, match_phrase, user):
"""
Called from within search handler. Finds desired subclass and decides if the
result should be removed and adds properties derived from the result information
"""
result_processor = _load_class(getattr(settings, "SEARCH_RESULT_PROCESSOR", None), cls)
srp = result_processor(dictionary, match_phrase)
if srp.should_remove(user):
return None
try:
srp.add_properties()
# protect around any problems introduced by subclasses within their properties
| python | {
"resource": ""
} |
q258327 | SearchResultProcessor.excerpt | validation | def excerpt(self):
"""
Property to display a useful excerpt representing the matches within the results
"""
if "content" not in self._results_fields:
return None
match_phrases = [self._match_phrase]
if six.PY2:
separate_phrases = [
phrase.decode('utf-8')
for phrase in shlex.split(self._match_phrase.encode('utf-8'))
]
else:
separate_phrases = [
phrase
for phrase in shlex.split(self._match_phrase)
]
if len(separate_phrases) > 1:
| python | {
"resource": ""
} |
q258328 | SearchFilterGenerator.generate_field_filters | validation | def generate_field_filters(cls, **kwargs):
"""
Called from within search handler
Finds desired subclass and adds filter information based upon user information
"""
generator = _load_class(getattr(settings, "SEARCH_FILTER_GENERATOR", None), cls)()
return (
| python | {
"resource": ""
} |
q258329 | SearchInitializer.set_search_enviroment | validation | def set_search_enviroment(cls, **kwargs):
"""
Called from within search handler
Finds desired subclass and calls initialize method
"""
| python | {
"resource": ""
} |
q258330 | Detector._parse | validation | def _parse(self, filename):
"""Opens data file and for each line, calls _eat_name_line"""
self.names = {}
with codecs.open(filename, encoding="iso8859-1") as f:
for line in f:
if any(map(lambda | python | {
"resource": ""
} |
q258331 | Detector._eat_name_line | validation | def _eat_name_line(self, line):
"""Parses one line of data file"""
if line[0] not in "#=":
parts = line.split()
country_values = line[30:-1]
name = map_name(parts[1])
if not self.case_sensitive:
name = name.lower()
if parts[0] == "M":
self._set(name, u"male", country_values)
elif parts[0] == "1M" or parts[0] == "?M":
self._set(name, u"mostly_male", country_values)
elif parts[0] == "F":
self._set(name, | python | {
"resource": ""
} |
q258332 | Detector._set | validation | def _set(self, name, gender, country_values):
"""Sets gender and relevant country values for names dictionary of detector"""
if '+' in name:
for replacement in ['', ' ', '-']:
self._set(name.replace('+', replacement), gender, country_values)
else:
| python | {
"resource": ""
} |
q258333 | Detector._most_popular_gender | validation | def _most_popular_gender(self, name, counter):
"""Finds the most popular gender for the given name counting by given counter"""
if name not in self.names:
return self.unknown_value
max_count, max_tie = (0, 0)
best = self.names[name].keys()[0]
for gender, country_values in self.names[name].items():
| python | {
"resource": ""
} |
q258334 | Detector.get_gender | validation | def get_gender(self, name, country=None):
"""Returns best gender for the given name and country pair"""
if not self.case_sensitive:
name = name.lower()
if name not in self.names:
return self.unknown_value
elif not country:
def counter(country_values):
country_values = map(ord, country_values.replace(" ", ""))
return (len(country_values),
sum(map(lambda c: c > 64 and c-55 or c-48, country_values)))
return self._most_popular_gender(name, counter)
| python | {
"resource": ""
} |
q258335 | Report.output | validation | def output(self, msg, newline=True):
"""
Writes the specified string to the output target of the report.
:param msg: the message to output.
:type msg: str
:param newline:
whether or not | python | {
"resource": ""
} |
q258336 | execute_tools | validation | def execute_tools(config, path, progress=None):
"""
Executes the suite of TidyPy tools upon the project and returns the
issues that are found.
:param config: the TidyPy configuration to use
:type config: dict
:param path: that path to the project to analyze
:type path: str
:param progress:
the progress reporter object that will receive callbacks during the
execution of the tool suite. If not specified, not progress
notifications will occur.
:type progress: tidypy.Progress
:rtype: tidypy.Collector
"""
progress = progress or QuietProgress()
progress.on_start()
manager = SyncManager()
manager.start()
num_tools = 0
tools = manager.Queue()
for name, cls in iteritems(get_tools()):
if config[name]['use'] and cls.can_be_used():
num_tools += 1
tools.put({
'name': name,
'config': config[name],
})
collector = Collector(config)
if not num_tools:
progress.on_finish()
return collector
notifications = manager.Queue()
environment = manager.dict({
'finder': Finder(path, config),
| python | {
"resource": ""
} |
q258337 | execute_reports | validation | def execute_reports(
config,
path,
collector,
on_report_finish=None,
output_file=None):
"""
Executes the configured suite of issue reports.
:param config: the TidyPy configuration to use
:type config: dict
:param path: that path to the project that was analyzed
:type path: str
:param collector: the issues to report
| python | {
"resource": ""
} |
q258338 | Finder.is_excluded | validation | def is_excluded(self, path):
"""
Determines whether or not the specified file is excluded by the
project's configuration.
:param path: the path to check
:type path: pathlib.Path
:rtype: bool
| python | {
"resource": ""
} |
q258339 | Finder.is_excluded_dir | validation | def is_excluded_dir(self, path):
"""
Determines whether or not the specified directory is excluded by the
project's configuration.
:param path: the path to check
:type path: pathlib.Path
:rtype: bool | python | {
"resource": ""
} |
q258340 | Finder.files | validation | def files(self, filters=None):
"""
A generator that produces a sequence of paths to files in the project
that matches the specified filters.
:param filters:
the regular expressions to use when finding files in the project.
| python | {
"resource": ""
} |
q258341 | Finder.directories | validation | def directories(self, filters=None, containing=None):
"""
A generator that produces a sequence of paths to directories in the
project that matches the specified filters.
:param filters:
the regular expressions to use when finding directories in the
project. If not specified, all directories are returned.
:type filters: list(str)
:param containing:
if a directory passes through the specified filters, it is checked
for the presence of a file that matches one of the regular
expressions in this parameter.
:type containing: | python | {
"resource": ""
} |
q258342 | Collector.add_issues | validation | def add_issues(self, issues):
"""
Adds an issue to the collection.
:param issues: the issue(s) to add
:type issues: tidypy.Issue or list(tidypy.Issue)
"""
if not isinstance(issues, (list, tuple)):
| python | {
"resource": ""
} |
q258343 | Collector.issue_count | validation | def issue_count(self, include_unclean=False):
"""
Returns the number of issues in the collection.
:param include_unclean:
whether or not to include issues that are being ignored due to
being a duplicate, excluded, etc.
:type include_unclean: bool
| python | {
"resource": ""
} |
q258344 | Collector.get_issues | validation | def get_issues(self, sortby=None):
"""
Retrieves the issues in the collection.
:param sortby: the properties to sort the | python | {
"resource": ""
} |
q258345 | Collector.get_grouped_issues | validation | def get_grouped_issues(self, keyfunc=None, sortby=None):
"""
Retrieves the issues in the collection grouped into buckets according
to the key generated by the keyfunc.
:param keyfunc:
a function that will be used to generate the key that identifies
the group that an issue will be assigned to. This function receives
a single tidypy.Issue argument and must return a string. If not
specified, the filename of the issue will be used.
:type keyfunc: func
:param sortby: the properties to sort the issues by | python | {
"resource": ""
} |
q258346 | Extender.parse | validation | def parse(cls, content, is_pyproject=False):
"""
A convenience method for parsing a TOML-serialized configuration.
:param content: a TOML string containing a TidyPy configuration
:type content: str
:param is_pyproject:
whether or not the content is (or resembles) a ``pyproject.toml``
file, where the TidyPy configuration is located within a key named
| python | {
"resource": ""
} |
q258347 | get_tools | validation | def get_tools():
"""
Retrieves the TidyPy tools that are available in the current Python
environment.
The returned dictionary has keys that are the tool names and values are the
tool classes.
:rtype: dict
"""
# pylint: disable=protected-access
if not hasattr(get_tools, '_CACHE'):
get_tools._CACHE = dict()
for entry in pkg_resources.iter_entry_points('tidypy.tools'):
try:
get_tools._CACHE[entry.name] = entry.load()
except ImportError as exc: # pragma: no cover
| python | {
"resource": ""
} |
q258348 | get_reports | validation | def get_reports():
"""
Retrieves the TidyPy issue reports that are available in the current Python
environment.
The returned dictionary has keys are the report names and values are the
report classes.
:rtype: dict
"""
# pylint: disable=protected-access
if not hasattr(get_reports, '_CACHE'):
get_reports._CACHE = dict()
for entry in pkg_resources.iter_entry_points('tidypy.reports'):
try:
get_reports._CACHE[entry.name] = entry.load()
except ImportError as exc: # pragma: no cover
| python | {
"resource": ""
} |
q258349 | get_extenders | validation | def get_extenders():
"""
Retrieves the TidyPy configuration extenders that are available in the
current Python environment.
The returned dictionary has keys are the extender names and values are the
extender classes.
:rtype: dict
"""
# pylint: disable=protected-access
if not hasattr(get_extenders, '_CACHE'):
get_extenders._CACHE = dict()
for entry in pkg_resources.iter_entry_points('tidypy.extenders'):
try:
get_extenders._CACHE[entry.name] = entry.load()
except ImportError as exc: # pragma: | python | {
"resource": ""
} |
q258350 | purge_config_cache | validation | def purge_config_cache(location=None):
"""
Clears out the cache of TidyPy configurations that were retrieved from
outside the normal locations.
"""
| python | {
"resource": ""
} |
q258351 | get_user_config | validation | def get_user_config(project_path, use_cache=True):
"""
Produces a TidyPy configuration that incorporates the configuration files
stored in the current user's home directory.
:param project_path: the path to the project that is going to be analyzed
:type project_path: str
:param use_cache:
whether or not to use cached versions of any remote/referenced TidyPy
configurations. If not specified, defaults to ``True``.
:type use_cache: bool
:rtype: dict
"""
if sys.platform == 'win32':
user_config = os.path.expanduser(r'~\\tidypy')
else:
user_config = os.path.join(
os.getenv('XDG_CONFIG_HOME') or os.path.expanduser('~/.config'),
| python | {
"resource": ""
} |
q258352 | get_local_config | validation | def get_local_config(project_path, use_cache=True):
"""
Produces a TidyPy configuration using the ``pyproject.toml`` in the
project's directory.
:param project_path: the path to the project that is going to be analyzed
:type project_path: str
:param use_cache:
whether or not to use cached versions of any remote/referenced TidyPy
configurations. If not specified, defaults to ``True``.
:type use_cache: bool
:rtype: dict
"""
pyproject_path = os.path.join(project_path, | python | {
"resource": ""
} |
q258353 | get_project_config | validation | def get_project_config(project_path, use_cache=True):
"""
Produces the Tidypy configuration to use for the specified project.
If a ``pyproject.toml`` exists, the configuration will be based on that. If
not, the TidyPy configuration in the user's home directory will be used. If
one does not exist, the default configuration will be used.
:param project_path: the path to the project that is going to be analyzed
:type project_path: str
:param use_cache:
| python | {
"resource": ""
} |
q258354 | merge_list | validation | def merge_list(list1, list2):
"""
Merges the contents of two lists into a new list.
:param list1: the first list
:type list1: list
| python | {
"resource": ""
} |
q258355 | merge_dict | validation | def merge_dict(dict1, dict2, merge_lists=False):
"""
Recursively merges the contents of two dictionaries into a new dictionary.
When both input dictionaries share a key, the value from ``dict2`` is
kept.
:param dict1: the first dictionary
:type dict1: dict
:param dict2: the second dictionary
:type dict2: dict
:param merge_lists:
when this function encounters a key that contains lists in both input
dictionaries, this parameter dictates whether or not those lists should
be merged. If not specified, defaults to ``False``.
:type merge_lists: bool
:returns: dict
"""
merged = dict(dict1)
| python | {
"resource": ""
} |
q258356 | output_error | validation | def output_error(msg):
"""
Prints the specified string to ``stderr``.
:param msg: the message to print
:type msg: str
| python | {
"resource": ""
} |
q258357 | mod_sys_path | validation | def mod_sys_path(paths):
"""
A context manager that will append the specified paths to Python's
``sys.path`` during the execution of the | python | {
"resource": ""
} |
q258358 | compile_masks | validation | def compile_masks(masks):
"""
Compiles a list of regular expressions.
:param masks: the regular expressions to compile
:type masks: list(str) or str
:returns: list(regular expression object)
"""
if not masks:
masks = []
| python | {
"resource": ""
} |
q258359 | matches_masks | validation | def matches_masks(target, masks):
"""
Determines whether or not the target string matches any of the regular
expressions specified.
:param target: the string to check
:type target: str
:param masks: the regular expressions | python | {
"resource": ""
} |
q258360 | read_file | validation | def read_file(filepath):
"""
Retrieves the contents of the specified file.
This function performs simple caching so that the same file isn't read more
than once per process.
:param filepath: the file to read
:type filepath: str
:returns: str
"""
| python | {
"resource": ""
} |
q258361 | parse_python_file | validation | def parse_python_file(filepath):
"""
Retrieves the AST of the specified file.
This function performs simple caching so that the same file isn't read or
parsed more than once per process.
:param filepath: the file to parse
:type filepath: str
:returns: ast.AST
"""
with _AST_CACHE_LOCK: | python | {
"resource": ""
} |
q258362 | Progress.on_tool_finish | validation | def on_tool_finish(self, tool):
"""
Called when an individual tool completes execution.
:param tool: the name of the tool that completed
:type tool: str
"""
with self._lock:
| python | {
"resource": ""
} |
q258363 | Emulator.exec_command | validation | def exec_command(self, cmdstr):
"""
Execute an x3270 command
`cmdstr` gets sent directly to the x3270 subprocess on it's stdin.
"""
if self.is_terminated:
raise TerminatedError("this TerminalClient instance has been terminated")
log.debug("sending command: %s", cmdstr)
c = Command(self.app, cmdstr)
| python | {
"resource": ""
} |
q258364 | Emulator.terminate | validation | def terminate(self):
"""
terminates the underlying x3270 subprocess. Once called, this
Emulator instance must no longer be used.
"""
if not self.is_terminated:
log.debug("terminal client terminated")
try:
self.exec_command(b"Quit")
except BrokenPipeError: # noqa
# x3270 was terminated, since we are just quitting anyway, ignore it.
pass
| python | {
"resource": ""
} |
q258365 | Emulator.is_connected | validation | def is_connected(self):
"""
Return bool indicating connection state
"""
# need to wrap in try/except b/c of wc3270's socket connection dynamics
try:
# this is basically a no-op, but it results in the the current status
# getting updated
self.exec_command(b"Query(ConnectionState)") | python | {
"resource": ""
} |
q258366 | Emulator.connect | validation | def connect(self, host):
"""
Connect to a host
"""
if not self.app.connect(host):
| python | {
"resource": ""
} |
q258367 | Emulator.wait_for_field | validation | def wait_for_field(self):
"""
Wait until the screen is ready, the cursor has been positioned
on a modifiable field, and the keyboard is unlocked.
Sometimes the server will "unlock" the keyboard but the screen will
not yet be ready. In that case, an attempt to read or write to the
screen will result in a 'E' keyboard status because we tried to
read from a screen that is not yet ready.
Using this method tells the client to wait until a field is
detected and the cursor has been positioned on | python | {
"resource": ""
} |
q258368 | Emulator.move_to | validation | def move_to(self, ypos, xpos):
"""
move the cursor to the given co-ordinates. Co-ordinates are 1
based, as listed in the status area of the terminal.
"""
# the screen's co-ordinates are 1 based, but the command is 0 based
| python | {
"resource": ""
} |
q258369 | Emulator.fill_field | validation | def fill_field(self, ypos, xpos, tosend, length):
"""
clears the field at the position given and inserts the string
`tosend`
tosend: the string to insert
length: the length of the field
Co-ordinates are 1 based, as listed in the status area of the
terminal.
raises: FieldTruncateError if `tosend` is longer than
`length`.
"""
| python | {
"resource": ""
} |
q258370 | Constraint.from_func | validation | def from_func(cls, func, variables, vartype, name=None):
"""Construct a constraint from a validation function.
Args:
func (function):
Function that evaluates True when the variables satisfy the constraint.
variables (iterable):
Iterable of variable labels.
vartype (:class:`~dimod.Vartype`/str/set):
Variable type for the constraint. Accepted input values:
* :attr:`~dimod.Vartype.SPIN`, ``'SPIN'``, ``{-1, 1}``
* :attr:`~dimod.Vartype.BINARY`, ``'BINARY'``, ``{0, 1}``
name (string, optional, default='Constraint'):
Name for the constraint.
Examples:
This example creates a constraint that binary variables `a` and `b`
are not equal.
>>> import dwavebinarycsp
>>> import operator
>>> const = dwavebinarycsp.Constraint.from_func(operator.ne, ['a', 'b'], 'BINARY')
>>> print(const.name)
Constraint
>>> (0, 1) in const.configurations
True
This example creates a constraint that :math:`out = NOT(x)`
for spin variables. | python | {
"resource": ""
} |
q258371 | Constraint.from_configurations | validation | def from_configurations(cls, configurations, variables, vartype, name=None):
"""Construct a constraint from valid configurations.
Args:
configurations (iterable[tuple]):
Valid configurations of the variables. Each configuration is a tuple of variable
assignments ordered by :attr:`~Constraint.variables`.
variables (iterable):
Iterable of variable labels.
vartype (:class:`~dimod.Vartype`/str/set):
Variable type for the constraint. Accepted input values:
* :attr:`~dimod.Vartype.SPIN`, ``'SPIN'``, ``{-1, 1}``
* :attr:`~dimod.Vartype.BINARY`, ``'BINARY'``, ``{0, 1}``
name (string, optional, default='Constraint'):
Name for the constraint.
Examples:
This example creates a constraint that variables `a` and `b` are not equal.
>>> import dwavebinarycsp
>>> const = dwavebinarycsp.Constraint.from_configurations([(0, 1), (1, 0)],
... ['a', 'b'], dwavebinarycsp.BINARY)
>>> print(const.name)
Constraint
>>> | python | {
"resource": ""
} |
q258372 | Constraint.check | validation | def check(self, solution):
"""Check that a solution satisfies the constraint.
Args:
solution (container):
An assignment for the variables in the constraint.
Returns:
bool: True if the solution satisfies the constraint; otherwise False.
Examples:
This example creates a constraint that :math:`a \\ne b` on binary variables
and tests it for two candidate solutions, with additional unconstrained
variable c.
>>> import dwavebinarycsp
>>> const = dwavebinarycsp.Constraint.from_configurations([(0, 1), (1, 0)],
| python | {
"resource": ""
} |
q258373 | Constraint.fix_variable | validation | def fix_variable(self, v, value):
"""Fix the value of a variable and remove it from the constraint.
Args:
v (variable):
Variable in the constraint to be set to a constant value.
val (int):
Value assigned to the variable. Values must match the :class:`.Vartype` of the
constraint.
Examples:
This example creates a constraint that :math:`a \\ne b` on binary variables,
fixes variable a to 0, and tests two candidate solutions.
>>> import dwavebinarycsp
>>> const = dwavebinarycsp.Constraint.from_func(operator.ne,
... ['a', 'b'], dwavebinarycsp.BINARY)
>>> const.fix_variable('a', 0)
>>> const.check({'b': 1})
True
>>> const.check({'b': 0})
False
"""
variables = self.variables
try:
idx = variables.index(v)
except ValueError:
raise ValueError("given variable {} is not part of the constraint".format(v))
if value not | python | {
"resource": ""
} |
q258374 | Constraint.flip_variable | validation | def flip_variable(self, v):
"""Flip a variable in the constraint.
Args:
v (variable):
Variable in the constraint to take the complementary value of its
construction value.
Examples:
This example creates a constraint that :math:`a = b` on binary variables
and flips variable a.
>>> import dwavebinarycsp
>>> const = dwavebinarycsp.Constraint.from_func(operator.eq,
... ['a', 'b'], dwavebinarycsp.BINARY)
>>> const.check({'a': 0, 'b': 0})
True
>>> const.flip_variable('a')
>>> const.check({'a': 1, 'b': 0})
True
>>> const.check({'a': 0, 'b': 0})
False
"""
try:
idx = self.variables.index(v)
except ValueError:
raise ValueError("variable {} is not a variable in constraint {}".format(v, self.name))
if self.vartype is dimod.BINARY:
original_func = self.func
def func(*args):
new_args = list(args)
| python | {
"resource": ""
} |
q258375 | Constraint.copy | validation | def copy(self):
"""Create a copy.
Examples:
This example copies constraint :math:`a \\ne b` and tests a solution
on the copied constraint.
>>> import dwavebinarycsp
>>> import operator
>>> const = dwavebinarycsp.Constraint.from_func(operator.ne,
... ['a', 'b'], 'BINARY')
>>> const2 = const.copy()
>>> const2 is const
False | python | {
"resource": ""
} |
q258376 | Constraint.projection | validation | def projection(self, variables):
"""Create a new constraint that is the projection onto a subset of the variables.
Args:
variables (iterable):
Subset of the constraint's variables.
Returns:
:obj:`.Constraint`: A new constraint over a subset of the variables.
Examples:
>>> import dwavebinarycsp
...
>>> const = dwavebinarycsp.Constraint.from_configurations([(0, 0), (0, 1)],
... ['a', 'b'],
... dwavebinarycsp.BINARY)
>>> proj = const.projection(['a'])
>>> proj.variables
['a']
>>> proj.configurations
{(0,)}
| python | {
"resource": ""
} |
q258377 | assert_penaltymodel_factory_available | validation | def assert_penaltymodel_factory_available():
"""For `dwavebinarycsp` to be functional, at least one penalty model factory
has to be installed. See discussion in setup.py for details.
"""
from pkg_resources import iter_entry_points
from penaltymodel.core import FACTORY_ENTRYPOINT
from itertools import chain
supported = ('maxgap', 'mip')
factories = chain(*(iter_entry_points(FACTORY_ENTRYPOINT, name) for name in supported))
try:
| python | {
"resource": ""
} |
q258378 | add_constraint | validation | def add_constraint(self, constraint, variables=tuple()):
"""Add a constraint.
Args:
constraint (function/iterable/:obj:`.Constraint`):
Constraint definition in one of the supported formats:
1. Function, with input arguments matching the order and
:attr:`~.ConstraintSatisfactionProblem.vartype` type of the `variables`
argument, that evaluates True when the constraint is satisfied.
2. List explicitly specifying each allowed configuration as a tuple.
3. :obj:`.Constraint` object built either explicitly or by :mod:`dwavebinarycsp.factories`.
variables(iterable):
Variables associated with the constraint. Not required when `constraint` is
a :obj:`.Constraint` object.
Examples:
This example defines a function that evaluates True when the constraint is satisfied.
The function's input arguments match the order and type of the `variables` argument.
>>> import dwavebinarycsp
>>> csp = dwavebinarycsp.ConstraintSatisfactionProblem(dwavebinarycsp.BINARY)
>>> def all_equal(a, b, c): # works for both dwavebinarycsp.BINARY and dwavebinarycsp.SPIN
... return (a == b) and (b == c)
>>> csp.add_constraint(all_equal, ['a', 'b', 'c'])
>>> csp.check({'a': 0, 'b': 0, 'c': 0})
True
>>> csp.check({'a': 0, 'b': 0, 'c': 1})
False
This example explicitly lists allowed configurations.
>>> import dwavebinarycsp
>>> csp = dwavebinarycsp.ConstraintSatisfactionProblem(dwavebinarycsp.SPIN)
>>> eq_configurations = {(-1, -1), (1, 1)}
>>> csp.add_constraint(eq_configurations, ['v0', 'v1'])
>>> csp.check({'v0': -1, 'v1': +1})
False
>>> csp.check({'v0': -1, 'v1': -1})
True
This example uses a :obj:`.Constraint` object built by :mod:`dwavebinarycsp.factories`.
>>> import dwavebinarycsp
| python | {
"resource": ""
} |
q258379 | stitch | validation | def stitch(csp, min_classical_gap=2.0, max_graph_size=8):
"""Build a binary quadratic model with minimal energy levels at solutions to the specified constraint satisfaction
problem.
Args:
csp (:obj:`.ConstraintSatisfactionProblem`):
Constraint satisfaction problem.
min_classical_gap (float, optional, default=2.0):
Minimum energy gap from ground. Each constraint violated by the solution increases
the energy level of the binary quadratic model by at least this much relative
to ground energy.
max_graph_size (int, optional, default=8):
Maximum number of variables in the binary quadratic model that can be used to
represent a single constraint.
Returns:
:class:`~dimod.BinaryQuadraticModel`
Notes:
For a `min_classical_gap` > 2 or constraints with more than two variables, requires
access to factories from the penaltymodel_ ecosystem to construct the binary quadratic
model.
.. _penaltymodel: https://github.com/dwavesystems/penaltymodel
Examples:
This example creates a binary-valued constraint satisfaction problem
with two constraints, :math:`a = b` and :math:`b \\ne c`, and builds
a binary quadratic model with a minimum energy level of -2 such that
each constraint violation by a solution adds the default minimum energy gap.
>>> import dwavebinarycsp
>>> import operator
>>> csp = dwavebinarycsp.ConstraintSatisfactionProblem(dwavebinarycsp.BINARY)
>>> csp.add_constraint(operator.eq, ['a', 'b']) # a == b
>>> csp.add_constraint(operator.ne, ['b', 'c']) # b != c
>>> bqm = dwavebinarycsp.stitch(csp)
>>> bqm.energy({'a': 0, 'b': 0, 'c': 1}) # satisfies csp
-2.0
>>> bqm.energy({'a': 0, 'b': 0, 'c': 0}) # violates one constraint
0.0
>>> bqm.energy({'a': 1, 'b': 0, 'c': 0}) # violates two constraints
2.0
This example creates a binary-valued constraint satisfaction problem
with two constraints, :math:`a = b` and :math:`b \\ne c`, and builds
a binary quadratic model with a minimum energy gap of 4.
Note that in this case the conversion to binary quadratic model adds two
ancillary variables that must be minimized over when solving.
>>> import dwavebinarycsp
>>> import operator
>>> import itertools
>>> csp = dwavebinarycsp.ConstraintSatisfactionProblem(dwavebinarycsp.BINARY)
>>> csp.add_constraint(operator.eq, ['a', 'b']) # a == b
>>> csp.add_constraint(operator.ne, ['b', 'c']) # b != c
>>> bqm = dwavebinarycsp.stitch(csp, min_classical_gap=4.0)
>>> list(bqm) # # doctest: +SKIP
| python | {
"resource": ""
} |
q258380 | _bqm_from_1sat | validation | def _bqm_from_1sat(constraint):
"""create a bqm for a constraint with only one variable
bqm will have exactly classical gap 2.
"""
configurations = constraint.configurations
num_configurations = len(configurations)
bqm = dimod.BinaryQuadraticModel.empty(constraint.vartype)
if num_configurations == 1:
val, = next(iter(configurations))
| python | {
"resource": ""
} |
q258381 | _bqm_from_2sat | validation | def _bqm_from_2sat(constraint):
"""create a bqm for a constraint with two variables.
bqm will have exactly classical gap 2.
"""
configurations = constraint.configurations
variables = constraint.variables
vartype = constraint.vartype
u, v = constraint.variables
# if all configurations are present, then nothing is infeasible and the bqm is just all
# 0.0s
if len(configurations) == 4:
return dimod.BinaryQuadraticModel.empty(constraint.vartype)
# check if the constraint is irreducible, and if so, build the bqm for its two
# components
components = irreducible_components(constraint)
if len(components) > 1:
const0 = Constraint.from_configurations(((config[0],) for config in configurations),
(u,), vartype)
const1 = Constraint.from_configurations(((config[1],) for config in configurations),
(v,), vartype)
bqm = _bqm_from_1sat(const0)
bqm.update(_bqm_from_1sat(const1))
return bqm
assert len(configurations) > 1, "single configurations should be irreducible"
# if it is not irreducible, and there are infeasible configurations, then it is time to
# start building a bqm
bqm = dimod.BinaryQuadraticModel.empty(vartype)
# if the constraint is not irreducible and has two configurations, then it is either eq or ne
if all(operator.eq(*config) for config in configurations):
bqm.add_interaction(u, v, -1, vartype=dimod.SPIN) # equality
elif all(operator.ne(*config) for config in configurations):
| python | {
"resource": ""
} |
q258382 | iter_complete_graphs | validation | def iter_complete_graphs(start, stop, factory=None):
"""Iterate over complete graphs.
Args:
start (int/iterable):
Define the size of the starting graph.
If an int, the nodes will be index-labeled, otherwise should be an iterable of node
labels.
stop (int):
Stops yielding graphs when the size equals stop.
factory (iterator, optional):
If provided, nodes added will be labeled according to the values returned by factory.
Otherwise the extra nodes will be index-labeled.
Yields:
:class:`nx.Graph`
"""
_, nodes = start
nodes | python | {
"resource": ""
} |
q258383 | load_cnf | validation | def load_cnf(fp):
"""Load a constraint satisfaction problem from a .cnf file.
Args:
fp (file, optional):
`.write()`-supporting `file object`_ DIMACS CNF formatted_ file.
Returns:
:obj:`.ConstraintSatisfactionProblem` a binary-valued SAT problem.
Examples:
>>> import dwavebinarycsp as dbcsp
...
>>> with open('test.cnf', 'r') as fp: # doctest: +SKIP
... csp = dbcsp.cnf.load_cnf(fp)
.. _file object: https://docs.python.org/3/glossary.html#term-file-object
.. _formatted: http://www.satcompetition.org/2009/format-benchmarks2009.html
"""
fp = iter(fp) # handle lists/tuples/etc
csp = ConstraintSatisfactionProblem(dimod.BINARY)
# first look for the problem
num_clauses = num_variables = 0
problem_pattern = re.compile(_PROBLEM_REGEX)
for line in fp:
matches = problem_pattern.findall(line)
if matches:
if len(matches) > 1:
raise ValueError
nv, nc = matches[0]
num_variables, num_clauses = int(nv), int(nc)
break
# now parse the clauses, picking up where we left off looking for the header
clause_pattern = re.compile(_CLAUSE_REGEX)
for line in fp:
| python | {
"resource": ""
} |
q258384 | and_gate | validation | def and_gate(variables, vartype=dimod.BINARY, name='AND'):
"""AND gate.
Args:
variables (list): Variable labels for the and gate as `[in1, in2, out]`,
where `in1, in2` are inputs and `out` the gate's output.
vartype (Vartype, optional, default='BINARY'): Variable type. Accepted
input values:
* Vartype.SPIN, 'SPIN', {-1, 1}
* Vartype.BINARY, 'BINARY', {0, 1}
name (str, optional, default='AND'): Name for the constraint.
Returns:
Constraint(:obj:`.Constraint`): Constraint that is satisfied when its variables are
assigned values that match the valid states of an AND gate.
Examples:
>>> import dwavebinarycsp
>>> import dwavebinarycsp.factories.constraint.gates as gates
>>> csp = dwavebinarycsp.ConstraintSatisfactionProblem(dwavebinarycsp.BINARY)
>>> csp.add_constraint(gates.and_gate(['a', 'b', 'c'], name='AND1'))
>>> csp.check({'a': 1, 'b': 0, 'c': 0})
True
"""
variables = tuple(variables)
if vartype is dimod.BINARY:
configurations = frozenset([(0, 0, 0),
(0, 1, 0),
| python | {
"resource": ""
} |
q258385 | xor_gate | validation | def xor_gate(variables, vartype=dimod.BINARY, name='XOR'):
"""XOR gate.
Args:
variables (list): Variable labels for the and gate as `[in1, in2, out]`,
where `in1, in2` are inputs and `out` the gate's output.
vartype (Vartype, optional, default='BINARY'): Variable type. Accepted
input values:
* Vartype.SPIN, 'SPIN', {-1, 1}
* Vartype.BINARY, 'BINARY', {0, 1}
name (str, optional, default='XOR'): Name for the constraint.
Returns:
Constraint(:obj:`.Constraint`): Constraint that is satisfied when its variables are
assigned values that match the valid states of an XOR gate.
Examples:
>>> import dwavebinarycsp
>>> import dwavebinarycsp.factories.constraint.gates as gates
>>> csp = dwavebinarycsp.ConstraintSatisfactionProblem(dwavebinarycsp.BINARY)
>>> csp.add_constraint(gates.xor_gate(['x', 'y', 'z'], name='XOR1'))
>>> csp.check({'x': 1, 'y': 1, 'z': 1})
False
"""
variables = tuple(variables)
if vartype is dimod.BINARY:
configs = frozenset([(0, 0, 0),
(0, 1, 1),
| python | {
"resource": ""
} |
q258386 | halfadder_gate | validation | def halfadder_gate(variables, vartype=dimod.BINARY, name='HALF_ADDER'):
"""Half adder.
Args:
variables (list): Variable labels for the and gate as `[in1, in2, sum, carry]`,
where `in1, in2` are inputs to be added and `sum` and 'carry' the resultant
outputs.
vartype (Vartype, optional, default='BINARY'): Variable type. Accepted
input values:
* Vartype.SPIN, 'SPIN', {-1, 1}
* Vartype.BINARY, 'BINARY', {0, 1}
name (str, optional, default='HALF_ADDER'): Name for the constraint.
Returns:
Constraint(:obj:`.Constraint`): Constraint that is satisfied when its variables are
assigned values that match the valid states of a Boolean half adder.
Examples:
>>> import dwavebinarycsp
>>> import dwavebinarycsp.factories.constraint.gates as gates
>>> csp = dwavebinarycsp.ConstraintSatisfactionProblem(dwavebinarycsp.BINARY)
>>> csp.add_constraint(gates.halfadder_gate(['a', 'b', 'total', 'carry'], name='HA1'))
>>> csp.check({'a': 1, 'b': 1, 'total': 0, 'carry': 1})
True
"""
variables = tuple(variables)
if vartype is dimod.BINARY:
configs = frozenset([(0, 0, 0, 0),
(0, 1, 1, 0),
| python | {
"resource": ""
} |
q258387 | fulladder_gate | validation | def fulladder_gate(variables, vartype=dimod.BINARY, name='FULL_ADDER'):
"""Full adder.
Args:
variables (list): Variable labels for the and gate as `[in1, in2, in3, sum, carry]`,
where `in1, in2, in3` are inputs to be added and `sum` and 'carry' the resultant
outputs.
vartype (Vartype, optional, default='BINARY'): Variable type. Accepted
input values:
* Vartype.SPIN, 'SPIN', {-1, 1}
* Vartype.BINARY, 'BINARY', {0, 1}
name (str, optional, default='FULL_ADDER'): Name for the constraint.
Returns:
Constraint(:obj:`.Constraint`): Constraint that is satisfied when its variables are
assigned values that match the valid states of a Boolean full adder.
Examples:
>>> import dwavebinarycsp
>>> import dwavebinarycsp.factories.constraint.gates as gates
>>> csp = dwavebinarycsp.ConstraintSatisfactionProblem(dwavebinarycsp.BINARY)
>>> csp.add_constraint(gates.fulladder_gate(['a', 'b', 'c_in', 'total', 'c_out'], name='FA1'))
>>> csp.check({'a': 1, 'b': 0, 'c_in': 1, 'total': 0, 'c_out': 1})
True
"""
variables = tuple(variables)
if vartype is dimod.BINARY:
configs = frozenset([(0, 0, 0, 0, 0),
(0, 0, 1, 1, 0),
(0, 1, 0, 1, 0),
(0, 1, 1, 0, 1),
(1, 0, 0, 1, 0),
(1, 0, 1, 0, 1),
(1, 1, 0, 0, 1),
| python | {
"resource": ""
} |
q258388 | random_xorsat | validation | def random_xorsat(num_variables, num_clauses, vartype=dimod.BINARY, satisfiable=True):
"""Random XOR constraint satisfaction problem.
Args:
num_variables (integer): Number of variables (at least three).
num_clauses (integer): Number of constraints that together constitute the
constraint satisfaction problem.
vartype (Vartype, optional, default='BINARY'): Variable type. Accepted
input values:
* Vartype.SPIN, 'SPIN', {-1, 1}
* Vartype.BINARY, 'BINARY', {0, 1}
satisfiable (bool, optional, default=True): True if the CSP can be satisfied.
Returns:
CSP (:obj:`.ConstraintSatisfactionProblem`): CSP that is satisfied when its variables
are assigned values that satisfy a XOR satisfiability problem.
Examples:
This example creates a CSP with 5 variables and two random constraints and checks
whether a particular assignment of variables satisifies it.
>>> import dwavebinarycsp
>>> import dwavebinarycsp.factories as sat
>>> csp = sat.random_xorsat(5, 2)
>>> csp.constraints # doctest: +SKIP
[Constraint.from_configurations(frozenset({(1, 0, 0), (1, 1, 1), (0, 1, 0), (0, 0, 1)}), (4, 3, 0),
Vartype.BINARY, name='XOR (0 flipped)'),
Constraint.from_configurations(frozenset({(1, 1, 0), (0, 1, 1), (0, 0, 0), (1, 0, 1)}), (2, 0, 4),
Vartype.BINARY, name='XOR (2 flipped) (0 flipped)')]
>>> csp.check({0: 1, 1: 0, 2: 0, 3: 1, 4: 1}) # doctest: +SKIP
True
"""
if num_variables < 3:
raise ValueError("a xor problem needs at least 3 variables")
if num_clauses > 8 * _nchoosek(num_variables, 3): # 8 different negation patterns
raise ValueError("too many clauses")
# also checks the vartype argument
csp = ConstraintSatisfactionProblem(vartype)
variables = list(range(num_variables))
constraints = set()
if satisfiable:
values = tuple(vartype.value)
planted_solution = {v: choice(values) for v in variables}
configurations = [(0, 0, 0), (0, 1, 1), (1, 0, 1), (1, 1, 0)]
while len(constraints) < num_clauses:
# because constraints are hashed on configurations/variables, and because the inputs
# to xor can be swapped without loss of generality, we can order them
x, y, z = sample(variables, 3)
if y > x:
x, y = y, x
# | python | {
"resource": ""
} |
q258389 | signature_matches | validation | def signature_matches(func, args=(), kwargs={}):
"""
Work out if a function is callable with some args or not.
"""
try:
| python | {
"resource": ""
} |
q258390 | last_arg_decorator | validation | def last_arg_decorator(func):
"""
Allows a function to be used as either a decorator with args, or called as
a normal function.
@last_arg_decorator
def register_a_thing(foo, func, bar=True):
..
# Called as a decorator
@register_a_thing("abc", bar=False)
| python | {
"resource": ""
} |
q258391 | Registry.register_chooser | validation | def register_chooser(self, chooser, **kwargs):
"""Adds a model chooser definition to the registry."""
if not | python | {
"resource": ""
} |
q258392 | Registry.register_simple_chooser | validation | def register_simple_chooser(self, model, **kwargs):
"""
Generates a model chooser definition from a model, and adds it to the
registry.
"""
name = '{}Chooser'.format(model._meta.object_name)
attrs = {'model': model}
| python | {
"resource": ""
} |
q258393 | AudioField.formatter | validation | def formatter(self, api_client, data, newval):
"""Get audio-related fields
Try to find fields for the audio url for specified preferred quality
level, or next-lowest available quality url otherwise.
"""
url_map = data.get("audioUrlMap")
audio_url = data.get("audioUrl")
# Only an audio URL, not a quality map. This happens for most of the
# mobile client tokens and some of the others now. In this case
# substitute the empirically determined default values in the format
# used by the rest of the function so downstream consumers continue to
# work.
if audio_url and not url_map:
url_map = {
BaseAPIClient.HIGH_AUDIO_QUALITY: {
"audioUrl": audio_url,
"bitrate": 64,
"encoding": "aacplus",
}
}
elif not url_map: # No audio url available (e.g. ad tokens)
return None
valid_audio_formats = [BaseAPIClient.HIGH_AUDIO_QUALITY,
| python | {
"resource": ""
} |
q258394 | AdditionalUrlField.formatter | validation | def formatter(self, api_client, data, newval):
"""Parse additional url fields and map them to inputs
Attempt to create a dictionary with keys being user input, and
response being the returned URL
| python | {
"resource": ""
} |
q258395 | PandoraModel.from_json_list | validation | def from_json_list(cls, api_client, data):
"""Convert a list of JSON values to a list of models
"""
| python | {
"resource": ""
} |
q258396 | PandoraModel.populate_fields | validation | def populate_fields(api_client, instance, data):
"""Populate all fields of a model with data
Given a model with a PandoraModel superclass will enumerate all
declared fields on that model and populate the values of their Field
and SyntheticField classes. All declared fields will have a value after
this function runs even if they are missing from the incoming JSON.
"""
for key, value in instance.__class__._fields.items():
default = getattr(value, "default", None)
newval = data.get(value.field, default)
if isinstance(value, SyntheticField):
newval = value.formatter(api_client, data, newval)
| python | {
"resource": ""
} |
q258397 | PandoraModel.from_json | validation | def from_json(cls, api_client, data):
"""Convert one JSON value to a model object
"""
self | python | {
"resource": ""
} |
q258398 | PandoraModel._base_repr | validation | def _base_repr(self, and_also=None):
"""Common repr logic for subclasses to hook
"""
items = [
"=".join((key, repr(getattr(self, key))))
for key in sorted(self._fields.keys())]
if items:
output = ", ".join(items)
else:
output = None
if and_also:
| python | {
"resource": ""
} |
q258399 | BasePlayer._send_cmd | validation | def _send_cmd(self, cmd):
"""Write command to remote process
"""
| python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.