code stringlengths 66 870k | docstring stringlengths 19 26.7k | func_name stringlengths 1 138 | language stringclasses 1
value | repo stringlengths 7 68 | path stringlengths 5 324 | url stringlengths 46 389 | license stringclasses 7
values |
|---|---|---|---|---|---|---|---|
def _end_of_line(self, y):
"""Go to the location of the first blank on the given line,
returning the index of the last non-blank character."""
last = self.maxx
while True:
if curses.ascii.ascii(self.win.inch(y, last)) != curses.ascii.SP:
last = min(self.maxx, ... | Go to the location of the first blank on the given line,
returning the index of the last non-blank character. | _end_of_line | python | mchristopher/PokemonGo-DesktopMap | app/pywin/Lib/curses/textpad.py | https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/curses/textpad.py | MIT |
def gather(self):
"Collect and return the contents of the window."
result = ""
for y in range(self.maxy+1):
self.win.move(y, 0)
stop = self._end_of_line(y)
if stop == 0 and self.stripspaces:
continue
for x in range(self.maxx+1):
... | Collect and return the contents of the window. | gather | python | mchristopher/PokemonGo-DesktopMap | app/pywin/Lib/curses/textpad.py | https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/curses/textpad.py | MIT |
def edit(self, validate=None):
"Edit in the widget window and collect the results."
while 1:
ch = self.win.getch()
if validate:
ch = validate(ch)
if not ch:
continue
if not self.do_command(ch):
break
... | Edit in the widget window and collect the results. | edit | python | mchristopher/PokemonGo-DesktopMap | app/pywin/Lib/curses/textpad.py | https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/curses/textpad.py | MIT |
def wrapper(func, *args, **kwds):
"""Wrapper function that initializes curses and calls another function,
restoring normal keyboard/screen behavior on error.
The callable object 'func' is then passed the main window 'stdscr'
as its first argument, followed by any other arguments passed to
wrapper().... | Wrapper function that initializes curses and calls another function,
restoring normal keyboard/screen behavior on error.
The callable object 'func' is then passed the main window 'stdscr'
as its first argument, followed by any other arguments passed to
wrapper().
| wrapper | python | mchristopher/PokemonGo-DesktopMap | app/pywin/Lib/curses/wrapper.py | https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/curses/wrapper.py | MIT |
def is_cygwingcc():
'''Try to determine if the gcc that would be used is from cygwin.'''
out = os.popen('gcc -dumpmachine', 'r')
out_string = out.read()
out.close()
# out_string is the target triplet cpu-vendor-os
# Cygwin's gcc sets the os to 'cygwin'
return out_string.strip().endswith('cyg... | Try to determine if the gcc that would be used is from cygwin. | is_cygwingcc | python | mchristopher/PokemonGo-DesktopMap | app/pywin/Lib/distutils/cygwinccompiler.py | https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/distutils/cygwinccompiler.py | MIT |
def copy_file(src, dst, preserve_mode=1, preserve_times=1, update=0,
link=None, verbose=1, dry_run=0):
"""Copy a file 'src' to 'dst'.
If 'dst' is a directory, then 'src' is copied there with the same name;
otherwise, it must be a filename. (If the file exists, it will be
ruthlessly clobb... | Copy a file 'src' to 'dst'.
If 'dst' is a directory, then 'src' is copied there with the same name;
otherwise, it must be a filename. (If the file exists, it will be
ruthlessly clobbered.) If 'preserve_mode' is true (the default),
the file's mode (type and permission bits, or whatever is analogous on... | copy_file | python | mchristopher/PokemonGo-DesktopMap | app/pywin/Lib/distutils/file_util.py | https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/distutils/file_util.py | MIT |
def encode(s, binary=True, maxlinelen=76, eol=NL):
"""Encode a string with base64.
Each line will be wrapped at, at most, maxlinelen characters (defaults to
76 characters).
If binary is False, end-of-line characters will be converted to the
canonical email end-of-line sequence \\r\\n. Otherwise t... | Encode a string with base64.
Each line will be wrapped at, at most, maxlinelen characters (defaults to
76 characters).
If binary is False, end-of-line characters will be converted to the
canonical email end-of-line sequence \r\n. Otherwise they will be left
verbatim (this is the default).
Ea... | encode | python | mchristopher/PokemonGo-DesktopMap | app/pywin/Lib/email/base64mime.py | https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/email/base64mime.py | MIT |
def __init__(self, *args, **kws):
"""Parser of RFC 2822 and MIME email messages.
Creates an in-memory object tree representing the email message, which
can then be manipulated and turned over to a Generator to return the
textual representation of the message.
The string must be... | Parser of RFC 2822 and MIME email messages.
Creates an in-memory object tree representing the email message, which
can then be manipulated and turned over to a Generator to return the
textual representation of the message.
The string must be formatted as a block of RFC 2822 headers and... | __init__ | python | mchristopher/PokemonGo-DesktopMap | app/pywin/Lib/email/parser.py | https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/email/parser.py | MIT |
def _bdecode(s):
"""Decodes a base64 string.
This function is equivalent to base64.decodestring and it's retained only
for backward compatibility. It used to remove the last \\n of the decoded
string, if it had any (see issue 7143).
"""
if not s:
return s
return base64.decodestring(... | Decodes a base64 string.
This function is equivalent to base64.decodestring and it's retained only
for backward compatibility. It used to remove the last \n of the decoded
string, if it had any (see issue 7143).
| _bdecode | python | mchristopher/PokemonGo-DesktopMap | app/pywin/Lib/email/utils.py | https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/email/utils.py | MIT |
def fix_eols(s):
"""Replace all line-ending characters with \\r\\n."""
# Fix newlines with no preceding carriage return
s = re.sub(r'(?<!\r)\n', CRLF, s)
# Fix carriage returns with no following newline
s = re.sub(r'\r(?!\n)', CRLF, s)
return s | Replace all line-ending characters with \r\n. | fix_eols | python | mchristopher/PokemonGo-DesktopMap | app/pywin/Lib/email/utils.py | https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/email/utils.py | MIT |
def make_msgid(idstring=None):
"""Returns a string suitable for RFC 2822 compliant Message-ID, e.g:
<142480216486.20800.16526388040877946887@nightshade.la.mastaler.com>
Optional idstring if given is a string used to strengthen the
uniqueness of the message id.
"""
timeval = int(time.time()*100... | Returns a string suitable for RFC 2822 compliant Message-ID, e.g:
<142480216486.20800.16526388040877946887@nightshade.la.mastaler.com>
Optional idstring if given is a string used to strengthen the
uniqueness of the message id.
| make_msgid | python | mchristopher/PokemonGo-DesktopMap | app/pywin/Lib/email/utils.py | https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/email/utils.py | MIT |
def bootstrap(root=None, upgrade=False, user=False,
altinstall=False, default_pip=True,
verbosity=0):
"""
Bootstrap pip into the current Python installation (or the given root
directory).
Note that calling this function will alter both sys.path and os.environ.
"""
if... |
Bootstrap pip into the current Python installation (or the given root
directory).
Note that calling this function will alter both sys.path and os.environ.
| bootstrap | python | mchristopher/PokemonGo-DesktopMap | app/pywin/Lib/ensurepip/__init__.py | https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/ensurepip/__init__.py | MIT |
def _uninstall_helper(verbosity=0):
"""Helper to support a clean default uninstall process on Windows
Note that calling this function may alter os.environ.
"""
# Nothing to do if pip was never installed, or has been removed
try:
import pip
except ImportError:
return
# If th... | Helper to support a clean default uninstall process on Windows
Note that calling this function may alter os.environ.
| _uninstall_helper | python | mchristopher/PokemonGo-DesktopMap | app/pywin/Lib/ensurepip/__init__.py | https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/ensurepip/__init__.py | MIT |
def index(self, index):
"Return string version of index decoded according to current text."
return "%s.%s" % self._decode(index, endflag=1) | Return string version of index decoded according to current text. | index | python | mchristopher/PokemonGo-DesktopMap | app/pywin/Lib/idlelib/idle_test/mock_tk.py | https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/idlelib/idle_test/mock_tk.py | MIT |
def _decode(self, index, endflag=0):
"""Return a (line, char) tuple of int indexes into self.data.
This implements .index without converting the result back to a string.
The result is contrained by the number of lines and linelengths of
self.data. For many indexes, the result is initial... | Return a (line, char) tuple of int indexes into self.data.
This implements .index without converting the result back to a string.
The result is contrained by the number of lines and linelengths of
self.data. For many indexes, the result is initially (1, 0).
The input index may have any... | _decode | python | mchristopher/PokemonGo-DesktopMap | app/pywin/Lib/idlelib/idle_test/mock_tk.py | https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/idlelib/idle_test/mock_tk.py | MIT |
def _endex(self, endflag):
'''Return position for 'end' or line overflow corresponding to endflag.
-1: position before terminal \n; for .insert(), .delete
0: position after terminal \n; for .get, .delete index 1
1: same viewed as beginning of non-existent next line (for .index)
'''
... | Return position for 'end' or line overflow corresponding to endflag.
-1: position before terminal
; for .insert(), .delete
0: position after terminal
; for .get, .delete index 1
1: same viewed as beginning of non-existent next line (for .index)
| _endex | python | mchristopher/PokemonGo-DesktopMap | app/pywin/Lib/idlelib/idle_test/mock_tk.py | https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/idlelib/idle_test/mock_tk.py | MIT |
def insert(self, index, chars):
"Insert chars before the character at index."
if not chars: # ''.splitlines() is [], not ['']
return
chars = chars.splitlines(True)
if chars[-1][-1] == '\n':
chars.append('')
line, char = self._decode(index, -1)
be... | Insert chars before the character at index. | insert | python | mchristopher/PokemonGo-DesktopMap | app/pywin/Lib/idlelib/idle_test/mock_tk.py | https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/idlelib/idle_test/mock_tk.py | MIT |
def get(self, index1, index2=None):
"Return slice from index1 to index2 (default is 'index1+1')."
startline, startchar = self._decode(index1)
if index2 is None:
endline, endchar = startline, startchar+1
else:
endline, endchar = self._decode(index2)
if st... | Return slice from index1 to index2 (default is 'index1+1'). | get | python | mchristopher/PokemonGo-DesktopMap | app/pywin/Lib/idlelib/idle_test/mock_tk.py | https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/idlelib/idle_test/mock_tk.py | MIT |
def delete(self, index1, index2=None):
'''Delete slice from index1 to index2 (default is 'index1+1').
Adjust default index2 ('index+1) for line ends.
Do not delete the terminal \n at the very end of self.data ([-1][-1]).
'''
startline, startchar = self._decode(index1, -1)
... | Delete slice from index1 to index2 (default is 'index1+1').
Adjust default index2 ('index+1) for line ends.
Do not delete the terminal
at the very end of self.data ([-1][-1]).
| delete | python | mchristopher/PokemonGo-DesktopMap | app/pywin/Lib/idlelib/idle_test/mock_tk.py | https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/idlelib/idle_test/mock_tk.py | MIT |
def test_paste_text_no_selection(self):
"Test pasting into text without a selection."
text = self.text
tag, ans = '', 'onetwo\n'
text.delete('1.0', 'end')
text.insert('1.0', 'one', tag)
text.event_generate('<<Paste>>')
self.assertEqual(text.get('1.0', 'end'), ans) | Test pasting into text without a selection. | test_paste_text_no_selection | python | mchristopher/PokemonGo-DesktopMap | app/pywin/Lib/idlelib/idle_test/test_editmenu.py | https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/idlelib/idle_test/test_editmenu.py | MIT |
def test_paste_text_selection(self):
"Test pasting into text with a selection."
text = self.text
tag, ans = 'sel', 'two\n'
text.delete('1.0', 'end')
text.insert('1.0', 'one', tag)
text.event_generate('<<Paste>>')
self.assertEqual(text.get('1.0', 'end'), ans) | Test pasting into text with a selection. | test_paste_text_selection | python | mchristopher/PokemonGo-DesktopMap | app/pywin/Lib/idlelib/idle_test/test_editmenu.py | https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/idlelib/idle_test/test_editmenu.py | MIT |
def test_paste_entry_no_selection(self):
"Test pasting into an entry without a selection."
# On 3.6, generated <<Paste>> fails without empty select range
# for 'no selection'. Live widget works fine.
entry = self.entry
end, ans = 0, 'onetwo'
entry.delete(0, 'end')
... | Test pasting into an entry without a selection. | test_paste_entry_no_selection | python | mchristopher/PokemonGo-DesktopMap | app/pywin/Lib/idlelib/idle_test/test_editmenu.py | https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/idlelib/idle_test/test_editmenu.py | MIT |
def test_paste_entry_selection(self):
"Test pasting into an entry with a selection."
entry = self.entry
end, ans = 'end', 'two'
entry.delete(0, 'end')
entry.insert(0, 'one')
entry.select_range(0, end)
entry.event_generate('<<Paste>>')
self.assertEqual(entr... | Test pasting into an entry with a selection. | test_paste_entry_selection | python | mchristopher/PokemonGo-DesktopMap | app/pywin/Lib/idlelib/idle_test/test_editmenu.py | https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/idlelib/idle_test/test_editmenu.py | MIT |
def test_paste_spin_no_selection(self):
"Test pasting into a spinbox without a selection."
# See note above for entry.
spin = self.spin
end, ans = 0, 'onetwo'
spin.delete(0, 'end')
spin.insert(0, 'one')
spin.selection('range', 0, end) # see note
spin.even... | Test pasting into a spinbox without a selection. | test_paste_spin_no_selection | python | mchristopher/PokemonGo-DesktopMap | app/pywin/Lib/idlelib/idle_test/test_editmenu.py | https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/idlelib/idle_test/test_editmenu.py | MIT |
def test_paste_spin_selection(self):
"Test pasting into a spinbox with a selection."
spin = self.spin
end, ans = 'end', 'two'
spin.delete(0, 'end')
spin.insert(0, 'one')
spin.selection('range', 0, end)
spin.event_generate('<<Paste>>')
self.assertEqual(spin... | Test pasting into a spinbox with a selection. | test_paste_spin_selection | python | mchristopher/PokemonGo-DesktopMap | app/pywin/Lib/idlelib/idle_test/test_editmenu.py | https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/idlelib/idle_test/test_editmenu.py | MIT |
def test_init(self):
"""
test corner cases in the init method
"""
with self.assertRaises(ValueError) as ve:
self.text.tag_add('console', '1.0', '1.end')
p = self.get_parser('1.5')
self.assertIn('precedes', str(ve.exception))
# test without ps1
... |
test corner cases in the init method
| test_init | python | mchristopher/PokemonGo-DesktopMap | app/pywin/Lib/idlelib/idle_test/test_hyperparser.py | https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/idlelib/idle_test/test_hyperparser.py | MIT |
def test_paren_corner(self):
"""
Test corner cases in flash_paren_event and paren_closed_event.
These cases force conditional expression and alternate paths.
"""
text = self.text
pm = ParenMatch(self.editwin)
text.insert('insert', '# this is a commen)')
... |
Test corner cases in flash_paren_event and paren_closed_event.
These cases force conditional expression and alternate paths.
| test_paren_corner | python | mchristopher/PokemonGo-DesktopMap | app/pywin/Lib/idlelib/idle_test/test_parenmatch.py | https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/idlelib/idle_test/test_parenmatch.py | MIT |
def dumps(obj, skipkeys=False, ensure_ascii=True, check_circular=True,
allow_nan=True, cls=None, indent=None, separators=None,
encoding='utf-8', default=None, sort_keys=False, **kw):
"""Serialize ``obj`` to a JSON formatted ``str``.
If ``skipkeys`` is true then ``dict`` keys that are not basic ... | Serialize ``obj`` to a JSON formatted ``str``.
If ``skipkeys`` is true then ``dict`` keys that are not basic types
(``str``, ``unicode``, ``int``, ``long``, ``float``, ``bool``, ``None``)
will be skipped instead of raising a ``TypeError``.
If ``ensure_ascii`` is false, all non-ASCII characters are no... | dumps | python | mchristopher/PokemonGo-DesktopMap | app/pywin/Lib/json/__init__.py | https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/json/__init__.py | MIT |
def simulate_mouse_click(widget, x, y):
"""Generate proper events to click at the x, y position (tries to act
like an X server)."""
widget.event_generate('<Enter>', x=0, y=0)
widget.event_generate('<Motion>', x=x, y=y)
widget.event_generate('<ButtonPress-1>', x=x, y=y)
widget.event_generate('<Bu... | Generate proper events to click at the x, y position (tries to act
like an X server). | simulate_mouse_click | python | mchristopher/PokemonGo-DesktopMap | app/pywin/Lib/lib-tk/test/test_ttk/support.py | https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/lib-tk/test/test_ttk/support.py | MIT |
def exception(self, msg, *args, **kwargs):
"""
Convenience method for logging an ERROR with exception information.
"""
kwargs['exc_info'] = 1
self.error(msg, *args, **kwargs) |
Convenience method for logging an ERROR with exception information.
| exception | python | mchristopher/PokemonGo-DesktopMap | app/pywin/Lib/logging/__init__.py | https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/logging/__init__.py | MIT |
def exception(msg, *args, **kwargs):
"""
Log a message with severity 'ERROR' on the root logger,
with exception information.
"""
kwargs['exc_info'] = 1
error(msg, *args, **kwargs) |
Log a message with severity 'ERROR' on the root logger,
with exception information.
| exception | python | mchristopher/PokemonGo-DesktopMap | app/pywin/Lib/logging/__init__.py | https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/logging/__init__.py | MIT |
def add_file(self, file, src=None, version=None, language=None):
"""Add a file to the current component of the directory, starting a new one
if there is no current component. By default, the file name in the source
and the file table will be identical. If the src file is specified, it is
... | Add a file to the current component of the directory, starting a new one
if there is no current component. By default, the file name in the source
and the file table will be identical. If the src file is specified, it is
interpreted relative to the current directory. Optionally, a version and a
... | add_file | python | mchristopher/PokemonGo-DesktopMap | app/pywin/Lib/msilib/__init__.py | https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/msilib/__init__.py | MIT |
def arbitrary_address(family):
'''
Return an arbitrary free address for the given family
'''
if family == 'AF_INET':
return ('localhost', 0)
elif family == 'AF_UNIX':
return tempfile.mktemp(prefix='listener-', dir=get_temp_dir())
elif family == 'AF_PIPE':
return tempfile.... |
Return an arbitrary free address for the given family
| arbitrary_address | python | mchristopher/PokemonGo-DesktopMap | app/pywin/Lib/multiprocessing/connection.py | https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/multiprocessing/connection.py | MIT |
def address_type(address):
'''
Return the types of the address
This can be 'AF_INET', 'AF_UNIX', or 'AF_PIPE'
'''
if type(address) == tuple:
return 'AF_INET'
elif type(address) is str and address.startswith('\\\\'):
return 'AF_PIPE'
elif type(address) is str:
return ... |
Return the types of the address
This can be 'AF_INET', 'AF_UNIX', or 'AF_PIPE'
| address_type | python | mchristopher/PokemonGo-DesktopMap | app/pywin/Lib/multiprocessing/connection.py | https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/multiprocessing/connection.py | MIT |
def accept(self):
'''
Accept a connection on the bound socket or named pipe of `self`.
Returns a `Connection` object.
'''
c = self._listener.accept()
if self._authkey:
deliver_challenge(c, self._authkey)
answer_challenge(c, self._authkey)
... |
Accept a connection on the bound socket or named pipe of `self`.
Returns a `Connection` object.
| accept | python | mchristopher/PokemonGo-DesktopMap | app/pywin/Lib/multiprocessing/connection.py | https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/multiprocessing/connection.py | MIT |
def Client(address, family=None, authkey=None):
'''
Returns a connection to the address of a `Listener`
'''
family = family or address_type(address)
if family == 'AF_PIPE':
c = PipeClient(address)
else:
c = SocketClient(address)
if authkey is not None and not isinstance(auth... |
Returns a connection to the address of a `Listener`
| Client | python | mchristopher/PokemonGo-DesktopMap | app/pywin/Lib/multiprocessing/connection.py | https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/multiprocessing/connection.py | MIT |
def Pipe(duplex=True):
'''
Returns pair of connection objects at either end of a pipe
'''
if duplex:
s1, s2 = socket.socketpair()
s1.setblocking(True)
s2.setblocking(True)
c1 = _multiprocessing.Connection(os.dup(s1.fileno()))
c2... |
Returns pair of connection objects at either end of a pipe
| Pipe | python | mchristopher/PokemonGo-DesktopMap | app/pywin/Lib/multiprocessing/connection.py | https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/multiprocessing/connection.py | MIT |
def SocketClient(address):
'''
Return a connection object connected to the socket given by `address`
'''
family = getattr(socket, address_type(address))
t = _init_timeout()
while 1:
s = socket.socket(family)
s.setblocking(True)
try:
s.connect(address)
... |
Return a connection object connected to the socket given by `address`
| SocketClient | python | mchristopher/PokemonGo-DesktopMap | app/pywin/Lib/multiprocessing/connection.py | https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/multiprocessing/connection.py | MIT |
def PipeClient(address):
'''
Return a connection object connected to the pipe given by `address`
'''
t = _init_timeout()
while 1:
try:
win32.WaitNamedPipe(address, 1000)
h = win32.CreateFile(
address, win32.GENERIC_R... |
Return a connection object connected to the pipe given by `address`
| PipeClient | python | mchristopher/PokemonGo-DesktopMap | app/pywin/Lib/multiprocessing/connection.py | https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/multiprocessing/connection.py | MIT |
def is_forking(argv):
'''
Return whether commandline indicates we are forking
'''
if len(argv) >= 2 and argv[1] == '--multiprocessing-fork':
assert len(argv) == 3
return True
else:
return False |
Return whether commandline indicates we are forking
| is_forking | python | mchristopher/PokemonGo-DesktopMap | app/pywin/Lib/multiprocessing/forking.py | https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/multiprocessing/forking.py | MIT |
def get_command_line():
'''
Returns prefix of command line used for spawning a child process
'''
if getattr(process.current_process(), '_inheriting', False):
raise RuntimeError('''
Attempt to start a new process before the current process
has finished ... |
Returns prefix of command line used for spawning a child process
| get_command_line | python | mchristopher/PokemonGo-DesktopMap | app/pywin/Lib/multiprocessing/forking.py | https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/multiprocessing/forking.py | MIT |
def main():
'''
Run code specified by data received over pipe
'''
assert is_forking(sys.argv)
handle = int(sys.argv[-1])
fd = msvcrt.open_osfhandle(handle, os.O_RDONLY)
from_parent = os.fdopen(fd, 'rb')
process.current_process()._inheriting = True
... |
Run code specified by data received over pipe
| main | python | mchristopher/PokemonGo-DesktopMap | app/pywin/Lib/multiprocessing/forking.py | https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/multiprocessing/forking.py | MIT |
def get_preparation_data(name):
'''
Return info about parent needed by child to unpickle process object
'''
from .util import _logger, _log_to_stderr
d = dict(
name=name,
sys_path=sys.path,
sys_argv=sys.argv,
log_to_stderr=_log_to_... |
Return info about parent needed by child to unpickle process object
| get_preparation_data | python | mchristopher/PokemonGo-DesktopMap | app/pywin/Lib/multiprocessing/forking.py | https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/multiprocessing/forking.py | MIT |
def prepare(data):
'''
Try to get current process ready to unpickle process object
'''
old_main_modules.append(sys.modules['__main__'])
if 'name' in data:
process.current_process().name = data['name']
if 'authkey' in data:
process.current_process()._authkey = data['authkey']
... |
Try to get current process ready to unpickle process object
| prepare | python | mchristopher/PokemonGo-DesktopMap | app/pywin/Lib/multiprocessing/forking.py | https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/multiprocessing/forking.py | MIT |
def dispatch(c, id, methodname, args=(), kwds={}):
'''
Send a message to manager using connection `c` and return response
'''
c.send((id, methodname, args, kwds))
kind, result = c.recv()
if kind == '#RETURN':
return result
raise convert_to_error(kind, result) |
Send a message to manager using connection `c` and return response
| dispatch | python | mchristopher/PokemonGo-DesktopMap | app/pywin/Lib/multiprocessing/managers.py | https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/multiprocessing/managers.py | MIT |
def all_methods(obj):
'''
Return a list of names of methods of `obj`
'''
temp = []
for name in dir(obj):
func = getattr(obj, name)
if hasattr(func, '__call__'):
temp.append(name)
return temp |
Return a list of names of methods of `obj`
| all_methods | python | mchristopher/PokemonGo-DesktopMap | app/pywin/Lib/multiprocessing/managers.py | https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/multiprocessing/managers.py | MIT |
def serve_client(self, conn):
'''
Handle requests from the proxies in a particular process/thread
'''
util.debug('starting server thread to service %r',
threading.current_thread().name)
recv = conn.recv
send = conn.send
id_to_obj = self.id_to_o... |
Handle requests from the proxies in a particular process/thread
| serve_client | python | mchristopher/PokemonGo-DesktopMap | app/pywin/Lib/multiprocessing/managers.py | https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/multiprocessing/managers.py | MIT |
def debug_info(self, c):
'''
Return some info --- useful to spot problems with refcounting
'''
self.mutex.acquire()
try:
result = []
keys = self.id_to_obj.keys()
keys.sort()
for ident in keys:
if ident != '0':
... |
Return some info --- useful to spot problems with refcounting
| debug_info | python | mchristopher/PokemonGo-DesktopMap | app/pywin/Lib/multiprocessing/managers.py | https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/multiprocessing/managers.py | MIT |
def create(self, c, typeid, *args, **kwds):
'''
Create a new shared object and return its id
'''
self.mutex.acquire()
try:
callable, exposed, method_to_typeid, proxytype = \
self.registry[typeid]
if callable is None:
... |
Create a new shared object and return its id
| create | python | mchristopher/PokemonGo-DesktopMap | app/pywin/Lib/multiprocessing/managers.py | https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/multiprocessing/managers.py | MIT |
def accept_connection(self, c, name):
'''
Spawn a new thread to serve this connection
'''
threading.current_thread().name = name
c.send(('#RETURN', None))
self.serve_client(c) |
Spawn a new thread to serve this connection
| accept_connection | python | mchristopher/PokemonGo-DesktopMap | app/pywin/Lib/multiprocessing/managers.py | https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/multiprocessing/managers.py | MIT |
def get_server(self):
'''
Return server object with serve_forever() method and address attribute
'''
assert self._state.value == State.INITIAL
return Server(self._registry, self._address,
self._authkey, self._serializer) |
Return server object with serve_forever() method and address attribute
| get_server | python | mchristopher/PokemonGo-DesktopMap | app/pywin/Lib/multiprocessing/managers.py | https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/multiprocessing/managers.py | MIT |
def connect(self):
'''
Connect manager object to the server process
'''
Listener, Client = listener_client[self._serializer]
conn = Client(self._address, authkey=self._authkey)
dispatch(conn, None, 'dummy')
self._state.value = State.STARTED |
Connect manager object to the server process
| connect | python | mchristopher/PokemonGo-DesktopMap | app/pywin/Lib/multiprocessing/managers.py | https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/multiprocessing/managers.py | MIT |
def start(self, initializer=None, initargs=()):
'''
Spawn a server process for this manager object
'''
assert self._state.value == State.INITIAL
if initializer is not None and not hasattr(initializer, '__call__'):
raise TypeError('initializer must be a callable')
... |
Spawn a server process for this manager object
| start | python | mchristopher/PokemonGo-DesktopMap | app/pywin/Lib/multiprocessing/managers.py | https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/multiprocessing/managers.py | MIT |
def _run_server(cls, registry, address, authkey, serializer, writer,
initializer=None, initargs=()):
'''
Create a server, report its address and run it
'''
if initializer is not None:
initializer(*initargs)
# create server
server = cls._Se... |
Create a server, report its address and run it
| _run_server | python | mchristopher/PokemonGo-DesktopMap | app/pywin/Lib/multiprocessing/managers.py | https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/multiprocessing/managers.py | MIT |
def _create(self, typeid, *args, **kwds):
'''
Create a new shared object; return the token and exposed tuple
'''
assert self._state.value == State.STARTED, 'server not yet started'
conn = self._Client(self._address, authkey=self._authkey)
try:
id, exposed = di... |
Create a new shared object; return the token and exposed tuple
| _create | python | mchristopher/PokemonGo-DesktopMap | app/pywin/Lib/multiprocessing/managers.py | https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/multiprocessing/managers.py | MIT |
def _debug_info(self):
'''
Return some info about the servers shared objects and connections
'''
conn = self._Client(self._address, authkey=self._authkey)
try:
return dispatch(conn, None, 'debug_info')
finally:
conn.close() |
Return some info about the servers shared objects and connections
| _debug_info | python | mchristopher/PokemonGo-DesktopMap | app/pywin/Lib/multiprocessing/managers.py | https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/multiprocessing/managers.py | MIT |
def _number_of_objects(self):
'''
Return the number of shared objects
'''
conn = self._Client(self._address, authkey=self._authkey)
try:
return dispatch(conn, None, 'number_of_objects')
finally:
conn.close() |
Return the number of shared objects
| _number_of_objects | python | mchristopher/PokemonGo-DesktopMap | app/pywin/Lib/multiprocessing/managers.py | https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/multiprocessing/managers.py | MIT |
def _finalize_manager(process, address, authkey, state, _Client):
'''
Shutdown the manager process; will be registered as a finalizer
'''
if process.is_alive():
util.info('sending shutdown message to manager')
try:
conn = _Client(address, authkey=a... |
Shutdown the manager process; will be registered as a finalizer
| _finalize_manager | python | mchristopher/PokemonGo-DesktopMap | app/pywin/Lib/multiprocessing/managers.py | https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/multiprocessing/managers.py | MIT |
def register(cls, typeid, callable=None, proxytype=None, exposed=None,
method_to_typeid=None, create_method=True):
'''
Register a typeid with the manager type
'''
if '_registry' not in cls.__dict__:
cls._registry = cls._registry.copy()
if proxytype i... |
Register a typeid with the manager type
| register | python | mchristopher/PokemonGo-DesktopMap | app/pywin/Lib/multiprocessing/managers.py | https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/multiprocessing/managers.py | MIT |
def _callmethod(self, methodname, args=(), kwds={}):
'''
Try to call a method of the referrent and return a copy of the result
'''
try:
conn = self._tls.connection
except AttributeError:
util.debug('thread %r does not own a connection',
... |
Try to call a method of the referrent and return a copy of the result
| _callmethod | python | mchristopher/PokemonGo-DesktopMap | app/pywin/Lib/multiprocessing/managers.py | https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/multiprocessing/managers.py | MIT |
def __str__(self):
'''
Return representation of the referent (or a fall-back if that fails)
'''
try:
return self._callmethod('__repr__')
except Exception:
return repr(self)[:-1] + "; '__str__()' failed>" |
Return representation of the referent (or a fall-back if that fails)
| __str__ | python | mchristopher/PokemonGo-DesktopMap | app/pywin/Lib/multiprocessing/managers.py | https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/multiprocessing/managers.py | MIT |
def RebuildProxy(func, token, serializer, kwds):
'''
Function used for unpickling proxy objects.
If possible the shared object is returned, or otherwise a proxy for it.
'''
server = getattr(current_process(), '_manager_server', None)
if server and server.address == token.address:
retur... |
Function used for unpickling proxy objects.
If possible the shared object is returned, or otherwise a proxy for it.
| RebuildProxy | python | mchristopher/PokemonGo-DesktopMap | app/pywin/Lib/multiprocessing/managers.py | https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/multiprocessing/managers.py | MIT |
def imap(self, func, iterable, chunksize=1):
'''
Equivalent of `itertools.imap()` -- can be MUCH slower than `Pool.map()`
'''
assert self._state == RUN
if chunksize == 1:
result = IMapIterator(self._cache)
self._taskqueue.put((((result._job, i, func, (x,),... |
Equivalent of `itertools.imap()` -- can be MUCH slower than `Pool.map()`
| imap | python | mchristopher/PokemonGo-DesktopMap | app/pywin/Lib/multiprocessing/pool.py | https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/multiprocessing/pool.py | MIT |
def imap_unordered(self, func, iterable, chunksize=1):
'''
Like `imap()` method but ordering of results is arbitrary
'''
assert self._state == RUN
if chunksize == 1:
result = IMapUnorderedIterator(self._cache)
self._taskqueue.put((((result._job, i, func, (... |
Like `imap()` method but ordering of results is arbitrary
| imap_unordered | python | mchristopher/PokemonGo-DesktopMap | app/pywin/Lib/multiprocessing/pool.py | https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/multiprocessing/pool.py | MIT |
def exitcode(self):
'''
Return exit code of process or `None` if it has yet to stop
'''
if self._popen is None:
return self._popen
return self._popen.poll() |
Return exit code of process or `None` if it has yet to stop
| exitcode | python | mchristopher/PokemonGo-DesktopMap | app/pywin/Lib/multiprocessing/process.py | https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/multiprocessing/process.py | MIT |
def ident(self):
'''
Return identifier (PID) of process or `None` if it has yet to start
'''
if self is _current_process:
return os.getpid()
else:
return self._popen and self._popen.pid |
Return identifier (PID) of process or `None` if it has yet to start
| ident | python | mchristopher/PokemonGo-DesktopMap | app/pywin/Lib/multiprocessing/process.py | https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/multiprocessing/process.py | MIT |
def RawValue(typecode_or_type, *args):
'''
Returns a ctypes object allocated from shared memory
'''
type_ = typecode_to_type.get(typecode_or_type, typecode_or_type)
obj = _new_value(type_)
ctypes.memset(ctypes.addressof(obj), 0, ctypes.sizeof(obj))
obj.__init__(*args)
return obj |
Returns a ctypes object allocated from shared memory
| RawValue | python | mchristopher/PokemonGo-DesktopMap | app/pywin/Lib/multiprocessing/sharedctypes.py | https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/multiprocessing/sharedctypes.py | MIT |
def RawArray(typecode_or_type, size_or_initializer):
'''
Returns a ctypes array allocated from shared memory
'''
type_ = typecode_to_type.get(typecode_or_type, typecode_or_type)
if isinstance(size_or_initializer, (int, long)):
type_ = type_ * size_or_initializer
obj = _new_value(type... |
Returns a ctypes array allocated from shared memory
| RawArray | python | mchristopher/PokemonGo-DesktopMap | app/pywin/Lib/multiprocessing/sharedctypes.py | https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/multiprocessing/sharedctypes.py | MIT |
def validator(application):
"""
When applied between a WSGI server and a WSGI application, this
middleware will check for WSGI compliancy on a number of levels.
This middleware does not modify the request or response in any
way, but will raise an AssertionError if anything seems off
(except for... |
When applied between a WSGI server and a WSGI application, this
middleware will check for WSGI compliancy on a number of levels.
This middleware does not modify the request or response in any
way, but will raise an AssertionError if anything seems off
(except for a failure to close the application ... | validator | python | mchristopher/PokemonGo-DesktopMap | app/pywin/Lib/wsgiref/validate.py | https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/wsgiref/validate.py | MIT |
def _find_toml_section_end(lines, start):
"""Find the index of the start of the next section."""
return (
next(filter(itemgetter(1), enumerate(line.startswith('[') for line in lines[start + 1 :])))[0]
+ start
+ 1
) | Find the index of the start of the next section. | _find_toml_section_end | python | ProjectQ-Framework/ProjectQ | setup.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/setup.py | Apache-2.0 |
def _parse_list(lines):
"""Parse a TOML list into a Python list."""
# NB: This function expects the TOML list to be formatted like so (ignoring leading and trailing spaces):
# name = [
# '...',
# ]
# Any other format is not sup... | Parse a TOML list into a Python list. | _parse_list | python | ProjectQ-Framework/ProjectQ | setup.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/setup.py | Apache-2.0 |
def parse_toml(filename):
"""Very simple parser routine for pyproject.toml."""
result = {'project': {'optional-dependencies': {}}}
with open(filename) as toml_file:
lines = [line.strip() for line in toml_file.readlines()]
lines = [line for line in lines if... | Very simple parser routine for pyproject.toml. | parse_toml | python | ProjectQ-Framework/ProjectQ | setup.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/setup.py | Apache-2.0 |
def compiler_test(
compiler,
flagname=None,
link_executable=False,
link_shared_lib=False,
include='',
body='',
compile_postargs=None,
link_postargs=None,
): # pylint: disable=too-many-arguments,too-many-branches
"""Return a boolean indicating whether a flag name is supported on the ... | Return a boolean indicating whether a flag name is supported on the specified compiler. | compiler_test | python | ProjectQ-Framework/ProjectQ | setup.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/setup.py | Apache-2.0 |
def has_ext_modules(self):
"""Return whether this distribution has some external modules."""
# We want to always claim that we have ext_modules. This will be fine
# if we don't actually have them (such as on PyPy) because nothing
# will get built, however we don't want to provide an over... | Return whether this distribution has some external modules. | has_ext_modules | python | ProjectQ-Framework/ProjectQ | setup.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/setup.py | Apache-2.0 |
def recursive_getattr(obj, attr, *args):
"""Recursively get the attributes of a Python object."""
def _getattr(obj, attr):
return getattr(obj, attr, *args)
return functools.reduce(_getattr, [obj] + attr.split('.')) | Recursively get the attributes of a Python object. | recursive_getattr | python | ProjectQ-Framework/ProjectQ | docs/conf.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/docs/conf.py | Apache-2.0 |
def linkcode_resolve(domain, info):
"""Change URLs in documentation on the fly."""
# Copyright 2018 ProjectQ (www.projectq.ch), all rights reserved.
on_rtd = os.environ.get('READTHEDOCS') == 'True'
github_url = "https://github.com/ProjectQ-Framework/ProjectQ/tree/"
github_tag = 'v' + version
if ... | Change URLs in documentation on the fly. | linkcode_resolve | python | ProjectQ-Framework/ProjectQ | docs/conf.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/docs/conf.py | Apache-2.0 |
def __init__( # pylint: disable=too-many-arguments
self,
pkg_name,
desc='',
module_special_members='__init__',
submodule_special_members='',
submodules_desc='',
helper_submodules=None,
):
"""
Initialize a PackageDescription object.
Ar... |
Initialize a PackageDescription object.
Args:
name (str): Name of ProjectQ module
desc (str): (optional) Description of module
module_special_members (str): (optional) Special members to include in the documentation of the module
submodule_special_member... | __init__ | python | ProjectQ-Framework/ProjectQ | docs/package_description.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/docs/package_description.py | Apache-2.0 |
def run_entangle(eng, num_qubits=3):
"""
Run an entangling operation on the provided compiler engine.
Args:
eng (MainEngine): Main compiler engine to use.
num_qubits (int): Number of qubits to entangle.
Returns:
measurement (list<int>): List of measurement outcomes.
"""
... |
Run an entangling operation on the provided compiler engine.
Args:
eng (MainEngine): Main compiler engine to use.
num_qubits (int): Number of qubits to entangle.
Returns:
measurement (list<int>): List of measurement outcomes.
| run_entangle | python | ProjectQ-Framework/ProjectQ | examples/aqt.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/examples/aqt.py | Apache-2.0 |
def zoo_profile():
"""Generate and display the zoo of quantum gates."""
# create a main compiler engine with a drawing backend
drawing_engine = CircuitDrawer()
locations = {0: 1, 1: 2, 2: 0, 3: 3}
drawing_engine.set_qubit_locations(locations)
main_eng = MainEngine(drawing_engine)
qureg = mai... | Generate and display the zoo of quantum gates. | zoo_profile | python | ProjectQ-Framework/ProjectQ | examples/gate_zoo.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/examples/gate_zoo.py | Apache-2.0 |
def openfile(filename):
"""
Open a file.
Args:
filename (str): the target file.
Return:
bool: succeed if True.
"""
platform = sys.platform
if platform == "linux" or platform == "linux2":
os.system('xdg-open %s' % filename)
elif platform == "darwin":
os.s... |
Open a file.
Args:
filename (str): the target file.
Return:
bool: succeed if True.
| openfile | python | ProjectQ-Framework/ProjectQ | examples/gate_zoo.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/examples/gate_zoo.py | Apache-2.0 |
def run_grover(eng, n, oracle):
"""
Run Grover's algorithm on n qubit using the provided quantum oracle.
Args:
eng (MainEngine): Main compiler engine to run Grover on.
n (int): Number of bits in the solution.
oracle (function): Function accepting the engine, an n-qubit register,
... |
Run Grover's algorithm on n qubit using the provided quantum oracle.
Args:
eng (MainEngine): Main compiler engine to run Grover on.
n (int): Number of bits in the solution.
oracle (function): Function accepting the engine, an n-qubit register,
and an output qubit which is f... | run_grover | python | ProjectQ-Framework/ProjectQ | examples/grover.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/examples/grover.py | Apache-2.0 |
def alternating_bits_oracle(eng, qubits, output):
"""
Alternating bit oracle.
Mark the solution string 1,0,1,0,...,0,1 by flipping the output qubit, conditioned on qubits being equal to the
alternating bit-string.
Args:
eng (MainEngine): Main compiler engine the algorithm is being run on.
... |
Alternating bit oracle.
Mark the solution string 1,0,1,0,...,0,1 by flipping the output qubit, conditioned on qubits being equal to the
alternating bit-string.
Args:
eng (MainEngine): Main compiler engine the algorithm is being run on.
qubits (Qureg): n-qubit quantum register Grover s... | alternating_bits_oracle | python | ProjectQ-Framework/ProjectQ | examples/grover.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/examples/grover.py | Apache-2.0 |
def run_shor(eng, N, a, verbose=False):
"""
Run the quantum subroutine of Shor's algorithm for factoring.
Args:
eng (MainEngine): Main compiler engine to use.
N (int): Number to factor.
a (int): Relative prime to use as a base for a^x mod N.
verbose (bool): If True, display ... |
Run the quantum subroutine of Shor's algorithm for factoring.
Args:
eng (MainEngine): Main compiler engine to use.
N (int): Number to factor.
a (int): Relative prime to use as a base for a^x mod N.
verbose (bool): If True, display intermediate measurement results.
Returns:... | run_shor | python | ProjectQ-Framework/ProjectQ | examples/shor.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/examples/shor.py | Apache-2.0 |
def create_bell_pair(eng):
r"""
Create a Bell pair state with two qubits.
Returns a Bell-pair (two qubits in state :math:`|A\rangle \otimes |B \rangle = \frac 1{\sqrt 2} \left(
|0\rangle\otimes|0\rangle + |1\rangle \otimes|1\rangle \right)`).
Args:
eng (MainEngine): MainEngine from which t... |
Create a Bell pair state with two qubits.
Returns a Bell-pair (two qubits in state :math:`|A\rangle \otimes |B \rangle = \frac 1{\sqrt 2} \left(
|0\rangle\otimes|0\rangle + |1\rangle \otimes|1\rangle \right)`).
Args:
eng (MainEngine): MainEngine from which to allocate the qubits.
Returns... | create_bell_pair | python | ProjectQ-Framework/ProjectQ | examples/teleport.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/examples/teleport.py | Apache-2.0 |
def run_teleport(eng, state_creation_function, verbose=False):
"""
Run quantum teleportation on the provided main compiler engine.
Creates a state from |0> using the state_creation_function, teleports this state to Bob who then tries to
uncompute his qubit using the inverse of the state_creation_functi... |
Run quantum teleportation on the provided main compiler engine.
Creates a state from |0> using the state_creation_function, teleports this state to Bob who then tries to
uncompute his qubit using the inverse of the state_creation_function. If successful, deleting the qubit won't
raise an error in the ... | run_teleport | python | ProjectQ-Framework/ProjectQ | examples/teleport.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/examples/teleport.py | Apache-2.0 |
def run_circuit(eng, n_qubits, circuit_num, gate_after_measure=False):
"""Run a quantum circuit demonstrating the capabilities of the UnitarySimulator."""
qureg = eng.allocate_qureg(n_qubits)
if circuit_num == 1:
All(X) | qureg
elif circuit_num == 2:
X | qureg[0]
with Control(en... | Run a quantum circuit demonstrating the capabilities of the UnitarySimulator. | run_circuit | python | ProjectQ-Framework/ProjectQ | examples/unitary_simulator.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/examples/unitary_simulator.py | Apache-2.0 |
def main():
"""Definition of the main function of this example."""
# Create a MainEngine with a unitary simulator backend
eng = MainEngine(backend=UnitarySimulator())
n_qubits = 3
# Run out quantum circuit
# 1 - circuit applying X on all qubits
# 2 - circuit applying an X gate followed... | Definition of the main function of this example. | main | python | ProjectQ-Framework/ProjectQ | examples/unitary_simulator.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/examples/unitary_simulator.py | Apache-2.0 |
def __init__(self, accept_input=True, default_measure=False, in_place=False):
"""
Initialize a CommandPrinter.
Args:
accept_input (bool): If accept_input is true, the printer queries the user to input measurement results if
the CommandPrinter is the last engine. Othe... |
Initialize a CommandPrinter.
Args:
accept_input (bool): If accept_input is true, the printer queries the user to input measurement results if
the CommandPrinter is the last engine. Otherwise, all measurements yield default_measure.
default_measure (bool): Defaul... | __init__ | python | ProjectQ-Framework/ProjectQ | projectq/backends/_printer.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_printer.py | Apache-2.0 |
def is_available(self, cmd):
"""
Test whether a Command is supported by a compiler engine.
Specialized implementation of is_available: Returns True if the CommandPrinter is the last engine (since it
can print any command).
Args:
cmd (Command): Command of which to ch... |
Test whether a Command is supported by a compiler engine.
Specialized implementation of is_available: Returns True if the CommandPrinter is the last engine (since it
can print any command).
Args:
cmd (Command): Command of which to check availability (all Commands can be pr... | is_available | python | ProjectQ-Framework/ProjectQ | projectq/backends/_printer.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_printer.py | Apache-2.0 |
def _print_cmd(self, cmd):
"""
Print a command.
Print a command or, if the command is a measurement instruction and the CommandPrinter is the last engine in
the engine pipeline: Query the user for the measurement result (if accept_input = True) / Set the result to 0
(if it's Fal... |
Print a command.
Print a command or, if the command is a measurement instruction and the CommandPrinter is the last engine in
the engine pipeline: Query the user for the measurement result (if accept_input = True) / Set the result to 0
(if it's False).
Args:
cmd (C... | _print_cmd | python | ProjectQ-Framework/ProjectQ | projectq/backends/_printer.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_printer.py | Apache-2.0 |
def receive(self, command_list):
"""
Receive a list of commands.
Receive a list of commands from the previous engine, print the
commands, and then send them on to the next engine.
Args:
command_list (list<Command>): List of Commands to print (and
pot... |
Receive a list of commands.
Receive a list of commands from the previous engine, print the
commands, and then send them on to the next engine.
Args:
command_list (list<Command>): List of Commands to print (and
potentially send on to the next engine).
... | receive | python | ProjectQ-Framework/ProjectQ | projectq/backends/_printer.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_printer.py | Apache-2.0 |
def __init__(self):
"""
Initialize a resource counter engine.
Sets all statistics to zero.
"""
super().__init__()
self.gate_counts = {}
self.gate_class_counts = {}
self._active_qubits = 0
self.max_width = 0
# key: qubit id, depth of this q... |
Initialize a resource counter engine.
Sets all statistics to zero.
| __init__ | python | ProjectQ-Framework/ProjectQ | projectq/backends/_resource.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_resource.py | Apache-2.0 |
def is_available(self, cmd):
"""
Test whether a Command is supported by a compiler engine.
Specialized implementation of is_available: Returns True if the ResourceCounter is the last engine (since it
can count any command).
Args:
cmd (Command): Command for which to ... |
Test whether a Command is supported by a compiler engine.
Specialized implementation of is_available: Returns True if the ResourceCounter is the last engine (since it
can count any command).
Args:
cmd (Command): Command for which to check availability (all Commands can be ... | is_available | python | ProjectQ-Framework/ProjectQ | projectq/backends/_resource.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_resource.py | Apache-2.0 |
def depth_of_dag(self):
"""Return the depth of the DAG."""
if self._depth_of_qubit:
current_max = max(self._depth_of_qubit.values())
return max(current_max, self._previous_max_depth)
return self._previous_max_depth | Return the depth of the DAG. | depth_of_dag | python | ProjectQ-Framework/ProjectQ | projectq/backends/_resource.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_resource.py | Apache-2.0 |
def __str__(self):
"""
Return the string representation of this ResourceCounter.
Returns:
A summary (string) of resources used, including gates, number of calls, and max. number of qubits that
were active at the same time.
"""
if len(self.gate_counts)... |
Return the string representation of this ResourceCounter.
Returns:
A summary (string) of resources used, including gates, number of calls, and max. number of qubits that
were active at the same time.
| __str__ | python | ProjectQ-Framework/ProjectQ | projectq/backends/_resource.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_resource.py | Apache-2.0 |
def receive(self, command_list):
"""
Receive a list of commands.
Receive a list of commands from the previous engine, increases the counters of the received commands, and then
send them on to the next engine.
Args:
command_list (list<Command>): List of commands to r... |
Receive a list of commands.
Receive a list of commands from the previous engine, increases the counters of the received commands, and then
send them on to the next engine.
Args:
command_list (list<Command>): List of commands to receive (and count).
| receive | python | ProjectQ-Framework/ProjectQ | projectq/backends/_resource.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_resource.py | Apache-2.0 |
def _qidmask(target_ids, control_ids, n_qubits):
"""
Calculate index masks.
Args:
target_ids (list): list of target qubit indices
control_ids (list): list of control qubit indices
control_state (list): list of states for the control qubits (0 or 1)
n_qubits (int): number of ... |
Calculate index masks.
Args:
target_ids (list): list of target qubit indices
control_ids (list): list of control qubit indices
control_state (list): list of states for the control qubits (0 or 1)
n_qubits (int): number of qubits
| _qidmask | python | ProjectQ-Framework/ProjectQ | projectq/backends/_unitary.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_unitary.py | Apache-2.0 |
def is_available(self, cmd):
"""
Test whether a Command is supported by a compiler engine.
Specialized implementation of is_available: The unitary simulator can deal with all arbitrarily-controlled gates
which provide a gate-matrix (via gate.matrix).
Args:
cmd (Comm... |
Test whether a Command is supported by a compiler engine.
Specialized implementation of is_available: The unitary simulator can deal with all arbitrarily-controlled gates
which provide a gate-matrix (via gate.matrix).
Args:
cmd (Command): Command for which to check availab... | is_available | python | ProjectQ-Framework/ProjectQ | projectq/backends/_unitary.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_unitary.py | Apache-2.0 |
def receive(self, command_list):
"""
Receive a list of commands.
Receive a list of commands from the previous engine and handle them:
* update the unitary of the quantum circuit
* update the internal quantum state if a measurement or a qubit deallocation occurs
... |
Receive a list of commands.
Receive a list of commands from the previous engine and handle them:
* update the unitary of the quantum circuit
* update the internal quantum state if a measurement or a qubit deallocation occurs
prior to sending them on to the next engine.... | receive | python | ProjectQ-Framework/ProjectQ | projectq/backends/_unitary.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_unitary.py | Apache-2.0 |
def _handle(self, cmd):
"""
Handle all commands.
Args:
cmd (Command): Command to handle.
Raises:
RuntimeError: If a measurement is performed before flush gate.
"""
if isinstance(cmd.gate, AllocateQubitGate):
self._qubit_map[cmd.qubits... |
Handle all commands.
Args:
cmd (Command): Command to handle.
Raises:
RuntimeError: If a measurement is performed before flush gate.
| _handle | python | ProjectQ-Framework/ProjectQ | projectq/backends/_unitary.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_unitary.py | Apache-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.