INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
Loads the class from the class_path string | 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(
importlib.import_module(component[0]),
component[1],
default
) if len(comp... |
Checks if an item is iterable ( list tuple generator ) but not string | def _is_iterable(item):
""" Checks if an item is iterable (list, tuple, generator), but not string """
return isinstance(item, collections.Iterable) and not isinstance(item, six.string_types) |
process pagination requests from request parameter | 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 b... |
Create separate dictionary of supported filter values provided | def _process_field_values(request):
""" Create separate dictionary of supported filter values provided """
return {
field_key: request.POST[field_key]
for field_key in request.POST
if field_key in course_discovery_filter_fields()
} |
Search view for http requests | 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 second... |
Search for courses | 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... |
Provide resultset in our desired format from elasticsearch results | 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("_sour... |
Return field to apply into filter if an array then use a range otherwise look for a term match | 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":... |
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 _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 el... |
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 _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 ... |
Based on values in the exclude_dictionary generate a list of term queries that will filter out unwanted results. | 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:... |
We have a list of terms with which we return facets | 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]:
facet_term[facet_option] =... |
fetch mapped - items structure from cache | def get_mappings(cls, index_name, doc_type):
""" fetch mapped-items structure from cache """
return cache.get(cls.get_cache_item_name(index_name, doc_type), {}) |
set new mapped - items structure into cache | def set_mappings(cls, index_name, doc_type, mappings):
""" set new mapped-items structure into cache """
cache.set(cls.get_cache_item_name(index_name, doc_type), mappings) |
Logs indexing errors and raises a general ElasticSearch Exception | 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:
indexing_errors_log.append(str(indexing_error))
raise exceptions.ElasticsearchException(', '.... |
Interfaces with the elasticsearch mappings for the index prevents multiple loading of the same mappings from ES when called more than once | 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"... |
We desire to index content so that anything we want to be textually searchable ( and therefore needing to be analysed ) but the other fields are designed to be filters and only require an exact match. So we want to set up the mappings for these fields as not_analyzed - this will allow our filters to work faster because... | def _check_mappings(self, doc_type, body):
"""
We desire to index content so that anything we want to be textually searchable(and therefore needing to be
analysed), but the other fields are designed to be filters, and only require an exact match. So, we want to
set up the mappings for th... |
Implements call to add documents to the ES index Note the call to _check_mappings which will setup fields with the desired mappings | 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_... |
Implements call to remove the documents from the index | 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 = []
... |
Implements call to search the index for the desired content. | 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... |
Returns the desired implementor ( defined in settings ) | def get_search_engine(index=None):
"""
Returns the desired implementor (defined in settings)
"""
search_engine_class = _load_class(getattr(settings, "SEARCH_ENGINE", None), None)
return search_engine_class(index=index) if search_engine_class else None |
Call the search engine with the appropriate parameters | 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 cou... |
Course Discovery activities against the search engine index of course details | 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... |
Used by default implementation for finding excerpt | 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 in six.itervalues(dictionary) if isinstance(dv, dict)]:
strings.exte... |
Used by default property excerpt | 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_w... |
decorate the matches within the excerpt | 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(
matched_string,
... |
Called during post processing of result Any properties defined in your subclass will get exposed as members of the result json from the search | def add_properties(self):
"""
Called during post processing of result
Any properties defined in your subclass will get exposed as members of the result json from the search
"""
for property_name in [p[0] for p in inspect.getmembers(self.__class__) if isinstance(p[1], property)]:
... |
Called from within search handler. Finds desired subclass and decides if the result should be removed and adds properties derived from the result information | 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_... |
Property to display a useful excerpt representing the matches within the results | 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 = [
... |
Called from within search handler Finds desired subclass and adds filter information based upon user information | 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 (
gene... |
Called from within search handler Finds desired subclass and calls initialize method | def set_search_enviroment(cls, **kwargs):
"""
Called from within search handler
Finds desired subclass and calls initialize method
"""
initializer = _load_class(getattr(settings, "SEARCH_INITIALIZER", None), cls)()
return initializer.initialize(**kwargs) |
Opens data file and for each line calls _eat_name_line | 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 c: 128 < ord(c) < 160, line)):
line = line.encode("iso... |
Parses one line of data file | 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] ... |
Sets gender and relevant country values for names dictionary of detector | 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:
if name ... |
Finds the most popular gender for the given name counting by given counter | 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_valu... |
Returns best gender for the given name and country pair | 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):... |
Writes the specified string to the output target of the report. | 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 to append a newline to the end of the message
:type newline: str
... |
Executes the suite of TidyPy tools upon the project and returns the issues that are found. | 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 progre... |
Executes the configured suite of issue reports. | 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 analyz... |
Determines whether or not the specified file is excluded by the project s configuration. | 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
"""
relpath = path.relative_to(self.base_path).as_posix()
... |
Determines whether or not the specified directory is excluded by the project s configuration. | 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
"""
if self.is_excluded(path):
return True... |
A generator that produces a sequence of paths to files in the project that matches the specified filters. | 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.
If not specified, all files are returned... |
A generator that produces a sequence of paths to directories in the project that matches the specified filters. | 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 no... |
A generator that produces a sequence of paths to files that look to be Python modules ( e. g. *. py ). | def modules(self, filters=None):
"""
A generator that produces a sequence of paths to files that look to be
Python modules (e.g., ``*.py``).
:param filters:
the regular expressions to use when finding files in the project.
If not specified, all files are returned... |
Produces a list of paths that would be suitable to use in sys. path in order to access the Python modules/ packages found in this project. | def sys_paths(self, filters=None):
"""
Produces a list of paths that would be suitable to use in ``sys.path``
in order to access the Python modules/packages found in this project.
:param filters:
the regular expressions to use when finding files in the project.
I... |
Adds an issue to the collection. | 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)):
issues = [issues]
with self._lock:
self._... |
Returns the number of issues in the collection. | 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
:rtype: ... |
Retrieves the issues in the collection. | def get_issues(self, sortby=None):
"""
Retrieves the issues in the collection.
:param sortby: the properties to sort the issues by
:type sortby: list(str)
:rtype: list(tidypy.Issue)
"""
self._ensure_cleaned_issues()
return self._sort_issues(self._cleaned... |
Retrieves the issues in the collection grouped into buckets according to the key generated by the keyfunc. | 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... |
A convenience method for parsing a TOML - serialized configuration. | 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 `... |
Retrieves the TidyPy tools that are available in the current Python environment. | 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'):... |
Retrieves the TidyPy issue reports that are available in the current Python environment. | 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,... |
Retrieves the TidyPy configuration extenders that are available in the current Python environment. | 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 hasa... |
Clears out the cache of TidyPy configurations that were retrieved from outside the normal locations. | def purge_config_cache(location=None):
"""
Clears out the cache of TidyPy configurations that were retrieved from
outside the normal locations.
"""
cache_path = get_cache_path(location)
if location:
os.remove(cache_path)
else:
shutil.rmtree(cache_path) |
Produces a stock/ out - of - the - box TidyPy configuration. | def get_default_config():
"""
Produces a stock/out-of-the-box TidyPy configuration.
:rtype: dict
"""
config = {}
for name, cls in iteritems(get_tools()):
config[name] = cls.get_default_config()
try:
workers = multiprocessing.cpu_count() - 1
except NotImplementedError:... |
Produces a TidyPy configuration that incorporates the configuration files stored in the current user s home directory. | 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:
... |
Produces a TidyPy configuration using the pyproject. toml in the project s directory. | 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 cach... |
Produces the Tidypy configuration to use for the specified project. | 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, t... |
Merges the contents of two lists into a new list. | def merge_list(list1, list2):
"""
Merges the contents of two lists into a new list.
:param list1: the first list
:type list1: list
:param list2: the second list
:type list2: list
:returns: list
"""
merged = list(list1)
for value in list2:
if value not in merged:
... |
Recursively merges the contents of two dictionaries into a new dictionary. | 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 dictiona... |
Prints the specified string to stderr. | def output_error(msg):
"""
Prints the specified string to ``stderr``.
:param msg: the message to print
:type msg: str
"""
click.echo(click.style(msg, fg='red'), err=True) |
A context manager that will append the specified paths to Python s sys. path during the execution of the block. | def mod_sys_path(paths):
"""
A context manager that will append the specified paths to Python's
``sys.path`` during the execution of the block.
:param paths: the paths to append
:type paths: list(str)
"""
old_path = sys.path
sys.path = paths + sys.path
try:
yield
finall... |
Compiles a list of regular expressions. | 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 = []
elif not isinstance(masks, (list, tuple)):
masks =... |
Determines whether or not the target string matches any of the regular expressions specified. | 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 to check against
:type masks: list(regular expression object)
:r... |
Retrieves the contents of the specified file. | 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
"""
with _FILE_CACHE_LOCK:
if f... |
Retrieves the AST of the specified file. | 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_L... |
Called when an individual tool completes execution. | 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:
if tool in self.current_tools:
self.current_tools.remove(tool)
... |
Execute an x3270 command | 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 co... |
terminates the underlying x3270 subprocess. Once called this Emulator instance must no longer be used. | 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")
... |
Return bool indicating connection state | 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
sel... |
Connect to a host | def connect(self, host):
"""
Connect to a host
"""
if not self.app.connect(host):
command = "Connect({0})".format(host).encode("ascii")
self.exec_command(command)
self.last_host = host |
Wait until the screen is ready the cursor has been positioned on a modifiable field and the keyboard is unlocked. | 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 re... |
move the cursor to the given co - ordinates. Co - ordinates are 1 based as listed in the status area of the terminal. | 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
xpos -= 1
ypos -= 1
self.... |
Send a string to the screen at the current cursor location or at screen co - ordinates ypos/ xpos if they are both given. | def send_string(self, tosend, ypos=None, xpos=None):
"""
Send a string to the screen at the current cursor location or at
screen co-ordinates `ypos`/`xpos` if they are both given.
Co-ordinates are 1 based, as listed in the status area of the
terminal.
"""... |
Get a string of length at screen co - ordinates ypos/ xpos | def string_get(self, ypos, xpos, length):
"""
Get a string of `length` at screen co-ordinates `ypos`/`xpos`
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
... |
Return True if string is found at screen co - ordinates ypos/ xpos False otherwise. | def string_found(self, ypos, xpos, string):
"""
Return True if `string` is found at screen co-ordinates
`ypos`/`xpos`, False otherwise.
Co-ordinates are 1 based, as listed in the status area of the
terminal.
"""
found = self.string_get(ypos, xpos,... |
clears the field at the position given and inserts the string tosend | 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
... |
Humidity is stored as an unsigned 16 bits in 1/ 512%RH. The default value is 50% = 0x64 0x00. As an example 48. 5% humidity would be 0x61 0x00. | def setEnvironmentalData(self, humidity, temperature):
''' Humidity is stored as an unsigned 16 bits in 1/512%RH. The
default value is 50% = 0x64, 0x00. As an example 48.5%
humidity would be 0x61, 0x00.'''
''' Temperature is stored as an unsigned 16 bits integer in 1/512
degrees there is an offset: 0 maps... |
Construct a constraint from a validation function. | 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 variab... |
Construct a constraint from valid configurations. | 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
assignme... |
Check that a solution satisfies the constraint. | 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:... |
Fix the value of a variable and remove it from the constraint. | 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 :cl... |
Flip a variable in the constraint. | 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 ... |
Create a copy. | 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.... |
Create a new constraint that is the projection onto a subset of the variables. | 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 variab... |
Multiplication circuit constraint satisfaction problem. | def multiplication_circuit(nbit, vartype=dimod.BINARY):
"""Multiplication circuit constraint satisfaction problem.
A constraint satisfaction problem that represents the binary multiplication :math:`ab=p`,
where the multiplicands are binary variables of length `nbit`; for example,
:math:`a_0 + 2a_1 + 4a... |
Returns True if XOR ( a b ) == out and fault == 0 or XOR ( a b ) ! = out and fault == 1. | def xor_fault(a, b, out, fault):
"""Returns True if XOR(a, b) == out and fault == 0 or XOR(a, b) != out and fault == 1."""
if (a != b) == out:
return fault == 0
else:
return fault == 1 |
Returns True if AND ( a b ) == out and fault == 0 or AND ( a b ) ! = out and fault == 1. | def and_fault(a, b, out, fault):
"""Returns True if AND(a, b) == out and fault == 0 or AND(a, b) != out and fault == 1."""
if (a and b) == out:
return fault == 0
else:
return fault == 1 |
Returns True if OR ( a b ) == out and fault == 0 or OR ( a b ) ! = out and fault == 1. | def or_fault(a, b, out, fault):
"""Returns True if OR(a, b) == out and fault == 0 or OR(a, b) != out and fault == 1."""
if (a or b) == out:
return fault == 0
else:
return fault == 1 |
For dwavebinarycsp to be functional at least one penalty model factory has to be installed. See discussion in setup. py for details. | 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 ... |
Add a constraint. | 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
... |
Build a binary quadratic model with minimal energy levels at solutions to the specified constraint satisfaction problem. | 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_classica... |
create a bqm for a constraint with only one variable | 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_configur... |
create a bqm for a constraint with two variables. | 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 a... |
Iterate over complete graphs. | 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):
... |
Load a constraint satisfaction problem from a. cnf file. | 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:
>>> impo... |
AND gate. | 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
... |
XOR gate. | 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
... |
Half adder. | 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 (Vart... |
Full adder. | 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.
var... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.