id
int32
0
252k
repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
51
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
233,200
nameko/nameko
nameko/extensions.py
ProviderCollector.wait_for_providers
def wait_for_providers(self): """ Wait for any providers registered with the collector to have unregistered. Returns immediately if no providers were ever registered. """ if self._providers_registered: _log.debug('waiting for providers to unregister %s', self) self._last_provider_unregistered.wait() _log.debug('all providers unregistered %s', self)
python
def wait_for_providers(self): if self._providers_registered: _log.debug('waiting for providers to unregister %s', self) self._last_provider_unregistered.wait() _log.debug('all providers unregistered %s', self)
[ "def", "wait_for_providers", "(", "self", ")", ":", "if", "self", ".", "_providers_registered", ":", "_log", ".", "debug", "(", "'waiting for providers to unregister %s'", ",", "self", ")", "self", ".", "_last_provider_unregistered", ".", "wait", "(", ")", "_log",...
Wait for any providers registered with the collector to have unregistered. Returns immediately if no providers were ever registered.
[ "Wait", "for", "any", "providers", "registered", "with", "the", "collector", "to", "have", "unregistered", "." ]
88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d
https://github.com/nameko/nameko/blob/88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d/nameko/extensions.py#L231-L240
233,201
nameko/nameko
nameko/extensions.py
Entrypoint.bind
def bind(self, container, method_name): """ Get an instance of this Entrypoint to bind to `container` with `method_name`. """ instance = super(Entrypoint, self).bind(container) instance.method_name = method_name return instance
python
def bind(self, container, method_name): instance = super(Entrypoint, self).bind(container) instance.method_name = method_name return instance
[ "def", "bind", "(", "self", ",", "container", ",", "method_name", ")", ":", "instance", "=", "super", "(", "Entrypoint", ",", "self", ")", ".", "bind", "(", "container", ")", "instance", ".", "method_name", "=", "method_name", "return", "instance" ]
Get an instance of this Entrypoint to bind to `container` with `method_name`.
[ "Get", "an", "instance", "of", "this", "Entrypoint", "to", "bind", "to", "container", "with", "method_name", "." ]
88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d
https://github.com/nameko/nameko/blob/88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d/nameko/extensions.py#L294-L300
233,202
nameko/nameko
nameko/containers.py
ServiceContainer.start
def start(self): """ Start a container by starting all of its extensions. """ _log.debug('starting %s', self) self.started = True with _log_time('started %s', self): self.extensions.all.setup() self.extensions.all.start()
python
def start(self): _log.debug('starting %s', self) self.started = True with _log_time('started %s', self): self.extensions.all.setup() self.extensions.all.start()
[ "def", "start", "(", "self", ")", ":", "_log", ".", "debug", "(", "'starting %s'", ",", "self", ")", "self", ".", "started", "=", "True", "with", "_log_time", "(", "'started %s'", ",", "self", ")", ":", "self", ".", "extensions", ".", "all", ".", "se...
Start a container by starting all of its extensions.
[ "Start", "a", "container", "by", "starting", "all", "of", "its", "extensions", "." ]
88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d
https://github.com/nameko/nameko/blob/88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d/nameko/containers.py#L182-L190
233,203
nameko/nameko
nameko/containers.py
ServiceContainer.stop
def stop(self): """ Stop the container gracefully. First all entrypoints are asked to ``stop()``. This ensures that no new worker threads are started. It is the extensions' responsibility to gracefully shut down when ``stop()`` is called on them and only return when they have stopped. After all entrypoints have stopped the container waits for any active workers to complete. After all active workers have stopped the container stops all dependency providers. At this point there should be no more managed threads. In case there are any managed threads, they are killed by the container. """ if self._died.ready(): _log.debug('already stopped %s', self) return if self._being_killed: # this race condition can happen when a container is hosted by a # runner and yields during its kill method; if it's unlucky in # scheduling the runner will try to stop() it before self._died # has a result _log.debug('already being killed %s', self) try: self._died.wait() except: pass # don't re-raise if we died with an exception return _log.debug('stopping %s', self) with _log_time('stopped %s', self): # entrypoint have to be stopped before dependencies to ensure # that running workers can successfully complete self.entrypoints.all.stop() # there might still be some running workers, which we have to # wait for to complete before we can stop dependencies self._worker_pool.waitall() # it should be safe now to stop any dependency as there is no # active worker which could be using it self.dependencies.all.stop() # finally, stop remaining extensions self.subextensions.all.stop() # any any managed threads they spawned self._kill_managed_threads() self.started = False # if `kill` is called after `stop`, they race to send this if not self._died.ready(): self._died.send(None)
python
def stop(self): if self._died.ready(): _log.debug('already stopped %s', self) return if self._being_killed: # this race condition can happen when a container is hosted by a # runner and yields during its kill method; if it's unlucky in # scheduling the runner will try to stop() it before self._died # has a result _log.debug('already being killed %s', self) try: self._died.wait() except: pass # don't re-raise if we died with an exception return _log.debug('stopping %s', self) with _log_time('stopped %s', self): # entrypoint have to be stopped before dependencies to ensure # that running workers can successfully complete self.entrypoints.all.stop() # there might still be some running workers, which we have to # wait for to complete before we can stop dependencies self._worker_pool.waitall() # it should be safe now to stop any dependency as there is no # active worker which could be using it self.dependencies.all.stop() # finally, stop remaining extensions self.subextensions.all.stop() # any any managed threads they spawned self._kill_managed_threads() self.started = False # if `kill` is called after `stop`, they race to send this if not self._died.ready(): self._died.send(None)
[ "def", "stop", "(", "self", ")", ":", "if", "self", ".", "_died", ".", "ready", "(", ")", ":", "_log", ".", "debug", "(", "'already stopped %s'", ",", "self", ")", "return", "if", "self", ".", "_being_killed", ":", "# this race condition can happen when a co...
Stop the container gracefully. First all entrypoints are asked to ``stop()``. This ensures that no new worker threads are started. It is the extensions' responsibility to gracefully shut down when ``stop()`` is called on them and only return when they have stopped. After all entrypoints have stopped the container waits for any active workers to complete. After all active workers have stopped the container stops all dependency providers. At this point there should be no more managed threads. In case there are any managed threads, they are killed by the container.
[ "Stop", "the", "container", "gracefully", "." ]
88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d
https://github.com/nameko/nameko/blob/88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d/nameko/containers.py#L192-L252
233,204
nameko/nameko
nameko/containers.py
ServiceContainer.kill
def kill(self, exc_info=None): """ Kill the container in a semi-graceful way. Entrypoints are killed, followed by any active worker threads. Next, dependencies are killed. Finally, any remaining managed threads are killed. If ``exc_info`` is provided, the exception will be raised by :meth:`~wait``. """ if self._being_killed: # this happens if a managed thread exits with an exception # while the container is being killed or if multiple errors # happen simultaneously _log.debug('already killing %s ... waiting for death', self) try: self._died.wait() except: pass # don't re-raise if we died with an exception return self._being_killed = True if self._died.ready(): _log.debug('already stopped %s', self) return if exc_info is not None: _log.info('killing %s due to %s', self, exc_info[1]) else: _log.info('killing %s', self) # protect against extensions that throw during kill; the container # is already dying with an exception, so ignore anything else def safely_kill_extensions(ext_set): try: ext_set.kill() except Exception as exc: _log.warning('Extension raised `%s` during kill', exc) safely_kill_extensions(self.entrypoints.all) self._kill_worker_threads() safely_kill_extensions(self.extensions.all) self._kill_managed_threads() self.started = False # if `kill` is called after `stop`, they race to send this if not self._died.ready(): self._died.send(None, exc_info)
python
def kill(self, exc_info=None): if self._being_killed: # this happens if a managed thread exits with an exception # while the container is being killed or if multiple errors # happen simultaneously _log.debug('already killing %s ... waiting for death', self) try: self._died.wait() except: pass # don't re-raise if we died with an exception return self._being_killed = True if self._died.ready(): _log.debug('already stopped %s', self) return if exc_info is not None: _log.info('killing %s due to %s', self, exc_info[1]) else: _log.info('killing %s', self) # protect against extensions that throw during kill; the container # is already dying with an exception, so ignore anything else def safely_kill_extensions(ext_set): try: ext_set.kill() except Exception as exc: _log.warning('Extension raised `%s` during kill', exc) safely_kill_extensions(self.entrypoints.all) self._kill_worker_threads() safely_kill_extensions(self.extensions.all) self._kill_managed_threads() self.started = False # if `kill` is called after `stop`, they race to send this if not self._died.ready(): self._died.send(None, exc_info)
[ "def", "kill", "(", "self", ",", "exc_info", "=", "None", ")", ":", "if", "self", ".", "_being_killed", ":", "# this happens if a managed thread exits with an exception", "# while the container is being killed or if multiple errors", "# happen simultaneously", "_log", ".", "d...
Kill the container in a semi-graceful way. Entrypoints are killed, followed by any active worker threads. Next, dependencies are killed. Finally, any remaining managed threads are killed. If ``exc_info`` is provided, the exception will be raised by :meth:`~wait``.
[ "Kill", "the", "container", "in", "a", "semi", "-", "graceful", "way", "." ]
88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d
https://github.com/nameko/nameko/blob/88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d/nameko/containers.py#L254-L303
233,205
nameko/nameko
nameko/containers.py
ServiceContainer.spawn_worker
def spawn_worker(self, entrypoint, args, kwargs, context_data=None, handle_result=None): """ Spawn a worker thread for running the service method decorated by `entrypoint`. ``args`` and ``kwargs`` are used as parameters for the service method. ``context_data`` is used to initialize a ``WorkerContext``. ``handle_result`` is an optional function which may be passed in by the entrypoint. It is called with the result returned or error raised by the service method. If provided it must return a value for ``result`` and ``exc_info`` to propagate to dependencies; these may be different to those returned by the service method. """ if self._being_killed: _log.info("Worker spawn prevented due to being killed") raise ContainerBeingKilled() service = self.service_cls() worker_ctx = WorkerContext( self, service, entrypoint, args, kwargs, data=context_data ) _log.debug('spawning %s', worker_ctx) gt = self._worker_pool.spawn( self._run_worker, worker_ctx, handle_result ) gt.link(self._handle_worker_thread_exited, worker_ctx) self._worker_threads[worker_ctx] = gt return worker_ctx
python
def spawn_worker(self, entrypoint, args, kwargs, context_data=None, handle_result=None): if self._being_killed: _log.info("Worker spawn prevented due to being killed") raise ContainerBeingKilled() service = self.service_cls() worker_ctx = WorkerContext( self, service, entrypoint, args, kwargs, data=context_data ) _log.debug('spawning %s', worker_ctx) gt = self._worker_pool.spawn( self._run_worker, worker_ctx, handle_result ) gt.link(self._handle_worker_thread_exited, worker_ctx) self._worker_threads[worker_ctx] = gt return worker_ctx
[ "def", "spawn_worker", "(", "self", ",", "entrypoint", ",", "args", ",", "kwargs", ",", "context_data", "=", "None", ",", "handle_result", "=", "None", ")", ":", "if", "self", ".", "_being_killed", ":", "_log", ".", "info", "(", "\"Worker spawn prevented due...
Spawn a worker thread for running the service method decorated by `entrypoint`. ``args`` and ``kwargs`` are used as parameters for the service method. ``context_data`` is used to initialize a ``WorkerContext``. ``handle_result`` is an optional function which may be passed in by the entrypoint. It is called with the result returned or error raised by the service method. If provided it must return a value for ``result`` and ``exc_info`` to propagate to dependencies; these may be different to those returned by the service method.
[ "Spawn", "a", "worker", "thread", "for", "running", "the", "service", "method", "decorated", "by", "entrypoint", "." ]
88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d
https://github.com/nameko/nameko/blob/88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d/nameko/containers.py#L318-L350
233,206
nameko/nameko
nameko/containers.py
ServiceContainer._kill_worker_threads
def _kill_worker_threads(self): """ Kill any currently executing worker threads. See :meth:`ServiceContainer.spawn_worker` """ num_workers = len(self._worker_threads) if num_workers: _log.warning('killing %s active workers(s)', num_workers) for worker_ctx, gt in list(self._worker_threads.items()): _log.warning('killing active worker for %s', worker_ctx) gt.kill()
python
def _kill_worker_threads(self): num_workers = len(self._worker_threads) if num_workers: _log.warning('killing %s active workers(s)', num_workers) for worker_ctx, gt in list(self._worker_threads.items()): _log.warning('killing active worker for %s', worker_ctx) gt.kill()
[ "def", "_kill_worker_threads", "(", "self", ")", ":", "num_workers", "=", "len", "(", "self", ".", "_worker_threads", ")", "if", "num_workers", ":", "_log", ".", "warning", "(", "'killing %s active workers(s)'", ",", "num_workers", ")", "for", "worker_ctx", ",",...
Kill any currently executing worker threads. See :meth:`ServiceContainer.spawn_worker`
[ "Kill", "any", "currently", "executing", "worker", "threads", "." ]
88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d
https://github.com/nameko/nameko/blob/88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d/nameko/containers.py#L439-L450
233,207
nameko/nameko
nameko/containers.py
ServiceContainer._kill_managed_threads
def _kill_managed_threads(self): """ Kill any currently executing managed threads. See :meth:`ServiceContainer.spawn_managed_thread` """ num_threads = len(self._managed_threads) if num_threads: _log.warning('killing %s managed thread(s)', num_threads) for gt, identifier in list(self._managed_threads.items()): _log.warning('killing managed thread `%s`', identifier) gt.kill()
python
def _kill_managed_threads(self): num_threads = len(self._managed_threads) if num_threads: _log.warning('killing %s managed thread(s)', num_threads) for gt, identifier in list(self._managed_threads.items()): _log.warning('killing managed thread `%s`', identifier) gt.kill()
[ "def", "_kill_managed_threads", "(", "self", ")", ":", "num_threads", "=", "len", "(", "self", ".", "_managed_threads", ")", "if", "num_threads", ":", "_log", ".", "warning", "(", "'killing %s managed thread(s)'", ",", "num_threads", ")", "for", "gt", ",", "id...
Kill any currently executing managed threads. See :meth:`ServiceContainer.spawn_managed_thread`
[ "Kill", "any", "currently", "executing", "managed", "threads", "." ]
88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d
https://github.com/nameko/nameko/blob/88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d/nameko/containers.py#L452-L463
233,208
nameko/nameko
nameko/standalone/rpc.py
ConsumeEvent.wait
def wait(self): """ Makes a blocking call to its queue_consumer until the message with the given correlation_id has been processed. By the time the blocking call exits, self.send() will have been called with the body of the received message (see :meth:`~nameko.rpc.ReplyListener.handle_message`). Exceptions are raised directly. """ # disconnected before starting to wait if self.exception: raise self.exception if self.queue_consumer.stopped: raise RuntimeError( "This consumer has been stopped, and can no longer be used" ) if self.queue_consumer.connection.connected is False: # we can't just reconnect here. the consumer (and its exclusive, # auto-delete reply queue) must be re-established _before_ sending # any request, otherwise the reply queue may not exist when the # response is published. raise RuntimeError( "This consumer has been disconnected, and can no longer " "be used" ) try: self.queue_consumer.get_message(self.correlation_id) except socket.error as exc: self.exception = exc # disconnected while waiting if self.exception: raise self.exception return self.body
python
def wait(self): # disconnected before starting to wait if self.exception: raise self.exception if self.queue_consumer.stopped: raise RuntimeError( "This consumer has been stopped, and can no longer be used" ) if self.queue_consumer.connection.connected is False: # we can't just reconnect here. the consumer (and its exclusive, # auto-delete reply queue) must be re-established _before_ sending # any request, otherwise the reply queue may not exist when the # response is published. raise RuntimeError( "This consumer has been disconnected, and can no longer " "be used" ) try: self.queue_consumer.get_message(self.correlation_id) except socket.error as exc: self.exception = exc # disconnected while waiting if self.exception: raise self.exception return self.body
[ "def", "wait", "(", "self", ")", ":", "# disconnected before starting to wait", "if", "self", ".", "exception", ":", "raise", "self", ".", "exception", "if", "self", ".", "queue_consumer", ".", "stopped", ":", "raise", "RuntimeError", "(", "\"This consumer has bee...
Makes a blocking call to its queue_consumer until the message with the given correlation_id has been processed. By the time the blocking call exits, self.send() will have been called with the body of the received message (see :meth:`~nameko.rpc.ReplyListener.handle_message`). Exceptions are raised directly.
[ "Makes", "a", "blocking", "call", "to", "its", "queue_consumer", "until", "the", "message", "with", "the", "given", "correlation_id", "has", "been", "processed", "." ]
88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d
https://github.com/nameko/nameko/blob/88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d/nameko/standalone/rpc.py#L37-L73
233,209
MechanicalSoup/MechanicalSoup
mechanicalsoup/stateful_browser.py
StatefulBrowser.select_form
def select_form(self, selector="form", nr=0): """Select a form in the current page. :param selector: CSS selector or a bs4.element.Tag object to identify the form to select. If not specified, ``selector`` defaults to "form", which is useful if, e.g., there is only one form on the page. For ``selector`` syntax, see the `.select() method in BeautifulSoup <https://www.crummy.com/software/BeautifulSoup/bs4/doc/#css-selectors>`__. :param nr: A zero-based index specifying which form among those that match ``selector`` will be selected. Useful when one or more forms have the same attributes as the form you want to select, and its position on the page is the only way to uniquely identify it. Default is the first matching form (``nr=0``). :return: The selected form as a soup object. It can also be retrieved later with :func:`get_current_form`. """ if isinstance(selector, bs4.element.Tag): if selector.name != "form": raise LinkNotFoundError self.__state.form = Form(selector) else: # nr is a 0-based index for consistency with mechanize found_forms = self.get_current_page().select(selector, limit=nr + 1) if len(found_forms) != nr + 1: if self.__debug: print('select_form failed for', selector) self.launch_browser() raise LinkNotFoundError() self.__state.form = Form(found_forms[-1]) return self.get_current_form()
python
def select_form(self, selector="form", nr=0): if isinstance(selector, bs4.element.Tag): if selector.name != "form": raise LinkNotFoundError self.__state.form = Form(selector) else: # nr is a 0-based index for consistency with mechanize found_forms = self.get_current_page().select(selector, limit=nr + 1) if len(found_forms) != nr + 1: if self.__debug: print('select_form failed for', selector) self.launch_browser() raise LinkNotFoundError() self.__state.form = Form(found_forms[-1]) return self.get_current_form()
[ "def", "select_form", "(", "self", ",", "selector", "=", "\"form\"", ",", "nr", "=", "0", ")", ":", "if", "isinstance", "(", "selector", ",", "bs4", ".", "element", ".", "Tag", ")", ":", "if", "selector", ".", "name", "!=", "\"form\"", ":", "raise", ...
Select a form in the current page. :param selector: CSS selector or a bs4.element.Tag object to identify the form to select. If not specified, ``selector`` defaults to "form", which is useful if, e.g., there is only one form on the page. For ``selector`` syntax, see the `.select() method in BeautifulSoup <https://www.crummy.com/software/BeautifulSoup/bs4/doc/#css-selectors>`__. :param nr: A zero-based index specifying which form among those that match ``selector`` will be selected. Useful when one or more forms have the same attributes as the form you want to select, and its position on the page is the only way to uniquely identify it. Default is the first matching form (``nr=0``). :return: The selected form as a soup object. It can also be retrieved later with :func:`get_current_form`.
[ "Select", "a", "form", "in", "the", "current", "page", "." ]
027a270febf5bcda6a75db60ea9838d631370f4b
https://github.com/MechanicalSoup/MechanicalSoup/blob/027a270febf5bcda6a75db60ea9838d631370f4b/mechanicalsoup/stateful_browser.py#L177-L210
233,210
MechanicalSoup/MechanicalSoup
mechanicalsoup/stateful_browser.py
StatefulBrowser.links
def links(self, url_regex=None, link_text=None, *args, **kwargs): """Return links in the page, as a list of bs4.element.Tag objects. To return links matching specific criteria, specify ``url_regex`` to match the *href*-attribute, or ``link_text`` to match the *text*-attribute of the Tag. All other arguments are forwarded to the `.find_all() method in BeautifulSoup <https://www.crummy.com/software/BeautifulSoup/bs4/doc/#find-all>`__. """ all_links = self.get_current_page().find_all( 'a', href=True, *args, **kwargs) if url_regex is not None: all_links = [a for a in all_links if re.search(url_regex, a['href'])] if link_text is not None: all_links = [a for a in all_links if a.text == link_text] return all_links
python
def links(self, url_regex=None, link_text=None, *args, **kwargs): all_links = self.get_current_page().find_all( 'a', href=True, *args, **kwargs) if url_regex is not None: all_links = [a for a in all_links if re.search(url_regex, a['href'])] if link_text is not None: all_links = [a for a in all_links if a.text == link_text] return all_links
[ "def", "links", "(", "self", ",", "url_regex", "=", "None", ",", "link_text", "=", "None", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "all_links", "=", "self", ".", "get_current_page", "(", ")", ".", "find_all", "(", "'a'", ",", "href", "...
Return links in the page, as a list of bs4.element.Tag objects. To return links matching specific criteria, specify ``url_regex`` to match the *href*-attribute, or ``link_text`` to match the *text*-attribute of the Tag. All other arguments are forwarded to the `.find_all() method in BeautifulSoup <https://www.crummy.com/software/BeautifulSoup/bs4/doc/#find-all>`__.
[ "Return", "links", "in", "the", "page", "as", "a", "list", "of", "bs4", ".", "element", ".", "Tag", "objects", "." ]
027a270febf5bcda6a75db60ea9838d631370f4b
https://github.com/MechanicalSoup/MechanicalSoup/blob/027a270febf5bcda6a75db60ea9838d631370f4b/mechanicalsoup/stateful_browser.py#L249-L266
233,211
MechanicalSoup/MechanicalSoup
mechanicalsoup/stateful_browser.py
StatefulBrowser.find_link
def find_link(self, *args, **kwargs): """Find and return a link, as a bs4.element.Tag object. The search can be refined by specifying any argument that is accepted by :func:`links`. If several links match, return the first one found. If no link is found, raise :class:`LinkNotFoundError`. """ links = self.links(*args, **kwargs) if len(links) == 0: raise LinkNotFoundError() else: return links[0]
python
def find_link(self, *args, **kwargs): links = self.links(*args, **kwargs) if len(links) == 0: raise LinkNotFoundError() else: return links[0]
[ "def", "find_link", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "links", "=", "self", ".", "links", "(", "*", "args", ",", "*", "*", "kwargs", ")", "if", "len", "(", "links", ")", "==", "0", ":", "raise", "LinkNotFoundError"...
Find and return a link, as a bs4.element.Tag object. The search can be refined by specifying any argument that is accepted by :func:`links`. If several links match, return the first one found. If no link is found, raise :class:`LinkNotFoundError`.
[ "Find", "and", "return", "a", "link", "as", "a", "bs4", ".", "element", ".", "Tag", "object", "." ]
027a270febf5bcda6a75db60ea9838d631370f4b
https://github.com/MechanicalSoup/MechanicalSoup/blob/027a270febf5bcda6a75db60ea9838d631370f4b/mechanicalsoup/stateful_browser.py#L268-L280
233,212
MechanicalSoup/MechanicalSoup
mechanicalsoup/stateful_browser.py
StatefulBrowser.follow_link
def follow_link(self, link=None, *args, **kwargs): """Follow a link. If ``link`` is a bs4.element.Tag (i.e. from a previous call to :func:`links` or :func:`find_link`), then follow the link. If ``link`` doesn't have a *href*-attribute or is None, treat ``link`` as a url_regex and look it up with :func:`find_link`. Any additional arguments specified are forwarded to this function. If the link is not found, raise :class:`LinkNotFoundError`. Before raising, if debug is activated, list available links in the page and launch a browser. :return: Forwarded from :func:`open_relative`. """ link = self._find_link_internal(link, args, kwargs) referer = self.get_url() headers = {'Referer': referer} if referer else None return self.open_relative(link['href'], headers=headers)
python
def follow_link(self, link=None, *args, **kwargs): link = self._find_link_internal(link, args, kwargs) referer = self.get_url() headers = {'Referer': referer} if referer else None return self.open_relative(link['href'], headers=headers)
[ "def", "follow_link", "(", "self", ",", "link", "=", "None", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "link", "=", "self", ".", "_find_link_internal", "(", "link", ",", "args", ",", "kwargs", ")", "referer", "=", "self", ".", "get_url", ...
Follow a link. If ``link`` is a bs4.element.Tag (i.e. from a previous call to :func:`links` or :func:`find_link`), then follow the link. If ``link`` doesn't have a *href*-attribute or is None, treat ``link`` as a url_regex and look it up with :func:`find_link`. Any additional arguments specified are forwarded to this function. If the link is not found, raise :class:`LinkNotFoundError`. Before raising, if debug is activated, list available links in the page and launch a browser. :return: Forwarded from :func:`open_relative`.
[ "Follow", "a", "link", "." ]
027a270febf5bcda6a75db60ea9838d631370f4b
https://github.com/MechanicalSoup/MechanicalSoup/blob/027a270febf5bcda6a75db60ea9838d631370f4b/mechanicalsoup/stateful_browser.py#L312-L333
233,213
MechanicalSoup/MechanicalSoup
mechanicalsoup/form.py
Form.set_input
def set_input(self, data): """Fill-in a set of fields in a form. Example: filling-in a login/password form .. code-block:: python form.set_input({"login": username, "password": password}) This will find the input element named "login" and give it the value ``username``, and the input element named "password" and give it the value ``password``. """ for (name, value) in data.items(): i = self.form.find("input", {"name": name}) if not i: raise InvalidFormMethod("No input field named " + name) i["value"] = value
python
def set_input(self, data): for (name, value) in data.items(): i = self.form.find("input", {"name": name}) if not i: raise InvalidFormMethod("No input field named " + name) i["value"] = value
[ "def", "set_input", "(", "self", ",", "data", ")", ":", "for", "(", "name", ",", "value", ")", "in", "data", ".", "items", "(", ")", ":", "i", "=", "self", ".", "form", ".", "find", "(", "\"input\"", ",", "{", "\"name\"", ":", "name", "}", ")",...
Fill-in a set of fields in a form. Example: filling-in a login/password form .. code-block:: python form.set_input({"login": username, "password": password}) This will find the input element named "login" and give it the value ``username``, and the input element named "password" and give it the value ``password``.
[ "Fill", "-", "in", "a", "set", "of", "fields", "in", "a", "form", "." ]
027a270febf5bcda6a75db60ea9838d631370f4b
https://github.com/MechanicalSoup/MechanicalSoup/blob/027a270febf5bcda6a75db60ea9838d631370f4b/mechanicalsoup/form.py#L52-L70
233,214
MechanicalSoup/MechanicalSoup
mechanicalsoup/form.py
Form.new_control
def new_control(self, type, name, value, **kwargs): """Add a new input element to the form. The arguments set the attributes of the new element. """ old_input = self.form.find_all('input', {'name': name}) for old in old_input: old.decompose() old_textarea = self.form.find_all('textarea', {'name': name}) for old in old_textarea: old.decompose() # We don't have access to the original soup object (just the # Tag), so we instantiate a new BeautifulSoup() to call # new_tag(). We're only building the soup object, not parsing # anything, so the parser doesn't matter. Specify the one # included in Python to avoid having dependency issue. control = BeautifulSoup("", "html.parser").new_tag('input') control['type'] = type control['name'] = name control['value'] = value for k, v in kwargs.items(): control[k] = v self.form.append(control) return control
python
def new_control(self, type, name, value, **kwargs): old_input = self.form.find_all('input', {'name': name}) for old in old_input: old.decompose() old_textarea = self.form.find_all('textarea', {'name': name}) for old in old_textarea: old.decompose() # We don't have access to the original soup object (just the # Tag), so we instantiate a new BeautifulSoup() to call # new_tag(). We're only building the soup object, not parsing # anything, so the parser doesn't matter. Specify the one # included in Python to avoid having dependency issue. control = BeautifulSoup("", "html.parser").new_tag('input') control['type'] = type control['name'] = name control['value'] = value for k, v in kwargs.items(): control[k] = v self.form.append(control) return control
[ "def", "new_control", "(", "self", ",", "type", ",", "name", ",", "value", ",", "*", "*", "kwargs", ")", ":", "old_input", "=", "self", ".", "form", ".", "find_all", "(", "'input'", ",", "{", "'name'", ":", "name", "}", ")", "for", "old", "in", "...
Add a new input element to the form. The arguments set the attributes of the new element.
[ "Add", "a", "new", "input", "element", "to", "the", "form", "." ]
027a270febf5bcda6a75db60ea9838d631370f4b
https://github.com/MechanicalSoup/MechanicalSoup/blob/027a270febf5bcda6a75db60ea9838d631370f4b/mechanicalsoup/form.py#L280-L303
233,215
MechanicalSoup/MechanicalSoup
mechanicalsoup/form.py
Form.print_summary
def print_summary(self): """Print a summary of the form. May help finding which fields need to be filled-in. """ for input in self.form.find_all( ("input", "textarea", "select", "button")): input_copy = copy.copy(input) # Text between the opening tag and the closing tag often # contains a lot of spaces that we don't want here. for subtag in input_copy.find_all() + [input_copy]: if subtag.string: subtag.string = subtag.string.strip() print(input_copy)
python
def print_summary(self): for input in self.form.find_all( ("input", "textarea", "select", "button")): input_copy = copy.copy(input) # Text between the opening tag and the closing tag often # contains a lot of spaces that we don't want here. for subtag in input_copy.find_all() + [input_copy]: if subtag.string: subtag.string = subtag.string.strip() print(input_copy)
[ "def", "print_summary", "(", "self", ")", ":", "for", "input", "in", "self", ".", "form", ".", "find_all", "(", "(", "\"input\"", ",", "\"textarea\"", ",", "\"select\"", ",", "\"button\"", ")", ")", ":", "input_copy", "=", "copy", ".", "copy", "(", "in...
Print a summary of the form. May help finding which fields need to be filled-in.
[ "Print", "a", "summary", "of", "the", "form", "." ]
027a270febf5bcda6a75db60ea9838d631370f4b
https://github.com/MechanicalSoup/MechanicalSoup/blob/027a270febf5bcda6a75db60ea9838d631370f4b/mechanicalsoup/form.py#L370-L383
233,216
MechanicalSoup/MechanicalSoup
mechanicalsoup/browser.py
Browser.__looks_like_html
def __looks_like_html(response): """Guesses entity type when Content-Type header is missing. Since Content-Type is not strictly required, some servers leave it out. """ text = response.text.lstrip().lower() return text.startswith('<html') or text.startswith('<!doctype')
python
def __looks_like_html(response): text = response.text.lstrip().lower() return text.startswith('<html') or text.startswith('<!doctype')
[ "def", "__looks_like_html", "(", "response", ")", ":", "text", "=", "response", ".", "text", ".", "lstrip", "(", ")", ".", "lower", "(", ")", "return", "text", ".", "startswith", "(", "'<html'", ")", "or", "text", ".", "startswith", "(", "'<!doctype'", ...
Guesses entity type when Content-Type header is missing. Since Content-Type is not strictly required, some servers leave it out.
[ "Guesses", "entity", "type", "when", "Content", "-", "Type", "header", "is", "missing", ".", "Since", "Content", "-", "Type", "is", "not", "strictly", "required", "some", "servers", "leave", "it", "out", "." ]
027a270febf5bcda6a75db60ea9838d631370f4b
https://github.com/MechanicalSoup/MechanicalSoup/blob/027a270febf5bcda6a75db60ea9838d631370f4b/mechanicalsoup/browser.py#L58-L63
233,217
MechanicalSoup/MechanicalSoup
mechanicalsoup/browser.py
Browser.add_soup
def add_soup(response, soup_config): """Attaches a soup object to a requests response.""" if ("text/html" in response.headers.get("Content-Type", "") or Browser.__looks_like_html(response)): response.soup = bs4.BeautifulSoup(response.content, **soup_config) else: response.soup = None
python
def add_soup(response, soup_config): if ("text/html" in response.headers.get("Content-Type", "") or Browser.__looks_like_html(response)): response.soup = bs4.BeautifulSoup(response.content, **soup_config) else: response.soup = None
[ "def", "add_soup", "(", "response", ",", "soup_config", ")", ":", "if", "(", "\"text/html\"", "in", "response", ".", "headers", ".", "get", "(", "\"Content-Type\"", ",", "\"\"", ")", "or", "Browser", ".", "__looks_like_html", "(", "response", ")", ")", ":"...
Attaches a soup object to a requests response.
[ "Attaches", "a", "soup", "object", "to", "a", "requests", "response", "." ]
027a270febf5bcda6a75db60ea9838d631370f4b
https://github.com/MechanicalSoup/MechanicalSoup/blob/027a270febf5bcda6a75db60ea9838d631370f4b/mechanicalsoup/browser.py#L66-L72
233,218
MechanicalSoup/MechanicalSoup
mechanicalsoup/browser.py
Browser.set_user_agent
def set_user_agent(self, user_agent): """Replaces the current user agent in the requests session headers.""" # set a default user_agent if not specified if user_agent is None: requests_ua = requests.utils.default_user_agent() user_agent = '%s (%s/%s)' % (requests_ua, __title__, __version__) # the requests module uses a case-insensitive dict for session headers self.session.headers['User-agent'] = user_agent
python
def set_user_agent(self, user_agent): # set a default user_agent if not specified if user_agent is None: requests_ua = requests.utils.default_user_agent() user_agent = '%s (%s/%s)' % (requests_ua, __title__, __version__) # the requests module uses a case-insensitive dict for session headers self.session.headers['User-agent'] = user_agent
[ "def", "set_user_agent", "(", "self", ",", "user_agent", ")", ":", "# set a default user_agent if not specified", "if", "user_agent", "is", "None", ":", "requests_ua", "=", "requests", ".", "utils", ".", "default_user_agent", "(", ")", "user_agent", "=", "'%s (%s/%s...
Replaces the current user agent in the requests session headers.
[ "Replaces", "the", "current", "user", "agent", "in", "the", "requests", "session", "headers", "." ]
027a270febf5bcda6a75db60ea9838d631370f4b
https://github.com/MechanicalSoup/MechanicalSoup/blob/027a270febf5bcda6a75db60ea9838d631370f4b/mechanicalsoup/browser.py#L89-L97
233,219
MechanicalSoup/MechanicalSoup
mechanicalsoup/browser.py
Browser._request
def _request(self, form, url=None, **kwargs): """Extract input data from the form to pass to a Requests session.""" method = str(form.get("method", "get")) action = form.get("action") url = urllib.parse.urljoin(url, action) if url is None: # This happens when both `action` and `url` are None. raise ValueError('no URL to submit to') # read https://www.w3.org/TR/html52/sec-forms.html data = kwargs.pop("data", dict()) files = kwargs.pop("files", dict()) # Use a list of 2-tuples to better reflect the behavior of browser QSL. # Requests also retains order when encoding form data in 2-tuple lists. data = [(k, v) for k, v in data.items()] # Process form tags in the order that they appear on the page, # skipping those tags that do not have a name-attribute. selector = ",".join("{}[name]".format(i) for i in ("input", "button", "textarea", "select")) for tag in form.select(selector): name = tag.get("name") # name-attribute of tag # Skip disabled elements, since they should not be submitted. if tag.has_attr('disabled'): continue if tag.name == "input": if tag.get("type", "").lower() in ("radio", "checkbox"): if "checked" not in tag.attrs: continue value = tag.get("value", "on") else: # browsers use empty string for inputs with missing values value = tag.get("value", "") if tag.get("type", "").lower() == "file": # read http://www.cs.tut.fi/~jkorpela/forms/file.html # in browsers, file upload only happens if the form # (or submit button) enctype attribute is set to # "multipart/form-data". We don't care, simplify. filename = value if filename != "" and isinstance(filename, string_types): content = open(filename, "rb") else: content = "" # If value is the empty string, we still pass it for # consistency with browsers (see #250). files[name] = (filename, content) else: data.append((name, value)) elif tag.name == "button": if tag.get("type", "").lower() in ("button", "reset"): continue else: data.append((name, tag.get("value", ""))) elif tag.name == "textarea": data.append((name, tag.text)) elif tag.name == "select": # If the value attribute is not specified, the content will # be passed as a value instead. options = tag.select("option") selected_values = [i.get("value", i.text) for i in options if "selected" in i.attrs] if "multiple" in tag.attrs: for value in selected_values: data.append((name, value)) elif selected_values: # A standard select element only allows one option to be # selected, but browsers pick last if somehow multiple. data.append((name, selected_values[-1])) elif options: # Selects the first option if none are selected first_value = options[0].get("value", options[0].text) data.append((name, first_value)) if method.lower() == "get": kwargs["params"] = data else: kwargs["data"] = data return self.session.request(method, url, files=files, **kwargs)
python
def _request(self, form, url=None, **kwargs): method = str(form.get("method", "get")) action = form.get("action") url = urllib.parse.urljoin(url, action) if url is None: # This happens when both `action` and `url` are None. raise ValueError('no URL to submit to') # read https://www.w3.org/TR/html52/sec-forms.html data = kwargs.pop("data", dict()) files = kwargs.pop("files", dict()) # Use a list of 2-tuples to better reflect the behavior of browser QSL. # Requests also retains order when encoding form data in 2-tuple lists. data = [(k, v) for k, v in data.items()] # Process form tags in the order that they appear on the page, # skipping those tags that do not have a name-attribute. selector = ",".join("{}[name]".format(i) for i in ("input", "button", "textarea", "select")) for tag in form.select(selector): name = tag.get("name") # name-attribute of tag # Skip disabled elements, since they should not be submitted. if tag.has_attr('disabled'): continue if tag.name == "input": if tag.get("type", "").lower() in ("radio", "checkbox"): if "checked" not in tag.attrs: continue value = tag.get("value", "on") else: # browsers use empty string for inputs with missing values value = tag.get("value", "") if tag.get("type", "").lower() == "file": # read http://www.cs.tut.fi/~jkorpela/forms/file.html # in browsers, file upload only happens if the form # (or submit button) enctype attribute is set to # "multipart/form-data". We don't care, simplify. filename = value if filename != "" and isinstance(filename, string_types): content = open(filename, "rb") else: content = "" # If value is the empty string, we still pass it for # consistency with browsers (see #250). files[name] = (filename, content) else: data.append((name, value)) elif tag.name == "button": if tag.get("type", "").lower() in ("button", "reset"): continue else: data.append((name, tag.get("value", ""))) elif tag.name == "textarea": data.append((name, tag.text)) elif tag.name == "select": # If the value attribute is not specified, the content will # be passed as a value instead. options = tag.select("option") selected_values = [i.get("value", i.text) for i in options if "selected" in i.attrs] if "multiple" in tag.attrs: for value in selected_values: data.append((name, value)) elif selected_values: # A standard select element only allows one option to be # selected, but browsers pick last if somehow multiple. data.append((name, selected_values[-1])) elif options: # Selects the first option if none are selected first_value = options[0].get("value", options[0].text) data.append((name, first_value)) if method.lower() == "get": kwargs["params"] = data else: kwargs["data"] = data return self.session.request(method, url, files=files, **kwargs)
[ "def", "_request", "(", "self", ",", "form", ",", "url", "=", "None", ",", "*", "*", "kwargs", ")", ":", "method", "=", "str", "(", "form", ".", "get", "(", "\"method\"", ",", "\"get\"", ")", ")", "action", "=", "form", ".", "get", "(", "\"action...
Extract input data from the form to pass to a Requests session.
[ "Extract", "input", "data", "from", "the", "form", "to", "pass", "to", "a", "Requests", "session", "." ]
027a270febf5bcda6a75db60ea9838d631370f4b
https://github.com/MechanicalSoup/MechanicalSoup/blob/027a270febf5bcda6a75db60ea9838d631370f4b/mechanicalsoup/browser.py#L142-L226
233,220
MechanicalSoup/MechanicalSoup
mechanicalsoup/browser.py
Browser.submit
def submit(self, form, url=None, **kwargs): """Prepares and sends a form request. NOTE: To submit a form with a :class:`StatefulBrowser` instance, it is recommended to use :func:`StatefulBrowser.submit_selected` instead of this method so that the browser state is correctly updated. :param form: The filled-out form. :param url: URL of the page the form is on. If the form action is a relative path, then this must be specified. :param \\*\\*kwargs: Arguments forwarded to `requests.Session.request <http://docs.python-requests.org/en/master/api/#requests.Session.request>`__. :return: `requests.Response <http://docs.python-requests.org/en/master/api/#requests.Response>`__ object with a *soup*-attribute added by :func:`add_soup`. """ if isinstance(form, Form): form = form.form response = self._request(form, url, **kwargs) Browser.add_soup(response, self.soup_config) return response
python
def submit(self, form, url=None, **kwargs): if isinstance(form, Form): form = form.form response = self._request(form, url, **kwargs) Browser.add_soup(response, self.soup_config) return response
[ "def", "submit", "(", "self", ",", "form", ",", "url", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "isinstance", "(", "form", ",", "Form", ")", ":", "form", "=", "form", ".", "form", "response", "=", "self", ".", "_request", "(", "form"...
Prepares and sends a form request. NOTE: To submit a form with a :class:`StatefulBrowser` instance, it is recommended to use :func:`StatefulBrowser.submit_selected` instead of this method so that the browser state is correctly updated. :param form: The filled-out form. :param url: URL of the page the form is on. If the form action is a relative path, then this must be specified. :param \\*\\*kwargs: Arguments forwarded to `requests.Session.request <http://docs.python-requests.org/en/master/api/#requests.Session.request>`__. :return: `requests.Response <http://docs.python-requests.org/en/master/api/#requests.Response>`__ object with a *soup*-attribute added by :func:`add_soup`.
[ "Prepares", "and", "sends", "a", "form", "request", "." ]
027a270febf5bcda6a75db60ea9838d631370f4b
https://github.com/MechanicalSoup/MechanicalSoup/blob/027a270febf5bcda6a75db60ea9838d631370f4b/mechanicalsoup/browser.py#L228-L249
233,221
MechanicalSoup/MechanicalSoup
mechanicalsoup/browser.py
Browser.close
def close(self): """Close the current session, if still open.""" if self.session is not None: self.session.cookies.clear() self.session.close() self.session = None
python
def close(self): if self.session is not None: self.session.cookies.clear() self.session.close() self.session = None
[ "def", "close", "(", "self", ")", ":", "if", "self", ".", "session", "is", "not", "None", ":", "self", ".", "session", ".", "cookies", ".", "clear", "(", ")", "self", ".", "session", ".", "close", "(", ")", "self", ".", "session", "=", "None" ]
Close the current session, if still open.
[ "Close", "the", "current", "session", "if", "still", "open", "." ]
027a270febf5bcda6a75db60ea9838d631370f4b
https://github.com/MechanicalSoup/MechanicalSoup/blob/027a270febf5bcda6a75db60ea9838d631370f4b/mechanicalsoup/browser.py#L260-L265
233,222
MechanicalSoup/MechanicalSoup
setup.py
requirements_from_file
def requirements_from_file(filename): """Parses a pip requirements file into a list.""" return [line.strip() for line in open(filename, 'r') if line.strip() and not line.strip().startswith('--')]
python
def requirements_from_file(filename): return [line.strip() for line in open(filename, 'r') if line.strip() and not line.strip().startswith('--')]
[ "def", "requirements_from_file", "(", "filename", ")", ":", "return", "[", "line", ".", "strip", "(", ")", "for", "line", "in", "open", "(", "filename", ",", "'r'", ")", "if", "line", ".", "strip", "(", ")", "and", "not", "line", ".", "strip", "(", ...
Parses a pip requirements file into a list.
[ "Parses", "a", "pip", "requirements", "file", "into", "a", "list", "." ]
027a270febf5bcda6a75db60ea9838d631370f4b
https://github.com/MechanicalSoup/MechanicalSoup/blob/027a270febf5bcda6a75db60ea9838d631370f4b/setup.py#L9-L12
233,223
MechanicalSoup/MechanicalSoup
setup.py
read
def read(fname, URL, URLImage): """Read the content of a file.""" readme = open(path.join(path.dirname(__file__), fname)).read() if hasattr(readme, 'decode'): # In Python 3, turn bytes into str. readme = readme.decode('utf8') # turn relative links into absolute ones readme = re.sub(r'`<([^>]*)>`__', r'`\1 <' + URL + r"/blob/master/\1>`__", readme) readme = re.sub(r"\.\. image:: /", ".. image:: " + URLImage + "/", readme) return readme
python
def read(fname, URL, URLImage): readme = open(path.join(path.dirname(__file__), fname)).read() if hasattr(readme, 'decode'): # In Python 3, turn bytes into str. readme = readme.decode('utf8') # turn relative links into absolute ones readme = re.sub(r'`<([^>]*)>`__', r'`\1 <' + URL + r"/blob/master/\1>`__", readme) readme = re.sub(r"\.\. image:: /", ".. image:: " + URLImage + "/", readme) return readme
[ "def", "read", "(", "fname", ",", "URL", ",", "URLImage", ")", ":", "readme", "=", "open", "(", "path", ".", "join", "(", "path", ".", "dirname", "(", "__file__", ")", ",", "fname", ")", ")", ".", "read", "(", ")", "if", "hasattr", "(", "readme",...
Read the content of a file.
[ "Read", "the", "content", "of", "a", "file", "." ]
027a270febf5bcda6a75db60ea9838d631370f4b
https://github.com/MechanicalSoup/MechanicalSoup/blob/027a270febf5bcda6a75db60ea9838d631370f4b/setup.py#L15-L27
233,224
DmitryUlyanov/Multicore-TSNE
tsne-embedding.py
imscatter
def imscatter(images, positions): ''' Creates a scatter plot, where each plot is shown by corresponding image ''' positions = np.array(positions) bottoms = positions[:, 1] - np.array([im.shape[1] / 2.0 for im in images]) tops = bottoms + np.array([im.shape[1] for im in images]) lefts = positions[:, 0] - np.array([im.shape[0] / 2.0 for im in images]) rigths = lefts + np.array([im.shape[0] for im in images]) most_bottom = int(np.floor(bottoms.min())) most_top = int(np.ceil(tops.max())) most_left = int(np.floor(lefts.min())) most_right = int(np.ceil(rigths.max())) scatter_image = np.zeros( [most_right - most_left, most_top - most_bottom, 3], dtype=imgs[0].dtype) # shift, now all from zero positions -= [most_left, most_bottom] for im, pos in zip(images, positions): xl = int(pos[0] - im.shape[0] / 2) xr = xl + im.shape[0] yb = int(pos[1] - im.shape[1] / 2) yt = yb + im.shape[1] scatter_image[xl:xr, yb:yt, :] = im return scatter_image
python
def imscatter(images, positions): ''' Creates a scatter plot, where each plot is shown by corresponding image ''' positions = np.array(positions) bottoms = positions[:, 1] - np.array([im.shape[1] / 2.0 for im in images]) tops = bottoms + np.array([im.shape[1] for im in images]) lefts = positions[:, 0] - np.array([im.shape[0] / 2.0 for im in images]) rigths = lefts + np.array([im.shape[0] for im in images]) most_bottom = int(np.floor(bottoms.min())) most_top = int(np.ceil(tops.max())) most_left = int(np.floor(lefts.min())) most_right = int(np.ceil(rigths.max())) scatter_image = np.zeros( [most_right - most_left, most_top - most_bottom, 3], dtype=imgs[0].dtype) # shift, now all from zero positions -= [most_left, most_bottom] for im, pos in zip(images, positions): xl = int(pos[0] - im.shape[0] / 2) xr = xl + im.shape[0] yb = int(pos[1] - im.shape[1] / 2) yt = yb + im.shape[1] scatter_image[xl:xr, yb:yt, :] = im return scatter_image
[ "def", "imscatter", "(", "images", ",", "positions", ")", ":", "positions", "=", "np", ".", "array", "(", "positions", ")", "bottoms", "=", "positions", "[", ":", ",", "1", "]", "-", "np", ".", "array", "(", "[", "im", ".", "shape", "[", "1", "]"...
Creates a scatter plot, where each plot is shown by corresponding image
[ "Creates", "a", "scatter", "plot", "where", "each", "plot", "is", "shown", "by", "corresponding", "image" ]
62dedde52469f3a0aeb22fdd7bce2538f17f77ef
https://github.com/DmitryUlyanov/Multicore-TSNE/blob/62dedde52469f3a0aeb22fdd7bce2538f17f77ef/tsne-embedding.py#L9-L42
233,225
Blueqat/Blueqat
blueqat/opt.py
pauli
def pauli(qubo): """ Convert to pauli operators of universal gate model. Requires blueqat. """ from blueqat.pauli import qubo_bit h = 0.0 assert all(len(q) == len(qubo) for q in qubo) for i in range(len(qubo)): h += qubo_bit(i) * qubo[i][i] for j in range(i + 1, len(qubo)): h += qubo_bit(i)*qubo_bit(j) * (qubo[i][j] + qubo[j][i]) return h
python
def pauli(qubo): from blueqat.pauli import qubo_bit h = 0.0 assert all(len(q) == len(qubo) for q in qubo) for i in range(len(qubo)): h += qubo_bit(i) * qubo[i][i] for j in range(i + 1, len(qubo)): h += qubo_bit(i)*qubo_bit(j) * (qubo[i][j] + qubo[j][i]) return h
[ "def", "pauli", "(", "qubo", ")", ":", "from", "blueqat", ".", "pauli", "import", "qubo_bit", "h", "=", "0.0", "assert", "all", "(", "len", "(", "q", ")", "==", "len", "(", "qubo", ")", "for", "q", "in", "qubo", ")", "for", "i", "in", "range", ...
Convert to pauli operators of universal gate model. Requires blueqat.
[ "Convert", "to", "pauli", "operators", "of", "universal", "gate", "model", ".", "Requires", "blueqat", "." ]
2ac8592c79e7acf4f385d982af82fbd68dafa5cc
https://github.com/Blueqat/Blueqat/blob/2ac8592c79e7acf4f385d982af82fbd68dafa5cc/blueqat/opt.py#L18-L30
233,226
Blueqat/Blueqat
blueqat/opt.py
opt.plot
def plot(self): """ Draws energy chart using matplotlib. """ import matplotlib.pyplot as plt plt.plot(self.E) plt.show()
python
def plot(self): import matplotlib.pyplot as plt plt.plot(self.E) plt.show()
[ "def", "plot", "(", "self", ")", ":", "import", "matplotlib", ".", "pyplot", "as", "plt", "plt", ".", "plot", "(", "self", ".", "E", ")", "plt", ".", "show", "(", ")" ]
Draws energy chart using matplotlib.
[ "Draws", "energy", "chart", "using", "matplotlib", "." ]
2ac8592c79e7acf4f385d982af82fbd68dafa5cc
https://github.com/Blueqat/Blueqat/blob/2ac8592c79e7acf4f385d982af82fbd68dafa5cc/blueqat/opt.py#L366-L372
233,227
Blueqat/Blueqat
blueqat/opt.py
Opt.run
def run(self,shots=1,targetT=0.02,verbose=False): """ Run SA with provided QUBO. Set qubo attribute in advance of calling this method. """ if self.qubo != []: self.qi() J = self.reJ() N = len(J) itetemp = 100 Rtemp = 0.75 self.E = [] qq = [] for i in range(shots): T = self.Ts q = np.random.choice([-1,1],N) EE = [] EE.append(Ei(q,self.J)+self.ep) while T>targetT: x_list = np.random.randint(0, N, itetemp) for x in x_list: q2 = np.ones(N)*q[x] q2[x] = 1 dE = -2*sum(q*q2*J[:,x]) if dE < 0 or np.exp(-dE/T) > np.random.random_sample(): q[x] *= -1 EE.append(Ei(q,self.J)+self.ep) T *= Rtemp self.E.append(EE) qtemp = (np.asarray(q,int)+1)/2 qq.append([int(s) for s in qtemp]) if verbose == True: print(i,':',[int(s) for s in qtemp]) if shots == 1: qq = qq[0] if shots == 1: self.E = self.E[0] return qq
python
def run(self,shots=1,targetT=0.02,verbose=False): if self.qubo != []: self.qi() J = self.reJ() N = len(J) itetemp = 100 Rtemp = 0.75 self.E = [] qq = [] for i in range(shots): T = self.Ts q = np.random.choice([-1,1],N) EE = [] EE.append(Ei(q,self.J)+self.ep) while T>targetT: x_list = np.random.randint(0, N, itetemp) for x in x_list: q2 = np.ones(N)*q[x] q2[x] = 1 dE = -2*sum(q*q2*J[:,x]) if dE < 0 or np.exp(-dE/T) > np.random.random_sample(): q[x] *= -1 EE.append(Ei(q,self.J)+self.ep) T *= Rtemp self.E.append(EE) qtemp = (np.asarray(q,int)+1)/2 qq.append([int(s) for s in qtemp]) if verbose == True: print(i,':',[int(s) for s in qtemp]) if shots == 1: qq = qq[0] if shots == 1: self.E = self.E[0] return qq
[ "def", "run", "(", "self", ",", "shots", "=", "1", ",", "targetT", "=", "0.02", ",", "verbose", "=", "False", ")", ":", "if", "self", ".", "qubo", "!=", "[", "]", ":", "self", ".", "qi", "(", ")", "J", "=", "self", ".", "reJ", "(", ")", "N"...
Run SA with provided QUBO. Set qubo attribute in advance of calling this method.
[ "Run", "SA", "with", "provided", "QUBO", ".", "Set", "qubo", "attribute", "in", "advance", "of", "calling", "this", "method", "." ]
2ac8592c79e7acf4f385d982af82fbd68dafa5cc
https://github.com/Blueqat/Blueqat/blob/2ac8592c79e7acf4f385d982af82fbd68dafa5cc/blueqat/opt.py#L554-L594
233,228
Blueqat/Blueqat
blueqat/gate.py
Gate._str_targets
def _str_targets(self): """Returns printable string of targets.""" def _slice_to_str(obj): if isinstance(obj, slice): start = "" if obj.start is None else str(obj.start.__index__()) stop = "" if obj.stop is None else str(obj.stop.__index__()) if obj.step is None: return f"{start}:{stop}" else: step = str(obj.step.__index__()) return f"{start}:{stop}:{step}" else: return obj.__index__() if isinstance(self.targets, tuple): return f"[{', '.join(_slice_to_str(idx for idx in self.targets))}]" else: return f"[{_slice_to_str(self.targets)}]"
python
def _str_targets(self): def _slice_to_str(obj): if isinstance(obj, slice): start = "" if obj.start is None else str(obj.start.__index__()) stop = "" if obj.stop is None else str(obj.stop.__index__()) if obj.step is None: return f"{start}:{stop}" else: step = str(obj.step.__index__()) return f"{start}:{stop}:{step}" else: return obj.__index__() if isinstance(self.targets, tuple): return f"[{', '.join(_slice_to_str(idx for idx in self.targets))}]" else: return f"[{_slice_to_str(self.targets)}]"
[ "def", "_str_targets", "(", "self", ")", ":", "def", "_slice_to_str", "(", "obj", ")", ":", "if", "isinstance", "(", "obj", ",", "slice", ")", ":", "start", "=", "\"\"", "if", "obj", ".", "start", "is", "None", "else", "str", "(", "obj", ".", "star...
Returns printable string of targets.
[ "Returns", "printable", "string", "of", "targets", "." ]
2ac8592c79e7acf4f385d982af82fbd68dafa5cc
https://github.com/Blueqat/Blueqat/blob/2ac8592c79e7acf4f385d982af82fbd68dafa5cc/blueqat/gate.py#L36-L53
233,229
Blueqat/Blueqat
blueqat/vqe.py
get_scipy_minimizer
def get_scipy_minimizer(**kwargs): """Get minimizer which uses `scipy.optimize.minimize`""" def minimizer(objective, n_params): params = [random.random() for _ in range(n_params)] result = scipy_minimizer(objective, params, **kwargs) return result.x return minimizer
python
def get_scipy_minimizer(**kwargs): def minimizer(objective, n_params): params = [random.random() for _ in range(n_params)] result = scipy_minimizer(objective, params, **kwargs) return result.x return minimizer
[ "def", "get_scipy_minimizer", "(", "*", "*", "kwargs", ")", ":", "def", "minimizer", "(", "objective", ",", "n_params", ")", ":", "params", "=", "[", "random", ".", "random", "(", ")", "for", "_", "in", "range", "(", "n_params", ")", "]", "result", "...
Get minimizer which uses `scipy.optimize.minimize`
[ "Get", "minimizer", "which", "uses", "scipy", ".", "optimize", ".", "minimize" ]
2ac8592c79e7acf4f385d982af82fbd68dafa5cc
https://github.com/Blueqat/Blueqat/blob/2ac8592c79e7acf4f385d982af82fbd68dafa5cc/blueqat/vqe.py#L158-L164
233,230
Blueqat/Blueqat
blueqat/vqe.py
expect
def expect(qubits, meas): "For the VQE simulation without sampling." result = {} i = np.arange(len(qubits)) meas = tuple(meas) def to_mask(n): return reduce(lambda acc, im: acc | (n & (1 << im[0])) << (im[1] - im[0]), enumerate(meas), 0) def to_key(k): return tuple(1 if k & (1 << i) else 0 for i in meas) mask = reduce(lambda acc, v: acc | (1 << v), meas, 0) cnt = defaultdict(float) for i, v in enumerate(qubits): p = v.real ** 2 + v.imag ** 2 if p != 0.0: cnt[i & mask] += p return {to_key(k): v for k, v in cnt.items()}
python
def expect(qubits, meas): "For the VQE simulation without sampling." result = {} i = np.arange(len(qubits)) meas = tuple(meas) def to_mask(n): return reduce(lambda acc, im: acc | (n & (1 << im[0])) << (im[1] - im[0]), enumerate(meas), 0) def to_key(k): return tuple(1 if k & (1 << i) else 0 for i in meas) mask = reduce(lambda acc, v: acc | (1 << v), meas, 0) cnt = defaultdict(float) for i, v in enumerate(qubits): p = v.real ** 2 + v.imag ** 2 if p != 0.0: cnt[i & mask] += p return {to_key(k): v for k, v in cnt.items()}
[ "def", "expect", "(", "qubits", ",", "meas", ")", ":", "result", "=", "{", "}", "i", "=", "np", ".", "arange", "(", "len", "(", "qubits", ")", ")", "meas", "=", "tuple", "(", "meas", ")", "def", "to_mask", "(", "n", ")", ":", "return", "reduce"...
For the VQE simulation without sampling.
[ "For", "the", "VQE", "simulation", "without", "sampling", "." ]
2ac8592c79e7acf4f385d982af82fbd68dafa5cc
https://github.com/Blueqat/Blueqat/blob/2ac8592c79e7acf4f385d982af82fbd68dafa5cc/blueqat/vqe.py#L166-L185
233,231
Blueqat/Blueqat
blueqat/vqe.py
non_sampling_sampler
def non_sampling_sampler(circuit, meas): """Calculate the expectations without sampling.""" meas = tuple(meas) n_qubits = circuit.n_qubits return expect(circuit.run(returns="statevector"), meas)
python
def non_sampling_sampler(circuit, meas): meas = tuple(meas) n_qubits = circuit.n_qubits return expect(circuit.run(returns="statevector"), meas)
[ "def", "non_sampling_sampler", "(", "circuit", ",", "meas", ")", ":", "meas", "=", "tuple", "(", "meas", ")", "n_qubits", "=", "circuit", ".", "n_qubits", "return", "expect", "(", "circuit", ".", "run", "(", "returns", "=", "\"statevector\"", ")", ",", "...
Calculate the expectations without sampling.
[ "Calculate", "the", "expectations", "without", "sampling", "." ]
2ac8592c79e7acf4f385d982af82fbd68dafa5cc
https://github.com/Blueqat/Blueqat/blob/2ac8592c79e7acf4f385d982af82fbd68dafa5cc/blueqat/vqe.py#L187-L191
233,232
Blueqat/Blueqat
blueqat/vqe.py
get_measurement_sampler
def get_measurement_sampler(n_sample, run_options=None): """Returns a function which get the expectations by sampling the measured circuit""" if run_options is None: run_options = {} def sampling_by_measurement(circuit, meas): def reduce_bits(bits, meas): bits = [int(x) for x in bits[::-1]] return tuple(bits[m] for m in meas) meas = tuple(meas) circuit.measure[meas] counter = circuit.run(shots=n_sample, returns="shots", **run_options) counts = Counter({reduce_bits(bits, meas): val for bits, val in counter.items()}) return {k: v / n_sample for k, v in counts.items()} return sampling_by_measurement
python
def get_measurement_sampler(n_sample, run_options=None): if run_options is None: run_options = {} def sampling_by_measurement(circuit, meas): def reduce_bits(bits, meas): bits = [int(x) for x in bits[::-1]] return tuple(bits[m] for m in meas) meas = tuple(meas) circuit.measure[meas] counter = circuit.run(shots=n_sample, returns="shots", **run_options) counts = Counter({reduce_bits(bits, meas): val for bits, val in counter.items()}) return {k: v / n_sample for k, v in counts.items()} return sampling_by_measurement
[ "def", "get_measurement_sampler", "(", "n_sample", ",", "run_options", "=", "None", ")", ":", "if", "run_options", "is", "None", ":", "run_options", "=", "{", "}", "def", "sampling_by_measurement", "(", "circuit", ",", "meas", ")", ":", "def", "reduce_bits", ...
Returns a function which get the expectations by sampling the measured circuit
[ "Returns", "a", "function", "which", "get", "the", "expectations", "by", "sampling", "the", "measured", "circuit" ]
2ac8592c79e7acf4f385d982af82fbd68dafa5cc
https://github.com/Blueqat/Blueqat/blob/2ac8592c79e7acf4f385d982af82fbd68dafa5cc/blueqat/vqe.py#L193-L209
233,233
Blueqat/Blueqat
blueqat/vqe.py
get_state_vector_sampler
def get_state_vector_sampler(n_sample): """Returns a function which get the expectations by sampling the state vector""" def sampling_by_measurement(circuit, meas): val = 0.0 e = expect(circuit.run(returns="statevector"), meas) bits, probs = zip(*e.items()) dists = np.random.multinomial(n_sample, probs) / n_sample return dict(zip(tuple(bits), dists)) return sampling_by_measurement
python
def get_state_vector_sampler(n_sample): def sampling_by_measurement(circuit, meas): val = 0.0 e = expect(circuit.run(returns="statevector"), meas) bits, probs = zip(*e.items()) dists = np.random.multinomial(n_sample, probs) / n_sample return dict(zip(tuple(bits), dists)) return sampling_by_measurement
[ "def", "get_state_vector_sampler", "(", "n_sample", ")", ":", "def", "sampling_by_measurement", "(", "circuit", ",", "meas", ")", ":", "val", "=", "0.0", "e", "=", "expect", "(", "circuit", ".", "run", "(", "returns", "=", "\"statevector\"", ")", ",", "mea...
Returns a function which get the expectations by sampling the state vector
[ "Returns", "a", "function", "which", "get", "the", "expectations", "by", "sampling", "the", "state", "vector" ]
2ac8592c79e7acf4f385d982af82fbd68dafa5cc
https://github.com/Blueqat/Blueqat/blob/2ac8592c79e7acf4f385d982af82fbd68dafa5cc/blueqat/vqe.py#L211-L219
233,234
Blueqat/Blueqat
blueqat/vqe.py
get_qiskit_sampler
def get_qiskit_sampler(backend, **execute_kwargs): """Returns a function which get the expectation by sampling via Qiskit. This function requires `qiskit` module. """ try: import qiskit except ImportError: raise ImportError("blueqat.vqe.get_qiskit_sampler() requires qiskit. Please install before call this function.") try: shots = execute_kwargs['shots'] except KeyError: execute_kwargs['shots'] = shots = 1024 def reduce_bits(bits, meas): # In Qiskit 0.6.1, For example # Aer backend returns bit string and IBMQ backend returns hex string. # Sample code: """ from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, execute, Aer, IBMQ IBMQ.load_accounts() q, c = QuantumRegister(4, 'q'), ClassicalRegister(4, 'c') circ = QuantumCircuit(q, c) circ.x(q[1]) for i in range(4): circ.measure(q[i], c[i]) print("Aer qasm_simulator_py") print(execute(circ, Aer.get_backend('qasm_simulator_py')).result().get_counts()) print("IBMQ ibmq_qasm_simulator") print(execute(circ, IBMQ.get_backend('ibmq_qasm_simulator')).result().get_counts()) """ # The result is, # Aer: {'0010': 1024} # IBMQ: {'0x2': 1024} # This is workaround for this IBM's specifications. if bits.startswith("0x"): bits = int(bits, base=16) bits = "0"*100 + format(bits, "b") bits = [int(x) for x in bits[::-1]] return tuple(bits[m] for m in meas) def sampling(circuit, meas): meas = tuple(meas) if not meas: return {} circuit.measure[meas] qasm = circuit.to_qasm() qk_circuit = qiskit.load_qasm_string(qasm) result = qiskit.execute(qk_circuit, backend, **execute_kwargs).result() counts = Counter({reduce_bits(bits, meas): val for bits, val in result.get_counts().items()}) return {k: v / shots for k, v in counts.items()} return sampling
python
def get_qiskit_sampler(backend, **execute_kwargs): try: import qiskit except ImportError: raise ImportError("blueqat.vqe.get_qiskit_sampler() requires qiskit. Please install before call this function.") try: shots = execute_kwargs['shots'] except KeyError: execute_kwargs['shots'] = shots = 1024 def reduce_bits(bits, meas): # In Qiskit 0.6.1, For example # Aer backend returns bit string and IBMQ backend returns hex string. # Sample code: """ from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, execute, Aer, IBMQ IBMQ.load_accounts() q, c = QuantumRegister(4, 'q'), ClassicalRegister(4, 'c') circ = QuantumCircuit(q, c) circ.x(q[1]) for i in range(4): circ.measure(q[i], c[i]) print("Aer qasm_simulator_py") print(execute(circ, Aer.get_backend('qasm_simulator_py')).result().get_counts()) print("IBMQ ibmq_qasm_simulator") print(execute(circ, IBMQ.get_backend('ibmq_qasm_simulator')).result().get_counts()) """ # The result is, # Aer: {'0010': 1024} # IBMQ: {'0x2': 1024} # This is workaround for this IBM's specifications. if bits.startswith("0x"): bits = int(bits, base=16) bits = "0"*100 + format(bits, "b") bits = [int(x) for x in bits[::-1]] return tuple(bits[m] for m in meas) def sampling(circuit, meas): meas = tuple(meas) if not meas: return {} circuit.measure[meas] qasm = circuit.to_qasm() qk_circuit = qiskit.load_qasm_string(qasm) result = qiskit.execute(qk_circuit, backend, **execute_kwargs).result() counts = Counter({reduce_bits(bits, meas): val for bits, val in result.get_counts().items()}) return {k: v / shots for k, v in counts.items()} return sampling
[ "def", "get_qiskit_sampler", "(", "backend", ",", "*", "*", "execute_kwargs", ")", ":", "try", ":", "import", "qiskit", "except", "ImportError", ":", "raise", "ImportError", "(", "\"blueqat.vqe.get_qiskit_sampler() requires qiskit. Please install before call this function.\""...
Returns a function which get the expectation by sampling via Qiskit. This function requires `qiskit` module.
[ "Returns", "a", "function", "which", "get", "the", "expectation", "by", "sampling", "via", "Qiskit", "." ]
2ac8592c79e7acf4f385d982af82fbd68dafa5cc
https://github.com/Blueqat/Blueqat/blob/2ac8592c79e7acf4f385d982af82fbd68dafa5cc/blueqat/vqe.py#L221-L273
233,235
Blueqat/Blueqat
blueqat/vqe.py
AnsatzBase.get_energy
def get_energy(self, circuit, sampler): """Calculate energy from circuit and sampler.""" val = 0.0 for meas in self.hamiltonian: c = circuit.copy() for op in meas.ops: if op.op == "X": c.h[op.n] elif op.op == "Y": c.rx(-np.pi / 2)[op.n] measured = sampler(c, meas.n_iter()) for bits, prob in measured.items(): if sum(bits) % 2: val -= prob * meas.coeff else: val += prob * meas.coeff return val.real
python
def get_energy(self, circuit, sampler): val = 0.0 for meas in self.hamiltonian: c = circuit.copy() for op in meas.ops: if op.op == "X": c.h[op.n] elif op.op == "Y": c.rx(-np.pi / 2)[op.n] measured = sampler(c, meas.n_iter()) for bits, prob in measured.items(): if sum(bits) % 2: val -= prob * meas.coeff else: val += prob * meas.coeff return val.real
[ "def", "get_energy", "(", "self", ",", "circuit", ",", "sampler", ")", ":", "val", "=", "0.0", "for", "meas", "in", "self", ".", "hamiltonian", ":", "c", "=", "circuit", ".", "copy", "(", ")", "for", "op", "in", "meas", ".", "ops", ":", "if", "op...
Calculate energy from circuit and sampler.
[ "Calculate", "energy", "from", "circuit", "and", "sampler", "." ]
2ac8592c79e7acf4f385d982af82fbd68dafa5cc
https://github.com/Blueqat/Blueqat/blob/2ac8592c79e7acf4f385d982af82fbd68dafa5cc/blueqat/vqe.py#L36-L52
233,236
Blueqat/Blueqat
blueqat/vqe.py
AnsatzBase.get_objective
def get_objective(self, sampler): """Get an objective function to be optimized.""" def objective(params): circuit = self.get_circuit(params) circuit.make_cache() return self.get_energy(circuit, sampler) return objective
python
def get_objective(self, sampler): def objective(params): circuit = self.get_circuit(params) circuit.make_cache() return self.get_energy(circuit, sampler) return objective
[ "def", "get_objective", "(", "self", ",", "sampler", ")", ":", "def", "objective", "(", "params", ")", ":", "circuit", "=", "self", ".", "get_circuit", "(", "params", ")", "circuit", ".", "make_cache", "(", ")", "return", "self", ".", "get_energy", "(", ...
Get an objective function to be optimized.
[ "Get", "an", "objective", "function", "to", "be", "optimized", "." ]
2ac8592c79e7acf4f385d982af82fbd68dafa5cc
https://github.com/Blueqat/Blueqat/blob/2ac8592c79e7acf4f385d982af82fbd68dafa5cc/blueqat/vqe.py#L54-L60
233,237
Blueqat/Blueqat
blueqat/vqe.py
VqeResult.get_probs
def get_probs(self, sampler=None, rerun=None, store=True): """Get probabilities.""" if rerun is None: rerun = sampler is not None if self._probs is not None and not rerun: return self._probs if sampler is None: sampler = self.vqe.sampler probs = sampler(self.circuit, range(self.circuit.n_qubits)) if store: self._probs = probs return probs
python
def get_probs(self, sampler=None, rerun=None, store=True): if rerun is None: rerun = sampler is not None if self._probs is not None and not rerun: return self._probs if sampler is None: sampler = self.vqe.sampler probs = sampler(self.circuit, range(self.circuit.n_qubits)) if store: self._probs = probs return probs
[ "def", "get_probs", "(", "self", ",", "sampler", "=", "None", ",", "rerun", "=", "None", ",", "store", "=", "True", ")", ":", "if", "rerun", "is", "None", ":", "rerun", "=", "sampler", "is", "not", "None", "if", "self", ".", "_probs", "is", "not", ...
Get probabilities.
[ "Get", "probabilities", "." ]
2ac8592c79e7acf4f385d982af82fbd68dafa5cc
https://github.com/Blueqat/Blueqat/blob/2ac8592c79e7acf4f385d982af82fbd68dafa5cc/blueqat/vqe.py#L113-L124
233,238
Blueqat/Blueqat
blueqat/backends/backendbase.py
Backend._run_gates
def _run_gates(self, gates, n_qubits, ctx): """Iterate gates and call backend's action for each gates""" for gate in gates: action = self._get_action(gate) if action is not None: ctx = action(gate, ctx) else: ctx = self._run_gates(gate.fallback(n_qubits), n_qubits, ctx) return ctx
python
def _run_gates(self, gates, n_qubits, ctx): for gate in gates: action = self._get_action(gate) if action is not None: ctx = action(gate, ctx) else: ctx = self._run_gates(gate.fallback(n_qubits), n_qubits, ctx) return ctx
[ "def", "_run_gates", "(", "self", ",", "gates", ",", "n_qubits", ",", "ctx", ")", ":", "for", "gate", "in", "gates", ":", "action", "=", "self", ".", "_get_action", "(", "gate", ")", "if", "action", "is", "not", "None", ":", "ctx", "=", "action", "...
Iterate gates and call backend's action for each gates
[ "Iterate", "gates", "and", "call", "backend", "s", "action", "for", "each", "gates" ]
2ac8592c79e7acf4f385d982af82fbd68dafa5cc
https://github.com/Blueqat/Blueqat/blob/2ac8592c79e7acf4f385d982af82fbd68dafa5cc/blueqat/backends/backendbase.py#L45-L53
233,239
Blueqat/Blueqat
blueqat/backends/backendbase.py
Backend._run
def _run(self, gates, n_qubits, args, kwargs): """Default implementation of `Backend.run`. Backend developer shouldn't override this function, but override `run` instead of this. The default flow of running is: 1. preprocessing 2. call the gate action which defined in backend 3. postprocessing Backend developer can: 1. Define preprocessing process. Override `_preprocess_run` 2. Define the gate action. Define methods `gate_{gate.lowername}`, for example, `gate_x` for X gate, `gate_cx` for CX gate. 3. Define postprocessing process (and make return value). Override `_postprocess_run` Otherwise, the developer can override `run` method if they want to change the flow of run. """ gates, ctx = self._preprocess_run(gates, n_qubits, args, kwargs) self._run_gates(gates, n_qubits, ctx) return self._postprocess_run(ctx)
python
def _run(self, gates, n_qubits, args, kwargs): gates, ctx = self._preprocess_run(gates, n_qubits, args, kwargs) self._run_gates(gates, n_qubits, ctx) return self._postprocess_run(ctx)
[ "def", "_run", "(", "self", ",", "gates", ",", "n_qubits", ",", "args", ",", "kwargs", ")", ":", "gates", ",", "ctx", "=", "self", ".", "_preprocess_run", "(", "gates", ",", "n_qubits", ",", "args", ",", "kwargs", ")", "self", ".", "_run_gates", "(",...
Default implementation of `Backend.run`. Backend developer shouldn't override this function, but override `run` instead of this. The default flow of running is: 1. preprocessing 2. call the gate action which defined in backend 3. postprocessing Backend developer can: 1. Define preprocessing process. Override `_preprocess_run` 2. Define the gate action. Define methods `gate_{gate.lowername}`, for example, `gate_x` for X gate, `gate_cx` for CX gate. 3. Define postprocessing process (and make return value). Override `_postprocess_run` Otherwise, the developer can override `run` method if they want to change the flow of run.
[ "Default", "implementation", "of", "Backend", ".", "run", ".", "Backend", "developer", "shouldn", "t", "override", "this", "function", "but", "override", "run", "instead", "of", "this", "." ]
2ac8592c79e7acf4f385d982af82fbd68dafa5cc
https://github.com/Blueqat/Blueqat/blob/2ac8592c79e7acf4f385d982af82fbd68dafa5cc/blueqat/backends/backendbase.py#L55-L73
233,240
Blueqat/Blueqat
blueqat/backends/backendbase.py
Backend.run
def run(self, gates, n_qubits, *args, **kwargs): """Run the backend.""" return self._run(gates, n_qubits, args, kwargs)
python
def run(self, gates, n_qubits, *args, **kwargs): return self._run(gates, n_qubits, args, kwargs)
[ "def", "run", "(", "self", ",", "gates", ",", "n_qubits", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "_run", "(", "gates", ",", "n_qubits", ",", "args", ",", "kwargs", ")" ]
Run the backend.
[ "Run", "the", "backend", "." ]
2ac8592c79e7acf4f385d982af82fbd68dafa5cc
https://github.com/Blueqat/Blueqat/blob/2ac8592c79e7acf4f385d982af82fbd68dafa5cc/blueqat/backends/backendbase.py#L82-L84
233,241
Blueqat/Blueqat
blueqat/backends/backendbase.py
Backend._resolve_fallback
def _resolve_fallback(self, gates, n_qubits): """Resolve fallbacks and flatten gates.""" flattened = [] for g in gates: if self._has_action(g): flattened.append(g) else: flattened += self._resolve_fallback(g.fallback(n_qubits), n_qubits) return flattened
python
def _resolve_fallback(self, gates, n_qubits): flattened = [] for g in gates: if self._has_action(g): flattened.append(g) else: flattened += self._resolve_fallback(g.fallback(n_qubits), n_qubits) return flattened
[ "def", "_resolve_fallback", "(", "self", ",", "gates", ",", "n_qubits", ")", ":", "flattened", "=", "[", "]", "for", "g", "in", "gates", ":", "if", "self", ".", "_has_action", "(", "g", ")", ":", "flattened", ".", "append", "(", "g", ")", "else", "...
Resolve fallbacks and flatten gates.
[ "Resolve", "fallbacks", "and", "flatten", "gates", "." ]
2ac8592c79e7acf4f385d982af82fbd68dafa5cc
https://github.com/Blueqat/Blueqat/blob/2ac8592c79e7acf4f385d982af82fbd68dafa5cc/blueqat/backends/backendbase.py#L95-L103
233,242
Blueqat/Blueqat
blueqat/backends/numpy_backend.py
_NumPyBackendContext.prepare
def prepare(self, cache): """Prepare to run next shot.""" if cache is not None: np.copyto(self.qubits, cache) else: self.qubits.fill(0.0) self.qubits[0] = 1.0 self.cregs = [0] * self.n_qubits
python
def prepare(self, cache): if cache is not None: np.copyto(self.qubits, cache) else: self.qubits.fill(0.0) self.qubits[0] = 1.0 self.cregs = [0] * self.n_qubits
[ "def", "prepare", "(", "self", ",", "cache", ")", ":", "if", "cache", "is", "not", "None", ":", "np", ".", "copyto", "(", "self", ".", "qubits", ",", "cache", ")", "else", ":", "self", ".", "qubits", ".", "fill", "(", "0.0", ")", "self", ".", "...
Prepare to run next shot.
[ "Prepare", "to", "run", "next", "shot", "." ]
2ac8592c79e7acf4f385d982af82fbd68dafa5cc
https://github.com/Blueqat/Blueqat/blob/2ac8592c79e7acf4f385d982af82fbd68dafa5cc/blueqat/backends/numpy_backend.py#L38-L45
233,243
Blueqat/Blueqat
blueqat/backends/numpy_backend.py
_NumPyBackendContext.store_shot
def store_shot(self): """Store current cregs to shots_result""" def to_str(cregs): return ''.join(str(b) for b in cregs) key = to_str(self.cregs) self.shots_result[key] = self.shots_result.get(key, 0) + 1
python
def store_shot(self): def to_str(cregs): return ''.join(str(b) for b in cregs) key = to_str(self.cregs) self.shots_result[key] = self.shots_result.get(key, 0) + 1
[ "def", "store_shot", "(", "self", ")", ":", "def", "to_str", "(", "cregs", ")", ":", "return", "''", ".", "join", "(", "str", "(", "b", ")", "for", "b", "in", "cregs", ")", "key", "=", "to_str", "(", "self", ".", "cregs", ")", "self", ".", "sho...
Store current cregs to shots_result
[ "Store", "current", "cregs", "to", "shots_result" ]
2ac8592c79e7acf4f385d982af82fbd68dafa5cc
https://github.com/Blueqat/Blueqat/blob/2ac8592c79e7acf4f385d982af82fbd68dafa5cc/blueqat/backends/numpy_backend.py#L47-L52
233,244
Blueqat/Blueqat
blueqat/circuit.py
Circuit.copy
def copy(self, copy_backends=True, copy_default_backend=True, copy_cache=None, copy_history=None): """Copy the circuit. :params copy_backends :bool copy backends if True. copy_default_backend :bool copy default_backend if True. """ copied = Circuit(self.n_qubits, self.ops.copy()) if copy_backends: copied._backends = {k: v.copy() for k, v in self._backends.items()} if copy_default_backend: copied._default_backend = self._default_backend # Warn for deprecated options if copy_cache is not None: warnings.warn("copy_cache is deprecated. Use copy_backends instead.", DeprecationWarning) if copy_history is not None: warnings.warn("copy_history is deprecated.", DeprecationWarning) return copied
python
def copy(self, copy_backends=True, copy_default_backend=True, copy_cache=None, copy_history=None): copied = Circuit(self.n_qubits, self.ops.copy()) if copy_backends: copied._backends = {k: v.copy() for k, v in self._backends.items()} if copy_default_backend: copied._default_backend = self._default_backend # Warn for deprecated options if copy_cache is not None: warnings.warn("copy_cache is deprecated. Use copy_backends instead.", DeprecationWarning) if copy_history is not None: warnings.warn("copy_history is deprecated.", DeprecationWarning) return copied
[ "def", "copy", "(", "self", ",", "copy_backends", "=", "True", ",", "copy_default_backend", "=", "True", ",", "copy_cache", "=", "None", ",", "copy_history", "=", "None", ")", ":", "copied", "=", "Circuit", "(", "self", ".", "n_qubits", ",", "self", ".",...
Copy the circuit. :params copy_backends :bool copy backends if True. copy_default_backend :bool copy default_backend if True.
[ "Copy", "the", "circuit", "." ]
2ac8592c79e7acf4f385d982af82fbd68dafa5cc
https://github.com/Blueqat/Blueqat/blob/2ac8592c79e7acf4f385d982af82fbd68dafa5cc/blueqat/circuit.py#L127-L148
233,245
Blueqat/Blueqat
blueqat/circuit.py
Circuit.run
def run(self, *args, backend=None, **kwargs): """Run the circuit. `Circuit` have several backends. When `backend` parameter is specified, use specified backend, and otherwise, default backend is used. Other parameters are passed to the backend. The meaning of parameters are depends on the backend specifications. However, following parameters are commonly used. Commonly used args (Depends on backend): shots (int, optional): The number of sampling the circuit. returns (str, optional): The category of returns value. e.g. "statevector" returns the state vector after run the circuit. "shots" returns the counter of measured value. token, url (str, optional): The token and URL for cloud resource. Returns: Depends on backend. Raises: Depends on backend. """ if backend is None: if self._default_backend is None: backend = self.__get_backend(DEFAULT_BACKEND_NAME) else: backend = self.__get_backend(self._default_backend) elif isinstance(backend, str): backend = self.__get_backend(backend) return backend.run(self.ops, self.n_qubits, *args, **kwargs)
python
def run(self, *args, backend=None, **kwargs): if backend is None: if self._default_backend is None: backend = self.__get_backend(DEFAULT_BACKEND_NAME) else: backend = self.__get_backend(self._default_backend) elif isinstance(backend, str): backend = self.__get_backend(backend) return backend.run(self.ops, self.n_qubits, *args, **kwargs)
[ "def", "run", "(", "self", ",", "*", "args", ",", "backend", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "backend", "is", "None", ":", "if", "self", ".", "_default_backend", "is", "None", ":", "backend", "=", "self", ".", "__get_backend", ...
Run the circuit. `Circuit` have several backends. When `backend` parameter is specified, use specified backend, and otherwise, default backend is used. Other parameters are passed to the backend. The meaning of parameters are depends on the backend specifications. However, following parameters are commonly used. Commonly used args (Depends on backend): shots (int, optional): The number of sampling the circuit. returns (str, optional): The category of returns value. e.g. "statevector" returns the state vector after run the circuit. "shots" returns the counter of measured value. token, url (str, optional): The token and URL for cloud resource. Returns: Depends on backend. Raises: Depends on backend.
[ "Run", "the", "circuit", "." ]
2ac8592c79e7acf4f385d982af82fbd68dafa5cc
https://github.com/Blueqat/Blueqat/blob/2ac8592c79e7acf4f385d982af82fbd68dafa5cc/blueqat/circuit.py#L150-L180
233,246
Blueqat/Blueqat
blueqat/circuit.py
Circuit.make_cache
def make_cache(self, backend=None): """Make a cache to reduce the time of run. Some backends may implemented it. This is temporary API. It may changed or deprecated.""" if backend is None: if self._default_backend is None: backend = DEFAULT_BACKEND_NAME else: backend = self._default_backend return self.__get_backend(backend).make_cache(self.ops, self.n_qubits)
python
def make_cache(self, backend=None): if backend is None: if self._default_backend is None: backend = DEFAULT_BACKEND_NAME else: backend = self._default_backend return self.__get_backend(backend).make_cache(self.ops, self.n_qubits)
[ "def", "make_cache", "(", "self", ",", "backend", "=", "None", ")", ":", "if", "backend", "is", "None", ":", "if", "self", ".", "_default_backend", "is", "None", ":", "backend", "=", "DEFAULT_BACKEND_NAME", "else", ":", "backend", "=", "self", ".", "_def...
Make a cache to reduce the time of run. Some backends may implemented it. This is temporary API. It may changed or deprecated.
[ "Make", "a", "cache", "to", "reduce", "the", "time", "of", "run", ".", "Some", "backends", "may", "implemented", "it", "." ]
2ac8592c79e7acf4f385d982af82fbd68dafa5cc
https://github.com/Blueqat/Blueqat/blob/2ac8592c79e7acf4f385d982af82fbd68dafa5cc/blueqat/circuit.py#L182-L191
233,247
Blueqat/Blueqat
blueqat/circuit.py
Circuit.set_default_backend
def set_default_backend(self, backend_name): """Set the default backend of this circuit. This setting is only applied for this circuit. If you want to change the default backend of all gates, use `BlueqatGlobalSetting.set_default_backend()`. After set the default backend by this method, global setting is ignored even if `BlueqatGlobalSetting.set_default_backend()` is called. If you want to use global default setting, call this method with backend_name=None. Args: backend_name (str or None): new default backend name. If None is given, global setting is applied. Raises: ValueError: If `backend_name` is not registered backend. """ if backend_name not in BACKENDS: raise ValueError(f"Unknown backend '{backend_name}'.") self._default_backend = backend_name
python
def set_default_backend(self, backend_name): if backend_name not in BACKENDS: raise ValueError(f"Unknown backend '{backend_name}'.") self._default_backend = backend_name
[ "def", "set_default_backend", "(", "self", ",", "backend_name", ")", ":", "if", "backend_name", "not", "in", "BACKENDS", ":", "raise", "ValueError", "(", "f\"Unknown backend '{backend_name}'.\"", ")", "self", ".", "_default_backend", "=", "backend_name" ]
Set the default backend of this circuit. This setting is only applied for this circuit. If you want to change the default backend of all gates, use `BlueqatGlobalSetting.set_default_backend()`. After set the default backend by this method, global setting is ignored even if `BlueqatGlobalSetting.set_default_backend()` is called. If you want to use global default setting, call this method with backend_name=None. Args: backend_name (str or None): new default backend name. If None is given, global setting is applied. Raises: ValueError: If `backend_name` is not registered backend.
[ "Set", "the", "default", "backend", "of", "this", "circuit", "." ]
2ac8592c79e7acf4f385d982af82fbd68dafa5cc
https://github.com/Blueqat/Blueqat/blob/2ac8592c79e7acf4f385d982af82fbd68dafa5cc/blueqat/circuit.py#L201-L221
233,248
Blueqat/Blueqat
blueqat/circuit.py
BlueqatGlobalSetting.register_macro
def register_macro(name: str, func: Callable, allow_overwrite: bool = False) -> None: """Register new macro to Circuit. Args: name (str): The name of macro. func (callable): The function to be called. allow_overwrite (bool, optional): If True, allow to overwrite the existing macro. Otherwise, raise the ValueError. Raises: ValueError: The name is duplicated with existing macro, gate or method. When `allow_overwrite=True`, this error is not raised. """ if hasattr(Circuit, name): if allow_overwrite: warnings.warn(f"Circuit has attribute `{name}`.") else: raise ValueError(f"Circuit has attribute `{name}`.") if name.startswith("run_with_"): if allow_overwrite: warnings.warn(f"Gate name `{name}` may conflict with run of backend.") else: raise ValueError(f"Gate name `{name}` shall not start with 'run_with_'.") if not allow_overwrite: if name in GATE_SET: raise ValueError(f"Gate '{name}' is already exists in gate set.") if name in GLOBAL_MACROS: raise ValueError(f"Macro '{name}' is already exists.") GLOBAL_MACROS[name] = func
python
def register_macro(name: str, func: Callable, allow_overwrite: bool = False) -> None: if hasattr(Circuit, name): if allow_overwrite: warnings.warn(f"Circuit has attribute `{name}`.") else: raise ValueError(f"Circuit has attribute `{name}`.") if name.startswith("run_with_"): if allow_overwrite: warnings.warn(f"Gate name `{name}` may conflict with run of backend.") else: raise ValueError(f"Gate name `{name}` shall not start with 'run_with_'.") if not allow_overwrite: if name in GATE_SET: raise ValueError(f"Gate '{name}' is already exists in gate set.") if name in GLOBAL_MACROS: raise ValueError(f"Macro '{name}' is already exists.") GLOBAL_MACROS[name] = func
[ "def", "register_macro", "(", "name", ":", "str", ",", "func", ":", "Callable", ",", "allow_overwrite", ":", "bool", "=", "False", ")", "->", "None", ":", "if", "hasattr", "(", "Circuit", ",", "name", ")", ":", "if", "allow_overwrite", ":", "warnings", ...
Register new macro to Circuit. Args: name (str): The name of macro. func (callable): The function to be called. allow_overwrite (bool, optional): If True, allow to overwrite the existing macro. Otherwise, raise the ValueError. Raises: ValueError: The name is duplicated with existing macro, gate or method. When `allow_overwrite=True`, this error is not raised.
[ "Register", "new", "macro", "to", "Circuit", "." ]
2ac8592c79e7acf4f385d982af82fbd68dafa5cc
https://github.com/Blueqat/Blueqat/blob/2ac8592c79e7acf4f385d982af82fbd68dafa5cc/blueqat/circuit.py#L267-L295
233,249
Blueqat/Blueqat
blueqat/circuit.py
BlueqatGlobalSetting.register_gate
def register_gate(name, gateclass, allow_overwrite=False): """Register new gate to gate set. Args: name (str): The name of gate. gateclass (type): The type object of gate. allow_overwrite (bool, optional): If True, allow to overwrite the existing gate. Otherwise, raise the ValueError. Raises: ValueError: The name is duplicated with existing gate. When `allow_overwrite=True`, this error is not raised. """ if hasattr(Circuit, name): if allow_overwrite: warnings.warn(f"Circuit has attribute `{name}`.") else: raise ValueError(f"Circuit has attribute `{name}`.") if name.startswith("run_with_"): if allow_overwrite: warnings.warn(f"Gate name `{name}` may conflict with run of backend.") else: raise ValueError(f"Gate name `{name}` shall not start with 'run_with_'.") if not allow_overwrite: if name in GATE_SET: raise ValueError(f"Gate '{name}' is already exists in gate set.") if name in GLOBAL_MACROS: raise ValueError(f"Macro '{name}' is already exists.") GATE_SET[name] = gateclass
python
def register_gate(name, gateclass, allow_overwrite=False): if hasattr(Circuit, name): if allow_overwrite: warnings.warn(f"Circuit has attribute `{name}`.") else: raise ValueError(f"Circuit has attribute `{name}`.") if name.startswith("run_with_"): if allow_overwrite: warnings.warn(f"Gate name `{name}` may conflict with run of backend.") else: raise ValueError(f"Gate name `{name}` shall not start with 'run_with_'.") if not allow_overwrite: if name in GATE_SET: raise ValueError(f"Gate '{name}' is already exists in gate set.") if name in GLOBAL_MACROS: raise ValueError(f"Macro '{name}' is already exists.") GATE_SET[name] = gateclass
[ "def", "register_gate", "(", "name", ",", "gateclass", ",", "allow_overwrite", "=", "False", ")", ":", "if", "hasattr", "(", "Circuit", ",", "name", ")", ":", "if", "allow_overwrite", ":", "warnings", ".", "warn", "(", "f\"Circuit has attribute `{name}`.\"", "...
Register new gate to gate set. Args: name (str): The name of gate. gateclass (type): The type object of gate. allow_overwrite (bool, optional): If True, allow to overwrite the existing gate. Otherwise, raise the ValueError. Raises: ValueError: The name is duplicated with existing gate. When `allow_overwrite=True`, this error is not raised.
[ "Register", "new", "gate", "to", "gate", "set", "." ]
2ac8592c79e7acf4f385d982af82fbd68dafa5cc
https://github.com/Blueqat/Blueqat/blob/2ac8592c79e7acf4f385d982af82fbd68dafa5cc/blueqat/circuit.py#L312-L340
233,250
Blueqat/Blueqat
blueqat/circuit.py
BlueqatGlobalSetting.register_backend
def register_backend(name, backend, allow_overwrite=False): """Register new backend. Args: name (str): The name of backend. gateclass (type): The type object of backend allow_overwrite (bool, optional): If True, allow to overwrite the existing backend. Otherwise, raise the ValueError. Raises: ValueError: The name is duplicated with existing backend. When `allow_overwrite=True`, this error is not raised. """ if hasattr(Circuit, "run_with_" + name): if allow_overwrite: warnings.warn(f"Circuit has attribute `run_with_{name}`.") else: raise ValueError(f"Circuit has attribute `run_with_{name}`.") if not allow_overwrite: if name in BACKENDS: raise ValueError(f"Backend '{name}' is already registered as backend.") BACKENDS[name] = backend
python
def register_backend(name, backend, allow_overwrite=False): if hasattr(Circuit, "run_with_" + name): if allow_overwrite: warnings.warn(f"Circuit has attribute `run_with_{name}`.") else: raise ValueError(f"Circuit has attribute `run_with_{name}`.") if not allow_overwrite: if name in BACKENDS: raise ValueError(f"Backend '{name}' is already registered as backend.") BACKENDS[name] = backend
[ "def", "register_backend", "(", "name", ",", "backend", ",", "allow_overwrite", "=", "False", ")", ":", "if", "hasattr", "(", "Circuit", ",", "\"run_with_\"", "+", "name", ")", ":", "if", "allow_overwrite", ":", "warnings", ".", "warn", "(", "f\"Circuit has ...
Register new backend. Args: name (str): The name of backend. gateclass (type): The type object of backend allow_overwrite (bool, optional): If True, allow to overwrite the existing backend. Otherwise, raise the ValueError. Raises: ValueError: The name is duplicated with existing backend. When `allow_overwrite=True`, this error is not raised.
[ "Register", "new", "backend", "." ]
2ac8592c79e7acf4f385d982af82fbd68dafa5cc
https://github.com/Blueqat/Blueqat/blob/2ac8592c79e7acf4f385d982af82fbd68dafa5cc/blueqat/circuit.py#L357-L378
233,251
Blueqat/Blueqat
examples/maxcut_qaoa.py
maxcut_qaoa
def maxcut_qaoa(n_step, edges, minimizer=None, sampler=None, verbose=True): """Setup QAOA. :param n_step: The number of step of QAOA :param n_sample: The number of sampling time of each measurement in VQE. If None, use calculated ideal value. :param edges: The edges list of the graph. :returns Vqe object """ sampler = sampler or vqe.non_sampling_sampler minimizer = minimizer or vqe.get_scipy_minimizer( method="Powell", options={"ftol": 5.0e-2, "xtol": 5.0e-2, "maxiter": 1000, "disp": True} ) hamiltonian = pauli.I() * 0 for i, j in edges: hamiltonian += pauli.Z(i) * pauli.Z(j) return vqe.Vqe(vqe.QaoaAnsatz(hamiltonian, n_step), minimizer, sampler)
python
def maxcut_qaoa(n_step, edges, minimizer=None, sampler=None, verbose=True): sampler = sampler or vqe.non_sampling_sampler minimizer = minimizer or vqe.get_scipy_minimizer( method="Powell", options={"ftol": 5.0e-2, "xtol": 5.0e-2, "maxiter": 1000, "disp": True} ) hamiltonian = pauli.I() * 0 for i, j in edges: hamiltonian += pauli.Z(i) * pauli.Z(j) return vqe.Vqe(vqe.QaoaAnsatz(hamiltonian, n_step), minimizer, sampler)
[ "def", "maxcut_qaoa", "(", "n_step", ",", "edges", ",", "minimizer", "=", "None", ",", "sampler", "=", "None", ",", "verbose", "=", "True", ")", ":", "sampler", "=", "sampler", "or", "vqe", ".", "non_sampling_sampler", "minimizer", "=", "minimizer", "or", ...
Setup QAOA. :param n_step: The number of step of QAOA :param n_sample: The number of sampling time of each measurement in VQE. If None, use calculated ideal value. :param edges: The edges list of the graph. :returns Vqe object
[ "Setup", "QAOA", "." ]
2ac8592c79e7acf4f385d982af82fbd68dafa5cc
https://github.com/Blueqat/Blueqat/blob/2ac8592c79e7acf4f385d982af82fbd68dafa5cc/examples/maxcut_qaoa.py#L3-L22
233,252
Blueqat/Blueqat
blueqat/pauli.py
pauli_from_char
def pauli_from_char(ch, n=0): """Make Pauli matrix from an character. Args: ch (str): "X" or "Y" or "Z" or "I". n (int, optional): Make Pauli matrix as n-th qubits. Returns: If ch is "X" => X, "Y" => Y, "Z" => Z, "I" => I Raises: ValueError: When ch is not "X", "Y", "Z" nor "I". """ ch = ch.upper() if ch == "I": return I if ch == "X": return X(n) if ch == "Y": return Y(n) if ch == "Z": return Z(n) raise ValueError("ch shall be X, Y, Z or I")
python
def pauli_from_char(ch, n=0): ch = ch.upper() if ch == "I": return I if ch == "X": return X(n) if ch == "Y": return Y(n) if ch == "Z": return Z(n) raise ValueError("ch shall be X, Y, Z or I")
[ "def", "pauli_from_char", "(", "ch", ",", "n", "=", "0", ")", ":", "ch", "=", "ch", ".", "upper", "(", ")", "if", "ch", "==", "\"I\"", ":", "return", "I", "if", "ch", "==", "\"X\"", ":", "return", "X", "(", "n", ")", "if", "ch", "==", "\"Y\""...
Make Pauli matrix from an character. Args: ch (str): "X" or "Y" or "Z" or "I". n (int, optional): Make Pauli matrix as n-th qubits. Returns: If ch is "X" => X, "Y" => Y, "Z" => Z, "I" => I Raises: ValueError: When ch is not "X", "Y", "Z" nor "I".
[ "Make", "Pauli", "matrix", "from", "an", "character", "." ]
2ac8592c79e7acf4f385d982af82fbd68dafa5cc
https://github.com/Blueqat/Blueqat/blob/2ac8592c79e7acf4f385d982af82fbd68dafa5cc/blueqat/pauli.py#L28-L50
233,253
Blueqat/Blueqat
blueqat/pauli.py
is_commutable
def is_commutable(expr1, expr2, eps=0.00000001): """Test whether expr1 and expr2 are commutable. Args: expr1 (Expr, Term or Pauli operator): Pauli's expression. expr2 (Expr, Term or Pauli operator): Pauli's expression. eps (float, optional): Machine epsilon. If |[expr1, expr2]| < eps, consider it is commutable. Returns: bool: if expr1 and expr2 are commutable, returns True, otherwise False. """ return sum((x * x.conjugate()).real for x in commutator(expr1, expr2).coeffs()) < eps
python
def is_commutable(expr1, expr2, eps=0.00000001): return sum((x * x.conjugate()).real for x in commutator(expr1, expr2).coeffs()) < eps
[ "def", "is_commutable", "(", "expr1", ",", "expr2", ",", "eps", "=", "0.00000001", ")", ":", "return", "sum", "(", "(", "x", "*", "x", ".", "conjugate", "(", ")", ")", ".", "real", "for", "x", "in", "commutator", "(", "expr1", ",", "expr2", ")", ...
Test whether expr1 and expr2 are commutable. Args: expr1 (Expr, Term or Pauli operator): Pauli's expression. expr2 (Expr, Term or Pauli operator): Pauli's expression. eps (float, optional): Machine epsilon. If |[expr1, expr2]| < eps, consider it is commutable. Returns: bool: if expr1 and expr2 are commutable, returns True, otherwise False.
[ "Test", "whether", "expr1", "and", "expr2", "are", "commutable", "." ]
2ac8592c79e7acf4f385d982af82fbd68dafa5cc
https://github.com/Blueqat/Blueqat/blob/2ac8592c79e7acf4f385d982af82fbd68dafa5cc/blueqat/pauli.py#L103-L115
233,254
Blueqat/Blueqat
blueqat/pauli.py
Term.from_pauli
def from_pauli(pauli, coeff=1.0): """Make new Term from an Pauli operator""" if pauli.is_identity or coeff == 0: return Term((), coeff) return Term((pauli,), coeff)
python
def from_pauli(pauli, coeff=1.0): if pauli.is_identity or coeff == 0: return Term((), coeff) return Term((pauli,), coeff)
[ "def", "from_pauli", "(", "pauli", ",", "coeff", "=", "1.0", ")", ":", "if", "pauli", ".", "is_identity", "or", "coeff", "==", "0", ":", "return", "Term", "(", "(", ")", ",", "coeff", ")", "return", "Term", "(", "(", "pauli", ",", ")", ",", "coef...
Make new Term from an Pauli operator
[ "Make", "new", "Term", "from", "an", "Pauli", "operator" ]
2ac8592c79e7acf4f385d982af82fbd68dafa5cc
https://github.com/Blueqat/Blueqat/blob/2ac8592c79e7acf4f385d982af82fbd68dafa5cc/blueqat/pauli.py#L281-L285
233,255
Blueqat/Blueqat
blueqat/pauli.py
Term.simplify
def simplify(self): """Simplify the Term.""" def mul(op1, op2): if op1 == "I": return 1.0, op2 if op2 == "I": return 1.0, op1 if op1 == op2: return 1.0, "I" if op1 == "X": return (-1j, "Z") if op2 == "Y" else (1j, "Y") if op1 == "Y": return (-1j, "X") if op2 == "Z" else (1j, "Z") if op1 == "Z": return (-1j, "Y") if op2 == "X" else (1j, "X") before = defaultdict(list) for op in self.ops: if op.op == "I": continue before[op.n].append(op.op) new_coeff = self.coeff new_ops = [] for n in sorted(before.keys()): ops = before[n] assert ops k = 1.0 op = ops[0] for _op in ops[1:]: _k, op = mul(op, _op) k *= _k new_coeff *= k if new_coeff.imag == 0: # cast to float new_coeff = new_coeff.real if op != "I": new_ops.append(pauli_from_char(op, n)) return Term(tuple(new_ops), new_coeff)
python
def simplify(self): def mul(op1, op2): if op1 == "I": return 1.0, op2 if op2 == "I": return 1.0, op1 if op1 == op2: return 1.0, "I" if op1 == "X": return (-1j, "Z") if op2 == "Y" else (1j, "Y") if op1 == "Y": return (-1j, "X") if op2 == "Z" else (1j, "Z") if op1 == "Z": return (-1j, "Y") if op2 == "X" else (1j, "X") before = defaultdict(list) for op in self.ops: if op.op == "I": continue before[op.n].append(op.op) new_coeff = self.coeff new_ops = [] for n in sorted(before.keys()): ops = before[n] assert ops k = 1.0 op = ops[0] for _op in ops[1:]: _k, op = mul(op, _op) k *= _k new_coeff *= k if new_coeff.imag == 0: # cast to float new_coeff = new_coeff.real if op != "I": new_ops.append(pauli_from_char(op, n)) return Term(tuple(new_ops), new_coeff)
[ "def", "simplify", "(", "self", ")", ":", "def", "mul", "(", "op1", ",", "op2", ")", ":", "if", "op1", "==", "\"I\"", ":", "return", "1.0", ",", "op2", "if", "op2", "==", "\"I\"", ":", "return", "1.0", ",", "op1", "if", "op1", "==", "op2", ":",...
Simplify the Term.
[ "Simplify", "the", "Term", "." ]
2ac8592c79e7acf4f385d982af82fbd68dafa5cc
https://github.com/Blueqat/Blueqat/blob/2ac8592c79e7acf4f385d982af82fbd68dafa5cc/blueqat/pauli.py#L423-L460
233,256
Blueqat/Blueqat
blueqat/pauli.py
Term.append_to_circuit
def append_to_circuit(self, circuit, simplify=True): """Append Pauli gates to `Circuit`.""" if simplify: term = self.simplify() else: term = self for op in term.ops[::-1]: gate = op.op.lower() if gate != "i": getattr(circuit, gate)[op.n]
python
def append_to_circuit(self, circuit, simplify=True): if simplify: term = self.simplify() else: term = self for op in term.ops[::-1]: gate = op.op.lower() if gate != "i": getattr(circuit, gate)[op.n]
[ "def", "append_to_circuit", "(", "self", ",", "circuit", ",", "simplify", "=", "True", ")", ":", "if", "simplify", ":", "term", "=", "self", ".", "simplify", "(", ")", "else", ":", "term", "=", "self", "for", "op", "in", "term", ".", "ops", "[", ":...
Append Pauli gates to `Circuit`.
[ "Append", "Pauli", "gates", "to", "Circuit", "." ]
2ac8592c79e7acf4f385d982af82fbd68dafa5cc
https://github.com/Blueqat/Blueqat/blob/2ac8592c79e7acf4f385d982af82fbd68dafa5cc/blueqat/pauli.py#L470-L479
233,257
Blueqat/Blueqat
blueqat/pauli.py
Term.get_time_evolution
def get_time_evolution(self): """Get the function to append the time evolution of this term. Returns: function(circuit: Circuit, t: float): Add gates for time evolution to `circuit` with time `t` """ term = self.simplify() coeff = term.coeff if coeff.imag: raise ValueError("Not a real coefficient.") ops = term.ops def append_to_circuit(circuit, t): if not ops: return for op in ops: n = op.n if op.op == "X": circuit.h[n] elif op.op == "Y": circuit.rx(-half_pi)[n] for i in range(1, len(ops)): circuit.cx[ops[i-1].n, ops[i].n] circuit.rz(-2 * coeff * t)[ops[-1].n] for i in range(len(ops)-1, 0, -1): circuit.cx[ops[i-1].n, ops[i].n] for op in ops: n = op.n if op.op == "X": circuit.h[n] elif op.op == "Y": circuit.rx(half_pi)[n] return append_to_circuit
python
def get_time_evolution(self): term = self.simplify() coeff = term.coeff if coeff.imag: raise ValueError("Not a real coefficient.") ops = term.ops def append_to_circuit(circuit, t): if not ops: return for op in ops: n = op.n if op.op == "X": circuit.h[n] elif op.op == "Y": circuit.rx(-half_pi)[n] for i in range(1, len(ops)): circuit.cx[ops[i-1].n, ops[i].n] circuit.rz(-2 * coeff * t)[ops[-1].n] for i in range(len(ops)-1, 0, -1): circuit.cx[ops[i-1].n, ops[i].n] for op in ops: n = op.n if op.op == "X": circuit.h[n] elif op.op == "Y": circuit.rx(half_pi)[n] return append_to_circuit
[ "def", "get_time_evolution", "(", "self", ")", ":", "term", "=", "self", ".", "simplify", "(", ")", "coeff", "=", "term", ".", "coeff", "if", "coeff", ".", "imag", ":", "raise", "ValueError", "(", "\"Not a real coefficient.\"", ")", "ops", "=", "term", "...
Get the function to append the time evolution of this term. Returns: function(circuit: Circuit, t: float): Add gates for time evolution to `circuit` with time `t`
[ "Get", "the", "function", "to", "append", "the", "time", "evolution", "of", "this", "term", "." ]
2ac8592c79e7acf4f385d982af82fbd68dafa5cc
https://github.com/Blueqat/Blueqat/blob/2ac8592c79e7acf4f385d982af82fbd68dafa5cc/blueqat/pauli.py#L481-L513
233,258
Blueqat/Blueqat
blueqat/pauli.py
Expr.is_identity
def is_identity(self): """If `self` is I, returns True, otherwise False.""" if not self.terms: return True return len(self.terms) == 1 and not self.terms[0].ops and self.terms[0].coeff == 1.0
python
def is_identity(self): if not self.terms: return True return len(self.terms) == 1 and not self.terms[0].ops and self.terms[0].coeff == 1.0
[ "def", "is_identity", "(", "self", ")", ":", "if", "not", "self", ".", "terms", ":", "return", "True", "return", "len", "(", "self", ".", "terms", ")", "==", "1", "and", "not", "self", ".", "terms", "[", "0", "]", ".", "ops", "and", "self", ".", ...
If `self` is I, returns True, otherwise False.
[ "If", "self", "is", "I", "returns", "True", "otherwise", "False", "." ]
2ac8592c79e7acf4f385d982af82fbd68dafa5cc
https://github.com/Blueqat/Blueqat/blob/2ac8592c79e7acf4f385d982af82fbd68dafa5cc/blueqat/pauli.py#L565-L569
233,259
Blueqat/Blueqat
blueqat/pauli.py
Expr.max_n
def max_n(self): """Returns the maximum index of Pauli matrices in the Term.""" return max(term.max_n() for term in self.terms if term.ops)
python
def max_n(self): return max(term.max_n() for term in self.terms if term.ops)
[ "def", "max_n", "(", "self", ")", ":", "return", "max", "(", "term", ".", "max_n", "(", ")", "for", "term", "in", "self", ".", "terms", "if", "term", ".", "ops", ")" ]
Returns the maximum index of Pauli matrices in the Term.
[ "Returns", "the", "maximum", "index", "of", "Pauli", "matrices", "in", "the", "Term", "." ]
2ac8592c79e7acf4f385d982af82fbd68dafa5cc
https://github.com/Blueqat/Blueqat/blob/2ac8592c79e7acf4f385d982af82fbd68dafa5cc/blueqat/pauli.py#L707-L709
233,260
Blueqat/Blueqat
blueqat/pauli.py
Expr.is_all_terms_commutable
def is_all_terms_commutable(self): """Test whether all terms are commutable. This function may very slow.""" return all(is_commutable(a, b) for a, b in combinations(self.terms, 2))
python
def is_all_terms_commutable(self): return all(is_commutable(a, b) for a, b in combinations(self.terms, 2))
[ "def", "is_all_terms_commutable", "(", "self", ")", ":", "return", "all", "(", "is_commutable", "(", "a", ",", "b", ")", "for", "a", ",", "b", "in", "combinations", "(", "self", ".", "terms", ",", "2", ")", ")" ]
Test whether all terms are commutable. This function may very slow.
[ "Test", "whether", "all", "terms", "are", "commutable", ".", "This", "function", "may", "very", "slow", "." ]
2ac8592c79e7acf4f385d982af82fbd68dafa5cc
https://github.com/Blueqat/Blueqat/blob/2ac8592c79e7acf4f385d982af82fbd68dafa5cc/blueqat/pauli.py#L724-L726
233,261
Blueqat/Blueqat
blueqat/pauli.py
Expr.simplify
def simplify(self): """Simplify the Expr.""" d = defaultdict(float) for term in self.terms: term = term.simplify() d[term.ops] += term.coeff return Expr.from_terms_iter( Term.from_ops_iter(k, d[k]) for k in sorted(d, key=repr) if d[k])
python
def simplify(self): d = defaultdict(float) for term in self.terms: term = term.simplify() d[term.ops] += term.coeff return Expr.from_terms_iter( Term.from_ops_iter(k, d[k]) for k in sorted(d, key=repr) if d[k])
[ "def", "simplify", "(", "self", ")", ":", "d", "=", "defaultdict", "(", "float", ")", "for", "term", "in", "self", ".", "terms", ":", "term", "=", "term", ".", "simplify", "(", ")", "d", "[", "term", ".", "ops", "]", "+=", "term", ".", "coeff", ...
Simplify the Expr.
[ "Simplify", "the", "Expr", "." ]
2ac8592c79e7acf4f385d982af82fbd68dafa5cc
https://github.com/Blueqat/Blueqat/blob/2ac8592c79e7acf4f385d982af82fbd68dafa5cc/blueqat/pauli.py#L728-L735
233,262
dddomodossola/remi
examples/svgplot_app.py
SvgComposedPoly.add_coord
def add_coord(self, x, y): """ Adds a coord to the polyline and creates another circle """ x = x*self.x_factor y = y*self.y_factor self.plotData.add_coord(x, y) self.circles_list.append(gui.SvgCircle(x, y, self.circle_radius)) self.append(self.circles_list[-1]) if len(self.circles_list) > self.maxlen: self.remove_child(self.circles_list[0]) del self.circles_list[0]
python
def add_coord(self, x, y): x = x*self.x_factor y = y*self.y_factor self.plotData.add_coord(x, y) self.circles_list.append(gui.SvgCircle(x, y, self.circle_radius)) self.append(self.circles_list[-1]) if len(self.circles_list) > self.maxlen: self.remove_child(self.circles_list[0]) del self.circles_list[0]
[ "def", "add_coord", "(", "self", ",", "x", ",", "y", ")", ":", "x", "=", "x", "*", "self", ".", "x_factor", "y", "=", "y", "*", "self", ".", "y_factor", "self", ".", "plotData", ".", "add_coord", "(", "x", ",", "y", ")", "self", ".", "circles_l...
Adds a coord to the polyline and creates another circle
[ "Adds", "a", "coord", "to", "the", "polyline", "and", "creates", "another", "circle" ]
85206f62220662bb7ecd471042268def71ccad28
https://github.com/dddomodossola/remi/blob/85206f62220662bb7ecd471042268def71ccad28/examples/svgplot_app.py#L39-L49
233,263
dddomodossola/remi
examples/examples_from_contributors/Display_TreeTable.py
MyApp.My_TreeTable
def My_TreeTable(self, table, heads, heads2=None): ''' Define and display a table in which the values in first column form one or more trees. ''' self.Define_TreeTable(heads, heads2) self.Display_TreeTable(table)
python
def My_TreeTable(self, table, heads, heads2=None): ''' Define and display a table in which the values in first column form one or more trees. ''' self.Define_TreeTable(heads, heads2) self.Display_TreeTable(table)
[ "def", "My_TreeTable", "(", "self", ",", "table", ",", "heads", ",", "heads2", "=", "None", ")", ":", "self", ".", "Define_TreeTable", "(", "heads", ",", "heads2", ")", "self", ".", "Display_TreeTable", "(", "table", ")" ]
Define and display a table in which the values in first column form one or more trees.
[ "Define", "and", "display", "a", "table", "in", "which", "the", "values", "in", "first", "column", "form", "one", "or", "more", "trees", "." ]
85206f62220662bb7ecd471042268def71ccad28
https://github.com/dddomodossola/remi/blob/85206f62220662bb7ecd471042268def71ccad28/examples/examples_from_contributors/Display_TreeTable.py#L26-L31
233,264
dddomodossola/remi
examples/examples_from_contributors/Display_TreeTable.py
MyApp.Define_TreeTable
def Define_TreeTable(self, heads, heads2=None): ''' Define a TreeTable with a heading row and optionally a second heading row. ''' display_heads = [] display_heads.append(tuple(heads[2:])) self.tree_table = TreeTable() self.tree_table.append_from_list(display_heads, fill_title=True) if heads2 is not None: heads2_color = heads2[1] row_widget = gui.TableRow() for index, field in enumerate(heads2[2:]): row_item = gui.TableItem(text=field, style={'background-color': heads2_color}) row_widget.append(row_item, field) self.tree_table.append(row_widget, heads2[0]) self.wid.append(self.tree_table)
python
def Define_TreeTable(self, heads, heads2=None): ''' Define a TreeTable with a heading row and optionally a second heading row. ''' display_heads = [] display_heads.append(tuple(heads[2:])) self.tree_table = TreeTable() self.tree_table.append_from_list(display_heads, fill_title=True) if heads2 is not None: heads2_color = heads2[1] row_widget = gui.TableRow() for index, field in enumerate(heads2[2:]): row_item = gui.TableItem(text=field, style={'background-color': heads2_color}) row_widget.append(row_item, field) self.tree_table.append(row_widget, heads2[0]) self.wid.append(self.tree_table)
[ "def", "Define_TreeTable", "(", "self", ",", "heads", ",", "heads2", "=", "None", ")", ":", "display_heads", "=", "[", "]", "display_heads", ".", "append", "(", "tuple", "(", "heads", "[", "2", ":", "]", ")", ")", "self", ".", "tree_table", "=", "Tre...
Define a TreeTable with a heading row and optionally a second heading row.
[ "Define", "a", "TreeTable", "with", "a", "heading", "row", "and", "optionally", "a", "second", "heading", "row", "." ]
85206f62220662bb7ecd471042268def71ccad28
https://github.com/dddomodossola/remi/blob/85206f62220662bb7ecd471042268def71ccad28/examples/examples_from_contributors/Display_TreeTable.py#L33-L49
233,265
dddomodossola/remi
examples/gauge_app.py
InputGauge.confirm_value
def confirm_value(self, widget, x, y): """event called clicking on the gauge and so changing its value. propagates the new value """ self.gauge.onmousedown(self.gauge, x, y) params = (self.gauge.value) return params
python
def confirm_value(self, widget, x, y): self.gauge.onmousedown(self.gauge, x, y) params = (self.gauge.value) return params
[ "def", "confirm_value", "(", "self", ",", "widget", ",", "x", ",", "y", ")", ":", "self", ".", "gauge", ".", "onmousedown", "(", "self", ".", "gauge", ",", "x", ",", "y", ")", "params", "=", "(", "self", ".", "gauge", ".", "value", ")", "return",...
event called clicking on the gauge and so changing its value. propagates the new value
[ "event", "called", "clicking", "on", "the", "gauge", "and", "so", "changing", "its", "value", ".", "propagates", "the", "new", "value" ]
85206f62220662bb7ecd471042268def71ccad28
https://github.com/dddomodossola/remi/blob/85206f62220662bb7ecd471042268def71ccad28/examples/gauge_app.py#L40-L46
233,266
dddomodossola/remi
editor/editor.py
Editor.configure_widget_for_editing
def configure_widget_for_editing(self, widget): """ A widget have to be added to the editor, it is configured here in order to be conformant to the editor """ if not 'editor_varname' in widget.attributes: return widget.onclick.do(self.on_widget_selection) #setup of the on_dropped function of the widget in order to manage the dragNdrop widget.__class__.on_dropped = on_dropped #drag properties #widget.style['resize'] = 'both' widget.style['overflow'] = 'auto' widget.attributes['draggable'] = 'true' widget.attributes['tabindex']=str(self.tabindex) #if not 'position' in widget.style.keys(): # widget.style['position'] = 'absolute' #if not 'left' in widget.style.keys(): # widget.style['left'] = '1px' #if not 'top' in widget.style.keys(): # widget.style['top'] = '1px' self.tabindex += 1
python
def configure_widget_for_editing(self, widget): if not 'editor_varname' in widget.attributes: return widget.onclick.do(self.on_widget_selection) #setup of the on_dropped function of the widget in order to manage the dragNdrop widget.__class__.on_dropped = on_dropped #drag properties #widget.style['resize'] = 'both' widget.style['overflow'] = 'auto' widget.attributes['draggable'] = 'true' widget.attributes['tabindex']=str(self.tabindex) #if not 'position' in widget.style.keys(): # widget.style['position'] = 'absolute' #if not 'left' in widget.style.keys(): # widget.style['left'] = '1px' #if not 'top' in widget.style.keys(): # widget.style['top'] = '1px' self.tabindex += 1
[ "def", "configure_widget_for_editing", "(", "self", ",", "widget", ")", ":", "if", "not", "'editor_varname'", "in", "widget", ".", "attributes", ":", "return", "widget", ".", "onclick", ".", "do", "(", "self", ".", "on_widget_selection", ")", "#setup of the on_d...
A widget have to be added to the editor, it is configured here in order to be conformant to the editor
[ "A", "widget", "have", "to", "be", "added", "to", "the", "editor", "it", "is", "configured", "here", "in", "order", "to", "be", "conformant", "to", "the", "editor" ]
85206f62220662bb7ecd471042268def71ccad28
https://github.com/dddomodossola/remi/blob/85206f62220662bb7ecd471042268def71ccad28/editor/editor.py#L656-L680
233,267
dddomodossola/remi
examples/minefield_app.py
Cell.on_right_click
def on_right_click(self, widget): """ Here with right click the change of cell is changed """ if self.opened: return self.state = (self.state + 1) % 3 self.set_icon() self.game.check_if_win()
python
def on_right_click(self, widget): if self.opened: return self.state = (self.state + 1) % 3 self.set_icon() self.game.check_if_win()
[ "def", "on_right_click", "(", "self", ",", "widget", ")", ":", "if", "self", ".", "opened", ":", "return", "self", ".", "state", "=", "(", "self", ".", "state", "+", "1", ")", "%", "3", "self", ".", "set_icon", "(", ")", "self", ".", "game", ".",...
Here with right click the change of cell is changed
[ "Here", "with", "right", "click", "the", "change", "of", "cell", "is", "changed" ]
85206f62220662bb7ecd471042268def71ccad28
https://github.com/dddomodossola/remi/blob/85206f62220662bb7ecd471042268def71ccad28/examples/minefield_app.py#L49-L55
233,268
dddomodossola/remi
examples/minefield_app.py
MyApp.build_mine_matrix
def build_mine_matrix(self, w, h, minenum): """random fill cells with mines and increments nearest mines num in adiacent cells""" self.minecount = 0 matrix = [[Cell(30, 30, x, y, self) for x in range(w)] for y in range(h)] for i in range(0, minenum): x = random.randint(0, w - 1) y = random.randint(0, h - 1) if matrix[y][x].has_mine: continue self.minecount += 1 matrix[y][x].has_mine = True for coord in [[-1, -1], [-1, 0], [-1, 1], [0, -1], [0, 1], [1, -1], [1, 0], [1, 1]]: _x, _y = coord if not self.coord_in_map(x + _x, y + _y, w, h): continue matrix[y + _y][x + _x].add_nearest_mine() return matrix
python
def build_mine_matrix(self, w, h, minenum): self.minecount = 0 matrix = [[Cell(30, 30, x, y, self) for x in range(w)] for y in range(h)] for i in range(0, minenum): x = random.randint(0, w - 1) y = random.randint(0, h - 1) if matrix[y][x].has_mine: continue self.minecount += 1 matrix[y][x].has_mine = True for coord in [[-1, -1], [-1, 0], [-1, 1], [0, -1], [0, 1], [1, -1], [1, 0], [1, 1]]: _x, _y = coord if not self.coord_in_map(x + _x, y + _y, w, h): continue matrix[y + _y][x + _x].add_nearest_mine() return matrix
[ "def", "build_mine_matrix", "(", "self", ",", "w", ",", "h", ",", "minenum", ")", ":", "self", ".", "minecount", "=", "0", "matrix", "=", "[", "[", "Cell", "(", "30", ",", "30", ",", "x", ",", "y", ",", "self", ")", "for", "x", "in", "range", ...
random fill cells with mines and increments nearest mines num in adiacent cells
[ "random", "fill", "cells", "with", "mines", "and", "increments", "nearest", "mines", "num", "in", "adiacent", "cells" ]
85206f62220662bb7ecd471042268def71ccad28
https://github.com/dddomodossola/remi/blob/85206f62220662bb7ecd471042268def71ccad28/examples/minefield_app.py#L184-L201
233,269
dddomodossola/remi
examples/minefield_app.py
MyApp.check_if_win
def check_if_win(self): """Here are counted the flags. Is checked if the user win.""" self.flagcount = 0 win = True for x in range(0, len(self.mine_matrix[0])): for y in range(0, len(self.mine_matrix)): if self.mine_matrix[y][x].state == 1: self.flagcount += 1 if not self.mine_matrix[y][x].has_mine: win = False elif self.mine_matrix[y][x].has_mine: win = False self.lblMineCount.set_text("%s" % self.minecount) self.lblFlagCount.set_text("%s" % self.flagcount) if win: self.dialog = gui.GenericDialog(title='You Win!', message='Game done in %s seconds' % self.time_count) self.dialog.confirm_dialog.do(self.new_game) self.dialog.cancel_dialog.do(self.new_game) self.dialog.show(self)
python
def check_if_win(self): self.flagcount = 0 win = True for x in range(0, len(self.mine_matrix[0])): for y in range(0, len(self.mine_matrix)): if self.mine_matrix[y][x].state == 1: self.flagcount += 1 if not self.mine_matrix[y][x].has_mine: win = False elif self.mine_matrix[y][x].has_mine: win = False self.lblMineCount.set_text("%s" % self.minecount) self.lblFlagCount.set_text("%s" % self.flagcount) if win: self.dialog = gui.GenericDialog(title='You Win!', message='Game done in %s seconds' % self.time_count) self.dialog.confirm_dialog.do(self.new_game) self.dialog.cancel_dialog.do(self.new_game) self.dialog.show(self)
[ "def", "check_if_win", "(", "self", ")", ":", "self", ".", "flagcount", "=", "0", "win", "=", "True", "for", "x", "in", "range", "(", "0", ",", "len", "(", "self", ".", "mine_matrix", "[", "0", "]", ")", ")", ":", "for", "y", "in", "range", "("...
Here are counted the flags. Is checked if the user win.
[ "Here", "are", "counted", "the", "flags", ".", "Is", "checked", "if", "the", "user", "win", "." ]
85206f62220662bb7ecd471042268def71ccad28
https://github.com/dddomodossola/remi/blob/85206f62220662bb7ecd471042268def71ccad28/examples/minefield_app.py#L209-L227
233,270
dddomodossola/remi
examples/session_app.py
LoginManager.renew_session
def renew_session(self): """Have to be called on user actions to check and renew session """ if ((not 'user_uid' in self.cookieInterface.cookies) or self.cookieInterface.cookies['user_uid']!=self.session_uid) and (not self.expired): self.on_session_expired() if self.expired: self.session_uid = str(random.randint(1,999999999)) self.cookieInterface.set_cookie('user_uid', self.session_uid, str(self.session_timeout_seconds)) #here we renew the internal timeout timer if self.timeout_timer: self.timeout_timer.cancel() self.timeout_timer = threading.Timer(self.session_timeout_seconds, self.on_session_expired) self.expired = False self.timeout_timer.start()
python
def renew_session(self): if ((not 'user_uid' in self.cookieInterface.cookies) or self.cookieInterface.cookies['user_uid']!=self.session_uid) and (not self.expired): self.on_session_expired() if self.expired: self.session_uid = str(random.randint(1,999999999)) self.cookieInterface.set_cookie('user_uid', self.session_uid, str(self.session_timeout_seconds)) #here we renew the internal timeout timer if self.timeout_timer: self.timeout_timer.cancel() self.timeout_timer = threading.Timer(self.session_timeout_seconds, self.on_session_expired) self.expired = False self.timeout_timer.start()
[ "def", "renew_session", "(", "self", ")", ":", "if", "(", "(", "not", "'user_uid'", "in", "self", ".", "cookieInterface", ".", "cookies", ")", "or", "self", ".", "cookieInterface", ".", "cookies", "[", "'user_uid'", "]", "!=", "self", ".", "session_uid", ...
Have to be called on user actions to check and renew session
[ "Have", "to", "be", "called", "on", "user", "actions", "to", "check", "and", "renew", "session" ]
85206f62220662bb7ecd471042268def71ccad28
https://github.com/dddomodossola/remi/blob/85206f62220662bb7ecd471042268def71ccad28/examples/session_app.py#L146-L162
233,271
dddomodossola/remi
remi/gui.py
decorate_event_js
def decorate_event_js(js_code): """setup a method as an event, adding also javascript code to generate Args: js_code (str): javascript code to generate the event client-side. js_code is added to the widget html as widget.attributes['onclick'] = js_code%{'emitter_identifier':widget.identifier, 'event_name':'onclick'} """ def add_annotation(method): setattr(method, "__is_event", True ) setattr(method, "_js_code", js_code ) return method return add_annotation
python
def decorate_event_js(js_code): def add_annotation(method): setattr(method, "__is_event", True ) setattr(method, "_js_code", js_code ) return method return add_annotation
[ "def", "decorate_event_js", "(", "js_code", ")", ":", "def", "add_annotation", "(", "method", ")", ":", "setattr", "(", "method", ",", "\"__is_event\"", ",", "True", ")", "setattr", "(", "method", ",", "\"_js_code\"", ",", "js_code", ")", "return", "method",...
setup a method as an event, adding also javascript code to generate Args: js_code (str): javascript code to generate the event client-side. js_code is added to the widget html as widget.attributes['onclick'] = js_code%{'emitter_identifier':widget.identifier, 'event_name':'onclick'}
[ "setup", "a", "method", "as", "an", "event", "adding", "also", "javascript", "code", "to", "generate" ]
85206f62220662bb7ecd471042268def71ccad28
https://github.com/dddomodossola/remi/blob/85206f62220662bb7ecd471042268def71ccad28/remi/gui.py#L128-L140
233,272
dddomodossola/remi
remi/gui.py
decorate_set_on_listener
def decorate_set_on_listener(prototype): """ Private decorator for use in the editor. Allows the Editor to create listener methods. Args: params (str): The list of parameters for the listener method (es. "(self, new_value)") """ # noinspection PyDictCreation,PyProtectedMember def add_annotation(method): method._event_info = {} method._event_info['name'] = method.__name__ method._event_info['prototype'] = prototype return method return add_annotation
python
def decorate_set_on_listener(prototype): # noinspection PyDictCreation,PyProtectedMember def add_annotation(method): method._event_info = {} method._event_info['name'] = method.__name__ method._event_info['prototype'] = prototype return method return add_annotation
[ "def", "decorate_set_on_listener", "(", "prototype", ")", ":", "# noinspection PyDictCreation,PyProtectedMember", "def", "add_annotation", "(", "method", ")", ":", "method", ".", "_event_info", "=", "{", "}", "method", ".", "_event_info", "[", "'name'", "]", "=", ...
Private decorator for use in the editor. Allows the Editor to create listener methods. Args: params (str): The list of parameters for the listener method (es. "(self, new_value)")
[ "Private", "decorator", "for", "use", "in", "the", "editor", ".", "Allows", "the", "Editor", "to", "create", "listener", "methods", "." ]
85206f62220662bb7ecd471042268def71ccad28
https://github.com/dddomodossola/remi/blob/85206f62220662bb7ecd471042268def71ccad28/remi/gui.py#L143-L158
233,273
dddomodossola/remi
remi/gui.py
ClassEventConnector.do
def do(self, callback, *userdata): """ The callback and userdata gets stored, and if there is some javascript to add the js code is appended as attribute for the event source """ if hasattr(self.event_method_bound, '_js_code'): self.event_source_instance.attributes[self.event_name] = self.event_method_bound._js_code%{ 'emitter_identifier':self.event_source_instance.identifier, 'event_name':self.event_name} self.callback = callback self.userdata = userdata
python
def do(self, callback, *userdata): if hasattr(self.event_method_bound, '_js_code'): self.event_source_instance.attributes[self.event_name] = self.event_method_bound._js_code%{ 'emitter_identifier':self.event_source_instance.identifier, 'event_name':self.event_name} self.callback = callback self.userdata = userdata
[ "def", "do", "(", "self", ",", "callback", ",", "*", "userdata", ")", ":", "if", "hasattr", "(", "self", ".", "event_method_bound", ",", "'_js_code'", ")", ":", "self", ".", "event_source_instance", ".", "attributes", "[", "self", ".", "event_name", "]", ...
The callback and userdata gets stored, and if there is some javascript to add the js code is appended as attribute for the event source
[ "The", "callback", "and", "userdata", "gets", "stored", "and", "if", "there", "is", "some", "javascript", "to", "add", "the", "js", "code", "is", "appended", "as", "attribute", "for", "the", "event", "source" ]
85206f62220662bb7ecd471042268def71ccad28
https://github.com/dddomodossola/remi/blob/85206f62220662bb7ecd471042268def71ccad28/remi/gui.py#L98-L106
233,274
dddomodossola/remi
remi/gui.py
Tag.add_child
def add_child(self, key, value): """Adds a child to the Tag To retrieve the child call get_child or access to the Tag.children[key] dictionary. Args: key (str): Unique child's identifier, or iterable of keys value (Tag, str): can be a Tag, an iterable of Tag or a str. In case of iterable of Tag is a dict, each item's key is set as 'key' param """ if type(value) in (list, tuple, dict): if type(value)==dict: for k in value.keys(): self.add_child(k, value[k]) return i = 0 for child in value: self.add_child(key[i], child) i = i + 1 return if hasattr(value, 'attributes'): value.attributes['data-parent-widget'] = self.identifier value._parent = self if key in self.children: self._render_children_list.remove(key) self._render_children_list.append(key) self.children[key] = value
python
def add_child(self, key, value): if type(value) in (list, tuple, dict): if type(value)==dict: for k in value.keys(): self.add_child(k, value[k]) return i = 0 for child in value: self.add_child(key[i], child) i = i + 1 return if hasattr(value, 'attributes'): value.attributes['data-parent-widget'] = self.identifier value._parent = self if key in self.children: self._render_children_list.remove(key) self._render_children_list.append(key) self.children[key] = value
[ "def", "add_child", "(", "self", ",", "key", ",", "value", ")", ":", "if", "type", "(", "value", ")", "in", "(", "list", ",", "tuple", ",", "dict", ")", ":", "if", "type", "(", "value", ")", "==", "dict", ":", "for", "k", "in", "value", ".", ...
Adds a child to the Tag To retrieve the child call get_child or access to the Tag.children[key] dictionary. Args: key (str): Unique child's identifier, or iterable of keys value (Tag, str): can be a Tag, an iterable of Tag or a str. In case of iterable of Tag is a dict, each item's key is set as 'key' param
[ "Adds", "a", "child", "to", "the", "Tag" ]
85206f62220662bb7ecd471042268def71ccad28
https://github.com/dddomodossola/remi/blob/85206f62220662bb7ecd471042268def71ccad28/remi/gui.py#L380-L409
233,275
dddomodossola/remi
remi/gui.py
Tag.empty
def empty(self): """remove all children from the widget""" for k in list(self.children.keys()): self.remove_child(self.children[k])
python
def empty(self): for k in list(self.children.keys()): self.remove_child(self.children[k])
[ "def", "empty", "(", "self", ")", ":", "for", "k", "in", "list", "(", "self", ".", "children", ".", "keys", "(", ")", ")", ":", "self", ".", "remove_child", "(", "self", ".", "children", "[", "k", "]", ")" ]
remove all children from the widget
[ "remove", "all", "children", "from", "the", "widget" ]
85206f62220662bb7ecd471042268def71ccad28
https://github.com/dddomodossola/remi/blob/85206f62220662bb7ecd471042268def71ccad28/remi/gui.py#L425-L428
233,276
dddomodossola/remi
remi/gui.py
Tag.remove_child
def remove_child(self, child): """Removes a child instance from the Tag's children. Args: child (Tag): The child to be removed. """ if child in self.children.values() and hasattr(child, 'identifier'): for k in self.children.keys(): if hasattr(self.children[k], 'identifier'): if self.children[k].identifier == child.identifier: if k in self._render_children_list: self._render_children_list.remove(k) self.children.pop(k) # when the child is removed we stop the iteration # this implies that a child replication should not be allowed break
python
def remove_child(self, child): if child in self.children.values() and hasattr(child, 'identifier'): for k in self.children.keys(): if hasattr(self.children[k], 'identifier'): if self.children[k].identifier == child.identifier: if k in self._render_children_list: self._render_children_list.remove(k) self.children.pop(k) # when the child is removed we stop the iteration # this implies that a child replication should not be allowed break
[ "def", "remove_child", "(", "self", ",", "child", ")", ":", "if", "child", "in", "self", ".", "children", ".", "values", "(", ")", "and", "hasattr", "(", "child", ",", "'identifier'", ")", ":", "for", "k", "in", "self", ".", "children", ".", "keys", ...
Removes a child instance from the Tag's children. Args: child (Tag): The child to be removed.
[ "Removes", "a", "child", "instance", "from", "the", "Tag", "s", "children", "." ]
85206f62220662bb7ecd471042268def71ccad28
https://github.com/dddomodossola/remi/blob/85206f62220662bb7ecd471042268def71ccad28/remi/gui.py#L430-L445
233,277
dddomodossola/remi
remi/gui.py
Widget.set_size
def set_size(self, width, height): """Set the widget size. Args: width (int or str): An optional width for the widget (es. width=10 or width='10px' or width='10%'). height (int or str): An optional height for the widget (es. height=10 or height='10px' or height='10%'). """ if width is not None: try: width = to_pix(int(width)) except ValueError: # now we know w has 'px or % in it' pass self.style['width'] = width if height is not None: try: height = to_pix(int(height)) except ValueError: # now we know w has 'px or % in it' pass self.style['height'] = height
python
def set_size(self, width, height): if width is not None: try: width = to_pix(int(width)) except ValueError: # now we know w has 'px or % in it' pass self.style['width'] = width if height is not None: try: height = to_pix(int(height)) except ValueError: # now we know w has 'px or % in it' pass self.style['height'] = height
[ "def", "set_size", "(", "self", ",", "width", ",", "height", ")", ":", "if", "width", "is", "not", "None", ":", "try", ":", "width", "=", "to_pix", "(", "int", "(", "width", ")", ")", "except", "ValueError", ":", "# now we know w has 'px or % in it'", "p...
Set the widget size. Args: width (int or str): An optional width for the widget (es. width=10 or width='10px' or width='10%'). height (int or str): An optional height for the widget (es. height=10 or height='10px' or height='10%').
[ "Set", "the", "widget", "size", "." ]
85206f62220662bb7ecd471042268def71ccad28
https://github.com/dddomodossola/remi/blob/85206f62220662bb7ecd471042268def71ccad28/remi/gui.py#L548-L569
233,278
dddomodossola/remi
remi/gui.py
Widget.repr
def repr(self, changed_widgets=None): """Represents the widget as HTML format, packs all the attributes, children and so on. Args: client (App): Client instance. changed_widgets (dict): A dictionary containing a collection of widgets that have to be updated. The Widget that have to be updated is the key, and the value is its textual repr. """ if changed_widgets is None: changed_widgets={} return super(Widget, self).repr(changed_widgets)
python
def repr(self, changed_widgets=None): if changed_widgets is None: changed_widgets={} return super(Widget, self).repr(changed_widgets)
[ "def", "repr", "(", "self", ",", "changed_widgets", "=", "None", ")", ":", "if", "changed_widgets", "is", "None", ":", "changed_widgets", "=", "{", "}", "return", "super", "(", "Widget", ",", "self", ")", ".", "repr", "(", "changed_widgets", ")" ]
Represents the widget as HTML format, packs all the attributes, children and so on. Args: client (App): Client instance. changed_widgets (dict): A dictionary containing a collection of widgets that have to be updated. The Widget that have to be updated is the key, and the value is its textual repr.
[ "Represents", "the", "widget", "as", "HTML", "format", "packs", "all", "the", "attributes", "children", "and", "so", "on", "." ]
85206f62220662bb7ecd471042268def71ccad28
https://github.com/dddomodossola/remi/blob/85206f62220662bb7ecd471042268def71ccad28/remi/gui.py#L583-L593
233,279
dddomodossola/remi
remi/gui.py
HEAD.set_icon_file
def set_icon_file(self, filename, rel="icon"): """ Allows to define an icon for the App Args: filename (str): the resource file name (ie. "/res:myicon.png") rel (str): leave it unchanged (standard "icon") """ mimetype, encoding = mimetypes.guess_type(filename) self.add_child("favicon", '<link rel="%s" href="%s" type="%s" />'%(rel, filename, mimetype))
python
def set_icon_file(self, filename, rel="icon"): mimetype, encoding = mimetypes.guess_type(filename) self.add_child("favicon", '<link rel="%s" href="%s" type="%s" />'%(rel, filename, mimetype))
[ "def", "set_icon_file", "(", "self", ",", "filename", ",", "rel", "=", "\"icon\"", ")", ":", "mimetype", ",", "encoding", "=", "mimetypes", ".", "guess_type", "(", "filename", ")", "self", ".", "add_child", "(", "\"favicon\"", ",", "'<link rel=\"%s\" href=\"%s...
Allows to define an icon for the App Args: filename (str): the resource file name (ie. "/res:myicon.png") rel (str): leave it unchanged (standard "icon")
[ "Allows", "to", "define", "an", "icon", "for", "the", "App" ]
85206f62220662bb7ecd471042268def71ccad28
https://github.com/dddomodossola/remi/blob/85206f62220662bb7ecd471042268def71ccad28/remi/gui.py#L981-L989
233,280
dddomodossola/remi
remi/gui.py
BODY.onerror
def onerror(self, message, source, lineno, colno): """Called when an error occurs.""" return (message, source, lineno, colno)
python
def onerror(self, message, source, lineno, colno): return (message, source, lineno, colno)
[ "def", "onerror", "(", "self", ",", "message", ",", "source", ",", "lineno", ",", "colno", ")", ":", "return", "(", "message", ",", "source", ",", "lineno", ",", "colno", ")" ]
Called when an error occurs.
[ "Called", "when", "an", "error", "occurs", "." ]
85206f62220662bb7ecd471042268def71ccad28
https://github.com/dddomodossola/remi/blob/85206f62220662bb7ecd471042268def71ccad28/remi/gui.py#L1306-L1308
233,281
dddomodossola/remi
remi/gui.py
GridBox.set_column_sizes
def set_column_sizes(self, values): """Sets the size value for each column Args: values (iterable of int or str): values are treated as percentage. """ self.style['grid-template-columns'] = ' '.join(map(lambda value: (str(value) if str(value).endswith('%') else str(value) + '%') , values))
python
def set_column_sizes(self, values): self.style['grid-template-columns'] = ' '.join(map(lambda value: (str(value) if str(value).endswith('%') else str(value) + '%') , values))
[ "def", "set_column_sizes", "(", "self", ",", "values", ")", ":", "self", ".", "style", "[", "'grid-template-columns'", "]", "=", "' '", ".", "join", "(", "map", "(", "lambda", "value", ":", "(", "str", "(", "value", ")", "if", "str", "(", "value", ")...
Sets the size value for each column Args: values (iterable of int or str): values are treated as percentage.
[ "Sets", "the", "size", "value", "for", "each", "column" ]
85206f62220662bb7ecd471042268def71ccad28
https://github.com/dddomodossola/remi/blob/85206f62220662bb7ecd471042268def71ccad28/remi/gui.py#L1406-L1412
233,282
dddomodossola/remi
remi/gui.py
GridBox.set_column_gap
def set_column_gap(self, value): """Sets the gap value between columns Args: value (int or str): gap value (i.e. 10 or "10px") """ value = str(value) + 'px' value = value.replace('pxpx', 'px') self.style['grid-column-gap'] = value
python
def set_column_gap(self, value): value = str(value) + 'px' value = value.replace('pxpx', 'px') self.style['grid-column-gap'] = value
[ "def", "set_column_gap", "(", "self", ",", "value", ")", ":", "value", "=", "str", "(", "value", ")", "+", "'px'", "value", "=", "value", ".", "replace", "(", "'pxpx'", ",", "'px'", ")", "self", ".", "style", "[", "'grid-column-gap'", "]", "=", "valu...
Sets the gap value between columns Args: value (int or str): gap value (i.e. 10 or "10px")
[ "Sets", "the", "gap", "value", "between", "columns" ]
85206f62220662bb7ecd471042268def71ccad28
https://github.com/dddomodossola/remi/blob/85206f62220662bb7ecd471042268def71ccad28/remi/gui.py#L1422-L1430
233,283
dddomodossola/remi
remi/gui.py
GridBox.set_row_gap
def set_row_gap(self, value): """Sets the gap value between rows Args: value (int or str): gap value (i.e. 10 or "10px") """ value = str(value) + 'px' value = value.replace('pxpx', 'px') self.style['grid-row-gap'] = value
python
def set_row_gap(self, value): value = str(value) + 'px' value = value.replace('pxpx', 'px') self.style['grid-row-gap'] = value
[ "def", "set_row_gap", "(", "self", ",", "value", ")", ":", "value", "=", "str", "(", "value", ")", "+", "'px'", "value", "=", "value", ".", "replace", "(", "'pxpx'", ",", "'px'", ")", "self", ".", "style", "[", "'grid-row-gap'", "]", "=", "value" ]
Sets the gap value between rows Args: value (int or str): gap value (i.e. 10 or "10px")
[ "Sets", "the", "gap", "value", "between", "rows" ]
85206f62220662bb7ecd471042268def71ccad28
https://github.com/dddomodossola/remi/blob/85206f62220662bb7ecd471042268def71ccad28/remi/gui.py#L1432-L1440
233,284
dddomodossola/remi
remi/gui.py
TabBox.select_by_widget
def select_by_widget(self, widget): """ shows a tab identified by the contained widget """ for a, li, holder in self._tabs.values(): if holder.children['content'] == widget: self._on_tab_pressed(a, li, holder) return
python
def select_by_widget(self, widget): for a, li, holder in self._tabs.values(): if holder.children['content'] == widget: self._on_tab_pressed(a, li, holder) return
[ "def", "select_by_widget", "(", "self", ",", "widget", ")", ":", "for", "a", ",", "li", ",", "holder", "in", "self", ".", "_tabs", ".", "values", "(", ")", ":", "if", "holder", ".", "children", "[", "'content'", "]", "==", "widget", ":", "self", "....
shows a tab identified by the contained widget
[ "shows", "a", "tab", "identified", "by", "the", "contained", "widget" ]
85206f62220662bb7ecd471042268def71ccad28
https://github.com/dddomodossola/remi/blob/85206f62220662bb7ecd471042268def71ccad28/remi/gui.py#L1573-L1578
233,285
dddomodossola/remi
remi/gui.py
TabBox.select_by_name
def select_by_name(self, name): """ shows a tab identified by the name """ for a, li, holder in self._tabs.values(): if a.children['text'] == name: self._on_tab_pressed(a, li, holder) return
python
def select_by_name(self, name): for a, li, holder in self._tabs.values(): if a.children['text'] == name: self._on_tab_pressed(a, li, holder) return
[ "def", "select_by_name", "(", "self", ",", "name", ")", ":", "for", "a", ",", "li", ",", "holder", "in", "self", ".", "_tabs", ".", "values", "(", ")", ":", "if", "a", ".", "children", "[", "'text'", "]", "==", "name", ":", "self", ".", "_on_tab_...
shows a tab identified by the name
[ "shows", "a", "tab", "identified", "by", "the", "name" ]
85206f62220662bb7ecd471042268def71ccad28
https://github.com/dddomodossola/remi/blob/85206f62220662bb7ecd471042268def71ccad28/remi/gui.py#L1580-L1585
233,286
dddomodossola/remi
remi/gui.py
TextInput.set_value
def set_value(self, text): """Sets the text content. Args: text (str): The string content that have to be appended as standard child identified by the key 'text' """ if self.single_line: text = text.replace('\n', '') self.set_text(text)
python
def set_value(self, text): if self.single_line: text = text.replace('\n', '') self.set_text(text)
[ "def", "set_value", "(", "self", ",", "text", ")", ":", "if", "self", ".", "single_line", ":", "text", "=", "text", ".", "replace", "(", "'\\n'", ",", "''", ")", "self", ".", "set_text", "(", "text", ")" ]
Sets the text content. Args: text (str): The string content that have to be appended as standard child identified by the key 'text'
[ "Sets", "the", "text", "content", "." ]
85206f62220662bb7ecd471042268def71ccad28
https://github.com/dddomodossola/remi/blob/85206f62220662bb7ecd471042268def71ccad28/remi/gui.py#L1711-L1719
233,287
dddomodossola/remi
remi/gui.py
TextInput.onchange
def onchange(self, new_value): """Called when the user changes the TextInput content. With single_line=True it fires in case of focus lost and Enter key pressed. With single_line=False it fires at each key released. Args: new_value (str): the new string content of the TextInput. """ self.disable_refresh() self.set_value(new_value) self.enable_refresh() return (new_value, )
python
def onchange(self, new_value): self.disable_refresh() self.set_value(new_value) self.enable_refresh() return (new_value, )
[ "def", "onchange", "(", "self", ",", "new_value", ")", ":", "self", ".", "disable_refresh", "(", ")", "self", ".", "set_value", "(", "new_value", ")", "self", ".", "enable_refresh", "(", ")", "return", "(", "new_value", ",", ")" ]
Called when the user changes the TextInput content. With single_line=True it fires in case of focus lost and Enter key pressed. With single_line=False it fires at each key released. Args: new_value (str): the new string content of the TextInput.
[ "Called", "when", "the", "user", "changes", "the", "TextInput", "content", ".", "With", "single_line", "=", "True", "it", "fires", "in", "case", "of", "focus", "lost", "and", "Enter", "key", "pressed", ".", "With", "single_line", "=", "False", "it", "fires...
85206f62220662bb7ecd471042268def71ccad28
https://github.com/dddomodossola/remi/blob/85206f62220662bb7ecd471042268def71ccad28/remi/gui.py#L1730-L1741
233,288
dddomodossola/remi
remi/gui.py
GenericDialog.add_field_with_label
def add_field_with_label(self, key, label_description, field): """ Adds a field to the dialog together with a descriptive label and a unique identifier. Note: You can access to the fields content calling the function GenericDialog.get_field(key). Args: key (str): The unique identifier for the field. label_description (str): The string content of the description label. field (Widget): The instance of the field Widget. It can be for example a TextInput or maybe a custom widget. """ self.inputs[key] = field label = Label(label_description) label.style['margin'] = '0px 5px' label.style['min-width'] = '30%' container = HBox() container.style.update({'justify-content':'space-between', 'overflow':'auto', 'padding':'3px'}) container.append(label, key='lbl' + key) container.append(self.inputs[key], key=key) self.container.append(container, key=key)
python
def add_field_with_label(self, key, label_description, field): self.inputs[key] = field label = Label(label_description) label.style['margin'] = '0px 5px' label.style['min-width'] = '30%' container = HBox() container.style.update({'justify-content':'space-between', 'overflow':'auto', 'padding':'3px'}) container.append(label, key='lbl' + key) container.append(self.inputs[key], key=key) self.container.append(container, key=key)
[ "def", "add_field_with_label", "(", "self", ",", "key", ",", "label_description", ",", "field", ")", ":", "self", ".", "inputs", "[", "key", "]", "=", "field", "label", "=", "Label", "(", "label_description", ")", "label", ".", "style", "[", "'margin'", ...
Adds a field to the dialog together with a descriptive label and a unique identifier. Note: You can access to the fields content calling the function GenericDialog.get_field(key). Args: key (str): The unique identifier for the field. label_description (str): The string content of the description label. field (Widget): The instance of the field Widget. It can be for example a TextInput or maybe a custom widget.
[ "Adds", "a", "field", "to", "the", "dialog", "together", "with", "a", "descriptive", "label", "and", "a", "unique", "identifier", "." ]
85206f62220662bb7ecd471042268def71ccad28
https://github.com/dddomodossola/remi/blob/85206f62220662bb7ecd471042268def71ccad28/remi/gui.py#L1894-L1914
233,289
dddomodossola/remi
remi/gui.py
GenericDialog.add_field
def add_field(self, key, field): """ Adds a field to the dialog with a unique identifier. Note: You can access to the fields content calling the function GenericDialog.get_field(key). Args: key (str): The unique identifier for the field. field (Widget): The widget to be added to the dialog, TextInput or any Widget for example. """ self.inputs[key] = field container = HBox() container.style.update({'justify-content':'space-between', 'overflow':'auto', 'padding':'3px'}) container.append(self.inputs[key], key=key) self.container.append(container, key=key)
python
def add_field(self, key, field): self.inputs[key] = field container = HBox() container.style.update({'justify-content':'space-between', 'overflow':'auto', 'padding':'3px'}) container.append(self.inputs[key], key=key) self.container.append(container, key=key)
[ "def", "add_field", "(", "self", ",", "key", ",", "field", ")", ":", "self", ".", "inputs", "[", "key", "]", "=", "field", "container", "=", "HBox", "(", ")", "container", ".", "style", ".", "update", "(", "{", "'justify-content'", ":", "'space-between...
Adds a field to the dialog with a unique identifier. Note: You can access to the fields content calling the function GenericDialog.get_field(key). Args: key (str): The unique identifier for the field. field (Widget): The widget to be added to the dialog, TextInput or any Widget for example.
[ "Adds", "a", "field", "to", "the", "dialog", "with", "a", "unique", "identifier", "." ]
85206f62220662bb7ecd471042268def71ccad28
https://github.com/dddomodossola/remi/blob/85206f62220662bb7ecd471042268def71ccad28/remi/gui.py#L1916-L1930
233,290
dddomodossola/remi
remi/gui.py
InputDialog.on_keydown_listener
def on_keydown_listener(self, widget, value, keycode): """event called pressing on ENTER key. propagates the string content of the input field """ if keycode=="13": self.hide() self.inputText.set_text(value) self.confirm_value(self)
python
def on_keydown_listener(self, widget, value, keycode): if keycode=="13": self.hide() self.inputText.set_text(value) self.confirm_value(self)
[ "def", "on_keydown_listener", "(", "self", ",", "widget", ",", "value", ",", "keycode", ")", ":", "if", "keycode", "==", "\"13\"", ":", "self", ".", "hide", "(", ")", "self", ".", "inputText", ".", "set_text", "(", "value", ")", "self", ".", "confirm_v...
event called pressing on ENTER key. propagates the string content of the input field
[ "event", "called", "pressing", "on", "ENTER", "key", "." ]
85206f62220662bb7ecd471042268def71ccad28
https://github.com/dddomodossola/remi/blob/85206f62220662bb7ecd471042268def71ccad28/remi/gui.py#L2001-L2009
233,291
dddomodossola/remi
remi/gui.py
ListView.new_from_list
def new_from_list(cls, items, **kwargs): """Populates the ListView with a string list. Args: items (list): list of strings to fill the widget with. """ obj = cls(**kwargs) for item in items: obj.append(ListItem(item)) return obj
python
def new_from_list(cls, items, **kwargs): obj = cls(**kwargs) for item in items: obj.append(ListItem(item)) return obj
[ "def", "new_from_list", "(", "cls", ",", "items", ",", "*", "*", "kwargs", ")", ":", "obj", "=", "cls", "(", "*", "*", "kwargs", ")", "for", "item", "in", "items", ":", "obj", ".", "append", "(", "ListItem", "(", "item", ")", ")", "return", "obj"...
Populates the ListView with a string list. Args: items (list): list of strings to fill the widget with.
[ "Populates", "the", "ListView", "with", "a", "string", "list", "." ]
85206f62220662bb7ecd471042268def71ccad28
https://github.com/dddomodossola/remi/blob/85206f62220662bb7ecd471042268def71ccad28/remi/gui.py#L2041-L2050
233,292
dddomodossola/remi
remi/gui.py
ListView.empty
def empty(self): """Removes all children from the list""" self._selected_item = None self._selected_key = None super(ListView, self).empty()
python
def empty(self): self._selected_item = None self._selected_key = None super(ListView, self).empty()
[ "def", "empty", "(", "self", ")", ":", "self", ".", "_selected_item", "=", "None", "self", ".", "_selected_key", "=", "None", "super", "(", "ListView", ",", "self", ")", ".", "empty", "(", ")" ]
Removes all children from the list
[ "Removes", "all", "children", "from", "the", "list" ]
85206f62220662bb7ecd471042268def71ccad28
https://github.com/dddomodossola/remi/blob/85206f62220662bb7ecd471042268def71ccad28/remi/gui.py#L2077-L2081
233,293
dddomodossola/remi
remi/gui.py
ListView.onselection
def onselection(self, widget): """Called when a new item gets selected in the list.""" self._selected_key = None for k in self.children: if self.children[k] == widget: # widget is the selected ListItem self._selected_key = k if (self._selected_item is not None) and self._selectable: self._selected_item.attributes['selected'] = False self._selected_item = self.children[self._selected_key] if self._selectable: self._selected_item.attributes['selected'] = True break return (self._selected_key,)
python
def onselection(self, widget): self._selected_key = None for k in self.children: if self.children[k] == widget: # widget is the selected ListItem self._selected_key = k if (self._selected_item is not None) and self._selectable: self._selected_item.attributes['selected'] = False self._selected_item = self.children[self._selected_key] if self._selectable: self._selected_item.attributes['selected'] = True break return (self._selected_key,)
[ "def", "onselection", "(", "self", ",", "widget", ")", ":", "self", ".", "_selected_key", "=", "None", "for", "k", "in", "self", ".", "children", ":", "if", "self", ".", "children", "[", "k", "]", "==", "widget", ":", "# widget is the selected ListItem", ...
Called when a new item gets selected in the list.
[ "Called", "when", "a", "new", "item", "gets", "selected", "in", "the", "list", "." ]
85206f62220662bb7ecd471042268def71ccad28
https://github.com/dddomodossola/remi/blob/85206f62220662bb7ecd471042268def71ccad28/remi/gui.py#L2085-L2097
233,294
dddomodossola/remi
remi/gui.py
ListView.select_by_key
def select_by_key(self, key): """Selects an item by its key. Args: key (str): The unique string identifier of the item that have to be selected. """ self._selected_key = None self._selected_item = None for item in self.children.values(): item.attributes['selected'] = False if key in self.children: self.children[key].attributes['selected'] = True self._selected_key = key self._selected_item = self.children[key]
python
def select_by_key(self, key): self._selected_key = None self._selected_item = None for item in self.children.values(): item.attributes['selected'] = False if key in self.children: self.children[key].attributes['selected'] = True self._selected_key = key self._selected_item = self.children[key]
[ "def", "select_by_key", "(", "self", ",", "key", ")", ":", "self", ".", "_selected_key", "=", "None", "self", ".", "_selected_item", "=", "None", "for", "item", "in", "self", ".", "children", ".", "values", "(", ")", ":", "item", ".", "attributes", "["...
Selects an item by its key. Args: key (str): The unique string identifier of the item that have to be selected.
[ "Selects", "an", "item", "by", "its", "key", "." ]
85206f62220662bb7ecd471042268def71ccad28
https://github.com/dddomodossola/remi/blob/85206f62220662bb7ecd471042268def71ccad28/remi/gui.py#L2122-L2136
233,295
dddomodossola/remi
remi/gui.py
ListView.select_by_value
def select_by_value(self, value): """Selects an item by the text content of the child. Args: value (str): Text content of the item that have to be selected. """ self._selected_key = None self._selected_item = None for k in self.children: item = self.children[k] item.attributes['selected'] = False if value == item.get_value(): self._selected_key = k self._selected_item = item self._selected_item.attributes['selected'] = True
python
def select_by_value(self, value): self._selected_key = None self._selected_item = None for k in self.children: item = self.children[k] item.attributes['selected'] = False if value == item.get_value(): self._selected_key = k self._selected_item = item self._selected_item.attributes['selected'] = True
[ "def", "select_by_value", "(", "self", ",", "value", ")", ":", "self", ".", "_selected_key", "=", "None", "self", ".", "_selected_item", "=", "None", "for", "k", "in", "self", ".", "children", ":", "item", "=", "self", ".", "children", "[", "k", "]", ...
Selects an item by the text content of the child. Args: value (str): Text content of the item that have to be selected.
[ "Selects", "an", "item", "by", "the", "text", "content", "of", "the", "child", "." ]
85206f62220662bb7ecd471042268def71ccad28
https://github.com/dddomodossola/remi/blob/85206f62220662bb7ecd471042268def71ccad28/remi/gui.py#L2141-L2155
233,296
dddomodossola/remi
remi/gui.py
DropDown.select_by_key
def select_by_key(self, key): """Selects an item by its unique string identifier. Args: key (str): Unique string identifier of the DropDownItem that have to be selected. """ for item in self.children.values(): if 'selected' in item.attributes: del item.attributes['selected'] self.children[key].attributes['selected'] = 'selected' self._selected_key = key self._selected_item = self.children[key]
python
def select_by_key(self, key): for item in self.children.values(): if 'selected' in item.attributes: del item.attributes['selected'] self.children[key].attributes['selected'] = 'selected' self._selected_key = key self._selected_item = self.children[key]
[ "def", "select_by_key", "(", "self", ",", "key", ")", ":", "for", "item", "in", "self", ".", "children", ".", "values", "(", ")", ":", "if", "'selected'", "in", "item", ".", "attributes", ":", "del", "item", ".", "attributes", "[", "'selected'", "]", ...
Selects an item by its unique string identifier. Args: key (str): Unique string identifier of the DropDownItem that have to be selected.
[ "Selects", "an", "item", "by", "its", "unique", "string", "identifier", "." ]
85206f62220662bb7ecd471042268def71ccad28
https://github.com/dddomodossola/remi/blob/85206f62220662bb7ecd471042268def71ccad28/remi/gui.py#L2235-L2246
233,297
dddomodossola/remi
remi/gui.py
DropDown.select_by_value
def select_by_value(self, value): """Selects a DropDownItem by means of the contained text- Args: value (str): Textual content of the DropDownItem that have to be selected. """ self._selected_key = None self._selected_item = None for k in self.children: item = self.children[k] if item.get_text() == value: item.attributes['selected'] = 'selected' self._selected_key = k self._selected_item = item else: if 'selected' in item.attributes: del item.attributes['selected']
python
def select_by_value(self, value): self._selected_key = None self._selected_item = None for k in self.children: item = self.children[k] if item.get_text() == value: item.attributes['selected'] = 'selected' self._selected_key = k self._selected_item = item else: if 'selected' in item.attributes: del item.attributes['selected']
[ "def", "select_by_value", "(", "self", ",", "value", ")", ":", "self", ".", "_selected_key", "=", "None", "self", ".", "_selected_item", "=", "None", "for", "k", "in", "self", ".", "children", ":", "item", "=", "self", ".", "children", "[", "k", "]", ...
Selects a DropDownItem by means of the contained text- Args: value (str): Textual content of the DropDownItem that have to be selected.
[ "Selects", "a", "DropDownItem", "by", "means", "of", "the", "contained", "text", "-" ]
85206f62220662bb7ecd471042268def71ccad28
https://github.com/dddomodossola/remi/blob/85206f62220662bb7ecd471042268def71ccad28/remi/gui.py#L2251-L2267
233,298
dddomodossola/remi
remi/gui.py
DropDown.onchange
def onchange(self, value): """Called when a new DropDownItem gets selected. """ log.debug('combo box. selected %s' % value) self.select_by_value(value) return (value, )
python
def onchange(self, value): log.debug('combo box. selected %s' % value) self.select_by_value(value) return (value, )
[ "def", "onchange", "(", "self", ",", "value", ")", ":", "log", ".", "debug", "(", "'combo box. selected %s'", "%", "value", ")", "self", ".", "select_by_value", "(", "value", ")", "return", "(", "value", ",", ")" ]
Called when a new DropDownItem gets selected.
[ "Called", "when", "a", "new", "DropDownItem", "gets", "selected", "." ]
85206f62220662bb7ecd471042268def71ccad28
https://github.com/dddomodossola/remi/blob/85206f62220662bb7ecd471042268def71ccad28/remi/gui.py#L2294-L2299
233,299
dddomodossola/remi
remi/gui.py
Table.append_from_list
def append_from_list(self, content, fill_title=False): """ Appends rows created from the data contained in the provided list of tuples of strings. The first tuple of the list can be set as table title. Args: content (list): list of tuples of strings. Each tuple is a row. fill_title (bool): if true, the first tuple in the list will be set as title. """ row_index = 0 for row in content: tr = TableRow() column_index = 0 for item in row: if row_index == 0 and fill_title: ti = TableTitle(item) else: ti = TableItem(item) tr.append(ti, str(column_index)) column_index = column_index + 1 self.append(tr, str(row_index)) row_index = row_index + 1
python
def append_from_list(self, content, fill_title=False): row_index = 0 for row in content: tr = TableRow() column_index = 0 for item in row: if row_index == 0 and fill_title: ti = TableTitle(item) else: ti = TableItem(item) tr.append(ti, str(column_index)) column_index = column_index + 1 self.append(tr, str(row_index)) row_index = row_index + 1
[ "def", "append_from_list", "(", "self", ",", "content", ",", "fill_title", "=", "False", ")", ":", "row_index", "=", "0", "for", "row", "in", "content", ":", "tr", "=", "TableRow", "(", ")", "column_index", "=", "0", "for", "item", "in", "row", ":", ...
Appends rows created from the data contained in the provided list of tuples of strings. The first tuple of the list can be set as table title. Args: content (list): list of tuples of strings. Each tuple is a row. fill_title (bool): if true, the first tuple in the list will be set as title.
[ "Appends", "rows", "created", "from", "the", "data", "contained", "in", "the", "provided", "list", "of", "tuples", "of", "strings", ".", "The", "first", "tuple", "of", "the", "list", "can", "be", "set", "as", "table", "title", "." ]
85206f62220662bb7ecd471042268def71ccad28
https://github.com/dddomodossola/remi/blob/85206f62220662bb7ecd471042268def71ccad28/remi/gui.py#L2377-L2400