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 75 19.8k | code_tokens listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1 value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
gvanderheide/discreteMarkovChain | discreteMarkovChain/markovChain.py | markovChain.printPi | def printPi(self):
"""
Prints all states state and their steady state probabilities.
Not recommended for large state spaces.
"""
assert self.pi is not None, "Calculate pi before calling printPi()"
assert len(self.mapping)>0, "printPi() can only be used in combination with the direct or indirect method. Use print(mc.pi) if your subclass is called mc."
for key,state in self.mapping.items():
print(state,self.pi[key]) | python | def printPi(self):
"""
Prints all states state and their steady state probabilities.
Not recommended for large state spaces.
"""
assert self.pi is not None, "Calculate pi before calling printPi()"
assert len(self.mapping)>0, "printPi() can only be used in combination with the direct or indirect method. Use print(mc.pi) if your subclass is called mc."
for key,state in self.mapping.items():
print(state,self.pi[key]) | [
"def",
"printPi",
"(",
"self",
")",
":",
"assert",
"self",
".",
"pi",
"is",
"not",
"None",
",",
"\"Calculate pi before calling printPi()\"",
"assert",
"len",
"(",
"self",
".",
"mapping",
")",
">",
"0",
",",
"\"printPi() can only be used in combination with the direc... | Prints all states state and their steady state probabilities.
Not recommended for large state spaces. | [
"Prints",
"all",
"states",
"state",
"and",
"their",
"steady",
"state",
"probabilities",
".",
"Not",
"recommended",
"for",
"large",
"state",
"spaces",
"."
] | 8325ffdb791c109eee600684ee0dc9126ce80700 | https://github.com/gvanderheide/discreteMarkovChain/blob/8325ffdb791c109eee600684ee0dc9126ce80700/discreteMarkovChain/markovChain.py#L596-L604 | train | 31,900 |
insilichem/pychimera | pychimera/platforms/win.py | launch_ipython | def launch_ipython(argv=None):
"""
Force usage of QtConsole under Windows
"""
from .linux import launch_ipython as _launch_ipython_linux
os.environ = {str(k): str(v) for k,v in os.environ.items()}
try:
from qtconsole.qtconsoleapp import JupyterQtConsoleApp
except ImportError:
sys.exit("ERROR: IPython QtConsole not installed in this environment. "
"Try with `conda install jupyter ipython qtconsole`")
else:
_launch_ipython_linux(ipython_app=JupyterQtConsoleApp) | python | def launch_ipython(argv=None):
"""
Force usage of QtConsole under Windows
"""
from .linux import launch_ipython as _launch_ipython_linux
os.environ = {str(k): str(v) for k,v in os.environ.items()}
try:
from qtconsole.qtconsoleapp import JupyterQtConsoleApp
except ImportError:
sys.exit("ERROR: IPython QtConsole not installed in this environment. "
"Try with `conda install jupyter ipython qtconsole`")
else:
_launch_ipython_linux(ipython_app=JupyterQtConsoleApp) | [
"def",
"launch_ipython",
"(",
"argv",
"=",
"None",
")",
":",
"from",
".",
"linux",
"import",
"launch_ipython",
"as",
"_launch_ipython_linux",
"os",
".",
"environ",
"=",
"{",
"str",
"(",
"k",
")",
":",
"str",
"(",
"v",
")",
"for",
"k",
",",
"v",
"in",... | Force usage of QtConsole under Windows | [
"Force",
"usage",
"of",
"QtConsole",
"under",
"Windows"
] | 5227d1c0e9e1ce165fc68157eda788cd0843842b | https://github.com/insilichem/pychimera/blob/5227d1c0e9e1ce165fc68157eda788cd0843842b/pychimera/platforms/win.py#L44-L56 | train | 31,901 |
insilichem/pychimera | pychimera/platforms/linux.py | launch_ipython | def launch_ipython(argv=None, ipython_app=None):
"""
Launch IPython from this interpreter with custom args if needed.
Chimera magic commands are also enabled automatically.
"""
try:
if ipython_app is None:
from IPython.terminal.ipapp import TerminalIPythonApp as ipython_app
from traitlets.config import Config
except ImportError:
sys.exit("ERROR: IPython not installed in this environment. "
"Try with `conda install ipython`")
else:
# launch_new_instance(argv)
app = ipython_app()
c = Config()
code = ["from pychimera import enable_chimera_inline",
"enable_chimera_inline()"]
c.InteractiveShellApp.exec_lines = code
app.update_config(c)
app.initialize(argv)
app.start() | python | def launch_ipython(argv=None, ipython_app=None):
"""
Launch IPython from this interpreter with custom args if needed.
Chimera magic commands are also enabled automatically.
"""
try:
if ipython_app is None:
from IPython.terminal.ipapp import TerminalIPythonApp as ipython_app
from traitlets.config import Config
except ImportError:
sys.exit("ERROR: IPython not installed in this environment. "
"Try with `conda install ipython`")
else:
# launch_new_instance(argv)
app = ipython_app()
c = Config()
code = ["from pychimera import enable_chimera_inline",
"enable_chimera_inline()"]
c.InteractiveShellApp.exec_lines = code
app.update_config(c)
app.initialize(argv)
app.start() | [
"def",
"launch_ipython",
"(",
"argv",
"=",
"None",
",",
"ipython_app",
"=",
"None",
")",
":",
"try",
":",
"if",
"ipython_app",
"is",
"None",
":",
"from",
"IPython",
".",
"terminal",
".",
"ipapp",
"import",
"TerminalIPythonApp",
"as",
"ipython_app",
"from",
... | Launch IPython from this interpreter with custom args if needed.
Chimera magic commands are also enabled automatically. | [
"Launch",
"IPython",
"from",
"this",
"interpreter",
"with",
"custom",
"args",
"if",
"needed",
".",
"Chimera",
"magic",
"commands",
"are",
"also",
"enabled",
"automatically",
"."
] | 5227d1c0e9e1ce165fc68157eda788cd0843842b | https://github.com/insilichem/pychimera/blob/5227d1c0e9e1ce165fc68157eda788cd0843842b/pychimera/platforms/linux.py#L46-L67 | train | 31,902 |
insilichem/pychimera | pychimera/jupyter_utils.py | launch_notebook | def launch_notebook(argv=None):
"""
Launch a Jupyter Notebook, with custom Untitled filenames and
a prepopulated first cell with necessary boilerplate code.
Notes
-----
To populate the first cell, the function `new_notebook` imported
in notebook.services.contents needs to be monkey patched. Dirty
but functional. Same thing could be achieved with custom.js or
a ContentsManager subclass, but this is easier!
"""
try:
import nbformat.v4 as nbf
from notebook.notebookapp import NotebookApp
from notebook.services.contents import manager
from traitlets.config import Config
except ImportError:
sys.exit("ERROR: Jupyter Notebook not installed in this environment. "
"Try with `conda install ipython jupyter notebook`")
else:
nbf._original_new_notebook = nbf.new_notebook
def _prepopulate_nb_patch():
nb = nbf._original_new_notebook()
cell = nbf.new_code_cell("# Run this cell to complete Chimera initialization\n"
"from pychimera import enable_chimera, enable_chimera_inline, chimera_view\n"
"enable_chimera()\nenable_chimera_inline()\nimport chimera")
nb['cells'].append(cell)
return nb
manager.new_notebook = _prepopulate_nb_patch
app = NotebookApp()
c = Config()
c.FileContentsManager.untitled_notebook = "Untitled PyChimera Notebook"
app.update_config(c)
app.initialize(argv)
app.start() | python | def launch_notebook(argv=None):
"""
Launch a Jupyter Notebook, with custom Untitled filenames and
a prepopulated first cell with necessary boilerplate code.
Notes
-----
To populate the first cell, the function `new_notebook` imported
in notebook.services.contents needs to be monkey patched. Dirty
but functional. Same thing could be achieved with custom.js or
a ContentsManager subclass, but this is easier!
"""
try:
import nbformat.v4 as nbf
from notebook.notebookapp import NotebookApp
from notebook.services.contents import manager
from traitlets.config import Config
except ImportError:
sys.exit("ERROR: Jupyter Notebook not installed in this environment. "
"Try with `conda install ipython jupyter notebook`")
else:
nbf._original_new_notebook = nbf.new_notebook
def _prepopulate_nb_patch():
nb = nbf._original_new_notebook()
cell = nbf.new_code_cell("# Run this cell to complete Chimera initialization\n"
"from pychimera import enable_chimera, enable_chimera_inline, chimera_view\n"
"enable_chimera()\nenable_chimera_inline()\nimport chimera")
nb['cells'].append(cell)
return nb
manager.new_notebook = _prepopulate_nb_patch
app = NotebookApp()
c = Config()
c.FileContentsManager.untitled_notebook = "Untitled PyChimera Notebook"
app.update_config(c)
app.initialize(argv)
app.start() | [
"def",
"launch_notebook",
"(",
"argv",
"=",
"None",
")",
":",
"try",
":",
"import",
"nbformat",
".",
"v4",
"as",
"nbf",
"from",
"notebook",
".",
"notebookapp",
"import",
"NotebookApp",
"from",
"notebook",
".",
"services",
".",
"contents",
"import",
"manager"... | Launch a Jupyter Notebook, with custom Untitled filenames and
a prepopulated first cell with necessary boilerplate code.
Notes
-----
To populate the first cell, the function `new_notebook` imported
in notebook.services.contents needs to be monkey patched. Dirty
but functional. Same thing could be achieved with custom.js or
a ContentsManager subclass, but this is easier! | [
"Launch",
"a",
"Jupyter",
"Notebook",
"with",
"custom",
"Untitled",
"filenames",
"and",
"a",
"prepopulated",
"first",
"cell",
"with",
"necessary",
"boilerplate",
"code",
"."
] | 5227d1c0e9e1ce165fc68157eda788cd0843842b | https://github.com/insilichem/pychimera/blob/5227d1c0e9e1ce165fc68157eda788cd0843842b/pychimera/jupyter_utils.py#L28-L63 | train | 31,903 |
insilichem/pychimera | pychimera/jupyter_utils.py | enable_chimera_inline | def enable_chimera_inline():
"""
Enable IPython magic commands to run some Chimera actions
Currently supported:
- %chimera_export_3D [<model>]:
Depicts the Chimera 3D canvas in a WebGL iframe. Requires
a headless Chimera build and a Notebook instance. SLOW.
- %chimera_run <command>:
Runs Chimera commands meant to be input in the GUI command line
"""
from IPython.display import IFrame
from IPython.core.magic import register_line_magic
import chimera
import Midas
@register_line_magic
def chimera_export_3D(line):
if chimera.viewer.__class__.__name__ == 'NoGuiViewer':
print('This magic requires a headless Chimera build. '
'Check http://www.cgl.ucsf.edu/chimera/download.html#unsupported.',
file=sys.stderr)
return
models = eval(line) if line else []
def html(*models):
if models:
for m in chimera.openModels.list():
m.display = False
chimera.selection.clearCurrent()
for model in models:
model.display = True
chimera.selection.addCurrent(model)
chimera.runCommand('focus sel')
chimera.viewer.windowSize = 800, 600
path = 'chimera_scene_export.html'
Midas.export(filename=path, format='WebGL')
return IFrame(path, *[x + 20 for x in chimera.viewer.windowSize])
return html(*models)
del chimera_export_3D
@register_line_magic
def chimera_run(line):
if not line:
print("Usage: %chimera_run <chimera command>", file=sys.stderr)
return
chimera.runCommand(line)
del chimera_run | python | def enable_chimera_inline():
"""
Enable IPython magic commands to run some Chimera actions
Currently supported:
- %chimera_export_3D [<model>]:
Depicts the Chimera 3D canvas in a WebGL iframe. Requires
a headless Chimera build and a Notebook instance. SLOW.
- %chimera_run <command>:
Runs Chimera commands meant to be input in the GUI command line
"""
from IPython.display import IFrame
from IPython.core.magic import register_line_magic
import chimera
import Midas
@register_line_magic
def chimera_export_3D(line):
if chimera.viewer.__class__.__name__ == 'NoGuiViewer':
print('This magic requires a headless Chimera build. '
'Check http://www.cgl.ucsf.edu/chimera/download.html#unsupported.',
file=sys.stderr)
return
models = eval(line) if line else []
def html(*models):
if models:
for m in chimera.openModels.list():
m.display = False
chimera.selection.clearCurrent()
for model in models:
model.display = True
chimera.selection.addCurrent(model)
chimera.runCommand('focus sel')
chimera.viewer.windowSize = 800, 600
path = 'chimera_scene_export.html'
Midas.export(filename=path, format='WebGL')
return IFrame(path, *[x + 20 for x in chimera.viewer.windowSize])
return html(*models)
del chimera_export_3D
@register_line_magic
def chimera_run(line):
if not line:
print("Usage: %chimera_run <chimera command>", file=sys.stderr)
return
chimera.runCommand(line)
del chimera_run | [
"def",
"enable_chimera_inline",
"(",
")",
":",
"from",
"IPython",
".",
"display",
"import",
"IFrame",
"from",
"IPython",
".",
"core",
".",
"magic",
"import",
"register_line_magic",
"import",
"chimera",
"import",
"Midas",
"@",
"register_line_magic",
"def",
"chimera... | Enable IPython magic commands to run some Chimera actions
Currently supported:
- %chimera_export_3D [<model>]:
Depicts the Chimera 3D canvas in a WebGL iframe. Requires
a headless Chimera build and a Notebook instance. SLOW.
- %chimera_run <command>:
Runs Chimera commands meant to be input in the GUI command line | [
"Enable",
"IPython",
"magic",
"commands",
"to",
"run",
"some",
"Chimera",
"actions"
] | 5227d1c0e9e1ce165fc68157eda788cd0843842b | https://github.com/insilichem/pychimera/blob/5227d1c0e9e1ce165fc68157eda788cd0843842b/pychimera/jupyter_utils.py#L77-L125 | train | 31,904 |
insilichem/pychimera | pychimera/jupyter_utils.py | chimera_view | def chimera_view(*molecules):
"""
Depicts the requested molecules with NGLViewer in a Python notebook.
This method does not require a headless Chimera build, however.
Parameters
----------
molecules : tuple of chimera.Molecule
Molecules to display. If none is given, all present molecules
in Chimera canvas will be displayed.
"""
try:
import nglview as nv
except ImportError:
raise ImportError('You must install nglview!')
import chimera
class _ChimeraStructure(nv.Structure):
def __init__(self, *molecules):
if not molecules:
raise ValueError('Please supply at least one chimera.Molecule.')
self.ext = "pdb"
self.params = {}
self.id = str(id(molecules[0]))
self.molecules = molecules
def get_structure_string(self):
s = StringIO()
chimera.pdbWrite(self.molecules, self.molecules[0].openState.xform, s)
return s.getvalue()
if not molecules:
molecules = chimera.openModels.list(modelTypes=[chimera.Molecule])
structure = _ChimeraStructure(*molecules)
return nv.NGLWidget(structure) | python | def chimera_view(*molecules):
"""
Depicts the requested molecules with NGLViewer in a Python notebook.
This method does not require a headless Chimera build, however.
Parameters
----------
molecules : tuple of chimera.Molecule
Molecules to display. If none is given, all present molecules
in Chimera canvas will be displayed.
"""
try:
import nglview as nv
except ImportError:
raise ImportError('You must install nglview!')
import chimera
class _ChimeraStructure(nv.Structure):
def __init__(self, *molecules):
if not molecules:
raise ValueError('Please supply at least one chimera.Molecule.')
self.ext = "pdb"
self.params = {}
self.id = str(id(molecules[0]))
self.molecules = molecules
def get_structure_string(self):
s = StringIO()
chimera.pdbWrite(self.molecules, self.molecules[0].openState.xform, s)
return s.getvalue()
if not molecules:
molecules = chimera.openModels.list(modelTypes=[chimera.Molecule])
structure = _ChimeraStructure(*molecules)
return nv.NGLWidget(structure) | [
"def",
"chimera_view",
"(",
"*",
"molecules",
")",
":",
"try",
":",
"import",
"nglview",
"as",
"nv",
"except",
"ImportError",
":",
"raise",
"ImportError",
"(",
"'You must install nglview!'",
")",
"import",
"chimera",
"class",
"_ChimeraStructure",
"(",
"nv",
".",... | Depicts the requested molecules with NGLViewer in a Python notebook.
This method does not require a headless Chimera build, however.
Parameters
----------
molecules : tuple of chimera.Molecule
Molecules to display. If none is given, all present molecules
in Chimera canvas will be displayed. | [
"Depicts",
"the",
"requested",
"molecules",
"with",
"NGLViewer",
"in",
"a",
"Python",
"notebook",
".",
"This",
"method",
"does",
"not",
"require",
"a",
"headless",
"Chimera",
"build",
"however",
"."
] | 5227d1c0e9e1ce165fc68157eda788cd0843842b | https://github.com/insilichem/pychimera/blob/5227d1c0e9e1ce165fc68157eda788cd0843842b/pychimera/jupyter_utils.py#L128-L163 | train | 31,905 |
insilichem/pychimera | pychimera/core.py | enable_chimera | def enable_chimera(verbose=False, nogui=True):
"""
Bypass script loading and initialize Chimera correctly, once
the env has been properly patched.
Parameters
----------
verbose : bool, optional, default=False
If True, let Chimera speak freely. It can be _very_ verbose.
nogui : bool, optional, default=True
Don't start the GUI.
"""
if os.getenv('CHIMERA_ENABLED'):
return
import chimera
_pre_gui_patches()
if not nogui:
chimera.registerPostGraphicsFunc(_post_gui_patches)
try:
import chimeraInit
if verbose:
chimera.replyobj.status('initializing pychimera')
except ImportError as e:
sys.exit(str(e) + "\nERROR: Chimera could not be loaded!")
chimeraInit.init(['', '--script', NULL] + (sys.argv[1:] if not nogui else []),
debug=verbose, silent=not verbose, nostatus=not verbose,
nogui=nogui, eventloop=not nogui, exitonquit=not nogui,
title=chimera.title+' (PyChimera)')
os.environ['CHIMERA_ENABLED'] = '1' | python | def enable_chimera(verbose=False, nogui=True):
"""
Bypass script loading and initialize Chimera correctly, once
the env has been properly patched.
Parameters
----------
verbose : bool, optional, default=False
If True, let Chimera speak freely. It can be _very_ verbose.
nogui : bool, optional, default=True
Don't start the GUI.
"""
if os.getenv('CHIMERA_ENABLED'):
return
import chimera
_pre_gui_patches()
if not nogui:
chimera.registerPostGraphicsFunc(_post_gui_patches)
try:
import chimeraInit
if verbose:
chimera.replyobj.status('initializing pychimera')
except ImportError as e:
sys.exit(str(e) + "\nERROR: Chimera could not be loaded!")
chimeraInit.init(['', '--script', NULL] + (sys.argv[1:] if not nogui else []),
debug=verbose, silent=not verbose, nostatus=not verbose,
nogui=nogui, eventloop=not nogui, exitonquit=not nogui,
title=chimera.title+' (PyChimera)')
os.environ['CHIMERA_ENABLED'] = '1' | [
"def",
"enable_chimera",
"(",
"verbose",
"=",
"False",
",",
"nogui",
"=",
"True",
")",
":",
"if",
"os",
".",
"getenv",
"(",
"'CHIMERA_ENABLED'",
")",
":",
"return",
"import",
"chimera",
"_pre_gui_patches",
"(",
")",
"if",
"not",
"nogui",
":",
"chimera",
... | Bypass script loading and initialize Chimera correctly, once
the env has been properly patched.
Parameters
----------
verbose : bool, optional, default=False
If True, let Chimera speak freely. It can be _very_ verbose.
nogui : bool, optional, default=True
Don't start the GUI. | [
"Bypass",
"script",
"loading",
"and",
"initialize",
"Chimera",
"correctly",
"once",
"the",
"env",
"has",
"been",
"properly",
"patched",
"."
] | 5227d1c0e9e1ce165fc68157eda788cd0843842b | https://github.com/insilichem/pychimera/blob/5227d1c0e9e1ce165fc68157eda788cd0843842b/pychimera/core.py#L37-L65 | train | 31,906 |
insilichem/pychimera | pychimera/core.py | patch_sys_version | def patch_sys_version():
""" Remove Continuum copyright statement to avoid parsing errors in IDLE """
if '|' in sys.version:
sys_version = sys.version.split('|')
sys.version = ' '.join([sys_version[0].strip(), sys_version[-1].strip()]) | python | def patch_sys_version():
""" Remove Continuum copyright statement to avoid parsing errors in IDLE """
if '|' in sys.version:
sys_version = sys.version.split('|')
sys.version = ' '.join([sys_version[0].strip(), sys_version[-1].strip()]) | [
"def",
"patch_sys_version",
"(",
")",
":",
"if",
"'|'",
"in",
"sys",
".",
"version",
":",
"sys_version",
"=",
"sys",
".",
"version",
".",
"split",
"(",
"'|'",
")",
"sys",
".",
"version",
"=",
"' '",
".",
"join",
"(",
"[",
"sys_version",
"[",
"0",
"... | Remove Continuum copyright statement to avoid parsing errors in IDLE | [
"Remove",
"Continuum",
"copyright",
"statement",
"to",
"avoid",
"parsing",
"errors",
"in",
"IDLE"
] | 5227d1c0e9e1ce165fc68157eda788cd0843842b | https://github.com/insilichem/pychimera/blob/5227d1c0e9e1ce165fc68157eda788cd0843842b/pychimera/core.py#L100-L104 | train | 31,907 |
insilichem/pychimera | pychimera/core.py | patch_environ | def patch_environ(nogui=True):
"""
Patch current environment variables so Chimera can start up and we can import its modules.
Be warned that calling this function WILL restart your interpreter. Otherwise, Python
won't catch the new LD_LIBRARY_PATH (or platform equivalent) and Chimera won't find its
libraries during import.
Parameters
----------
nogui : bool, optional, default=False
If the GUI is not going to be launched, try to locate a headless
Chimera build to enable inline Chimera visualization.
"""
if 'CHIMERA' in os.environ:
return
paths = guess_chimera_path(search_all=nogui)
CHIMERA_BASE = paths[0]
if nogui: # try finding a headless version
try:
CHIMERA_BASE = next(p for p in paths if 'headless' in p)
except StopIteration:
pass
if not os.path.isdir(CHIMERA_BASE):
sys.exit("Could not find UCSF Chimera.\n{}".format(_INSTRUCTIONS))
os.environ['CHIMERA'] = CHIMERA_BASE
CHIMERA_LIB = os.path.join(CHIMERA_BASE, 'lib')
# Set Tcl/Tk for gui mode
if 'TCL_LIBRARY' in os.environ:
os.environ['CHIMERA_TCL_LIBRARY'] = os.environ['TCL_LIBRARY']
os.environ['TCL_LIBRARY'] = os.path.join(CHIMERA_LIB, 'tcl8.6')
if 'TCLLIBPATH' in os.environ:
os.environ['CHIMERA_TCLLIBPATH'] = os.environ['TCLLIBPATH']
os.environ['TCLLIBPATH'] = '{' + CHIMERA_LIB + '}'
if 'TK_LIBRARY' in os.environ:
os.environ['CHIMERA_TK_LIBRARY'] = os.environ['TK_LIBRARY']
del os.environ['TK_LIBRARY']
if 'TIX_LIBRARY' in os.environ:
os.environ['CHIMERA_TIX_LIBRARY'] = os.environ['TIX_LIBRARY']
del os.environ['TIX_LIBRARY']
if 'PYTHONNOUSERSITE' in os.environ:
os.environ['CHIMERA_PYTHONNOUSERSITE'] = os.environ['PYTHONNOUSERSITE']
os.environ['PYTHONNOUSERSITE'] = '1'
# Check interactive and IPython
if in_ipython() and hasattr(sys, 'ps1') and not sys.argv[0].endswith('ipython'):
sys.argv.insert(1, 'ipython')
# Platform-specific patches
patch_environ_for_platform(CHIMERA_BASE, CHIMERA_LIB, nogui=nogui)
os.execve(sys.executable, [sys.executable] + sys.argv, os.environ) | python | def patch_environ(nogui=True):
"""
Patch current environment variables so Chimera can start up and we can import its modules.
Be warned that calling this function WILL restart your interpreter. Otherwise, Python
won't catch the new LD_LIBRARY_PATH (or platform equivalent) and Chimera won't find its
libraries during import.
Parameters
----------
nogui : bool, optional, default=False
If the GUI is not going to be launched, try to locate a headless
Chimera build to enable inline Chimera visualization.
"""
if 'CHIMERA' in os.environ:
return
paths = guess_chimera_path(search_all=nogui)
CHIMERA_BASE = paths[0]
if nogui: # try finding a headless version
try:
CHIMERA_BASE = next(p for p in paths if 'headless' in p)
except StopIteration:
pass
if not os.path.isdir(CHIMERA_BASE):
sys.exit("Could not find UCSF Chimera.\n{}".format(_INSTRUCTIONS))
os.environ['CHIMERA'] = CHIMERA_BASE
CHIMERA_LIB = os.path.join(CHIMERA_BASE, 'lib')
# Set Tcl/Tk for gui mode
if 'TCL_LIBRARY' in os.environ:
os.environ['CHIMERA_TCL_LIBRARY'] = os.environ['TCL_LIBRARY']
os.environ['TCL_LIBRARY'] = os.path.join(CHIMERA_LIB, 'tcl8.6')
if 'TCLLIBPATH' in os.environ:
os.environ['CHIMERA_TCLLIBPATH'] = os.environ['TCLLIBPATH']
os.environ['TCLLIBPATH'] = '{' + CHIMERA_LIB + '}'
if 'TK_LIBRARY' in os.environ:
os.environ['CHIMERA_TK_LIBRARY'] = os.environ['TK_LIBRARY']
del os.environ['TK_LIBRARY']
if 'TIX_LIBRARY' in os.environ:
os.environ['CHIMERA_TIX_LIBRARY'] = os.environ['TIX_LIBRARY']
del os.environ['TIX_LIBRARY']
if 'PYTHONNOUSERSITE' in os.environ:
os.environ['CHIMERA_PYTHONNOUSERSITE'] = os.environ['PYTHONNOUSERSITE']
os.environ['PYTHONNOUSERSITE'] = '1'
# Check interactive and IPython
if in_ipython() and hasattr(sys, 'ps1') and not sys.argv[0].endswith('ipython'):
sys.argv.insert(1, 'ipython')
# Platform-specific patches
patch_environ_for_platform(CHIMERA_BASE, CHIMERA_LIB, nogui=nogui)
os.execve(sys.executable, [sys.executable] + sys.argv, os.environ) | [
"def",
"patch_environ",
"(",
"nogui",
"=",
"True",
")",
":",
"if",
"'CHIMERA'",
"in",
"os",
".",
"environ",
":",
"return",
"paths",
"=",
"guess_chimera_path",
"(",
"search_all",
"=",
"nogui",
")",
"CHIMERA_BASE",
"=",
"paths",
"[",
"0",
"]",
"if",
"nogui... | Patch current environment variables so Chimera can start up and we can import its modules.
Be warned that calling this function WILL restart your interpreter. Otherwise, Python
won't catch the new LD_LIBRARY_PATH (or platform equivalent) and Chimera won't find its
libraries during import.
Parameters
----------
nogui : bool, optional, default=False
If the GUI is not going to be launched, try to locate a headless
Chimera build to enable inline Chimera visualization. | [
"Patch",
"current",
"environment",
"variables",
"so",
"Chimera",
"can",
"start",
"up",
"and",
"we",
"can",
"import",
"its",
"modules",
"."
] | 5227d1c0e9e1ce165fc68157eda788cd0843842b | https://github.com/insilichem/pychimera/blob/5227d1c0e9e1ce165fc68157eda788cd0843842b/pychimera/core.py#L107-L164 | train | 31,908 |
insilichem/pychimera | pychimera/core.py | guess_chimera_path | def guess_chimera_path(search_all=False):
"""
Try to guess Chimera installation path.
Parameters
----------
search_all : bool, optional, default=False
If no CHIMERADIR env var is set, collect all posible
locations of Chimera installations.
Returns
-------
paths: list of str
Alphabetically sorted list of possible Chimera locations
"""
paths = _search_chimera(CHIMERA_BINARY, CHIMERA_LOCATIONS, CHIMERA_PREFIX,
search_all=search_all)
if not paths and search_all: # try headless?
headless = '{0[0]}{1}{0[1]}'.format(os.path.split(CHIMERA_BINARY), '-headless')
paths = _search_chimera(headless, CHIMERA_LOCATIONS, CHIMERA_PREFIX,
search_all=search_all)
if not paths:
sys.exit("Could not find UCSF Chimera.\n{}".format(_INSTRUCTIONS))
return paths | python | def guess_chimera_path(search_all=False):
"""
Try to guess Chimera installation path.
Parameters
----------
search_all : bool, optional, default=False
If no CHIMERADIR env var is set, collect all posible
locations of Chimera installations.
Returns
-------
paths: list of str
Alphabetically sorted list of possible Chimera locations
"""
paths = _search_chimera(CHIMERA_BINARY, CHIMERA_LOCATIONS, CHIMERA_PREFIX,
search_all=search_all)
if not paths and search_all: # try headless?
headless = '{0[0]}{1}{0[1]}'.format(os.path.split(CHIMERA_BINARY), '-headless')
paths = _search_chimera(headless, CHIMERA_LOCATIONS, CHIMERA_PREFIX,
search_all=search_all)
if not paths:
sys.exit("Could not find UCSF Chimera.\n{}".format(_INSTRUCTIONS))
return paths | [
"def",
"guess_chimera_path",
"(",
"search_all",
"=",
"False",
")",
":",
"paths",
"=",
"_search_chimera",
"(",
"CHIMERA_BINARY",
",",
"CHIMERA_LOCATIONS",
",",
"CHIMERA_PREFIX",
",",
"search_all",
"=",
"search_all",
")",
"if",
"not",
"paths",
"and",
"search_all",
... | Try to guess Chimera installation path.
Parameters
----------
search_all : bool, optional, default=False
If no CHIMERADIR env var is set, collect all posible
locations of Chimera installations.
Returns
-------
paths: list of str
Alphabetically sorted list of possible Chimera locations | [
"Try",
"to",
"guess",
"Chimera",
"installation",
"path",
"."
] | 5227d1c0e9e1ce165fc68157eda788cd0843842b | https://github.com/insilichem/pychimera/blob/5227d1c0e9e1ce165fc68157eda788cd0843842b/pychimera/core.py#L167-L190 | train | 31,909 |
heuer/segno | segno/__init__.py | make_micro | def make_micro(content, error=None, version=None, mode=None, mask=None,
encoding=None, boost_error=True):
"""\
Creates a Micro QR Code.
See :py:func:`make` for a description of the parameters.
Note: Error correction level "H" isn't available for Micro QR Codes. If
used, this function raises a :py:class:`segno.ErrorLevelError`.
:rtype: QRCode
"""
return make(content, error=error, version=version, mode=mode, mask=mask,
encoding=encoding, micro=True, boost_error=boost_error) | python | def make_micro(content, error=None, version=None, mode=None, mask=None,
encoding=None, boost_error=True):
"""\
Creates a Micro QR Code.
See :py:func:`make` for a description of the parameters.
Note: Error correction level "H" isn't available for Micro QR Codes. If
used, this function raises a :py:class:`segno.ErrorLevelError`.
:rtype: QRCode
"""
return make(content, error=error, version=version, mode=mode, mask=mask,
encoding=encoding, micro=True, boost_error=boost_error) | [
"def",
"make_micro",
"(",
"content",
",",
"error",
"=",
"None",
",",
"version",
"=",
"None",
",",
"mode",
"=",
"None",
",",
"mask",
"=",
"None",
",",
"encoding",
"=",
"None",
",",
"boost_error",
"=",
"True",
")",
":",
"return",
"make",
"(",
"content"... | \
Creates a Micro QR Code.
See :py:func:`make` for a description of the parameters.
Note: Error correction level "H" isn't available for Micro QR Codes. If
used, this function raises a :py:class:`segno.ErrorLevelError`.
:rtype: QRCode | [
"\\",
"Creates",
"a",
"Micro",
"QR",
"Code",
"."
] | 64d912a2bd17d0b5ff3e8b5d37098edfc663c2b3 | https://github.com/heuer/segno/blob/64d912a2bd17d0b5ff3e8b5d37098edfc663c2b3/segno/__init__.py#L164-L177 | train | 31,910 |
heuer/segno | segno/__init__.py | make_sequence | def make_sequence(content, error=None, version=None, mode=None, mask=None,
encoding=None, boost_error=True, symbol_count=None):
"""\
Creates a sequence of QR Codes.
If the content fits into one QR Code and neither ``version`` nor
``symbol_count`` is provided, this function may return a sequence with
one QR Code which does not use the Structured Append mode. Otherwise a
sequence of 2 .. n (max. n = 16) QR Codes is returned which use the
Structured Append mode.
The Structured Append mode allows to split the content over a number
(max. 16) QR Codes.
The Structured Append mode isn't available for Micro QR Codes, therefor
the returned sequence contains QR Codes, only.
Since this function returns an iterable object, it may be used as follows:
.. code-block:: python
for i, qrcode in enumerate(segno.make_sequence(data, symbol_count=2)):
qrcode.save('seq-%d.svg' % i, scale=10, color='darkblue')
The returned number of QR Codes is determined by the `version` or
`symbol_count` parameter
See :py:func:`make` for a description of the other parameters.
:param int symbol_count: Number of symbols.
:rtype: QRCodeSequence
"""
return QRCodeSequence(map(QRCode,
encoder.encode_sequence(content, error=error,
version=version,
mode=mode, mask=mask,
encoding=encoding,
boost_error=boost_error,
symbol_count=symbol_count))) | python | def make_sequence(content, error=None, version=None, mode=None, mask=None,
encoding=None, boost_error=True, symbol_count=None):
"""\
Creates a sequence of QR Codes.
If the content fits into one QR Code and neither ``version`` nor
``symbol_count`` is provided, this function may return a sequence with
one QR Code which does not use the Structured Append mode. Otherwise a
sequence of 2 .. n (max. n = 16) QR Codes is returned which use the
Structured Append mode.
The Structured Append mode allows to split the content over a number
(max. 16) QR Codes.
The Structured Append mode isn't available for Micro QR Codes, therefor
the returned sequence contains QR Codes, only.
Since this function returns an iterable object, it may be used as follows:
.. code-block:: python
for i, qrcode in enumerate(segno.make_sequence(data, symbol_count=2)):
qrcode.save('seq-%d.svg' % i, scale=10, color='darkblue')
The returned number of QR Codes is determined by the `version` or
`symbol_count` parameter
See :py:func:`make` for a description of the other parameters.
:param int symbol_count: Number of symbols.
:rtype: QRCodeSequence
"""
return QRCodeSequence(map(QRCode,
encoder.encode_sequence(content, error=error,
version=version,
mode=mode, mask=mask,
encoding=encoding,
boost_error=boost_error,
symbol_count=symbol_count))) | [
"def",
"make_sequence",
"(",
"content",
",",
"error",
"=",
"None",
",",
"version",
"=",
"None",
",",
"mode",
"=",
"None",
",",
"mask",
"=",
"None",
",",
"encoding",
"=",
"None",
",",
"boost_error",
"=",
"True",
",",
"symbol_count",
"=",
"None",
")",
... | \
Creates a sequence of QR Codes.
If the content fits into one QR Code and neither ``version`` nor
``symbol_count`` is provided, this function may return a sequence with
one QR Code which does not use the Structured Append mode. Otherwise a
sequence of 2 .. n (max. n = 16) QR Codes is returned which use the
Structured Append mode.
The Structured Append mode allows to split the content over a number
(max. 16) QR Codes.
The Structured Append mode isn't available for Micro QR Codes, therefor
the returned sequence contains QR Codes, only.
Since this function returns an iterable object, it may be used as follows:
.. code-block:: python
for i, qrcode in enumerate(segno.make_sequence(data, symbol_count=2)):
qrcode.save('seq-%d.svg' % i, scale=10, color='darkblue')
The returned number of QR Codes is determined by the `version` or
`symbol_count` parameter
See :py:func:`make` for a description of the other parameters.
:param int symbol_count: Number of symbols.
:rtype: QRCodeSequence | [
"\\",
"Creates",
"a",
"sequence",
"of",
"QR",
"Codes",
"."
] | 64d912a2bd17d0b5ff3e8b5d37098edfc663c2b3 | https://github.com/heuer/segno/blob/64d912a2bd17d0b5ff3e8b5d37098edfc663c2b3/segno/__init__.py#L180-L218 | train | 31,911 |
heuer/segno | segno/__init__.py | QRCode.designator | def designator(self):
"""\
Returns the version and error correction level as string `V-E` where
`V` represents the version number and `E` the error level.
"""
version = str(self.version)
return '-'.join((version, self.error) if self.error else (version,)) | python | def designator(self):
"""\
Returns the version and error correction level as string `V-E` where
`V` represents the version number and `E` the error level.
"""
version = str(self.version)
return '-'.join((version, self.error) if self.error else (version,)) | [
"def",
"designator",
"(",
"self",
")",
":",
"version",
"=",
"str",
"(",
"self",
".",
"version",
")",
"return",
"'-'",
".",
"join",
"(",
"(",
"version",
",",
"self",
".",
"error",
")",
"if",
"self",
".",
"error",
"else",
"(",
"version",
",",
")",
... | \
Returns the version and error correction level as string `V-E` where
`V` represents the version number and `E` the error level. | [
"\\",
"Returns",
"the",
"version",
"and",
"error",
"correction",
"level",
"as",
"string",
"V",
"-",
"E",
"where",
"V",
"represents",
"the",
"version",
"number",
"and",
"E",
"the",
"error",
"level",
"."
] | 64d912a2bd17d0b5ff3e8b5d37098edfc663c2b3 | https://github.com/heuer/segno/blob/64d912a2bd17d0b5ff3e8b5d37098edfc663c2b3/segno/__init__.py#L269-L275 | train | 31,912 |
heuer/segno | segno/__init__.py | QRCode.matrix_iter | def matrix_iter(self, scale=1, border=None):
"""\
Returns an iterator over the matrix which includes the border.
The border is returned as sequence of light modules.
Dark modules are reported as ``0x1``, light modules have the value
``0x0``.
The following example converts the QR Code matrix into a list of
lists which use boolean values for the modules (True = dark module,
False = light module)::
>>> import segno
>>> qr = segno.make('The Beatles')
>>> size = qr.symbol_size()[0]
>>> res = []
>>> # Scaling factor 2, default border
>>> for row in qr.matrix_iter(scale=2):
>>> res.append([col == 0x1 for col in row])
>>> size * 2 == len(res[0])
True
:param int scale: The scaling factor (default: ``1``).
:param int border: The size of border / quiet zone or ``None`` to
indicate the default border.
:raises: :py:exc:`ValueError` if the scaling factor or the border is
invalid (i.e. negative).
"""
return utils.matrix_iter(self.matrix, self._version, scale, border) | python | def matrix_iter(self, scale=1, border=None):
"""\
Returns an iterator over the matrix which includes the border.
The border is returned as sequence of light modules.
Dark modules are reported as ``0x1``, light modules have the value
``0x0``.
The following example converts the QR Code matrix into a list of
lists which use boolean values for the modules (True = dark module,
False = light module)::
>>> import segno
>>> qr = segno.make('The Beatles')
>>> size = qr.symbol_size()[0]
>>> res = []
>>> # Scaling factor 2, default border
>>> for row in qr.matrix_iter(scale=2):
>>> res.append([col == 0x1 for col in row])
>>> size * 2 == len(res[0])
True
:param int scale: The scaling factor (default: ``1``).
:param int border: The size of border / quiet zone or ``None`` to
indicate the default border.
:raises: :py:exc:`ValueError` if the scaling factor or the border is
invalid (i.e. negative).
"""
return utils.matrix_iter(self.matrix, self._version, scale, border) | [
"def",
"matrix_iter",
"(",
"self",
",",
"scale",
"=",
"1",
",",
"border",
"=",
"None",
")",
":",
"return",
"utils",
".",
"matrix_iter",
"(",
"self",
".",
"matrix",
",",
"self",
".",
"_version",
",",
"scale",
",",
"border",
")"
] | \
Returns an iterator over the matrix which includes the border.
The border is returned as sequence of light modules.
Dark modules are reported as ``0x1``, light modules have the value
``0x0``.
The following example converts the QR Code matrix into a list of
lists which use boolean values for the modules (True = dark module,
False = light module)::
>>> import segno
>>> qr = segno.make('The Beatles')
>>> size = qr.symbol_size()[0]
>>> res = []
>>> # Scaling factor 2, default border
>>> for row in qr.matrix_iter(scale=2):
>>> res.append([col == 0x1 for col in row])
>>> size * 2 == len(res[0])
True
:param int scale: The scaling factor (default: ``1``).
:param int border: The size of border / quiet zone or ``None`` to
indicate the default border.
:raises: :py:exc:`ValueError` if the scaling factor or the border is
invalid (i.e. negative). | [
"\\",
"Returns",
"an",
"iterator",
"over",
"the",
"matrix",
"which",
"includes",
"the",
"border",
"."
] | 64d912a2bd17d0b5ff3e8b5d37098edfc663c2b3 | https://github.com/heuer/segno/blob/64d912a2bd17d0b5ff3e8b5d37098edfc663c2b3/segno/__init__.py#L311-L339 | train | 31,913 |
heuer/segno | segno/__init__.py | QRCode.show | def show(self, delete_after=20, scale=10, border=None, color='#000',
background='#fff'): # pragma: no cover
"""\
Displays this QR code.
This method is mainly intended for debugging purposes.
This method saves the output of the :py:meth:`png` method (by default
with a scaling factor of 10) to a temporary file and opens it with the
standard PNG viewer application or within the standard webbrowser.
The temporary file is deleted afterwards (unless `delete_after` is set
to ``None``).
If this method does not show any result, try to increase the
`delete_after` value or set it to ``None``
:param delete_after: Time in seconds to wait till the temporary file is
deleted.
"""
import os
import time
import tempfile
import webbrowser
import threading
try: # Python 2
from urlparse import urljoin
from urllib import pathname2url
except ImportError: # Python 3
from urllib.parse import urljoin
from urllib.request import pathname2url
def delete_file(name):
time.sleep(delete_after)
try:
os.unlink(name)
except OSError:
pass
f = tempfile.NamedTemporaryFile('wb', suffix='.png', delete=False)
try:
self.save(f, scale=scale, color=color, background=background,
border=border)
except:
f.close()
os.unlink(f.name)
raise
f.close()
webbrowser.open_new_tab(urljoin('file:', pathname2url(f.name)))
if delete_after is not None:
t = threading.Thread(target=delete_file, args=(f.name,))
t.start() | python | def show(self, delete_after=20, scale=10, border=None, color='#000',
background='#fff'): # pragma: no cover
"""\
Displays this QR code.
This method is mainly intended for debugging purposes.
This method saves the output of the :py:meth:`png` method (by default
with a scaling factor of 10) to a temporary file and opens it with the
standard PNG viewer application or within the standard webbrowser.
The temporary file is deleted afterwards (unless `delete_after` is set
to ``None``).
If this method does not show any result, try to increase the
`delete_after` value or set it to ``None``
:param delete_after: Time in seconds to wait till the temporary file is
deleted.
"""
import os
import time
import tempfile
import webbrowser
import threading
try: # Python 2
from urlparse import urljoin
from urllib import pathname2url
except ImportError: # Python 3
from urllib.parse import urljoin
from urllib.request import pathname2url
def delete_file(name):
time.sleep(delete_after)
try:
os.unlink(name)
except OSError:
pass
f = tempfile.NamedTemporaryFile('wb', suffix='.png', delete=False)
try:
self.save(f, scale=scale, color=color, background=background,
border=border)
except:
f.close()
os.unlink(f.name)
raise
f.close()
webbrowser.open_new_tab(urljoin('file:', pathname2url(f.name)))
if delete_after is not None:
t = threading.Thread(target=delete_file, args=(f.name,))
t.start() | [
"def",
"show",
"(",
"self",
",",
"delete_after",
"=",
"20",
",",
"scale",
"=",
"10",
",",
"border",
"=",
"None",
",",
"color",
"=",
"'#000'",
",",
"background",
"=",
"'#fff'",
")",
":",
"# pragma: no cover",
"import",
"os",
"import",
"time",
"import",
... | \
Displays this QR code.
This method is mainly intended for debugging purposes.
This method saves the output of the :py:meth:`png` method (by default
with a scaling factor of 10) to a temporary file and opens it with the
standard PNG viewer application or within the standard webbrowser.
The temporary file is deleted afterwards (unless `delete_after` is set
to ``None``).
If this method does not show any result, try to increase the
`delete_after` value or set it to ``None``
:param delete_after: Time in seconds to wait till the temporary file is
deleted. | [
"\\",
"Displays",
"this",
"QR",
"code",
"."
] | 64d912a2bd17d0b5ff3e8b5d37098edfc663c2b3 | https://github.com/heuer/segno/blob/64d912a2bd17d0b5ff3e8b5d37098edfc663c2b3/segno/__init__.py#L341-L391 | train | 31,914 |
heuer/segno | segno/__init__.py | QRCode.svg_data_uri | def svg_data_uri(self, xmldecl=False, encode_minimal=False,
omit_charset=False, nl=False, **kw):
"""\
Converts the QR Code into a SVG data URI.
The XML declaration is omitted by default (set ``xmldecl`` to ``True``
to enable it), further the newline is omitted by default (set ``nl`` to
``True`` to enable it).
Aside from the missing ``out`` parameter and the different ``xmldecl``
and ``nl`` default values and the additional parameter ``encode_minimal``
and ``omit_charset`` this method uses the same parameters as the
usual SVG serializer.
:param bool xmldecl: Indicates if the XML declaration should be
serialized (default: ``False``)
:param bool encode_minimal: Indicates if the resulting data URI should
use minimal percent encoding (disabled by default).
:param bool omit_charset: Indicates if the ``;charset=...`` should be omitted
(disabled by default)
:rtype: str
"""
return writers.as_svg_data_uri(self.matrix, self._version,
xmldecl=xmldecl, nl=nl,
encode_minimal=encode_minimal,
omit_charset=omit_charset, **kw) | python | def svg_data_uri(self, xmldecl=False, encode_minimal=False,
omit_charset=False, nl=False, **kw):
"""\
Converts the QR Code into a SVG data URI.
The XML declaration is omitted by default (set ``xmldecl`` to ``True``
to enable it), further the newline is omitted by default (set ``nl`` to
``True`` to enable it).
Aside from the missing ``out`` parameter and the different ``xmldecl``
and ``nl`` default values and the additional parameter ``encode_minimal``
and ``omit_charset`` this method uses the same parameters as the
usual SVG serializer.
:param bool xmldecl: Indicates if the XML declaration should be
serialized (default: ``False``)
:param bool encode_minimal: Indicates if the resulting data URI should
use minimal percent encoding (disabled by default).
:param bool omit_charset: Indicates if the ``;charset=...`` should be omitted
(disabled by default)
:rtype: str
"""
return writers.as_svg_data_uri(self.matrix, self._version,
xmldecl=xmldecl, nl=nl,
encode_minimal=encode_minimal,
omit_charset=omit_charset, **kw) | [
"def",
"svg_data_uri",
"(",
"self",
",",
"xmldecl",
"=",
"False",
",",
"encode_minimal",
"=",
"False",
",",
"omit_charset",
"=",
"False",
",",
"nl",
"=",
"False",
",",
"*",
"*",
"kw",
")",
":",
"return",
"writers",
".",
"as_svg_data_uri",
"(",
"self",
... | \
Converts the QR Code into a SVG data URI.
The XML declaration is omitted by default (set ``xmldecl`` to ``True``
to enable it), further the newline is omitted by default (set ``nl`` to
``True`` to enable it).
Aside from the missing ``out`` parameter and the different ``xmldecl``
and ``nl`` default values and the additional parameter ``encode_minimal``
and ``omit_charset`` this method uses the same parameters as the
usual SVG serializer.
:param bool xmldecl: Indicates if the XML declaration should be
serialized (default: ``False``)
:param bool encode_minimal: Indicates if the resulting data URI should
use minimal percent encoding (disabled by default).
:param bool omit_charset: Indicates if the ``;charset=...`` should be omitted
(disabled by default)
:rtype: str | [
"\\",
"Converts",
"the",
"QR",
"Code",
"into",
"a",
"SVG",
"data",
"URI",
"."
] | 64d912a2bd17d0b5ff3e8b5d37098edfc663c2b3 | https://github.com/heuer/segno/blob/64d912a2bd17d0b5ff3e8b5d37098edfc663c2b3/segno/__init__.py#L393-L418 | train | 31,915 |
heuer/segno | segno/__init__.py | QRCode.png_data_uri | def png_data_uri(self, **kw):
"""\
Converts the QR Code into a PNG data URI.
Uses the same keyword parameters as the usual PNG serializer.
:rtype: str
"""
return writers.as_png_data_uri(self.matrix, self._version, **kw) | python | def png_data_uri(self, **kw):
"""\
Converts the QR Code into a PNG data URI.
Uses the same keyword parameters as the usual PNG serializer.
:rtype: str
"""
return writers.as_png_data_uri(self.matrix, self._version, **kw) | [
"def",
"png_data_uri",
"(",
"self",
",",
"*",
"*",
"kw",
")",
":",
"return",
"writers",
".",
"as_png_data_uri",
"(",
"self",
".",
"matrix",
",",
"self",
".",
"_version",
",",
"*",
"*",
"kw",
")"
] | \
Converts the QR Code into a PNG data URI.
Uses the same keyword parameters as the usual PNG serializer.
:rtype: str | [
"\\",
"Converts",
"the",
"QR",
"Code",
"into",
"a",
"PNG",
"data",
"URI",
"."
] | 64d912a2bd17d0b5ff3e8b5d37098edfc663c2b3 | https://github.com/heuer/segno/blob/64d912a2bd17d0b5ff3e8b5d37098edfc663c2b3/segno/__init__.py#L420-L428 | train | 31,916 |
heuer/segno | segno/__init__.py | QRCode.terminal | def terminal(self, out=None, border=None):
"""\
Serializes the matrix as ANSI escape code.
:param out: Filename or a file-like object supporting to write text.
If ``None`` (default), the matrix is written to ``sys.stdout``.
:param int border: Integer indicating the size of the quiet zone.
If set to ``None`` (default), the recommended border size
will be used (``4`` for QR Codes, ``2`` for a Micro QR Codes).
"""
if out is None and sys.platform == 'win32': # pragma: no cover
# Windows < 10 does not support ANSI escape sequences, try to
# call the a Windows specific terminal output which uses the
# Windows API.
try:
writers.write_terminal_win(self.matrix, self._version, border)
except OSError:
# Use the standard output even if it may print garbage
writers.write_terminal(self.matrix, self._version, sys.stdout,
border)
else:
writers.write_terminal(self.matrix, self._version, out or sys.stdout,
border) | python | def terminal(self, out=None, border=None):
"""\
Serializes the matrix as ANSI escape code.
:param out: Filename or a file-like object supporting to write text.
If ``None`` (default), the matrix is written to ``sys.stdout``.
:param int border: Integer indicating the size of the quiet zone.
If set to ``None`` (default), the recommended border size
will be used (``4`` for QR Codes, ``2`` for a Micro QR Codes).
"""
if out is None and sys.platform == 'win32': # pragma: no cover
# Windows < 10 does not support ANSI escape sequences, try to
# call the a Windows specific terminal output which uses the
# Windows API.
try:
writers.write_terminal_win(self.matrix, self._version, border)
except OSError:
# Use the standard output even if it may print garbage
writers.write_terminal(self.matrix, self._version, sys.stdout,
border)
else:
writers.write_terminal(self.matrix, self._version, out or sys.stdout,
border) | [
"def",
"terminal",
"(",
"self",
",",
"out",
"=",
"None",
",",
"border",
"=",
"None",
")",
":",
"if",
"out",
"is",
"None",
"and",
"sys",
".",
"platform",
"==",
"'win32'",
":",
"# pragma: no cover",
"# Windows < 10 does not support ANSI escape sequences, try to",
... | \
Serializes the matrix as ANSI escape code.
:param out: Filename or a file-like object supporting to write text.
If ``None`` (default), the matrix is written to ``sys.stdout``.
:param int border: Integer indicating the size of the quiet zone.
If set to ``None`` (default), the recommended border size
will be used (``4`` for QR Codes, ``2`` for a Micro QR Codes). | [
"\\",
"Serializes",
"the",
"matrix",
"as",
"ANSI",
"escape",
"code",
"."
] | 64d912a2bd17d0b5ff3e8b5d37098edfc663c2b3 | https://github.com/heuer/segno/blob/64d912a2bd17d0b5ff3e8b5d37098edfc663c2b3/segno/__init__.py#L430-L452 | train | 31,917 |
heuer/segno | segno/__init__.py | QRCode.save | def save(self, out, kind=None, **kw):
"""\
Serializes the QR Code in one of the supported formats.
The serialization format depends on the filename extension.
**Common keywords**
========== ==============================================================
Name Description
========== ==============================================================
scale Integer or float indicating the size of a single module.
Default: 1. The interpretation of the scaling factor depends
on the serializer. For pixel-based output (like PNG) the
scaling factor is interepreted as pixel-size (1 = 1 pixel).
EPS interprets ``1`` as 1 point (1/72 inch) per module.
Some serializers (like SVG) accept float values. If the
serializer does not accept float values, the value will be
converted to an integer value (note: int(1.6) == 1).
border Integer indicating the size of the quiet zone.
If set to ``None`` (default), the recommended border size
will be used (``4`` for QR Codes, ``2`` for a Micro QR Codes).
color A string or tuple representing a color value for the dark
modules. The default value is "black". The color can be
provided as ``(R, G, B)`` tuple, as web color name
(like "red") or in hexadecimal format (``#RGB`` or
``#RRGGBB``). Some serializers (SVG and PNG) accept an alpha
transparency value like ``#RRGGBBAA``.
background A string or tuple representing a color for the light modules
or background. See "color" for valid values.
The default value depends on the serializer. SVG uses no
background color (``None``) by default, other serializers
use "white" as default background color.
========== ==============================================================
**Scalable Vector Graphics (SVG)**
============= ==============================================================
Name Description
============= ==============================================================
out Filename or io.BytesIO
kind "svg" or "svgz" (to create a gzip compressed SVG)
scale integer or float
color Default: "#000" (black)
``None`` is a valid value. If set to ``None``, the resulting
path won't have a "stroke" attribute. The "stroke" attribute
may be defined via CSS (external).
If an alpha channel is defined, the output depends of the
used SVG version. For SVG versions >= 2.0, the "stroke"
attribute will have a value like "rgba(R, G, B, A)", otherwise
the path gets another attribute "stroke-opacity" to emulate
the alpha channel.
To minimize the document size, the SVG serializer uses
automatically the shortest color representation: If
a value like "#000000" is provided, the resulting
document will have a color value of "#000". If the color
is "#FF0000", the resulting color is not "#F00", but
the web color name "red".
background Default value ``None``. If this paramater is set to another
value, the resulting image will have another path which
is used to define the background color.
If an alpha channel is used, the resulting path may
have a "fill-opacity" attribute (for SVG version < 2.0)
or the "fill" attribute has a "rgba(R, G, B, A)" value.
See keyword "color" for further details.
xmldecl Boolean value (default: ``True``) indicating whether the
document should have an XML declaration header.
Set to ``False`` to omit the header.
svgns Boolean value (default: ``True``) indicating whether the
document should have an explicit SVG namespace declaration.
Set to ``False`` to omit the namespace declaration.
The latter might be useful if the document should be
embedded into a HTML 5 document where the SVG namespace
is implicitly defined.
title String (default: ``None``) Optional title of the generated
SVG document.
desc String (default: ``None``) Optional description of the
generated SVG document.
svgid A string indicating the ID of the SVG document
(if set to ``None`` (default), the SVG element won't have
an ID).
svgclass Default: "segno". The CSS class of the SVG document
(if set to ``None``, the SVG element won't have a class).
lineclass Default: "qrline". The CSS class of the path element
(which draws the dark modules (if set to ``None``, the path
won't have a class).
omitsize Indicates if width and height attributes should be
omitted (default: ``False``). If these attributes are
omitted, a ``viewBox`` attribute will be added to the
document.
unit Default: ``None``
Inidctaes the unit for width / height and other coordinates.
By default, the unit is unspecified and all values are
in the user space.
Valid values: em, ex, px, pt, pc, cm, mm, in, and percentages
(any string is accepted, this parameter is not validated
by the serializer)
encoding Encoding of the XML document. "utf-8" by default.
svgversion SVG version (default: ``None``). If specified (a float),
the resulting document has an explicit "version" attribute.
If set to ``None``, the document won't have a "version"
attribute. This parameter is not validated.
compresslevel Default: 9. This parameter is only valid, if a compressed
SVG document should be created (file extension "svgz").
1 is fastest and produces the least compression, 9 is slowest
and produces the most. 0 is no compression.
============= ==============================================================
**Portable Network Graphics (PNG)**
============= ==============================================================
Name Description
============= ==============================================================
out Filename or io.BytesIO
kind "png"
scale integer
color Default: "#000" (black)
``None`` is a valid value iff background is not ``None``.
background Default value ``#fff`` (white)
See keyword "color" for further details.
compresslevel Default: 9. Integer indicating the compression level
for the ``IDAT`` (data) chunk.
1 is fastest and produces the least compression, 9 is slowest
and produces the most. 0 is no compression.
dpi Default: None. Specifies the DPI value for the image.
By default, the DPI value is unspecified. Please note
that the DPI value is converted into meters (maybe with
rounding errors) since PNG does not support the unit
"dots per inch".
addad Boolean value (default: True) to (dis-)allow a "Software"
comment indicating that the file was created by Segno.
============= ==============================================================
**Encapsulated PostScript (EPS)**
============= ==============================================================
Name Description
============= ==============================================================
out Filename or io.StringIO
kind "eps"
scale integer or float
color Default: "#000" (black)
background Default value: ``None`` (no background)
============= ==============================================================
**Portable Document Format (PDF)**
============= ==============================================================
Name Description
============= ==============================================================
out Filename or io.BytesIO
kind "pdf"
scale integer or float
compresslevel Default: 9. Integer indicating the compression level.
1 is fastest and produces the least compression, 9 is slowest
and produces the most. 0 is no compression.
============= ==============================================================
**Text (TXT)**
Does not support the "scale" keyword!
============= ==============================================================
Name Description
============= ==============================================================
out Filename or io.StringIO
kind "txt"
color Default: "1"
background Default: "0"
============= ==============================================================
**ANSI escape code**
Supports the "border" keyword, only!
============= ==============================================================
Name Description
============= ==============================================================
kind "ans"
============= ==============================================================
**Portable Bitmap (PBM)**
============= ==============================================================
Name Description
============= ==============================================================
out Filename or io.BytesIO
kind "pbm"
scale integer
plain Default: False. Boolean to switch between the P4 and P1 format.
If set to ``True``, the (outdated) P1 serialization format is
used.
============= ==============================================================
**Portable Arbitrary Map (PAM)**
============= ==============================================================
Name Description
============= ==============================================================
out Filename or io.BytesIO
kind "pam"
scale integer
color Default: "#000" (black).
background Default value ``#fff`` (white). Use ``None`` for a transparent
background.
============= ==============================================================
**LaTeX / PGF/TikZ**
To use the output of this serializer, the ``PGF/TikZ`` (and optionally
``hyperref``) package is required in the LaTeX environment. The
serializer itself does not depend on any external packages.
============= ==============================================================
Name Description
============= ==============================================================
out Filename or io.StringIO
kind "tex"
scale integer or float
color LaTeX color name (default: "black"). The color is written
"at it is", so ensure that the color is a standard color or it
has been defined in the enclosing LaTeX document.
url Default: ``None``. Optional URL where the QR Code should
point to. Requires the ``hyperref`` package in your LaTeX
environment.
============= ==============================================================
**X BitMap (XBM)**
============= ==============================================================
Name Description
============= ==============================================================
out Filename or io.StringIO
kind "xbm"
scale integer
name Name of the variable (default: "img")
============= ==============================================================
**X PixMap (XPM)**
============= ==============================================================
Name Description
============= ==============================================================
out Filename or io.StringIO
kind "xpm"
scale integer
color Default: "#000" (black).
background Default value ``#fff`` (white)
``None`` indicates a transparent background.
name Name of the variable (default: "img")
============= ==============================================================
:param out: A filename or a writable file-like object with a
``name`` attribute. Use the `kind` parameter if `out` is
a :py:class:`io.ByteIO` or :py:class:`io.StringIO` stream which
don't have a ``name`` attribute.
:param kind: If the desired output format cannot be determined from
the ``out`` parameter, this parameter can be used to indicate the
serialization format (i.e. "svg" to enforce SVG output)
:param kw: Any of the supported keywords by the specific serialization
method.
"""
writers.save(self.matrix, self._version, out, kind, **kw) | python | def save(self, out, kind=None, **kw):
"""\
Serializes the QR Code in one of the supported formats.
The serialization format depends on the filename extension.
**Common keywords**
========== ==============================================================
Name Description
========== ==============================================================
scale Integer or float indicating the size of a single module.
Default: 1. The interpretation of the scaling factor depends
on the serializer. For pixel-based output (like PNG) the
scaling factor is interepreted as pixel-size (1 = 1 pixel).
EPS interprets ``1`` as 1 point (1/72 inch) per module.
Some serializers (like SVG) accept float values. If the
serializer does not accept float values, the value will be
converted to an integer value (note: int(1.6) == 1).
border Integer indicating the size of the quiet zone.
If set to ``None`` (default), the recommended border size
will be used (``4`` for QR Codes, ``2`` for a Micro QR Codes).
color A string or tuple representing a color value for the dark
modules. The default value is "black". The color can be
provided as ``(R, G, B)`` tuple, as web color name
(like "red") or in hexadecimal format (``#RGB`` or
``#RRGGBB``). Some serializers (SVG and PNG) accept an alpha
transparency value like ``#RRGGBBAA``.
background A string or tuple representing a color for the light modules
or background. See "color" for valid values.
The default value depends on the serializer. SVG uses no
background color (``None``) by default, other serializers
use "white" as default background color.
========== ==============================================================
**Scalable Vector Graphics (SVG)**
============= ==============================================================
Name Description
============= ==============================================================
out Filename or io.BytesIO
kind "svg" or "svgz" (to create a gzip compressed SVG)
scale integer or float
color Default: "#000" (black)
``None`` is a valid value. If set to ``None``, the resulting
path won't have a "stroke" attribute. The "stroke" attribute
may be defined via CSS (external).
If an alpha channel is defined, the output depends of the
used SVG version. For SVG versions >= 2.0, the "stroke"
attribute will have a value like "rgba(R, G, B, A)", otherwise
the path gets another attribute "stroke-opacity" to emulate
the alpha channel.
To minimize the document size, the SVG serializer uses
automatically the shortest color representation: If
a value like "#000000" is provided, the resulting
document will have a color value of "#000". If the color
is "#FF0000", the resulting color is not "#F00", but
the web color name "red".
background Default value ``None``. If this paramater is set to another
value, the resulting image will have another path which
is used to define the background color.
If an alpha channel is used, the resulting path may
have a "fill-opacity" attribute (for SVG version < 2.0)
or the "fill" attribute has a "rgba(R, G, B, A)" value.
See keyword "color" for further details.
xmldecl Boolean value (default: ``True``) indicating whether the
document should have an XML declaration header.
Set to ``False`` to omit the header.
svgns Boolean value (default: ``True``) indicating whether the
document should have an explicit SVG namespace declaration.
Set to ``False`` to omit the namespace declaration.
The latter might be useful if the document should be
embedded into a HTML 5 document where the SVG namespace
is implicitly defined.
title String (default: ``None``) Optional title of the generated
SVG document.
desc String (default: ``None``) Optional description of the
generated SVG document.
svgid A string indicating the ID of the SVG document
(if set to ``None`` (default), the SVG element won't have
an ID).
svgclass Default: "segno". The CSS class of the SVG document
(if set to ``None``, the SVG element won't have a class).
lineclass Default: "qrline". The CSS class of the path element
(which draws the dark modules (if set to ``None``, the path
won't have a class).
omitsize Indicates if width and height attributes should be
omitted (default: ``False``). If these attributes are
omitted, a ``viewBox`` attribute will be added to the
document.
unit Default: ``None``
Inidctaes the unit for width / height and other coordinates.
By default, the unit is unspecified and all values are
in the user space.
Valid values: em, ex, px, pt, pc, cm, mm, in, and percentages
(any string is accepted, this parameter is not validated
by the serializer)
encoding Encoding of the XML document. "utf-8" by default.
svgversion SVG version (default: ``None``). If specified (a float),
the resulting document has an explicit "version" attribute.
If set to ``None``, the document won't have a "version"
attribute. This parameter is not validated.
compresslevel Default: 9. This parameter is only valid, if a compressed
SVG document should be created (file extension "svgz").
1 is fastest and produces the least compression, 9 is slowest
and produces the most. 0 is no compression.
============= ==============================================================
**Portable Network Graphics (PNG)**
============= ==============================================================
Name Description
============= ==============================================================
out Filename or io.BytesIO
kind "png"
scale integer
color Default: "#000" (black)
``None`` is a valid value iff background is not ``None``.
background Default value ``#fff`` (white)
See keyword "color" for further details.
compresslevel Default: 9. Integer indicating the compression level
for the ``IDAT`` (data) chunk.
1 is fastest and produces the least compression, 9 is slowest
and produces the most. 0 is no compression.
dpi Default: None. Specifies the DPI value for the image.
By default, the DPI value is unspecified. Please note
that the DPI value is converted into meters (maybe with
rounding errors) since PNG does not support the unit
"dots per inch".
addad Boolean value (default: True) to (dis-)allow a "Software"
comment indicating that the file was created by Segno.
============= ==============================================================
**Encapsulated PostScript (EPS)**
============= ==============================================================
Name Description
============= ==============================================================
out Filename or io.StringIO
kind "eps"
scale integer or float
color Default: "#000" (black)
background Default value: ``None`` (no background)
============= ==============================================================
**Portable Document Format (PDF)**
============= ==============================================================
Name Description
============= ==============================================================
out Filename or io.BytesIO
kind "pdf"
scale integer or float
compresslevel Default: 9. Integer indicating the compression level.
1 is fastest and produces the least compression, 9 is slowest
and produces the most. 0 is no compression.
============= ==============================================================
**Text (TXT)**
Does not support the "scale" keyword!
============= ==============================================================
Name Description
============= ==============================================================
out Filename or io.StringIO
kind "txt"
color Default: "1"
background Default: "0"
============= ==============================================================
**ANSI escape code**
Supports the "border" keyword, only!
============= ==============================================================
Name Description
============= ==============================================================
kind "ans"
============= ==============================================================
**Portable Bitmap (PBM)**
============= ==============================================================
Name Description
============= ==============================================================
out Filename or io.BytesIO
kind "pbm"
scale integer
plain Default: False. Boolean to switch between the P4 and P1 format.
If set to ``True``, the (outdated) P1 serialization format is
used.
============= ==============================================================
**Portable Arbitrary Map (PAM)**
============= ==============================================================
Name Description
============= ==============================================================
out Filename or io.BytesIO
kind "pam"
scale integer
color Default: "#000" (black).
background Default value ``#fff`` (white). Use ``None`` for a transparent
background.
============= ==============================================================
**LaTeX / PGF/TikZ**
To use the output of this serializer, the ``PGF/TikZ`` (and optionally
``hyperref``) package is required in the LaTeX environment. The
serializer itself does not depend on any external packages.
============= ==============================================================
Name Description
============= ==============================================================
out Filename or io.StringIO
kind "tex"
scale integer or float
color LaTeX color name (default: "black"). The color is written
"at it is", so ensure that the color is a standard color or it
has been defined in the enclosing LaTeX document.
url Default: ``None``. Optional URL where the QR Code should
point to. Requires the ``hyperref`` package in your LaTeX
environment.
============= ==============================================================
**X BitMap (XBM)**
============= ==============================================================
Name Description
============= ==============================================================
out Filename or io.StringIO
kind "xbm"
scale integer
name Name of the variable (default: "img")
============= ==============================================================
**X PixMap (XPM)**
============= ==============================================================
Name Description
============= ==============================================================
out Filename or io.StringIO
kind "xpm"
scale integer
color Default: "#000" (black).
background Default value ``#fff`` (white)
``None`` indicates a transparent background.
name Name of the variable (default: "img")
============= ==============================================================
:param out: A filename or a writable file-like object with a
``name`` attribute. Use the `kind` parameter if `out` is
a :py:class:`io.ByteIO` or :py:class:`io.StringIO` stream which
don't have a ``name`` attribute.
:param kind: If the desired output format cannot be determined from
the ``out`` parameter, this parameter can be used to indicate the
serialization format (i.e. "svg" to enforce SVG output)
:param kw: Any of the supported keywords by the specific serialization
method.
"""
writers.save(self.matrix, self._version, out, kind, **kw) | [
"def",
"save",
"(",
"self",
",",
"out",
",",
"kind",
"=",
"None",
",",
"*",
"*",
"kw",
")",
":",
"writers",
".",
"save",
"(",
"self",
".",
"matrix",
",",
"self",
".",
"_version",
",",
"out",
",",
"kind",
",",
"*",
"*",
"kw",
")"
] | \
Serializes the QR Code in one of the supported formats.
The serialization format depends on the filename extension.
**Common keywords**
========== ==============================================================
Name Description
========== ==============================================================
scale Integer or float indicating the size of a single module.
Default: 1. The interpretation of the scaling factor depends
on the serializer. For pixel-based output (like PNG) the
scaling factor is interepreted as pixel-size (1 = 1 pixel).
EPS interprets ``1`` as 1 point (1/72 inch) per module.
Some serializers (like SVG) accept float values. If the
serializer does not accept float values, the value will be
converted to an integer value (note: int(1.6) == 1).
border Integer indicating the size of the quiet zone.
If set to ``None`` (default), the recommended border size
will be used (``4`` for QR Codes, ``2`` for a Micro QR Codes).
color A string or tuple representing a color value for the dark
modules. The default value is "black". The color can be
provided as ``(R, G, B)`` tuple, as web color name
(like "red") or in hexadecimal format (``#RGB`` or
``#RRGGBB``). Some serializers (SVG and PNG) accept an alpha
transparency value like ``#RRGGBBAA``.
background A string or tuple representing a color for the light modules
or background. See "color" for valid values.
The default value depends on the serializer. SVG uses no
background color (``None``) by default, other serializers
use "white" as default background color.
========== ==============================================================
**Scalable Vector Graphics (SVG)**
============= ==============================================================
Name Description
============= ==============================================================
out Filename or io.BytesIO
kind "svg" or "svgz" (to create a gzip compressed SVG)
scale integer or float
color Default: "#000" (black)
``None`` is a valid value. If set to ``None``, the resulting
path won't have a "stroke" attribute. The "stroke" attribute
may be defined via CSS (external).
If an alpha channel is defined, the output depends of the
used SVG version. For SVG versions >= 2.0, the "stroke"
attribute will have a value like "rgba(R, G, B, A)", otherwise
the path gets another attribute "stroke-opacity" to emulate
the alpha channel.
To minimize the document size, the SVG serializer uses
automatically the shortest color representation: If
a value like "#000000" is provided, the resulting
document will have a color value of "#000". If the color
is "#FF0000", the resulting color is not "#F00", but
the web color name "red".
background Default value ``None``. If this paramater is set to another
value, the resulting image will have another path which
is used to define the background color.
If an alpha channel is used, the resulting path may
have a "fill-opacity" attribute (for SVG version < 2.0)
or the "fill" attribute has a "rgba(R, G, B, A)" value.
See keyword "color" for further details.
xmldecl Boolean value (default: ``True``) indicating whether the
document should have an XML declaration header.
Set to ``False`` to omit the header.
svgns Boolean value (default: ``True``) indicating whether the
document should have an explicit SVG namespace declaration.
Set to ``False`` to omit the namespace declaration.
The latter might be useful if the document should be
embedded into a HTML 5 document where the SVG namespace
is implicitly defined.
title String (default: ``None``) Optional title of the generated
SVG document.
desc String (default: ``None``) Optional description of the
generated SVG document.
svgid A string indicating the ID of the SVG document
(if set to ``None`` (default), the SVG element won't have
an ID).
svgclass Default: "segno". The CSS class of the SVG document
(if set to ``None``, the SVG element won't have a class).
lineclass Default: "qrline". The CSS class of the path element
(which draws the dark modules (if set to ``None``, the path
won't have a class).
omitsize Indicates if width and height attributes should be
omitted (default: ``False``). If these attributes are
omitted, a ``viewBox`` attribute will be added to the
document.
unit Default: ``None``
Inidctaes the unit for width / height and other coordinates.
By default, the unit is unspecified and all values are
in the user space.
Valid values: em, ex, px, pt, pc, cm, mm, in, and percentages
(any string is accepted, this parameter is not validated
by the serializer)
encoding Encoding of the XML document. "utf-8" by default.
svgversion SVG version (default: ``None``). If specified (a float),
the resulting document has an explicit "version" attribute.
If set to ``None``, the document won't have a "version"
attribute. This parameter is not validated.
compresslevel Default: 9. This parameter is only valid, if a compressed
SVG document should be created (file extension "svgz").
1 is fastest and produces the least compression, 9 is slowest
and produces the most. 0 is no compression.
============= ==============================================================
**Portable Network Graphics (PNG)**
============= ==============================================================
Name Description
============= ==============================================================
out Filename or io.BytesIO
kind "png"
scale integer
color Default: "#000" (black)
``None`` is a valid value iff background is not ``None``.
background Default value ``#fff`` (white)
See keyword "color" for further details.
compresslevel Default: 9. Integer indicating the compression level
for the ``IDAT`` (data) chunk.
1 is fastest and produces the least compression, 9 is slowest
and produces the most. 0 is no compression.
dpi Default: None. Specifies the DPI value for the image.
By default, the DPI value is unspecified. Please note
that the DPI value is converted into meters (maybe with
rounding errors) since PNG does not support the unit
"dots per inch".
addad Boolean value (default: True) to (dis-)allow a "Software"
comment indicating that the file was created by Segno.
============= ==============================================================
**Encapsulated PostScript (EPS)**
============= ==============================================================
Name Description
============= ==============================================================
out Filename or io.StringIO
kind "eps"
scale integer or float
color Default: "#000" (black)
background Default value: ``None`` (no background)
============= ==============================================================
**Portable Document Format (PDF)**
============= ==============================================================
Name Description
============= ==============================================================
out Filename or io.BytesIO
kind "pdf"
scale integer or float
compresslevel Default: 9. Integer indicating the compression level.
1 is fastest and produces the least compression, 9 is slowest
and produces the most. 0 is no compression.
============= ==============================================================
**Text (TXT)**
Does not support the "scale" keyword!
============= ==============================================================
Name Description
============= ==============================================================
out Filename or io.StringIO
kind "txt"
color Default: "1"
background Default: "0"
============= ==============================================================
**ANSI escape code**
Supports the "border" keyword, only!
============= ==============================================================
Name Description
============= ==============================================================
kind "ans"
============= ==============================================================
**Portable Bitmap (PBM)**
============= ==============================================================
Name Description
============= ==============================================================
out Filename or io.BytesIO
kind "pbm"
scale integer
plain Default: False. Boolean to switch between the P4 and P1 format.
If set to ``True``, the (outdated) P1 serialization format is
used.
============= ==============================================================
**Portable Arbitrary Map (PAM)**
============= ==============================================================
Name Description
============= ==============================================================
out Filename or io.BytesIO
kind "pam"
scale integer
color Default: "#000" (black).
background Default value ``#fff`` (white). Use ``None`` for a transparent
background.
============= ==============================================================
**LaTeX / PGF/TikZ**
To use the output of this serializer, the ``PGF/TikZ`` (and optionally
``hyperref``) package is required in the LaTeX environment. The
serializer itself does not depend on any external packages.
============= ==============================================================
Name Description
============= ==============================================================
out Filename or io.StringIO
kind "tex"
scale integer or float
color LaTeX color name (default: "black"). The color is written
"at it is", so ensure that the color is a standard color or it
has been defined in the enclosing LaTeX document.
url Default: ``None``. Optional URL where the QR Code should
point to. Requires the ``hyperref`` package in your LaTeX
environment.
============= ==============================================================
**X BitMap (XBM)**
============= ==============================================================
Name Description
============= ==============================================================
out Filename or io.StringIO
kind "xbm"
scale integer
name Name of the variable (default: "img")
============= ==============================================================
**X PixMap (XPM)**
============= ==============================================================
Name Description
============= ==============================================================
out Filename or io.StringIO
kind "xpm"
scale integer
color Default: "#000" (black).
background Default value ``#fff`` (white)
``None`` indicates a transparent background.
name Name of the variable (default: "img")
============= ==============================================================
:param out: A filename or a writable file-like object with a
``name`` attribute. Use the `kind` parameter if `out` is
a :py:class:`io.ByteIO` or :py:class:`io.StringIO` stream which
don't have a ``name`` attribute.
:param kind: If the desired output format cannot be determined from
the ``out`` parameter, this parameter can be used to indicate the
serialization format (i.e. "svg" to enforce SVG output)
:param kw: Any of the supported keywords by the specific serialization
method. | [
"\\",
"Serializes",
"the",
"QR",
"Code",
"in",
"one",
"of",
"the",
"supported",
"formats",
".",
"The",
"serialization",
"format",
"depends",
"on",
"the",
"filename",
"extension",
"."
] | 64d912a2bd17d0b5ff3e8b5d37098edfc663c2b3 | https://github.com/heuer/segno/blob/64d912a2bd17d0b5ff3e8b5d37098edfc663c2b3/segno/__init__.py#L454-L728 | train | 31,918 |
heuer/segno | segno/__init__.py | QRCodeSequence.terminal | def terminal(self, out=None, border=None):
"""\
Serializes the sequence of QR Codes as ANSI escape code.
See :py:meth:`QRCode.terminal()` for details.
"""
for qrcode in self:
qrcode.terminal(out=out, border=border) | python | def terminal(self, out=None, border=None):
"""\
Serializes the sequence of QR Codes as ANSI escape code.
See :py:meth:`QRCode.terminal()` for details.
"""
for qrcode in self:
qrcode.terminal(out=out, border=border) | [
"def",
"terminal",
"(",
"self",
",",
"out",
"=",
"None",
",",
"border",
"=",
"None",
")",
":",
"for",
"qrcode",
"in",
"self",
":",
"qrcode",
".",
"terminal",
"(",
"out",
"=",
"out",
",",
"border",
"=",
"border",
")"
] | \
Serializes the sequence of QR Codes as ANSI escape code.
See :py:meth:`QRCode.terminal()` for details. | [
"\\",
"Serializes",
"the",
"sequence",
"of",
"QR",
"Codes",
"as",
"ANSI",
"escape",
"code",
"."
] | 64d912a2bd17d0b5ff3e8b5d37098edfc663c2b3 | https://github.com/heuer/segno/blob/64d912a2bd17d0b5ff3e8b5d37098edfc663c2b3/segno/__init__.py#L760-L767 | train | 31,919 |
heuer/segno | segno/__init__.py | QRCodeSequence.save | def save(self, out, kind=None, **kw):
"""\
Saves the sequence of QR Code to `out`.
If `out` is a filename, this method modifies the filename and adds
``<Number of QR Codes>-<Current QR Code>`` to it.
``structured-append.svg`` becomes (if the sequence contains two QR Codes):
``structured-append-02-01.svg`` and ``structured-append-02-02.svg``
Please note that using a file or file-like object may result into an
invalid serialization format since all QR Codes are written to the same
output.
See :py:meth:`QRCode.save()` for a detailed enumeration of options.
"""
m = len(self)
def prepare_fn_noop(o, n):
"""\
Function to enumerate file names, does nothing by default
"""
return o
def prepare_filename(o, n):
"""\
Function to enumerate file names.
"""
return o.format(m, n)
prepare_fn = prepare_fn_noop
if m > 1 and isinstance(out, str_type):
dot_idx = out.rfind('.')
if dot_idx > -1:
out = out[:dot_idx] + '-{0:02d}-{1:02d}' + out[dot_idx:]
prepare_fn = prepare_filename
for n, qrcode in enumerate(self, start=1):
qrcode.save(prepare_fn(out, n), kind=kind, **kw) | python | def save(self, out, kind=None, **kw):
"""\
Saves the sequence of QR Code to `out`.
If `out` is a filename, this method modifies the filename and adds
``<Number of QR Codes>-<Current QR Code>`` to it.
``structured-append.svg`` becomes (if the sequence contains two QR Codes):
``structured-append-02-01.svg`` and ``structured-append-02-02.svg``
Please note that using a file or file-like object may result into an
invalid serialization format since all QR Codes are written to the same
output.
See :py:meth:`QRCode.save()` for a detailed enumeration of options.
"""
m = len(self)
def prepare_fn_noop(o, n):
"""\
Function to enumerate file names, does nothing by default
"""
return o
def prepare_filename(o, n):
"""\
Function to enumerate file names.
"""
return o.format(m, n)
prepare_fn = prepare_fn_noop
if m > 1 and isinstance(out, str_type):
dot_idx = out.rfind('.')
if dot_idx > -1:
out = out[:dot_idx] + '-{0:02d}-{1:02d}' + out[dot_idx:]
prepare_fn = prepare_filename
for n, qrcode in enumerate(self, start=1):
qrcode.save(prepare_fn(out, n), kind=kind, **kw) | [
"def",
"save",
"(",
"self",
",",
"out",
",",
"kind",
"=",
"None",
",",
"*",
"*",
"kw",
")",
":",
"m",
"=",
"len",
"(",
"self",
")",
"def",
"prepare_fn_noop",
"(",
"o",
",",
"n",
")",
":",
"\"\"\"\\\n Function to enumerate file names, does nothin... | \
Saves the sequence of QR Code to `out`.
If `out` is a filename, this method modifies the filename and adds
``<Number of QR Codes>-<Current QR Code>`` to it.
``structured-append.svg`` becomes (if the sequence contains two QR Codes):
``structured-append-02-01.svg`` and ``structured-append-02-02.svg``
Please note that using a file or file-like object may result into an
invalid serialization format since all QR Codes are written to the same
output.
See :py:meth:`QRCode.save()` for a detailed enumeration of options. | [
"\\",
"Saves",
"the",
"sequence",
"of",
"QR",
"Code",
"to",
"out",
"."
] | 64d912a2bd17d0b5ff3e8b5d37098edfc663c2b3 | https://github.com/heuer/segno/blob/64d912a2bd17d0b5ff3e8b5d37098edfc663c2b3/segno/__init__.py#L769-L805 | train | 31,920 |
heuer/segno | segno/writers.py | writable | def writable(file_or_path, mode, encoding=None):
"""\
Returns a writable file-like object.
Usage::
with writable(file_name_or_path, 'wb') as f:
...
:param file_or_path: Either a file-like object or a filename.
:param str mode: String indicating the writing mode (i.e. ``'wb'``)
"""
f = file_or_path
must_close = False
try:
file_or_path.write
if encoding is not None:
f = codecs.getwriter(encoding)(file_or_path)
except AttributeError:
f = open(file_or_path, mode, encoding=encoding)
must_close = True
try:
yield f
finally:
if must_close:
f.close() | python | def writable(file_or_path, mode, encoding=None):
"""\
Returns a writable file-like object.
Usage::
with writable(file_name_or_path, 'wb') as f:
...
:param file_or_path: Either a file-like object or a filename.
:param str mode: String indicating the writing mode (i.e. ``'wb'``)
"""
f = file_or_path
must_close = False
try:
file_or_path.write
if encoding is not None:
f = codecs.getwriter(encoding)(file_or_path)
except AttributeError:
f = open(file_or_path, mode, encoding=encoding)
must_close = True
try:
yield f
finally:
if must_close:
f.close() | [
"def",
"writable",
"(",
"file_or_path",
",",
"mode",
",",
"encoding",
"=",
"None",
")",
":",
"f",
"=",
"file_or_path",
"must_close",
"=",
"False",
"try",
":",
"file_or_path",
".",
"write",
"if",
"encoding",
"is",
"not",
"None",
":",
"f",
"=",
"codecs",
... | \
Returns a writable file-like object.
Usage::
with writable(file_name_or_path, 'wb') as f:
...
:param file_or_path: Either a file-like object or a filename.
:param str mode: String indicating the writing mode (i.e. ``'wb'``) | [
"\\",
"Returns",
"a",
"writable",
"file",
"-",
"like",
"object",
"."
] | 64d912a2bd17d0b5ff3e8b5d37098edfc663c2b3 | https://github.com/heuer/segno/blob/64d912a2bd17d0b5ff3e8b5d37098edfc663c2b3/segno/writers.py#L49-L75 | train | 31,921 |
heuer/segno | segno/writers.py | as_svg_data_uri | def as_svg_data_uri(matrix, version, scale=1, border=None, color='#000',
background=None, xmldecl=False, svgns=True, title=None,
desc=None, svgid=None, svgclass='segno',
lineclass='qrline', omitsize=False, unit='',
encoding='utf-8', svgversion=None, nl=False,
encode_minimal=False, omit_charset=False):
"""\
Converts the matrix to a SVG data URI.
The XML declaration is omitted by default (set ``xmldecl`` to ``True``
to enable it), further the newline is omitted by default (set ``nl`` to
``True`` to enable it).
Aside from the missing ``out`` parameter and the different ``xmldecl``
and ``nl`` default values and the additional parameter ``encode_minimal``
and ``omit_charset`` this function uses the same parameters as the
usual SVG serializer.
:param bool encode_minimal: Indicates if the resulting data URI should
use minimal percent encoding (disabled by default).
:param bool omit_charset: Indicates if the ``;charset=...`` should be omitted
(disabled by default)
:rtype: str
"""
encode = partial(quote, safe=b"") if not encode_minimal else partial(quote, safe=b" :/='")
buff = io.BytesIO()
write_svg(matrix, version, buff, scale=scale, color=color, background=background,
border=border, xmldecl=xmldecl, svgns=svgns, title=title,
desc=desc, svgclass=svgclass, lineclass=lineclass,
omitsize=omitsize, encoding=encoding, svgid=svgid, unit=unit,
svgversion=svgversion, nl=nl)
return 'data:image/svg+xml{0},{1}' \
.format(';charset=' + encoding if not omit_charset else '',
# Replace " quotes with ' and URL encode the result
# See also https://codepen.io/tigt/post/optimizing-svgs-in-data-uris
encode(_replace_quotes(buff.getvalue()))) | python | def as_svg_data_uri(matrix, version, scale=1, border=None, color='#000',
background=None, xmldecl=False, svgns=True, title=None,
desc=None, svgid=None, svgclass='segno',
lineclass='qrline', omitsize=False, unit='',
encoding='utf-8', svgversion=None, nl=False,
encode_minimal=False, omit_charset=False):
"""\
Converts the matrix to a SVG data URI.
The XML declaration is omitted by default (set ``xmldecl`` to ``True``
to enable it), further the newline is omitted by default (set ``nl`` to
``True`` to enable it).
Aside from the missing ``out`` parameter and the different ``xmldecl``
and ``nl`` default values and the additional parameter ``encode_minimal``
and ``omit_charset`` this function uses the same parameters as the
usual SVG serializer.
:param bool encode_minimal: Indicates if the resulting data URI should
use minimal percent encoding (disabled by default).
:param bool omit_charset: Indicates if the ``;charset=...`` should be omitted
(disabled by default)
:rtype: str
"""
encode = partial(quote, safe=b"") if not encode_minimal else partial(quote, safe=b" :/='")
buff = io.BytesIO()
write_svg(matrix, version, buff, scale=scale, color=color, background=background,
border=border, xmldecl=xmldecl, svgns=svgns, title=title,
desc=desc, svgclass=svgclass, lineclass=lineclass,
omitsize=omitsize, encoding=encoding, svgid=svgid, unit=unit,
svgversion=svgversion, nl=nl)
return 'data:image/svg+xml{0},{1}' \
.format(';charset=' + encoding if not omit_charset else '',
# Replace " quotes with ' and URL encode the result
# See also https://codepen.io/tigt/post/optimizing-svgs-in-data-uris
encode(_replace_quotes(buff.getvalue()))) | [
"def",
"as_svg_data_uri",
"(",
"matrix",
",",
"version",
",",
"scale",
"=",
"1",
",",
"border",
"=",
"None",
",",
"color",
"=",
"'#000'",
",",
"background",
"=",
"None",
",",
"xmldecl",
"=",
"False",
",",
"svgns",
"=",
"True",
",",
"title",
"=",
"Non... | \
Converts the matrix to a SVG data URI.
The XML declaration is omitted by default (set ``xmldecl`` to ``True``
to enable it), further the newline is omitted by default (set ``nl`` to
``True`` to enable it).
Aside from the missing ``out`` parameter and the different ``xmldecl``
and ``nl`` default values and the additional parameter ``encode_minimal``
and ``omit_charset`` this function uses the same parameters as the
usual SVG serializer.
:param bool encode_minimal: Indicates if the resulting data URI should
use minimal percent encoding (disabled by default).
:param bool omit_charset: Indicates if the ``;charset=...`` should be omitted
(disabled by default)
:rtype: str | [
"\\",
"Converts",
"the",
"matrix",
"to",
"a",
"SVG",
"data",
"URI",
"."
] | 64d912a2bd17d0b5ff3e8b5d37098edfc663c2b3 | https://github.com/heuer/segno/blob/64d912a2bd17d0b5ff3e8b5d37098edfc663c2b3/segno/writers.py#L197-L232 | train | 31,922 |
heuer/segno | segno/writers.py | write_svg_debug | def write_svg_debug(matrix, version, out, scale=15, border=None,
fallback_color='fuchsia', color_mapping=None,
add_legend=True):
"""\
Internal SVG serializer which is useful to debugging purposes.
This function is not exposed to the QRCode class by intention and the
resulting SVG document is very inefficient (lots of <rect/>s).
Dark modules are black and light modules are white by default. Provide
a custom `color_mapping` to override these defaults.
Unknown modules are red by default.
:param matrix: The matrix
:param version: Version constant
:param out: binary file-like object or file name
:param scale: Scaling factor
:param border: Quiet zone
:param fallback_color: Color which is used for modules which are not 0x0 or 0x1
and for which no entry in `color_mapping` is defined.
:param color_mapping: dict of module values to color mapping (optional)
:param bool add_legend: Indicates if the bit values should be added to the
matrix (default: True)
"""
clr_mapping = {
0x0: '#fff',
0x1: '#000',
0x2: 'red',
0x3: 'orange',
0x4: 'gold',
0x5: 'green',
}
if color_mapping is not None:
clr_mapping.update(color_mapping)
border = get_border(version, border)
width, height = get_symbol_size(version, scale, border)
matrix_size = get_symbol_size(version, scale=1, border=0)[0]
with writable(out, 'wt', encoding='utf-8') as f:
legend = []
write = f.write
write('<?xml version="1.0" encoding="utf-8"?>\n')
write('<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 {0} {1}">'.format(width, height))
write('<style type="text/css"><![CDATA[ text { font-size: 1px; font-family: Helvetica, Arial, sans; } ]]></style>')
write('<g transform="scale({0})">'.format(scale))
for i in range(matrix_size):
y = i + border
for j in range(matrix_size):
x = j + border
bit = matrix[i][j]
if add_legend and bit not in (0x0, 0x1):
legend.append((x, y, bit))
fill = clr_mapping.get(bit, fallback_color)
write('<rect x="{0}" y="{1}" width="1" height="1" fill="{2}"/>'.format(x, y, fill))
# legend may be empty if add_legend == False
for x, y, val in legend:
write('<text x="{0}" y="{1}">{2}</text>'.format(x+.2, y+.9, val))
write('</g></svg>\n') | python | def write_svg_debug(matrix, version, out, scale=15, border=None,
fallback_color='fuchsia', color_mapping=None,
add_legend=True):
"""\
Internal SVG serializer which is useful to debugging purposes.
This function is not exposed to the QRCode class by intention and the
resulting SVG document is very inefficient (lots of <rect/>s).
Dark modules are black and light modules are white by default. Provide
a custom `color_mapping` to override these defaults.
Unknown modules are red by default.
:param matrix: The matrix
:param version: Version constant
:param out: binary file-like object or file name
:param scale: Scaling factor
:param border: Quiet zone
:param fallback_color: Color which is used for modules which are not 0x0 or 0x1
and for which no entry in `color_mapping` is defined.
:param color_mapping: dict of module values to color mapping (optional)
:param bool add_legend: Indicates if the bit values should be added to the
matrix (default: True)
"""
clr_mapping = {
0x0: '#fff',
0x1: '#000',
0x2: 'red',
0x3: 'orange',
0x4: 'gold',
0x5: 'green',
}
if color_mapping is not None:
clr_mapping.update(color_mapping)
border = get_border(version, border)
width, height = get_symbol_size(version, scale, border)
matrix_size = get_symbol_size(version, scale=1, border=0)[0]
with writable(out, 'wt', encoding='utf-8') as f:
legend = []
write = f.write
write('<?xml version="1.0" encoding="utf-8"?>\n')
write('<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 {0} {1}">'.format(width, height))
write('<style type="text/css"><![CDATA[ text { font-size: 1px; font-family: Helvetica, Arial, sans; } ]]></style>')
write('<g transform="scale({0})">'.format(scale))
for i in range(matrix_size):
y = i + border
for j in range(matrix_size):
x = j + border
bit = matrix[i][j]
if add_legend and bit not in (0x0, 0x1):
legend.append((x, y, bit))
fill = clr_mapping.get(bit, fallback_color)
write('<rect x="{0}" y="{1}" width="1" height="1" fill="{2}"/>'.format(x, y, fill))
# legend may be empty if add_legend == False
for x, y, val in legend:
write('<text x="{0}" y="{1}">{2}</text>'.format(x+.2, y+.9, val))
write('</g></svg>\n') | [
"def",
"write_svg_debug",
"(",
"matrix",
",",
"version",
",",
"out",
",",
"scale",
"=",
"15",
",",
"border",
"=",
"None",
",",
"fallback_color",
"=",
"'fuchsia'",
",",
"color_mapping",
"=",
"None",
",",
"add_legend",
"=",
"True",
")",
":",
"clr_mapping",
... | \
Internal SVG serializer which is useful to debugging purposes.
This function is not exposed to the QRCode class by intention and the
resulting SVG document is very inefficient (lots of <rect/>s).
Dark modules are black and light modules are white by default. Provide
a custom `color_mapping` to override these defaults.
Unknown modules are red by default.
:param matrix: The matrix
:param version: Version constant
:param out: binary file-like object or file name
:param scale: Scaling factor
:param border: Quiet zone
:param fallback_color: Color which is used for modules which are not 0x0 or 0x1
and for which no entry in `color_mapping` is defined.
:param color_mapping: dict of module values to color mapping (optional)
:param bool add_legend: Indicates if the bit values should be added to the
matrix (default: True) | [
"\\",
"Internal",
"SVG",
"serializer",
"which",
"is",
"useful",
"to",
"debugging",
"purposes",
"."
] | 64d912a2bd17d0b5ff3e8b5d37098edfc663c2b3 | https://github.com/heuer/segno/blob/64d912a2bd17d0b5ff3e8b5d37098edfc663c2b3/segno/writers.py#L235-L290 | train | 31,923 |
heuer/segno | segno/writers.py | write_eps | def write_eps(matrix, version, out, scale=1, border=None, color='#000',
background=None):
"""\
Serializes the QR Code as EPS document.
:param matrix: The matrix to serialize.
:param int version: The (Micro) QR code version
:param out: Filename or a file-like object supporting to write strings.
:param scale: Indicates the size of a single module (default: 1 which
corresponds to 1 point (1/72 inch) per module).
:param int border: Integer indicating the size of the quiet zone.
If set to ``None`` (default), the recommended border size
will be used (``4`` for QR Codes, ``2`` for a Micro QR Codes).
:param color: Color of the modules (default: black). The
color can be provided as ``(R, G, B)`` tuple (this method
acceppts floats as R, G, B values), as web color name (like
"red") or in hexadecimal format (``#RGB`` or ``#RRGGBB``).
:param background: Optional background color (default: ``None`` = no
background color). See `color` for valid values.
"""
import textwrap
def write_line(writemeth, content):
"""\
Writes `content` and ``LF``.
"""
# Postscript: Max. 255 characters per line
for line in textwrap.wrap(content, 254):
writemeth(line)
writemeth('\n')
def rgb_to_floats(clr):
"""\
Converts the provided color into an acceptable format for Postscript's
``setrgbcolor``
"""
def to_float(c):
if isinstance(c, float):
if not 0.0 <= c <= 1.0:
raise ValueError('Invalid color "{0}". Not in range 0 .. 1'
.format(c))
return c
return 1 / 255.0 * c if c != 1 else c
return tuple([to_float(i) for i in colors.color_to_rgb(clr)])
check_valid_scale(scale)
check_valid_border(border)
with writable(out, 'wt') as f:
writeline = partial(write_line, f.write)
border = get_border(version, border)
width, height = get_symbol_size(version, scale, border)
# Write common header
writeline('%!PS-Adobe-3.0 EPSF-3.0')
writeline('%%Creator: {0}'.format(CREATOR))
writeline('%%CreationDate: {0}'.format(time.strftime("%Y-%m-%d %H:%M:%S")))
writeline('%%DocumentData: Clean7Bit')
writeline('%%BoundingBox: 0 0 {0} {1}'.format(width, height))
# Write the shortcuts
writeline('/m { rmoveto } bind def')
writeline('/l { rlineto } bind def')
stroke_color_is_black = colors.color_is_black(color)
stroke_color = color if stroke_color_is_black else rgb_to_floats(color)
if background is not None:
writeline('{0:f} {1:f} {2:f} setrgbcolor clippath fill'
.format(*rgb_to_floats(background)))
if stroke_color_is_black:
# Reset RGB color back to black iff stroke color is black
# In case stroke color != black set the RGB color later
writeline('0 0 0 setrgbcolor')
if not stroke_color_is_black:
writeline('{0:f} {1:f} {2:f} setrgbcolor'.format(*stroke_color))
if scale != 1:
writeline('{0} {0} scale'.format(scale))
writeline('newpath')
# Current pen position y-axis
# Note: 0, 0 = lower left corner in PS coordinate system
y = get_symbol_size(version, scale=1, border=0)[1] + border - .5 # .5 = linewidth / 2
line_iter = matrix_to_lines(matrix, border, y, incby=-1)
# EPS supports absolute coordinates as well, but relative coordinates
# are more compact and IMO nicer; so the 1st coordinate is absolute, all
# other coordinates are relative
(x1, y1), (x2, y2) = next(line_iter)
coord = ['{0} {1} moveto {2} 0 l'.format(x1, y1, x2 - x1)]
append_coord = coord.append
x = x2
for (x1, y1), (x2, y2) in line_iter:
append_coord(' {0} {1} m {2} 0 l'.format(x1 - x, int(y1 - y), x2 - x1))
x, y = x2, y2
writeline(''.join(coord))
writeline('stroke')
writeline('%%EOF') | python | def write_eps(matrix, version, out, scale=1, border=None, color='#000',
background=None):
"""\
Serializes the QR Code as EPS document.
:param matrix: The matrix to serialize.
:param int version: The (Micro) QR code version
:param out: Filename or a file-like object supporting to write strings.
:param scale: Indicates the size of a single module (default: 1 which
corresponds to 1 point (1/72 inch) per module).
:param int border: Integer indicating the size of the quiet zone.
If set to ``None`` (default), the recommended border size
will be used (``4`` for QR Codes, ``2`` for a Micro QR Codes).
:param color: Color of the modules (default: black). The
color can be provided as ``(R, G, B)`` tuple (this method
acceppts floats as R, G, B values), as web color name (like
"red") or in hexadecimal format (``#RGB`` or ``#RRGGBB``).
:param background: Optional background color (default: ``None`` = no
background color). See `color` for valid values.
"""
import textwrap
def write_line(writemeth, content):
"""\
Writes `content` and ``LF``.
"""
# Postscript: Max. 255 characters per line
for line in textwrap.wrap(content, 254):
writemeth(line)
writemeth('\n')
def rgb_to_floats(clr):
"""\
Converts the provided color into an acceptable format for Postscript's
``setrgbcolor``
"""
def to_float(c):
if isinstance(c, float):
if not 0.0 <= c <= 1.0:
raise ValueError('Invalid color "{0}". Not in range 0 .. 1'
.format(c))
return c
return 1 / 255.0 * c if c != 1 else c
return tuple([to_float(i) for i in colors.color_to_rgb(clr)])
check_valid_scale(scale)
check_valid_border(border)
with writable(out, 'wt') as f:
writeline = partial(write_line, f.write)
border = get_border(version, border)
width, height = get_symbol_size(version, scale, border)
# Write common header
writeline('%!PS-Adobe-3.0 EPSF-3.0')
writeline('%%Creator: {0}'.format(CREATOR))
writeline('%%CreationDate: {0}'.format(time.strftime("%Y-%m-%d %H:%M:%S")))
writeline('%%DocumentData: Clean7Bit')
writeline('%%BoundingBox: 0 0 {0} {1}'.format(width, height))
# Write the shortcuts
writeline('/m { rmoveto } bind def')
writeline('/l { rlineto } bind def')
stroke_color_is_black = colors.color_is_black(color)
stroke_color = color if stroke_color_is_black else rgb_to_floats(color)
if background is not None:
writeline('{0:f} {1:f} {2:f} setrgbcolor clippath fill'
.format(*rgb_to_floats(background)))
if stroke_color_is_black:
# Reset RGB color back to black iff stroke color is black
# In case stroke color != black set the RGB color later
writeline('0 0 0 setrgbcolor')
if not stroke_color_is_black:
writeline('{0:f} {1:f} {2:f} setrgbcolor'.format(*stroke_color))
if scale != 1:
writeline('{0} {0} scale'.format(scale))
writeline('newpath')
# Current pen position y-axis
# Note: 0, 0 = lower left corner in PS coordinate system
y = get_symbol_size(version, scale=1, border=0)[1] + border - .5 # .5 = linewidth / 2
line_iter = matrix_to_lines(matrix, border, y, incby=-1)
# EPS supports absolute coordinates as well, but relative coordinates
# are more compact and IMO nicer; so the 1st coordinate is absolute, all
# other coordinates are relative
(x1, y1), (x2, y2) = next(line_iter)
coord = ['{0} {1} moveto {2} 0 l'.format(x1, y1, x2 - x1)]
append_coord = coord.append
x = x2
for (x1, y1), (x2, y2) in line_iter:
append_coord(' {0} {1} m {2} 0 l'.format(x1 - x, int(y1 - y), x2 - x1))
x, y = x2, y2
writeline(''.join(coord))
writeline('stroke')
writeline('%%EOF') | [
"def",
"write_eps",
"(",
"matrix",
",",
"version",
",",
"out",
",",
"scale",
"=",
"1",
",",
"border",
"=",
"None",
",",
"color",
"=",
"'#000'",
",",
"background",
"=",
"None",
")",
":",
"import",
"textwrap",
"def",
"write_line",
"(",
"writemeth",
",",
... | \
Serializes the QR Code as EPS document.
:param matrix: The matrix to serialize.
:param int version: The (Micro) QR code version
:param out: Filename or a file-like object supporting to write strings.
:param scale: Indicates the size of a single module (default: 1 which
corresponds to 1 point (1/72 inch) per module).
:param int border: Integer indicating the size of the quiet zone.
If set to ``None`` (default), the recommended border size
will be used (``4`` for QR Codes, ``2`` for a Micro QR Codes).
:param color: Color of the modules (default: black). The
color can be provided as ``(R, G, B)`` tuple (this method
acceppts floats as R, G, B values), as web color name (like
"red") or in hexadecimal format (``#RGB`` or ``#RRGGBB``).
:param background: Optional background color (default: ``None`` = no
background color). See `color` for valid values. | [
"\\",
"Serializes",
"the",
"QR",
"Code",
"as",
"EPS",
"document",
"."
] | 64d912a2bd17d0b5ff3e8b5d37098edfc663c2b3 | https://github.com/heuer/segno/blob/64d912a2bd17d0b5ff3e8b5d37098edfc663c2b3/segno/writers.py#L293-L384 | train | 31,924 |
heuer/segno | segno/writers.py | as_png_data_uri | def as_png_data_uri(matrix, version, scale=1, border=None, color='#000',
background='#fff', compresslevel=9, addad=True):
"""\
Converts the provided matrix into a PNG data URI.
:rtype: str
"""
buff = io.BytesIO()
write_png(matrix, version, buff, scale=scale, border=border, color=color,
background=background, compresslevel=compresslevel, addad=addad)
return 'data:image/png;base64,{0}' \
.format(base64.b64encode(buff.getvalue()).decode('ascii')) | python | def as_png_data_uri(matrix, version, scale=1, border=None, color='#000',
background='#fff', compresslevel=9, addad=True):
"""\
Converts the provided matrix into a PNG data URI.
:rtype: str
"""
buff = io.BytesIO()
write_png(matrix, version, buff, scale=scale, border=border, color=color,
background=background, compresslevel=compresslevel, addad=addad)
return 'data:image/png;base64,{0}' \
.format(base64.b64encode(buff.getvalue()).decode('ascii')) | [
"def",
"as_png_data_uri",
"(",
"matrix",
",",
"version",
",",
"scale",
"=",
"1",
",",
"border",
"=",
"None",
",",
"color",
"=",
"'#000'",
",",
"background",
"=",
"'#fff'",
",",
"compresslevel",
"=",
"9",
",",
"addad",
"=",
"True",
")",
":",
"buff",
"... | \
Converts the provided matrix into a PNG data URI.
:rtype: str | [
"\\",
"Converts",
"the",
"provided",
"matrix",
"into",
"a",
"PNG",
"data",
"URI",
"."
] | 64d912a2bd17d0b5ff3e8b5d37098edfc663c2b3 | https://github.com/heuer/segno/blob/64d912a2bd17d0b5ff3e8b5d37098edfc663c2b3/segno/writers.py#L568-L579 | train | 31,925 |
heuer/segno | segno/writers.py | write_txt | def write_txt(matrix, version, out, border=None, color='1', background='0'):
"""\
Serializes QR code in a text format.
:param matrix: The matrix to serialize.
:param int version: The (Micro) QR code version
:param out: Filename or a file-like object supporting to write text.
:param int border: Integer indicating the size of the quiet zone.
If set to ``None`` (default), the recommended border size
will be used (``4`` for QR Codes, ``2`` for a Micro QR Codes).
:param color: Character to use for the black modules (default: '1')
:param background: Character to use for the white modules (default: '0')
"""
row_iter = matrix_iter(matrix, version, scale=1, border=border)
colours = (str(background), str(color))
with writable(out, 'wt') as f:
write = f.write
for row in row_iter:
write(''.join([colours[i] for i in row]))
write('\n') | python | def write_txt(matrix, version, out, border=None, color='1', background='0'):
"""\
Serializes QR code in a text format.
:param matrix: The matrix to serialize.
:param int version: The (Micro) QR code version
:param out: Filename or a file-like object supporting to write text.
:param int border: Integer indicating the size of the quiet zone.
If set to ``None`` (default), the recommended border size
will be used (``4`` for QR Codes, ``2`` for a Micro QR Codes).
:param color: Character to use for the black modules (default: '1')
:param background: Character to use for the white modules (default: '0')
"""
row_iter = matrix_iter(matrix, version, scale=1, border=border)
colours = (str(background), str(color))
with writable(out, 'wt') as f:
write = f.write
for row in row_iter:
write(''.join([colours[i] for i in row]))
write('\n') | [
"def",
"write_txt",
"(",
"matrix",
",",
"version",
",",
"out",
",",
"border",
"=",
"None",
",",
"color",
"=",
"'1'",
",",
"background",
"=",
"'0'",
")",
":",
"row_iter",
"=",
"matrix_iter",
"(",
"matrix",
",",
"version",
",",
"scale",
"=",
"1",
",",
... | \
Serializes QR code in a text format.
:param matrix: The matrix to serialize.
:param int version: The (Micro) QR code version
:param out: Filename or a file-like object supporting to write text.
:param int border: Integer indicating the size of the quiet zone.
If set to ``None`` (default), the recommended border size
will be used (``4`` for QR Codes, ``2`` for a Micro QR Codes).
:param color: Character to use for the black modules (default: '1')
:param background: Character to use for the white modules (default: '0') | [
"\\",
"Serializes",
"QR",
"code",
"in",
"a",
"text",
"format",
"."
] | 64d912a2bd17d0b5ff3e8b5d37098edfc663c2b3 | https://github.com/heuer/segno/blob/64d912a2bd17d0b5ff3e8b5d37098edfc663c2b3/segno/writers.py#L677-L696 | train | 31,926 |
heuer/segno | segno/writers.py | write_tex | def write_tex(matrix, version, out, scale=1, border=None, color='black', unit='pt', url=None):
"""\
Serializes the matrix as LaTeX PGF picture.
Requires the `PGF/TikZ <https://en.wikipedia.org/wiki/PGF/TikZ>`_ package
(i.e. ``\\usepackage{pgf}``) in the LaTeX source.
:param matrix: The matrix to serialize.
:param int version: The (Micro) QR code version
:param out: Filename or a file-like object supporting to write text data.
:param scale: Indicates the size of a single module (default: 1 which
corresponds to 1 x 1 in the provided unit per module).
:param int border: Integer indicating the size of the quiet zone.
If set to ``None`` (default), the recommended border size
will be used (``4`` for QR Codes, ``2`` for a Micro QR Codes).
:param str color: LaTeX color name. The color name is taken at it is, so
ensure that it refers either to a default color name or that the
color was defined previously.
:param unit: Unit of the drawing (default: ``pt``)
:param url: Optional URL where the QR Code should point to. Requires the
"hyperref" package. Default: ``None``.
"""
def point(x, y):
return '\\pgfqpoint{{{0}{2}}}{{{1}{2}}}'.format(x, y, unit)
check_valid_scale(scale)
check_valid_border(border)
border = get_border(version, border)
with writable(out, 'wt') as f:
write = f.write
write('% Creator: {0}\n'.format(CREATOR))
write('% Date: {0}\n'.format(time.strftime('%Y-%m-%dT%H:%M:%S')))
if url:
write('\\href{{{0}}}{{'.format(url))
write('\\begin{pgfpicture}\n')
write(' \\pgfsetlinewidth{{{0}{1}}}\n'.format(scale, unit))
if color and color != 'black':
write(' \\color{{{0}}}\n'.format(color))
x, y = border, -border
for (x1, y1), (x2, y2) in matrix_to_lines(matrix, x, y, incby=-1):
write(' \\pgfpathmoveto{{{0}}}\n'.format(point(x1 * scale, y1 * scale)))
write(' \\pgfpathlineto{{{0}}}\n'.format(point(x2 * scale, y2 * scale)))
write(' \\pgfusepath{stroke}\n')
write('\\end{{pgfpicture}}{0}\n'.format('' if not url else '}')) | python | def write_tex(matrix, version, out, scale=1, border=None, color='black', unit='pt', url=None):
"""\
Serializes the matrix as LaTeX PGF picture.
Requires the `PGF/TikZ <https://en.wikipedia.org/wiki/PGF/TikZ>`_ package
(i.e. ``\\usepackage{pgf}``) in the LaTeX source.
:param matrix: The matrix to serialize.
:param int version: The (Micro) QR code version
:param out: Filename or a file-like object supporting to write text data.
:param scale: Indicates the size of a single module (default: 1 which
corresponds to 1 x 1 in the provided unit per module).
:param int border: Integer indicating the size of the quiet zone.
If set to ``None`` (default), the recommended border size
will be used (``4`` for QR Codes, ``2`` for a Micro QR Codes).
:param str color: LaTeX color name. The color name is taken at it is, so
ensure that it refers either to a default color name or that the
color was defined previously.
:param unit: Unit of the drawing (default: ``pt``)
:param url: Optional URL where the QR Code should point to. Requires the
"hyperref" package. Default: ``None``.
"""
def point(x, y):
return '\\pgfqpoint{{{0}{2}}}{{{1}{2}}}'.format(x, y, unit)
check_valid_scale(scale)
check_valid_border(border)
border = get_border(version, border)
with writable(out, 'wt') as f:
write = f.write
write('% Creator: {0}\n'.format(CREATOR))
write('% Date: {0}\n'.format(time.strftime('%Y-%m-%dT%H:%M:%S')))
if url:
write('\\href{{{0}}}{{'.format(url))
write('\\begin{pgfpicture}\n')
write(' \\pgfsetlinewidth{{{0}{1}}}\n'.format(scale, unit))
if color and color != 'black':
write(' \\color{{{0}}}\n'.format(color))
x, y = border, -border
for (x1, y1), (x2, y2) in matrix_to_lines(matrix, x, y, incby=-1):
write(' \\pgfpathmoveto{{{0}}}\n'.format(point(x1 * scale, y1 * scale)))
write(' \\pgfpathlineto{{{0}}}\n'.format(point(x2 * scale, y2 * scale)))
write(' \\pgfusepath{stroke}\n')
write('\\end{{pgfpicture}}{0}\n'.format('' if not url else '}')) | [
"def",
"write_tex",
"(",
"matrix",
",",
"version",
",",
"out",
",",
"scale",
"=",
"1",
",",
"border",
"=",
"None",
",",
"color",
"=",
"'black'",
",",
"unit",
"=",
"'pt'",
",",
"url",
"=",
"None",
")",
":",
"def",
"point",
"(",
"x",
",",
"y",
")... | \
Serializes the matrix as LaTeX PGF picture.
Requires the `PGF/TikZ <https://en.wikipedia.org/wiki/PGF/TikZ>`_ package
(i.e. ``\\usepackage{pgf}``) in the LaTeX source.
:param matrix: The matrix to serialize.
:param int version: The (Micro) QR code version
:param out: Filename or a file-like object supporting to write text data.
:param scale: Indicates the size of a single module (default: 1 which
corresponds to 1 x 1 in the provided unit per module).
:param int border: Integer indicating the size of the quiet zone.
If set to ``None`` (default), the recommended border size
will be used (``4`` for QR Codes, ``2`` for a Micro QR Codes).
:param str color: LaTeX color name. The color name is taken at it is, so
ensure that it refers either to a default color name or that the
color was defined previously.
:param unit: Unit of the drawing (default: ``pt``)
:param url: Optional URL where the QR Code should point to. Requires the
"hyperref" package. Default: ``None``. | [
"\\",
"Serializes",
"the",
"matrix",
"as",
"LaTeX",
"PGF",
"picture",
"."
] | 64d912a2bd17d0b5ff3e8b5d37098edfc663c2b3 | https://github.com/heuer/segno/blob/64d912a2bd17d0b5ff3e8b5d37098edfc663c2b3/segno/writers.py#L878-L921 | train | 31,927 |
heuer/segno | segno/writers.py | write_terminal | def write_terminal(matrix, version, out, border=None):
"""\
Function to write to a terminal which supports ANSI escape codes.
:param matrix: The matrix to serialize.
:param int version: The (Micro) QR code version.
:param out: Filename or a file-like object supporting to write text.
:param int border: Integer indicating the size of the quiet zone.
If set to ``None`` (default), the recommended border size
will be used (``4`` for QR Codes, ``2`` for a Micro QR Codes).
"""
with writable(out, 'wt') as f:
write = f.write
colours = ['\033[{0}m'.format(i) for i in (7, 49)]
for row in matrix_iter(matrix, version, scale=1, border=border):
prev_bit = -1
cnt = 0
for bit in row:
if bit == prev_bit:
cnt += 1
else:
if cnt:
write(colours[prev_bit])
write(' ' * cnt)
write('\033[0m') # reset color
prev_bit = bit
cnt = 1
if cnt:
write(colours[prev_bit])
write(' ' * cnt)
write('\033[0m') # reset color
write('\n') | python | def write_terminal(matrix, version, out, border=None):
"""\
Function to write to a terminal which supports ANSI escape codes.
:param matrix: The matrix to serialize.
:param int version: The (Micro) QR code version.
:param out: Filename or a file-like object supporting to write text.
:param int border: Integer indicating the size of the quiet zone.
If set to ``None`` (default), the recommended border size
will be used (``4`` for QR Codes, ``2`` for a Micro QR Codes).
"""
with writable(out, 'wt') as f:
write = f.write
colours = ['\033[{0}m'.format(i) for i in (7, 49)]
for row in matrix_iter(matrix, version, scale=1, border=border):
prev_bit = -1
cnt = 0
for bit in row:
if bit == prev_bit:
cnt += 1
else:
if cnt:
write(colours[prev_bit])
write(' ' * cnt)
write('\033[0m') # reset color
prev_bit = bit
cnt = 1
if cnt:
write(colours[prev_bit])
write(' ' * cnt)
write('\033[0m') # reset color
write('\n') | [
"def",
"write_terminal",
"(",
"matrix",
",",
"version",
",",
"out",
",",
"border",
"=",
"None",
")",
":",
"with",
"writable",
"(",
"out",
",",
"'wt'",
")",
"as",
"f",
":",
"write",
"=",
"f",
".",
"write",
"colours",
"=",
"[",
"'\\033[{0}m'",
".",
"... | \
Function to write to a terminal which supports ANSI escape codes.
:param matrix: The matrix to serialize.
:param int version: The (Micro) QR code version.
:param out: Filename or a file-like object supporting to write text.
:param int border: Integer indicating the size of the quiet zone.
If set to ``None`` (default), the recommended border size
will be used (``4`` for QR Codes, ``2`` for a Micro QR Codes). | [
"\\",
"Function",
"to",
"write",
"to",
"a",
"terminal",
"which",
"supports",
"ANSI",
"escape",
"codes",
"."
] | 64d912a2bd17d0b5ff3e8b5d37098edfc663c2b3 | https://github.com/heuer/segno/blob/64d912a2bd17d0b5ff3e8b5d37098edfc663c2b3/segno/writers.py#L924-L955 | train | 31,928 |
heuer/segno | segno/writers.py | write_terminal_win | def write_terminal_win(matrix, version, border=None): # pragma: no cover
"""\
Function to write a QR Code to a MS Windows terminal.
:param matrix: The matrix to serialize.
:param int version: The (Micro) QR code version
:param int border: Integer indicating the size of the quiet zone.
If set to ``None`` (default), the recommended border size
will be used (``4`` for QR Codes, ``2`` for a Micro QR Codes).
"""
import sys
import struct
import ctypes
write = sys.stdout.write
std_out = ctypes.windll.kernel32.GetStdHandle(-11)
csbi = ctypes.create_string_buffer(22)
res = ctypes.windll.kernel32.GetConsoleScreenBufferInfo(std_out, csbi)
if not res:
raise OSError('Cannot find information about the console. '
'Not running on the command line?')
default_color = struct.unpack(b'hhhhHhhhhhh', csbi.raw)[4]
set_color = partial(ctypes.windll.kernel32.SetConsoleTextAttribute, std_out)
colours = (240, default_color)
for row in matrix_iter(matrix, version, scale=1, border=border):
prev_bit = -1
cnt = 0
for bit in row:
if bit == prev_bit:
cnt += 1
else:
if cnt:
set_color(colours[prev_bit])
write(' ' * cnt)
prev_bit = bit
cnt = 1
if cnt:
set_color(colours[prev_bit])
write(' ' * cnt)
set_color(default_color) # reset color
write('\n') | python | def write_terminal_win(matrix, version, border=None): # pragma: no cover
"""\
Function to write a QR Code to a MS Windows terminal.
:param matrix: The matrix to serialize.
:param int version: The (Micro) QR code version
:param int border: Integer indicating the size of the quiet zone.
If set to ``None`` (default), the recommended border size
will be used (``4`` for QR Codes, ``2`` for a Micro QR Codes).
"""
import sys
import struct
import ctypes
write = sys.stdout.write
std_out = ctypes.windll.kernel32.GetStdHandle(-11)
csbi = ctypes.create_string_buffer(22)
res = ctypes.windll.kernel32.GetConsoleScreenBufferInfo(std_out, csbi)
if not res:
raise OSError('Cannot find information about the console. '
'Not running on the command line?')
default_color = struct.unpack(b'hhhhHhhhhhh', csbi.raw)[4]
set_color = partial(ctypes.windll.kernel32.SetConsoleTextAttribute, std_out)
colours = (240, default_color)
for row in matrix_iter(matrix, version, scale=1, border=border):
prev_bit = -1
cnt = 0
for bit in row:
if bit == prev_bit:
cnt += 1
else:
if cnt:
set_color(colours[prev_bit])
write(' ' * cnt)
prev_bit = bit
cnt = 1
if cnt:
set_color(colours[prev_bit])
write(' ' * cnt)
set_color(default_color) # reset color
write('\n') | [
"def",
"write_terminal_win",
"(",
"matrix",
",",
"version",
",",
"border",
"=",
"None",
")",
":",
"# pragma: no cover",
"import",
"sys",
"import",
"struct",
"import",
"ctypes",
"write",
"=",
"sys",
".",
"stdout",
".",
"write",
"std_out",
"=",
"ctypes",
".",
... | \
Function to write a QR Code to a MS Windows terminal.
:param matrix: The matrix to serialize.
:param int version: The (Micro) QR code version
:param int border: Integer indicating the size of the quiet zone.
If set to ``None`` (default), the recommended border size
will be used (``4`` for QR Codes, ``2`` for a Micro QR Codes). | [
"\\",
"Function",
"to",
"write",
"a",
"QR",
"Code",
"to",
"a",
"MS",
"Windows",
"terminal",
"."
] | 64d912a2bd17d0b5ff3e8b5d37098edfc663c2b3 | https://github.com/heuer/segno/blob/64d912a2bd17d0b5ff3e8b5d37098edfc663c2b3/segno/writers.py#L958-L997 | train | 31,929 |
heuer/segno | segno/writers.py | _pack_bits_into_byte | def _pack_bits_into_byte(iterable):
"""\
Packs eight bits into one byte.
If the length of the iterable is not a multiple of eight, ``0x0`` is used
to fill-up the missing values.
"""
return (reduce(lambda x, y: (x << 1) + y, e)
for e in zip_longest(*[iter(iterable)] * 8, fillvalue=0x0)) | python | def _pack_bits_into_byte(iterable):
"""\
Packs eight bits into one byte.
If the length of the iterable is not a multiple of eight, ``0x0`` is used
to fill-up the missing values.
"""
return (reduce(lambda x, y: (x << 1) + y, e)
for e in zip_longest(*[iter(iterable)] * 8, fillvalue=0x0)) | [
"def",
"_pack_bits_into_byte",
"(",
"iterable",
")",
":",
"return",
"(",
"reduce",
"(",
"lambda",
"x",
",",
"y",
":",
"(",
"x",
"<<",
"1",
")",
"+",
"y",
",",
"e",
")",
"for",
"e",
"in",
"zip_longest",
"(",
"*",
"[",
"iter",
"(",
"iterable",
")",... | \
Packs eight bits into one byte.
If the length of the iterable is not a multiple of eight, ``0x0`` is used
to fill-up the missing values. | [
"\\",
"Packs",
"eight",
"bits",
"into",
"one",
"byte",
"."
] | 64d912a2bd17d0b5ff3e8b5d37098edfc663c2b3 | https://github.com/heuer/segno/blob/64d912a2bd17d0b5ff3e8b5d37098edfc663c2b3/segno/writers.py#L1000-L1008 | train | 31,930 |
heuer/segno | segno/writers.py | save | def save(matrix, version, out, kind=None, **kw):
"""\
Serializes the matrix in any of the supported formats.
:param matrix: The matrix to serialize.
:param int version: The (Micro) QR code version
:param out: A filename or a writable file-like object with a
``name`` attribute. If a stream like :py:class:`io.ByteIO` or
:py:class:`io.StringIO` object without a ``name`` attribute is
provided, use the `kind` parameter to specify the serialization
format.
:param kind: If the desired output format cannot be extracted from
the filename, this parameter can be used to indicate the
serialization format (i.e. "svg" to enforce SVG output)
:param kw: Any of the supported keywords by the specific serialization
method.
"""
is_stream = False
if kind is None:
try:
fname = out.name
is_stream = True
except AttributeError:
fname = out
ext = fname[fname.rfind('.') + 1:].lower()
else:
ext = kind.lower()
if not is_stream and ext == 'svgz':
f = gzip.open(out, 'wb', compresslevel=kw.pop('compresslevel', 9))
try:
_VALID_SERIALISERS['svg'](matrix, version, f, **kw)
finally:
f.close()
else:
if kw.pop('debug', False) and ext == 'svg':
ext = 'svg_debug'
try:
_VALID_SERIALISERS[ext](matrix, version, out, **kw)
except KeyError:
raise ValueError('Unknown file extension ".{0}"'.format(ext)) | python | def save(matrix, version, out, kind=None, **kw):
"""\
Serializes the matrix in any of the supported formats.
:param matrix: The matrix to serialize.
:param int version: The (Micro) QR code version
:param out: A filename or a writable file-like object with a
``name`` attribute. If a stream like :py:class:`io.ByteIO` or
:py:class:`io.StringIO` object without a ``name`` attribute is
provided, use the `kind` parameter to specify the serialization
format.
:param kind: If the desired output format cannot be extracted from
the filename, this parameter can be used to indicate the
serialization format (i.e. "svg" to enforce SVG output)
:param kw: Any of the supported keywords by the specific serialization
method.
"""
is_stream = False
if kind is None:
try:
fname = out.name
is_stream = True
except AttributeError:
fname = out
ext = fname[fname.rfind('.') + 1:].lower()
else:
ext = kind.lower()
if not is_stream and ext == 'svgz':
f = gzip.open(out, 'wb', compresslevel=kw.pop('compresslevel', 9))
try:
_VALID_SERIALISERS['svg'](matrix, version, f, **kw)
finally:
f.close()
else:
if kw.pop('debug', False) and ext == 'svg':
ext = 'svg_debug'
try:
_VALID_SERIALISERS[ext](matrix, version, out, **kw)
except KeyError:
raise ValueError('Unknown file extension ".{0}"'.format(ext)) | [
"def",
"save",
"(",
"matrix",
",",
"version",
",",
"out",
",",
"kind",
"=",
"None",
",",
"*",
"*",
"kw",
")",
":",
"is_stream",
"=",
"False",
"if",
"kind",
"is",
"None",
":",
"try",
":",
"fname",
"=",
"out",
".",
"name",
"is_stream",
"=",
"True",... | \
Serializes the matrix in any of the supported formats.
:param matrix: The matrix to serialize.
:param int version: The (Micro) QR code version
:param out: A filename or a writable file-like object with a
``name`` attribute. If a stream like :py:class:`io.ByteIO` or
:py:class:`io.StringIO` object without a ``name`` attribute is
provided, use the `kind` parameter to specify the serialization
format.
:param kind: If the desired output format cannot be extracted from
the filename, this parameter can be used to indicate the
serialization format (i.e. "svg" to enforce SVG output)
:param kw: Any of the supported keywords by the specific serialization
method. | [
"\\",
"Serializes",
"the",
"matrix",
"in",
"any",
"of",
"the",
"supported",
"formats",
"."
] | 64d912a2bd17d0b5ff3e8b5d37098edfc663c2b3 | https://github.com/heuer/segno/blob/64d912a2bd17d0b5ff3e8b5d37098edfc663c2b3/segno/writers.py#L1026-L1065 | train | 31,931 |
heuer/segno | segno/cli.py | parse | def parse(args):
"""\
Parses the arguments and returns the result.
"""
parser = make_parser()
if not len(args):
parser.print_help()
sys.exit(1)
parsed_args = parser.parse_args(args)
if parsed_args.error == '-':
parsed_args.error = None
# 'micro' is False by default. If version is set to a Micro QR Code version,
# encoder.encode raises a VersionError.
# Small problem: --version=M4 --no-micro is allowed
version = parsed_args.version
if version is not None:
version = str(version).upper()
if not parsed_args.micro and version in ('M1', 'M2', 'M3', 'M4'):
parsed_args.micro = None
return _AttrDict(vars(parsed_args)) | python | def parse(args):
"""\
Parses the arguments and returns the result.
"""
parser = make_parser()
if not len(args):
parser.print_help()
sys.exit(1)
parsed_args = parser.parse_args(args)
if parsed_args.error == '-':
parsed_args.error = None
# 'micro' is False by default. If version is set to a Micro QR Code version,
# encoder.encode raises a VersionError.
# Small problem: --version=M4 --no-micro is allowed
version = parsed_args.version
if version is not None:
version = str(version).upper()
if not parsed_args.micro and version in ('M1', 'M2', 'M3', 'M4'):
parsed_args.micro = None
return _AttrDict(vars(parsed_args)) | [
"def",
"parse",
"(",
"args",
")",
":",
"parser",
"=",
"make_parser",
"(",
")",
"if",
"not",
"len",
"(",
"args",
")",
":",
"parser",
".",
"print_help",
"(",
")",
"sys",
".",
"exit",
"(",
"1",
")",
"parsed_args",
"=",
"parser",
".",
"parse_args",
"("... | \
Parses the arguments and returns the result. | [
"\\",
"Parses",
"the",
"arguments",
"and",
"returns",
"the",
"result",
"."
] | 64d912a2bd17d0b5ff3e8b5d37098edfc663c2b3 | https://github.com/heuer/segno/blob/64d912a2bd17d0b5ff3e8b5d37098edfc663c2b3/segno/cli.py#L124-L143 | train | 31,932 |
heuer/segno | segno/cli.py | build_config | def build_config(config, filename=None):
"""\
Builds a configuration and returns it. The config contains only keywords,
which are supported by the serializer. Unsupported values are ignored.
"""
# Done here since it seems not to be possible to detect if an argument
# was supplied by the user or if it's the default argument.
# If using type=lambda v: None if v in ('transparent', 'trans') else v
# we cannot detect if "None" comes from "transparent" or the default value
for clr in ('color', 'background'):
val = config.pop(clr, None)
if val in ('transparent', 'trans'):
config[clr] = None
elif val:
config[clr] = val
# SVG
for name in ('svgid', 'svgclass', 'lineclass'):
if config.get(name, None) is None:
config.pop(name, None)
if config.pop('no_classes', False):
config['svgclass'] = None
config['lineclass'] = None
if filename is not None:
ext = filename[filename.rfind('.') + 1:].lower()
if ext == 'svgz': # There is no svgz serializer, use same config as svg
ext = 'svg'
supported_args = _EXT_TO_KW_MAPPING.get(ext, ())
# Drop unsupported arguments from config rather than getting a
# "unsupported keyword" exception
for k in list(config):
if k not in supported_args:
del config[k]
return config | python | def build_config(config, filename=None):
"""\
Builds a configuration and returns it. The config contains only keywords,
which are supported by the serializer. Unsupported values are ignored.
"""
# Done here since it seems not to be possible to detect if an argument
# was supplied by the user or if it's the default argument.
# If using type=lambda v: None if v in ('transparent', 'trans') else v
# we cannot detect if "None" comes from "transparent" or the default value
for clr in ('color', 'background'):
val = config.pop(clr, None)
if val in ('transparent', 'trans'):
config[clr] = None
elif val:
config[clr] = val
# SVG
for name in ('svgid', 'svgclass', 'lineclass'):
if config.get(name, None) is None:
config.pop(name, None)
if config.pop('no_classes', False):
config['svgclass'] = None
config['lineclass'] = None
if filename is not None:
ext = filename[filename.rfind('.') + 1:].lower()
if ext == 'svgz': # There is no svgz serializer, use same config as svg
ext = 'svg'
supported_args = _EXT_TO_KW_MAPPING.get(ext, ())
# Drop unsupported arguments from config rather than getting a
# "unsupported keyword" exception
for k in list(config):
if k not in supported_args:
del config[k]
return config | [
"def",
"build_config",
"(",
"config",
",",
"filename",
"=",
"None",
")",
":",
"# Done here since it seems not to be possible to detect if an argument",
"# was supplied by the user or if it's the default argument.",
"# If using type=lambda v: None if v in ('transparent', 'trans') else v",
"... | \
Builds a configuration and returns it. The config contains only keywords,
which are supported by the serializer. Unsupported values are ignored. | [
"\\",
"Builds",
"a",
"configuration",
"and",
"returns",
"it",
".",
"The",
"config",
"contains",
"only",
"keywords",
"which",
"are",
"supported",
"by",
"the",
"serializer",
".",
"Unsupported",
"values",
"are",
"ignored",
"."
] | 64d912a2bd17d0b5ff3e8b5d37098edfc663c2b3 | https://github.com/heuer/segno/blob/64d912a2bd17d0b5ff3e8b5d37098edfc663c2b3/segno/cli.py#L146-L178 | train | 31,933 |
heuer/segno | segno/helpers.py | make_wifi_data | def make_wifi_data(ssid, password, security, hidden=False):
"""\
Creates WIFI configuration string.
:param str ssid: The SSID of the network.
:param str|None password: The password.
:param str|None security: Authentication type; the value should
be "WEP" or "WPA". Set to ``None`` to omit the value.
"nopass" is equivalent to setting the value to ``None`` but in
the former case, the value is not omitted.
:param bool hidden: Indicates if the network is hidden (default: ``False``)
:rtype: str
"""
def quotation_mark(x):
"""\
Returns '"' if x could be interpreted as hexadecimal value, otherwise
an empty string.
See: <https://github.com/zxing/zxing/wiki/Barcode-Contents>
[...] Enclose in double quotes if it is an ASCII name, but could be
interpreted as hex (i.e. "ABCD") [...]
"""
try:
int(x, 16)
except ValueError:
return ''
return '"'
escape = _escape_mecard
data = 'WIFI:'
if security:
data += 'T:{0};'.format(security.upper() if security != 'nopass' else security)
data += 'S:{1}{0}{1};'.format(escape(ssid), quotation_mark(ssid))
if password:
data += 'P:{1}{0}{1};'.format(escape(password), quotation_mark(password))
data += 'H:true;' if hidden else ';'
return data | python | def make_wifi_data(ssid, password, security, hidden=False):
"""\
Creates WIFI configuration string.
:param str ssid: The SSID of the network.
:param str|None password: The password.
:param str|None security: Authentication type; the value should
be "WEP" or "WPA". Set to ``None`` to omit the value.
"nopass" is equivalent to setting the value to ``None`` but in
the former case, the value is not omitted.
:param bool hidden: Indicates if the network is hidden (default: ``False``)
:rtype: str
"""
def quotation_mark(x):
"""\
Returns '"' if x could be interpreted as hexadecimal value, otherwise
an empty string.
See: <https://github.com/zxing/zxing/wiki/Barcode-Contents>
[...] Enclose in double quotes if it is an ASCII name, but could be
interpreted as hex (i.e. "ABCD") [...]
"""
try:
int(x, 16)
except ValueError:
return ''
return '"'
escape = _escape_mecard
data = 'WIFI:'
if security:
data += 'T:{0};'.format(security.upper() if security != 'nopass' else security)
data += 'S:{1}{0}{1};'.format(escape(ssid), quotation_mark(ssid))
if password:
data += 'P:{1}{0}{1};'.format(escape(password), quotation_mark(password))
data += 'H:true;' if hidden else ';'
return data | [
"def",
"make_wifi_data",
"(",
"ssid",
",",
"password",
",",
"security",
",",
"hidden",
"=",
"False",
")",
":",
"def",
"quotation_mark",
"(",
"x",
")",
":",
"\"\"\"\\\n Returns '\"' if x could be interpreted as hexadecimal value, otherwise\n an empty string.\n\n ... | \
Creates WIFI configuration string.
:param str ssid: The SSID of the network.
:param str|None password: The password.
:param str|None security: Authentication type; the value should
be "WEP" or "WPA". Set to ``None`` to omit the value.
"nopass" is equivalent to setting the value to ``None`` but in
the former case, the value is not omitted.
:param bool hidden: Indicates if the network is hidden (default: ``False``)
:rtype: str | [
"\\",
"Creates",
"WIFI",
"configuration",
"string",
"."
] | 64d912a2bd17d0b5ff3e8b5d37098edfc663c2b3 | https://github.com/heuer/segno/blob/64d912a2bd17d0b5ff3e8b5d37098edfc663c2b3/segno/helpers.py#L63-L99 | train | 31,934 |
heuer/segno | segno/helpers.py | make_wifi | def make_wifi(ssid, password, security, hidden=False):
"""\
Creates a WIFI configuration QR Code.
:param str ssid: The SSID of the network.
:param str|None password: The password.
:param str|None security: Authentication type; the value should
be "WEP" or "WPA". Set to ``None`` to omit the value.
"nopass" is equivalent to setting the value to ``None`` but in
the former case, the value is not omitted.
:param bool hidden: Indicates if the network is hidden (default: ``False``)
:rtype: segno.QRCode
"""
return segno.make_qr(make_wifi_data(ssid, password, security, hidden)) | python | def make_wifi(ssid, password, security, hidden=False):
"""\
Creates a WIFI configuration QR Code.
:param str ssid: The SSID of the network.
:param str|None password: The password.
:param str|None security: Authentication type; the value should
be "WEP" or "WPA". Set to ``None`` to omit the value.
"nopass" is equivalent to setting the value to ``None`` but in
the former case, the value is not omitted.
:param bool hidden: Indicates if the network is hidden (default: ``False``)
:rtype: segno.QRCode
"""
return segno.make_qr(make_wifi_data(ssid, password, security, hidden)) | [
"def",
"make_wifi",
"(",
"ssid",
",",
"password",
",",
"security",
",",
"hidden",
"=",
"False",
")",
":",
"return",
"segno",
".",
"make_qr",
"(",
"make_wifi_data",
"(",
"ssid",
",",
"password",
",",
"security",
",",
"hidden",
")",
")"
] | \
Creates a WIFI configuration QR Code.
:param str ssid: The SSID of the network.
:param str|None password: The password.
:param str|None security: Authentication type; the value should
be "WEP" or "WPA". Set to ``None`` to omit the value.
"nopass" is equivalent to setting the value to ``None`` but in
the former case, the value is not omitted.
:param bool hidden: Indicates if the network is hidden (default: ``False``)
:rtype: segno.QRCode | [
"\\",
"Creates",
"a",
"WIFI",
"configuration",
"QR",
"Code",
"."
] | 64d912a2bd17d0b5ff3e8b5d37098edfc663c2b3 | https://github.com/heuer/segno/blob/64d912a2bd17d0b5ff3e8b5d37098edfc663c2b3/segno/helpers.py#L102-L115 | train | 31,935 |
heuer/segno | segno/helpers.py | make_mecard_data | def make_mecard_data(name, reading=None, email=None, phone=None, videophone=None,
memo=None, nickname=None, birthday=None, url=None,
pobox=None, roomno=None, houseno=None, city=None,
prefecture=None, zipcode=None, country=None):
"""\
Creates a string encoding the contact information as MeCard.
:param str name: Name. If it contains a comma, the first part
is treated as lastname and the second part is treated as forename.
:param str|None reading: Designates a text string to be set as the
kana name in the phonebook
:param str|iterable email: E-mail address. Multiple values are
allowed.
:param str|iterable phone: Phone number. Multiple values are
allowed.
:param str|iterable videophone: Phone number for video calls.
Multiple values are allowed.
:param str memo: A notice for the contact.
:param str nickname: Nickname.
:param (str|int|date) birthday: Birthday. If a string is provided,
it should encode the date as YYYYMMDD value.
:param str|iterable url: Homepage. Multiple values are allowed.
:param str|None pobox: P.O. box (address information).
:param str|None roomno: Room number (address information).
:param str|None houseno: House number (address information).
:param str|None city: City (address information).
:param str|None prefecture: Prefecture (address information).
:param str|None zipcode: Zip code (address information).
:param str|None country: Country (address information).
:rtype: str
"""
def make_multifield(name, val):
if val is None:
return ()
if isinstance(val, str_type):
val = (val,)
return ['{0}:{1};'.format(name, escape(i)) for i in val]
escape = _escape_mecard
data = ['MECARD:N:{0};'.format(escape(name))]
if reading:
data.append('SOUND:{0};'.format(escape(reading)))
data.extend(make_multifield('TEL', phone))
data.extend(make_multifield('TELAV', videophone))
data.extend(make_multifield('EMAIL', email))
if nickname:
data.append('NICKNAME:{0};'.format(escape(nickname)))
if birthday:
try:
birthday = birthday.strftime('%Y%m%d')
except AttributeError:
pass
data.append('BDAY:{0};'.format(birthday))
data.extend(make_multifield('URL', url))
adr_properties = (pobox, roomno, houseno, city, prefecture, zipcode, country)
if any(adr_properties):
adr_data = [escape(i or '') for i in adr_properties]
data.append('ADR:{0},{1},{2},{3},{4},{5},{6};'.format(*adr_data))
if memo:
data.append('MEMO:{0};'.format(escape(memo)))
data.append(';')
return ''.join(data) | python | def make_mecard_data(name, reading=None, email=None, phone=None, videophone=None,
memo=None, nickname=None, birthday=None, url=None,
pobox=None, roomno=None, houseno=None, city=None,
prefecture=None, zipcode=None, country=None):
"""\
Creates a string encoding the contact information as MeCard.
:param str name: Name. If it contains a comma, the first part
is treated as lastname and the second part is treated as forename.
:param str|None reading: Designates a text string to be set as the
kana name in the phonebook
:param str|iterable email: E-mail address. Multiple values are
allowed.
:param str|iterable phone: Phone number. Multiple values are
allowed.
:param str|iterable videophone: Phone number for video calls.
Multiple values are allowed.
:param str memo: A notice for the contact.
:param str nickname: Nickname.
:param (str|int|date) birthday: Birthday. If a string is provided,
it should encode the date as YYYYMMDD value.
:param str|iterable url: Homepage. Multiple values are allowed.
:param str|None pobox: P.O. box (address information).
:param str|None roomno: Room number (address information).
:param str|None houseno: House number (address information).
:param str|None city: City (address information).
:param str|None prefecture: Prefecture (address information).
:param str|None zipcode: Zip code (address information).
:param str|None country: Country (address information).
:rtype: str
"""
def make_multifield(name, val):
if val is None:
return ()
if isinstance(val, str_type):
val = (val,)
return ['{0}:{1};'.format(name, escape(i)) for i in val]
escape = _escape_mecard
data = ['MECARD:N:{0};'.format(escape(name))]
if reading:
data.append('SOUND:{0};'.format(escape(reading)))
data.extend(make_multifield('TEL', phone))
data.extend(make_multifield('TELAV', videophone))
data.extend(make_multifield('EMAIL', email))
if nickname:
data.append('NICKNAME:{0};'.format(escape(nickname)))
if birthday:
try:
birthday = birthday.strftime('%Y%m%d')
except AttributeError:
pass
data.append('BDAY:{0};'.format(birthday))
data.extend(make_multifield('URL', url))
adr_properties = (pobox, roomno, houseno, city, prefecture, zipcode, country)
if any(adr_properties):
adr_data = [escape(i or '') for i in adr_properties]
data.append('ADR:{0},{1},{2},{3},{4},{5},{6};'.format(*adr_data))
if memo:
data.append('MEMO:{0};'.format(escape(memo)))
data.append(';')
return ''.join(data) | [
"def",
"make_mecard_data",
"(",
"name",
",",
"reading",
"=",
"None",
",",
"email",
"=",
"None",
",",
"phone",
"=",
"None",
",",
"videophone",
"=",
"None",
",",
"memo",
"=",
"None",
",",
"nickname",
"=",
"None",
",",
"birthday",
"=",
"None",
",",
"url... | \
Creates a string encoding the contact information as MeCard.
:param str name: Name. If it contains a comma, the first part
is treated as lastname and the second part is treated as forename.
:param str|None reading: Designates a text string to be set as the
kana name in the phonebook
:param str|iterable email: E-mail address. Multiple values are
allowed.
:param str|iterable phone: Phone number. Multiple values are
allowed.
:param str|iterable videophone: Phone number for video calls.
Multiple values are allowed.
:param str memo: A notice for the contact.
:param str nickname: Nickname.
:param (str|int|date) birthday: Birthday. If a string is provided,
it should encode the date as YYYYMMDD value.
:param str|iterable url: Homepage. Multiple values are allowed.
:param str|None pobox: P.O. box (address information).
:param str|None roomno: Room number (address information).
:param str|None houseno: House number (address information).
:param str|None city: City (address information).
:param str|None prefecture: Prefecture (address information).
:param str|None zipcode: Zip code (address information).
:param str|None country: Country (address information).
:rtype: str | [
"\\",
"Creates",
"a",
"string",
"encoding",
"the",
"contact",
"information",
"as",
"MeCard",
"."
] | 64d912a2bd17d0b5ff3e8b5d37098edfc663c2b3 | https://github.com/heuer/segno/blob/64d912a2bd17d0b5ff3e8b5d37098edfc663c2b3/segno/helpers.py#L118-L179 | train | 31,936 |
heuer/segno | segno/helpers.py | make_geo_data | def make_geo_data(lat, lng):
"""\
Creates a geo location URI.
:param float lat: Latitude
:param float lng: Longitude
:rtype: str
"""
def float_to_str(f):
return '{0:.8f}'.format(f).rstrip('0')
return 'geo:{0},{1}'.format(float_to_str(lat), float_to_str(lng)) | python | def make_geo_data(lat, lng):
"""\
Creates a geo location URI.
:param float lat: Latitude
:param float lng: Longitude
:rtype: str
"""
def float_to_str(f):
return '{0:.8f}'.format(f).rstrip('0')
return 'geo:{0},{1}'.format(float_to_str(lat), float_to_str(lng)) | [
"def",
"make_geo_data",
"(",
"lat",
",",
"lng",
")",
":",
"def",
"float_to_str",
"(",
"f",
")",
":",
"return",
"'{0:.8f}'",
".",
"format",
"(",
"f",
")",
".",
"rstrip",
"(",
"'0'",
")",
"return",
"'geo:{0},{1}'",
".",
"format",
"(",
"float_to_str",
"("... | \
Creates a geo location URI.
:param float lat: Latitude
:param float lng: Longitude
:rtype: str | [
"\\",
"Creates",
"a",
"geo",
"location",
"URI",
"."
] | 64d912a2bd17d0b5ff3e8b5d37098edfc663c2b3 | https://github.com/heuer/segno/blob/64d912a2bd17d0b5ff3e8b5d37098edfc663c2b3/segno/helpers.py#L364-L375 | train | 31,937 |
heuer/segno | segno/encoder.py | boost_error_level | def boost_error_level(version, error, segments, eci, is_sa=False):
"""\
Increases the error level if possible.
:param int version: Version constant.
:param int|None error: Error level constant or ``None``
:param Segments segments: Instance of :py:class:`Segments`
:param bool eci: Indicates if ECI designator should be written.
:param bool is_sa: Indicates if Structured Append mode ist used.
"""
if error not in (consts.ERROR_LEVEL_H, None) and len(segments) == 1:
levels = [consts.ERROR_LEVEL_L, consts.ERROR_LEVEL_M,
consts.ERROR_LEVEL_Q, consts.ERROR_LEVEL_H]
if version < 1:
levels.pop() # H isn't support by Micro QR Codes
if version < consts.VERSION_M4:
levels.pop() # Error level Q isn't supported by M2 and M3
data_length = segments.bit_length_with_overhead(version, eci, is_sa=is_sa)
for level in levels[levels.index(error)+1:]:
try:
found = consts.SYMBOL_CAPACITY[version][level] >= data_length
except KeyError:
break
if found:
error = level
return error | python | def boost_error_level(version, error, segments, eci, is_sa=False):
"""\
Increases the error level if possible.
:param int version: Version constant.
:param int|None error: Error level constant or ``None``
:param Segments segments: Instance of :py:class:`Segments`
:param bool eci: Indicates if ECI designator should be written.
:param bool is_sa: Indicates if Structured Append mode ist used.
"""
if error not in (consts.ERROR_LEVEL_H, None) and len(segments) == 1:
levels = [consts.ERROR_LEVEL_L, consts.ERROR_LEVEL_M,
consts.ERROR_LEVEL_Q, consts.ERROR_LEVEL_H]
if version < 1:
levels.pop() # H isn't support by Micro QR Codes
if version < consts.VERSION_M4:
levels.pop() # Error level Q isn't supported by M2 and M3
data_length = segments.bit_length_with_overhead(version, eci, is_sa=is_sa)
for level in levels[levels.index(error)+1:]:
try:
found = consts.SYMBOL_CAPACITY[version][level] >= data_length
except KeyError:
break
if found:
error = level
return error | [
"def",
"boost_error_level",
"(",
"version",
",",
"error",
",",
"segments",
",",
"eci",
",",
"is_sa",
"=",
"False",
")",
":",
"if",
"error",
"not",
"in",
"(",
"consts",
".",
"ERROR_LEVEL_H",
",",
"None",
")",
"and",
"len",
"(",
"segments",
")",
"==",
... | \
Increases the error level if possible.
:param int version: Version constant.
:param int|None error: Error level constant or ``None``
:param Segments segments: Instance of :py:class:`Segments`
:param bool eci: Indicates if ECI designator should be written.
:param bool is_sa: Indicates if Structured Append mode ist used. | [
"\\",
"Increases",
"the",
"error",
"level",
"if",
"possible",
"."
] | 64d912a2bd17d0b5ff3e8b5d37098edfc663c2b3 | https://github.com/heuer/segno/blob/64d912a2bd17d0b5ff3e8b5d37098edfc663c2b3/segno/encoder.py#L302-L327 | train | 31,938 |
heuer/segno | segno/encoder.py | write_segment | def write_segment(buff, segment, ver, ver_range, eci=False):
"""\
Writes a segment.
:param buff: The byte buffer.
:param _Segment segment: The segment to serialize.
:param ver: ``None`` if a QR Code is written, "M1", "M2", "M3", or "M4" if a
Micro QR Code is written.
:param ver_range: "M1", "M2", "M3", or "M4" if a Micro QR Code is written,
otherwise a constant representing a range of QR Code versions.
"""
mode = segment.mode
append_bits = buff.append_bits
# Write ECI header if requested
if eci and mode == consts.MODE_BYTE \
and segment.encoding != consts.DEFAULT_BYTE_ENCODING:
append_bits(consts.MODE_ECI, 4)
append_bits(get_eci_assignment_number(segment.encoding), 8)
if ver is None: # QR Code
append_bits(mode, 4)
elif ver > consts.VERSION_M1: # Micro QR Code (M1 has no mode indicator)
append_bits(consts.MODE_TO_MICRO_MODE_MAPPING[mode], ver + 3)
# Character count indicator
append_bits(segment.char_count,
consts.CHAR_COUNT_INDICATOR_LENGTH[mode][ver_range])
buff.extend(segment.bits) | python | def write_segment(buff, segment, ver, ver_range, eci=False):
"""\
Writes a segment.
:param buff: The byte buffer.
:param _Segment segment: The segment to serialize.
:param ver: ``None`` if a QR Code is written, "M1", "M2", "M3", or "M4" if a
Micro QR Code is written.
:param ver_range: "M1", "M2", "M3", or "M4" if a Micro QR Code is written,
otherwise a constant representing a range of QR Code versions.
"""
mode = segment.mode
append_bits = buff.append_bits
# Write ECI header if requested
if eci and mode == consts.MODE_BYTE \
and segment.encoding != consts.DEFAULT_BYTE_ENCODING:
append_bits(consts.MODE_ECI, 4)
append_bits(get_eci_assignment_number(segment.encoding), 8)
if ver is None: # QR Code
append_bits(mode, 4)
elif ver > consts.VERSION_M1: # Micro QR Code (M1 has no mode indicator)
append_bits(consts.MODE_TO_MICRO_MODE_MAPPING[mode], ver + 3)
# Character count indicator
append_bits(segment.char_count,
consts.CHAR_COUNT_INDICATOR_LENGTH[mode][ver_range])
buff.extend(segment.bits) | [
"def",
"write_segment",
"(",
"buff",
",",
"segment",
",",
"ver",
",",
"ver_range",
",",
"eci",
"=",
"False",
")",
":",
"mode",
"=",
"segment",
".",
"mode",
"append_bits",
"=",
"buff",
".",
"append_bits",
"# Write ECI header if requested",
"if",
"eci",
"and",... | \
Writes a segment.
:param buff: The byte buffer.
:param _Segment segment: The segment to serialize.
:param ver: ``None`` if a QR Code is written, "M1", "M2", "M3", or "M4" if a
Micro QR Code is written.
:param ver_range: "M1", "M2", "M3", or "M4" if a Micro QR Code is written,
otherwise a constant representing a range of QR Code versions. | [
"\\",
"Writes",
"a",
"segment",
"."
] | 64d912a2bd17d0b5ff3e8b5d37098edfc663c2b3 | https://github.com/heuer/segno/blob/64d912a2bd17d0b5ff3e8b5d37098edfc663c2b3/segno/encoder.py#L330-L355 | train | 31,939 |
heuer/segno | segno/encoder.py | write_terminator | def write_terminator(buff, capacity, ver, length):
"""\
Writes the terminator.
:param buff: The byte buffer.
:param capacity: Symbol capacity.
:param ver: ``None`` if a QR Code is written, "M1", "M2", "M3", or "M4" if a
Micro QR Code is written.
:param length: Length of the data bit stream.
"""
# ISO/IEC 18004:2015 -- 7.4.9 Terminator (page 32)
buff.extend([0] * min(capacity - length, consts.TERMINATOR_LENGTH[ver])) | python | def write_terminator(buff, capacity, ver, length):
"""\
Writes the terminator.
:param buff: The byte buffer.
:param capacity: Symbol capacity.
:param ver: ``None`` if a QR Code is written, "M1", "M2", "M3", or "M4" if a
Micro QR Code is written.
:param length: Length of the data bit stream.
"""
# ISO/IEC 18004:2015 -- 7.4.9 Terminator (page 32)
buff.extend([0] * min(capacity - length, consts.TERMINATOR_LENGTH[ver])) | [
"def",
"write_terminator",
"(",
"buff",
",",
"capacity",
",",
"ver",
",",
"length",
")",
":",
"# ISO/IEC 18004:2015 -- 7.4.9 Terminator (page 32)",
"buff",
".",
"extend",
"(",
"[",
"0",
"]",
"*",
"min",
"(",
"capacity",
"-",
"length",
",",
"consts",
".",
"TE... | \
Writes the terminator.
:param buff: The byte buffer.
:param capacity: Symbol capacity.
:param ver: ``None`` if a QR Code is written, "M1", "M2", "M3", or "M4" if a
Micro QR Code is written.
:param length: Length of the data bit stream. | [
"\\",
"Writes",
"the",
"terminator",
"."
] | 64d912a2bd17d0b5ff3e8b5d37098edfc663c2b3 | https://github.com/heuer/segno/blob/64d912a2bd17d0b5ff3e8b5d37098edfc663c2b3/segno/encoder.py#L358-L369 | train | 31,940 |
heuer/segno | segno/encoder.py | write_padding_bits | def write_padding_bits(buff, version, length):
"""\
Writes padding bits if the data stream does not meet the codeword boundary.
:param buff: The byte buffer.
:param int length: Data stream length.
"""
# ISO/IEC 18004:2015(E) - 7.4.10 Bit stream to codeword conversion -- page 32
# [...]
# All codewords are 8 bits in length, except for the final data symbol
# character in Micro QR Code versions M1 and M3 symbols, which is 4 bits
# in length. If the bit stream length is such that it does not end at a
# codeword boundary, padding bits with binary value 0 shall be added after
# the final bit (least significant bit) of the data stream to extend it
# to the codeword boundary. [...]
if version not in (consts.VERSION_M1, consts.VERSION_M3):
buff.extend([0] * (8 - (length % 8))) | python | def write_padding_bits(buff, version, length):
"""\
Writes padding bits if the data stream does not meet the codeword boundary.
:param buff: The byte buffer.
:param int length: Data stream length.
"""
# ISO/IEC 18004:2015(E) - 7.4.10 Bit stream to codeword conversion -- page 32
# [...]
# All codewords are 8 bits in length, except for the final data symbol
# character in Micro QR Code versions M1 and M3 symbols, which is 4 bits
# in length. If the bit stream length is such that it does not end at a
# codeword boundary, padding bits with binary value 0 shall be added after
# the final bit (least significant bit) of the data stream to extend it
# to the codeword boundary. [...]
if version not in (consts.VERSION_M1, consts.VERSION_M3):
buff.extend([0] * (8 - (length % 8))) | [
"def",
"write_padding_bits",
"(",
"buff",
",",
"version",
",",
"length",
")",
":",
"# ISO/IEC 18004:2015(E) - 7.4.10 Bit stream to codeword conversion -- page 32",
"# [...]",
"# All codewords are 8 bits in length, except for the final data symbol",
"# character in Micro QR Code versions M1... | \
Writes padding bits if the data stream does not meet the codeword boundary.
:param buff: The byte buffer.
:param int length: Data stream length. | [
"\\",
"Writes",
"padding",
"bits",
"if",
"the",
"data",
"stream",
"does",
"not",
"meet",
"the",
"codeword",
"boundary",
"."
] | 64d912a2bd17d0b5ff3e8b5d37098edfc663c2b3 | https://github.com/heuer/segno/blob/64d912a2bd17d0b5ff3e8b5d37098edfc663c2b3/segno/encoder.py#L372-L388 | train | 31,941 |
heuer/segno | segno/encoder.py | write_pad_codewords | def write_pad_codewords(buff, version, capacity, length):
"""\
Writes the pad codewords iff the data does not fill the capacity of the
symbol.
:param buff: The byte buffer.
:param int version: The (Micro) QR Code version.
:param int capacity: The total capacity of the symbol (incl. error correction)
:param int length: Length of the data bit stream.
"""
# ISO/IEC 18004:2015(E) -- 7.4.10 Bit stream to codeword conversion (page 32)
# The message bit stream shall then be extended to fill the data capacity
# of the symbol corresponding to the Version and Error Correction Level, as
# defined in Table 8, by adding the Pad Codewords 11101100 and 00010001
# alternately. For Micro QR Code versions M1 and M3 symbols, the final data
# codeword is 4 bits long. The Pad Codeword used in the final data symbol
# character position in Micro QR Code versions M1 and M3 symbols shall be
# represented as 0000.
write = buff.extend
if version in (consts.VERSION_M1, consts.VERSION_M3):
write([0] * (capacity - length))
else:
pad_codewords = ((1, 1, 1, 0, 1, 1, 0, 0), (0, 0, 0, 1, 0, 0, 0, 1))
for i in range(capacity // 8 - length // 8):
write(pad_codewords[i % 2]) | python | def write_pad_codewords(buff, version, capacity, length):
"""\
Writes the pad codewords iff the data does not fill the capacity of the
symbol.
:param buff: The byte buffer.
:param int version: The (Micro) QR Code version.
:param int capacity: The total capacity of the symbol (incl. error correction)
:param int length: Length of the data bit stream.
"""
# ISO/IEC 18004:2015(E) -- 7.4.10 Bit stream to codeword conversion (page 32)
# The message bit stream shall then be extended to fill the data capacity
# of the symbol corresponding to the Version and Error Correction Level, as
# defined in Table 8, by adding the Pad Codewords 11101100 and 00010001
# alternately. For Micro QR Code versions M1 and M3 symbols, the final data
# codeword is 4 bits long. The Pad Codeword used in the final data symbol
# character position in Micro QR Code versions M1 and M3 symbols shall be
# represented as 0000.
write = buff.extend
if version in (consts.VERSION_M1, consts.VERSION_M3):
write([0] * (capacity - length))
else:
pad_codewords = ((1, 1, 1, 0, 1, 1, 0, 0), (0, 0, 0, 1, 0, 0, 0, 1))
for i in range(capacity // 8 - length // 8):
write(pad_codewords[i % 2]) | [
"def",
"write_pad_codewords",
"(",
"buff",
",",
"version",
",",
"capacity",
",",
"length",
")",
":",
"# ISO/IEC 18004:2015(E) -- 7.4.10 Bit stream to codeword conversion (page 32)",
"# The message bit stream shall then be extended to fill the data capacity",
"# of the symbol correspondin... | \
Writes the pad codewords iff the data does not fill the capacity of the
symbol.
:param buff: The byte buffer.
:param int version: The (Micro) QR Code version.
:param int capacity: The total capacity of the symbol (incl. error correction)
:param int length: Length of the data bit stream. | [
"\\",
"Writes",
"the",
"pad",
"codewords",
"iff",
"the",
"data",
"does",
"not",
"fill",
"the",
"capacity",
"of",
"the",
"symbol",
"."
] | 64d912a2bd17d0b5ff3e8b5d37098edfc663c2b3 | https://github.com/heuer/segno/blob/64d912a2bd17d0b5ff3e8b5d37098edfc663c2b3/segno/encoder.py#L391-L415 | train | 31,942 |
heuer/segno | segno/encoder.py | add_alignment_patterns | def add_alignment_patterns(matrix, version):
"""\
Adds the adjustment patterns to the matrix. For versions < 2 this is a
no-op.
ISO/IEC 18004:2015(E) -- 6.3.6 Alignment patterns (page 17)
ISO/IEC 18004:2015(E) -- Annex E Position of alignment patterns (page 83)
"""
if version < 2:
return
matrix_size = len(matrix)
positions = consts.ALIGNMENT_POS[version - 2]
for pos_x in positions:
for pos_y in positions:
# Finder pattern?
if pos_x - 6 == 0 and (pos_y - 6 == 0 or pos_y + 7 == matrix_size) \
or pos_y - 6 == 0 and pos_x + 7 == matrix_size:
continue
row, col = pos_x - 2, pos_y - 2
for r in range(5):
matrix[row + r][col:col+5] = _ALIGNMENT_PATTERN[r] | python | def add_alignment_patterns(matrix, version):
"""\
Adds the adjustment patterns to the matrix. For versions < 2 this is a
no-op.
ISO/IEC 18004:2015(E) -- 6.3.6 Alignment patterns (page 17)
ISO/IEC 18004:2015(E) -- Annex E Position of alignment patterns (page 83)
"""
if version < 2:
return
matrix_size = len(matrix)
positions = consts.ALIGNMENT_POS[version - 2]
for pos_x in positions:
for pos_y in positions:
# Finder pattern?
if pos_x - 6 == 0 and (pos_y - 6 == 0 or pos_y + 7 == matrix_size) \
or pos_y - 6 == 0 and pos_x + 7 == matrix_size:
continue
row, col = pos_x - 2, pos_y - 2
for r in range(5):
matrix[row + r][col:col+5] = _ALIGNMENT_PATTERN[r] | [
"def",
"add_alignment_patterns",
"(",
"matrix",
",",
"version",
")",
":",
"if",
"version",
"<",
"2",
":",
"return",
"matrix_size",
"=",
"len",
"(",
"matrix",
")",
"positions",
"=",
"consts",
".",
"ALIGNMENT_POS",
"[",
"version",
"-",
"2",
"]",
"for",
"po... | \
Adds the adjustment patterns to the matrix. For versions < 2 this is a
no-op.
ISO/IEC 18004:2015(E) -- 6.3.6 Alignment patterns (page 17)
ISO/IEC 18004:2015(E) -- Annex E Position of alignment patterns (page 83) | [
"\\",
"Adds",
"the",
"adjustment",
"patterns",
"to",
"the",
"matrix",
".",
"For",
"versions",
"<",
"2",
"this",
"is",
"a",
"no",
"-",
"op",
"."
] | 64d912a2bd17d0b5ff3e8b5d37098edfc663c2b3 | https://github.com/heuer/segno/blob/64d912a2bd17d0b5ff3e8b5d37098edfc663c2b3/segno/encoder.py#L493-L513 | train | 31,943 |
heuer/segno | segno/encoder.py | make_blocks | def make_blocks(ec_infos, codewords):
"""\
Returns the data and error blocks.
:param ec_infos: Iterable of ECC information
:param codewords: Iterable of (integer) code words.
"""
data_blocks, error_blocks = [], []
offset = 0
for ec_info in ec_infos:
for i in range(ec_info.num_blocks):
block = codewords[offset:offset + ec_info.num_data]
data_blocks.append(block)
error_blocks.append(make_error_block(ec_info, block))
offset += ec_info.num_data
return data_blocks, error_blocks | python | def make_blocks(ec_infos, codewords):
"""\
Returns the data and error blocks.
:param ec_infos: Iterable of ECC information
:param codewords: Iterable of (integer) code words.
"""
data_blocks, error_blocks = [], []
offset = 0
for ec_info in ec_infos:
for i in range(ec_info.num_blocks):
block = codewords[offset:offset + ec_info.num_data]
data_blocks.append(block)
error_blocks.append(make_error_block(ec_info, block))
offset += ec_info.num_data
return data_blocks, error_blocks | [
"def",
"make_blocks",
"(",
"ec_infos",
",",
"codewords",
")",
":",
"data_blocks",
",",
"error_blocks",
"=",
"[",
"]",
",",
"[",
"]",
"offset",
"=",
"0",
"for",
"ec_info",
"in",
"ec_infos",
":",
"for",
"i",
"in",
"range",
"(",
"ec_info",
".",
"num_block... | \
Returns the data and error blocks.
:param ec_infos: Iterable of ECC information
:param codewords: Iterable of (integer) code words. | [
"\\",
"Returns",
"the",
"data",
"and",
"error",
"blocks",
"."
] | 64d912a2bd17d0b5ff3e8b5d37098edfc663c2b3 | https://github.com/heuer/segno/blob/64d912a2bd17d0b5ff3e8b5d37098edfc663c2b3/segno/encoder.py#L609-L624 | train | 31,944 |
heuer/segno | segno/encoder.py | make_error_block | def make_error_block(ec_info, data_block):
"""\
Creates the error code words for the provided data block.
:param ec_info: ECC information (number of blocks, number of code words etc.)
:param data_block: Iterable of (integer) code words.
"""
num_error_words = ec_info.num_total - ec_info.num_data
error_block = bytearray(data_block)
error_block.extend([0] * num_error_words)
gen = consts.GEN_POLY[num_error_words]
gen_log = consts.GALIOS_LOG
gen_exp = consts.GALIOS_EXP
len_data = len(data_block)
# Extended synthetic division, see http://research.swtch.com/field
for i in range(len_data):
coef = error_block[i]
if coef != 0: # log(0) is undefined
lcoef = gen_log[coef]
for j in range(num_error_words):
error_block[i + j + 1] ^= gen_exp[lcoef + gen[j]]
return error_block[len_data:] | python | def make_error_block(ec_info, data_block):
"""\
Creates the error code words for the provided data block.
:param ec_info: ECC information (number of blocks, number of code words etc.)
:param data_block: Iterable of (integer) code words.
"""
num_error_words = ec_info.num_total - ec_info.num_data
error_block = bytearray(data_block)
error_block.extend([0] * num_error_words)
gen = consts.GEN_POLY[num_error_words]
gen_log = consts.GALIOS_LOG
gen_exp = consts.GALIOS_EXP
len_data = len(data_block)
# Extended synthetic division, see http://research.swtch.com/field
for i in range(len_data):
coef = error_block[i]
if coef != 0: # log(0) is undefined
lcoef = gen_log[coef]
for j in range(num_error_words):
error_block[i + j + 1] ^= gen_exp[lcoef + gen[j]]
return error_block[len_data:] | [
"def",
"make_error_block",
"(",
"ec_info",
",",
"data_block",
")",
":",
"num_error_words",
"=",
"ec_info",
".",
"num_total",
"-",
"ec_info",
".",
"num_data",
"error_block",
"=",
"bytearray",
"(",
"data_block",
")",
"error_block",
".",
"extend",
"(",
"[",
"0",
... | \
Creates the error code words for the provided data block.
:param ec_info: ECC information (number of blocks, number of code words etc.)
:param data_block: Iterable of (integer) code words. | [
"\\",
"Creates",
"the",
"error",
"code",
"words",
"for",
"the",
"provided",
"data",
"block",
"."
] | 64d912a2bd17d0b5ff3e8b5d37098edfc663c2b3 | https://github.com/heuer/segno/blob/64d912a2bd17d0b5ff3e8b5d37098edfc663c2b3/segno/encoder.py#L627-L651 | train | 31,945 |
heuer/segno | segno/encoder.py | find_and_apply_best_mask | def find_and_apply_best_mask(matrix, version, is_micro, proposed_mask=None):
"""\
Applies all mask patterns against the provided QR Code matrix and returns
the best matrix and best pattern.
ISO/IEC 18004:2015(E) -- 7.8.2 Data mask patterns (page 50)
ISO/IEC 18004:2015(E) -- 7.8.3 Evaluation of data masking results (page 53)
ISO/IEC 18004:2015(E) -- 7.8.3.1 Evaluation of QR Code symbols (page 53/54)
ISO/IEC 18004:2015(E) -- 7.8.3.2 Evaluation of Micro QR Code symbols (page 54/55)
:param matrix: A matrix.
:param int version: A version (Micro) QR Code version constant.
:param bool is_micro: Indicates if the matrix represents a Micro QR Code
:param proposed_mask: Optional int to indicate the preferred mask.
:rtype: tuple
:return: A tuple of the best matrix and best data mask pattern index.
"""
matrix_size = len(matrix)
# ISO/IEC 18004:2015 -- 7.8.3.1 Evaluation of QR Code symbols (page 53/54)
# The data mask pattern which results in the lowest penalty score shall
# be selected for the symbol.
is_better = lt
best_score = _MAX_PENALTY_SCORE
eval_mask = evaluate_mask
if is_micro:
# ISO/IEC 18004:2015(E) - 7.8.3.2 Evaluation of Micro QR Code symbols (page 54/55)
# The data mask pattern which results in the highest score shall be
# selected for the symbol.
is_better = gt
best_score = -1
eval_mask = evaluate_micro_mask
# Matrix to check if a module belongs to the encoding region
# or function patterns
function_matrix = make_matrix(version)
add_finder_patterns(function_matrix, is_micro)
add_alignment_patterns(function_matrix, version)
if not is_micro:
function_matrix[-8][8] = 0x1
def is_encoding_region(i, j):
return function_matrix[i][j] == 0x2
mask_patterns = get_data_mask_functions(is_micro)
# If the user supplied a mask pattern, the evaluation step is skipped
if proposed_mask is not None:
apply_mask(matrix, mask_patterns[proposed_mask], matrix_size,
is_encoding_region)
return proposed_mask
for mask_number, mask_pattern in enumerate(mask_patterns):
apply_mask(matrix, mask_pattern, matrix_size, is_encoding_region)
# NOTE: DO NOT add format / version info in advance of evaluation
# See ISO/IEC 18004:2015(E) -- 7.8. Data masking (page 50)
score = eval_mask(matrix, matrix_size)
if is_better(score, best_score):
best_score = score
best_pattern = mask_number
# Undo mask
apply_mask(matrix, mask_pattern, matrix_size, is_encoding_region)
apply_mask(matrix, mask_patterns[best_pattern], matrix_size, is_encoding_region)
return best_pattern | python | def find_and_apply_best_mask(matrix, version, is_micro, proposed_mask=None):
"""\
Applies all mask patterns against the provided QR Code matrix and returns
the best matrix and best pattern.
ISO/IEC 18004:2015(E) -- 7.8.2 Data mask patterns (page 50)
ISO/IEC 18004:2015(E) -- 7.8.3 Evaluation of data masking results (page 53)
ISO/IEC 18004:2015(E) -- 7.8.3.1 Evaluation of QR Code symbols (page 53/54)
ISO/IEC 18004:2015(E) -- 7.8.3.2 Evaluation of Micro QR Code symbols (page 54/55)
:param matrix: A matrix.
:param int version: A version (Micro) QR Code version constant.
:param bool is_micro: Indicates if the matrix represents a Micro QR Code
:param proposed_mask: Optional int to indicate the preferred mask.
:rtype: tuple
:return: A tuple of the best matrix and best data mask pattern index.
"""
matrix_size = len(matrix)
# ISO/IEC 18004:2015 -- 7.8.3.1 Evaluation of QR Code symbols (page 53/54)
# The data mask pattern which results in the lowest penalty score shall
# be selected for the symbol.
is_better = lt
best_score = _MAX_PENALTY_SCORE
eval_mask = evaluate_mask
if is_micro:
# ISO/IEC 18004:2015(E) - 7.8.3.2 Evaluation of Micro QR Code symbols (page 54/55)
# The data mask pattern which results in the highest score shall be
# selected for the symbol.
is_better = gt
best_score = -1
eval_mask = evaluate_micro_mask
# Matrix to check if a module belongs to the encoding region
# or function patterns
function_matrix = make_matrix(version)
add_finder_patterns(function_matrix, is_micro)
add_alignment_patterns(function_matrix, version)
if not is_micro:
function_matrix[-8][8] = 0x1
def is_encoding_region(i, j):
return function_matrix[i][j] == 0x2
mask_patterns = get_data_mask_functions(is_micro)
# If the user supplied a mask pattern, the evaluation step is skipped
if proposed_mask is not None:
apply_mask(matrix, mask_patterns[proposed_mask], matrix_size,
is_encoding_region)
return proposed_mask
for mask_number, mask_pattern in enumerate(mask_patterns):
apply_mask(matrix, mask_pattern, matrix_size, is_encoding_region)
# NOTE: DO NOT add format / version info in advance of evaluation
# See ISO/IEC 18004:2015(E) -- 7.8. Data masking (page 50)
score = eval_mask(matrix, matrix_size)
if is_better(score, best_score):
best_score = score
best_pattern = mask_number
# Undo mask
apply_mask(matrix, mask_pattern, matrix_size, is_encoding_region)
apply_mask(matrix, mask_patterns[best_pattern], matrix_size, is_encoding_region)
return best_pattern | [
"def",
"find_and_apply_best_mask",
"(",
"matrix",
",",
"version",
",",
"is_micro",
",",
"proposed_mask",
"=",
"None",
")",
":",
"matrix_size",
"=",
"len",
"(",
"matrix",
")",
"# ISO/IEC 18004:2015 -- 7.8.3.1 Evaluation of QR Code symbols (page 53/54)",
"# The data mask patt... | \
Applies all mask patterns against the provided QR Code matrix and returns
the best matrix and best pattern.
ISO/IEC 18004:2015(E) -- 7.8.2 Data mask patterns (page 50)
ISO/IEC 18004:2015(E) -- 7.8.3 Evaluation of data masking results (page 53)
ISO/IEC 18004:2015(E) -- 7.8.3.1 Evaluation of QR Code symbols (page 53/54)
ISO/IEC 18004:2015(E) -- 7.8.3.2 Evaluation of Micro QR Code symbols (page 54/55)
:param matrix: A matrix.
:param int version: A version (Micro) QR Code version constant.
:param bool is_micro: Indicates if the matrix represents a Micro QR Code
:param proposed_mask: Optional int to indicate the preferred mask.
:rtype: tuple
:return: A tuple of the best matrix and best data mask pattern index. | [
"\\",
"Applies",
"all",
"mask",
"patterns",
"against",
"the",
"provided",
"QR",
"Code",
"matrix",
"and",
"returns",
"the",
"best",
"matrix",
"and",
"best",
"pattern",
"."
] | 64d912a2bd17d0b5ff3e8b5d37098edfc663c2b3 | https://github.com/heuer/segno/blob/64d912a2bd17d0b5ff3e8b5d37098edfc663c2b3/segno/encoder.py#L654-L715 | train | 31,946 |
heuer/segno | segno/encoder.py | apply_mask | def apply_mask(matrix, mask_pattern, matrix_size, is_encoding_region):
"""\
Applies the provided mask pattern on the `matrix`.
ISO/IEC 18004:2015(E) -- 7.8.2 Data mask patterns (page 50)
:param tuple matrix: A tuple of bytearrays
:param mask_pattern: A mask pattern (a function)
:param int matrix_size: width or height of the matrix
:param is_encoding_region: A function which returns ``True`` iff the
row index / col index belongs to the data region.
"""
for i in range(matrix_size):
for j in range(matrix_size):
if is_encoding_region(i, j):
matrix[i][j] ^= mask_pattern(i, j) | python | def apply_mask(matrix, mask_pattern, matrix_size, is_encoding_region):
"""\
Applies the provided mask pattern on the `matrix`.
ISO/IEC 18004:2015(E) -- 7.8.2 Data mask patterns (page 50)
:param tuple matrix: A tuple of bytearrays
:param mask_pattern: A mask pattern (a function)
:param int matrix_size: width or height of the matrix
:param is_encoding_region: A function which returns ``True`` iff the
row index / col index belongs to the data region.
"""
for i in range(matrix_size):
for j in range(matrix_size):
if is_encoding_region(i, j):
matrix[i][j] ^= mask_pattern(i, j) | [
"def",
"apply_mask",
"(",
"matrix",
",",
"mask_pattern",
",",
"matrix_size",
",",
"is_encoding_region",
")",
":",
"for",
"i",
"in",
"range",
"(",
"matrix_size",
")",
":",
"for",
"j",
"in",
"range",
"(",
"matrix_size",
")",
":",
"if",
"is_encoding_region",
... | \
Applies the provided mask pattern on the `matrix`.
ISO/IEC 18004:2015(E) -- 7.8.2 Data mask patterns (page 50)
:param tuple matrix: A tuple of bytearrays
:param mask_pattern: A mask pattern (a function)
:param int matrix_size: width or height of the matrix
:param is_encoding_region: A function which returns ``True`` iff the
row index / col index belongs to the data region. | [
"\\",
"Applies",
"the",
"provided",
"mask",
"pattern",
"on",
"the",
"matrix",
"."
] | 64d912a2bd17d0b5ff3e8b5d37098edfc663c2b3 | https://github.com/heuer/segno/blob/64d912a2bd17d0b5ff3e8b5d37098edfc663c2b3/segno/encoder.py#L718-L733 | train | 31,947 |
heuer/segno | segno/encoder.py | evaluate_mask | def evaluate_mask(matrix, matrix_size):
"""\
Evaluates the provided `matrix` of a QR code.
ISO/IEC 18004:2015(E) -- 7.8.3 Evaluation of data masking results (page 53)
:param matrix: The matrix to evaluate
:param matrix_size: The width (or height) of the matrix.
:return int: The penalty score of the matrix.
"""
return score_n1(matrix, matrix_size) + score_n2(matrix, matrix_size) \
+ score_n3(matrix, matrix_size) + score_n4(matrix, matrix_size) | python | def evaluate_mask(matrix, matrix_size):
"""\
Evaluates the provided `matrix` of a QR code.
ISO/IEC 18004:2015(E) -- 7.8.3 Evaluation of data masking results (page 53)
:param matrix: The matrix to evaluate
:param matrix_size: The width (or height) of the matrix.
:return int: The penalty score of the matrix.
"""
return score_n1(matrix, matrix_size) + score_n2(matrix, matrix_size) \
+ score_n3(matrix, matrix_size) + score_n4(matrix, matrix_size) | [
"def",
"evaluate_mask",
"(",
"matrix",
",",
"matrix_size",
")",
":",
"return",
"score_n1",
"(",
"matrix",
",",
"matrix_size",
")",
"+",
"score_n2",
"(",
"matrix",
",",
"matrix_size",
")",
"+",
"score_n3",
"(",
"matrix",
",",
"matrix_size",
")",
"+",
"score... | \
Evaluates the provided `matrix` of a QR code.
ISO/IEC 18004:2015(E) -- 7.8.3 Evaluation of data masking results (page 53)
:param matrix: The matrix to evaluate
:param matrix_size: The width (or height) of the matrix.
:return int: The penalty score of the matrix. | [
"\\",
"Evaluates",
"the",
"provided",
"matrix",
"of",
"a",
"QR",
"code",
"."
] | 64d912a2bd17d0b5ff3e8b5d37098edfc663c2b3 | https://github.com/heuer/segno/blob/64d912a2bd17d0b5ff3e8b5d37098edfc663c2b3/segno/encoder.py#L736-L747 | train | 31,948 |
heuer/segno | segno/encoder.py | score_n1 | def score_n1(matrix, matrix_size):
"""\
Implements the penalty score feature 1.
ISO/IEC 18004:2015(E) -- 7.8.3 Evaluation of data masking results - Table 11 (page 54)
============================================ ======================== ======
Feature Evaluation condition Points
============================================ ======================== ======
Adjacent modules in row/column in same color No. of modules = (5 + i) N1 + i
============================================ ======================== ======
N1 = 3
:param matrix: The matrix to evaluate
:param matrix_size: The width (or height) of the matrix.
:return int: The penalty score (feature 1) of the matrix.
"""
score = 0
for i in range(matrix_size):
prev_bit_row, prev_bit_col = -1, -1
row_counter, col_counter = 0, 0
for j in range(matrix_size):
# Row-wise
bit = matrix[i][j]
if bit == prev_bit_row:
row_counter += 1
else:
if row_counter >= 5:
score += row_counter - 2 # N1 == 3
row_counter = 1
prev_bit_row = bit
# Col-wise
bit = matrix[j][i]
if bit == prev_bit_col:
col_counter += 1
else:
if col_counter >= 5:
score += col_counter - 2 # N1 == 3
col_counter = 1
prev_bit_col = bit
if row_counter >= 5:
score += row_counter - 2 # N1 == 3
if col_counter >= 5:
score += col_counter - 2 # N1 == 3
return score | python | def score_n1(matrix, matrix_size):
"""\
Implements the penalty score feature 1.
ISO/IEC 18004:2015(E) -- 7.8.3 Evaluation of data masking results - Table 11 (page 54)
============================================ ======================== ======
Feature Evaluation condition Points
============================================ ======================== ======
Adjacent modules in row/column in same color No. of modules = (5 + i) N1 + i
============================================ ======================== ======
N1 = 3
:param matrix: The matrix to evaluate
:param matrix_size: The width (or height) of the matrix.
:return int: The penalty score (feature 1) of the matrix.
"""
score = 0
for i in range(matrix_size):
prev_bit_row, prev_bit_col = -1, -1
row_counter, col_counter = 0, 0
for j in range(matrix_size):
# Row-wise
bit = matrix[i][j]
if bit == prev_bit_row:
row_counter += 1
else:
if row_counter >= 5:
score += row_counter - 2 # N1 == 3
row_counter = 1
prev_bit_row = bit
# Col-wise
bit = matrix[j][i]
if bit == prev_bit_col:
col_counter += 1
else:
if col_counter >= 5:
score += col_counter - 2 # N1 == 3
col_counter = 1
prev_bit_col = bit
if row_counter >= 5:
score += row_counter - 2 # N1 == 3
if col_counter >= 5:
score += col_counter - 2 # N1 == 3
return score | [
"def",
"score_n1",
"(",
"matrix",
",",
"matrix_size",
")",
":",
"score",
"=",
"0",
"for",
"i",
"in",
"range",
"(",
"matrix_size",
")",
":",
"prev_bit_row",
",",
"prev_bit_col",
"=",
"-",
"1",
",",
"-",
"1",
"row_counter",
",",
"col_counter",
"=",
"0",
... | \
Implements the penalty score feature 1.
ISO/IEC 18004:2015(E) -- 7.8.3 Evaluation of data masking results - Table 11 (page 54)
============================================ ======================== ======
Feature Evaluation condition Points
============================================ ======================== ======
Adjacent modules in row/column in same color No. of modules = (5 + i) N1 + i
============================================ ======================== ======
N1 = 3
:param matrix: The matrix to evaluate
:param matrix_size: The width (or height) of the matrix.
:return int: The penalty score (feature 1) of the matrix. | [
"\\",
"Implements",
"the",
"penalty",
"score",
"feature",
"1",
"."
] | 64d912a2bd17d0b5ff3e8b5d37098edfc663c2b3 | https://github.com/heuer/segno/blob/64d912a2bd17d0b5ff3e8b5d37098edfc663c2b3/segno/encoder.py#L750-L795 | train | 31,949 |
heuer/segno | segno/encoder.py | score_n2 | def score_n2(matrix, matrix_size):
"""\
Implements the penalty score feature 2.
ISO/IEC 18004:2015(E) -- 7.8.3 Evaluation of data masking results - Table 11 (page 54)
============================== ==================== ===============
Feature Evaluation condition Points
============================== ==================== ===============
Block of modules in same color Block size = m × n N2 ×(m-1)×(n-1)
============================== ==================== ===============
N2 = 3
:param matrix: The matrix to evaluate
:param matrix_size: The width (or height) of the matrix.
:return int: The penalty score (feature 2) of the matrix.
"""
score = 0
for i in range(matrix_size - 1):
for j in range(matrix_size - 1):
bit = matrix[i][j]
if bit == matrix[i][j + 1] and bit == matrix[i + 1][j] \
and bit == matrix[i + 1][j + 1]:
score += 1
return score * 3 | python | def score_n2(matrix, matrix_size):
"""\
Implements the penalty score feature 2.
ISO/IEC 18004:2015(E) -- 7.8.3 Evaluation of data masking results - Table 11 (page 54)
============================== ==================== ===============
Feature Evaluation condition Points
============================== ==================== ===============
Block of modules in same color Block size = m × n N2 ×(m-1)×(n-1)
============================== ==================== ===============
N2 = 3
:param matrix: The matrix to evaluate
:param matrix_size: The width (or height) of the matrix.
:return int: The penalty score (feature 2) of the matrix.
"""
score = 0
for i in range(matrix_size - 1):
for j in range(matrix_size - 1):
bit = matrix[i][j]
if bit == matrix[i][j + 1] and bit == matrix[i + 1][j] \
and bit == matrix[i + 1][j + 1]:
score += 1
return score * 3 | [
"def",
"score_n2",
"(",
"matrix",
",",
"matrix_size",
")",
":",
"score",
"=",
"0",
"for",
"i",
"in",
"range",
"(",
"matrix_size",
"-",
"1",
")",
":",
"for",
"j",
"in",
"range",
"(",
"matrix_size",
"-",
"1",
")",
":",
"bit",
"=",
"matrix",
"[",
"i... | \
Implements the penalty score feature 2.
ISO/IEC 18004:2015(E) -- 7.8.3 Evaluation of data masking results - Table 11 (page 54)
============================== ==================== ===============
Feature Evaluation condition Points
============================== ==================== ===============
Block of modules in same color Block size = m × n N2 ×(m-1)×(n-1)
============================== ==================== ===============
N2 = 3
:param matrix: The matrix to evaluate
:param matrix_size: The width (or height) of the matrix.
:return int: The penalty score (feature 2) of the matrix. | [
"\\",
"Implements",
"the",
"penalty",
"score",
"feature",
"2",
"."
] | 64d912a2bd17d0b5ff3e8b5d37098edfc663c2b3 | https://github.com/heuer/segno/blob/64d912a2bd17d0b5ff3e8b5d37098edfc663c2b3/segno/encoder.py#L798-L823 | train | 31,950 |
heuer/segno | segno/encoder.py | score_n3 | def score_n3(matrix, matrix_size):
"""\
Implements the penalty score feature 3.
ISO/IEC 18004:2015(E) -- 7.8.3 Evaluation of data masking results - Table 11 (page 54)
========================================= ======================== ======
Feature Evaluation condition Points
========================================= ======================== ======
1 : 1 : 3 : 1 : 1 ratio Existence of the pattern N3
(dark:light:dark:light:dark) pattern in
row/column, preceded or followed by light
area 4 modules wide
========================================= ======================== ======
N3 = 40
:param matrix: The matrix to evaluate
:param matrix_size: The width (or height) of the matrix.
:return int: The penalty score (feature 3) of the matrix.
"""
def is_match(seq, start, end):
start = max(start, 0)
end = min(end, matrix_size)
for i in range(start, end):
if seq[i] == 0x1:
return False
return True
def find_occurrences(seq):
count = 0
idx = seq.find(_N3_PATTERN)
while idx != -1:
offset = idx + 7
if is_match(seq, idx - 4, idx) or is_match(seq, offset, offset + 4):
count += 1
else:
# Found no / not enough light patterns, start at next possible
# match:
# v
# dark light dark dark dark light dark
# ^
offset = idx + 4
idx = seq.find(_N3_PATTERN, offset)
return count
score = 0
for i in range(matrix_size):
score += find_occurrences(matrix[i])
score += find_occurrences(bytearray([matrix[y][i] for y in range(matrix_size)]))
return score * 40 | python | def score_n3(matrix, matrix_size):
"""\
Implements the penalty score feature 3.
ISO/IEC 18004:2015(E) -- 7.8.3 Evaluation of data masking results - Table 11 (page 54)
========================================= ======================== ======
Feature Evaluation condition Points
========================================= ======================== ======
1 : 1 : 3 : 1 : 1 ratio Existence of the pattern N3
(dark:light:dark:light:dark) pattern in
row/column, preceded or followed by light
area 4 modules wide
========================================= ======================== ======
N3 = 40
:param matrix: The matrix to evaluate
:param matrix_size: The width (or height) of the matrix.
:return int: The penalty score (feature 3) of the matrix.
"""
def is_match(seq, start, end):
start = max(start, 0)
end = min(end, matrix_size)
for i in range(start, end):
if seq[i] == 0x1:
return False
return True
def find_occurrences(seq):
count = 0
idx = seq.find(_N3_PATTERN)
while idx != -1:
offset = idx + 7
if is_match(seq, idx - 4, idx) or is_match(seq, offset, offset + 4):
count += 1
else:
# Found no / not enough light patterns, start at next possible
# match:
# v
# dark light dark dark dark light dark
# ^
offset = idx + 4
idx = seq.find(_N3_PATTERN, offset)
return count
score = 0
for i in range(matrix_size):
score += find_occurrences(matrix[i])
score += find_occurrences(bytearray([matrix[y][i] for y in range(matrix_size)]))
return score * 40 | [
"def",
"score_n3",
"(",
"matrix",
",",
"matrix_size",
")",
":",
"def",
"is_match",
"(",
"seq",
",",
"start",
",",
"end",
")",
":",
"start",
"=",
"max",
"(",
"start",
",",
"0",
")",
"end",
"=",
"min",
"(",
"end",
",",
"matrix_size",
")",
"for",
"i... | \
Implements the penalty score feature 3.
ISO/IEC 18004:2015(E) -- 7.8.3 Evaluation of data masking results - Table 11 (page 54)
========================================= ======================== ======
Feature Evaluation condition Points
========================================= ======================== ======
1 : 1 : 3 : 1 : 1 ratio Existence of the pattern N3
(dark:light:dark:light:dark) pattern in
row/column, preceded or followed by light
area 4 modules wide
========================================= ======================== ======
N3 = 40
:param matrix: The matrix to evaluate
:param matrix_size: The width (or height) of the matrix.
:return int: The penalty score (feature 3) of the matrix. | [
"\\",
"Implements",
"the",
"penalty",
"score",
"feature",
"3",
"."
] | 64d912a2bd17d0b5ff3e8b5d37098edfc663c2b3 | https://github.com/heuer/segno/blob/64d912a2bd17d0b5ff3e8b5d37098edfc663c2b3/segno/encoder.py#L827-L877 | train | 31,951 |
heuer/segno | segno/encoder.py | score_n4 | def score_n4(matrix, matrix_size):
"""\
Implements the penalty score feature 4.
ISO/IEC 18004:2015(E) -- 7.8.3 Evaluation of data masking results - Table 11 (page 54)
=========================================== ==================================== ======
Feature Evaluation condition Points
=========================================== ==================================== ======
Proportion of dark modules in entire symbol 50 × (5 × k)% to 50 × (5 × (k + 1))% N4 × k
=========================================== ==================================== ======
N4 = 10
:param matrix: The matrix to evaluate
:param matrix_size: The width (or height) of the matrix.
:return int: The penalty score (feature 4) of the matrix.
"""
dark_modules = sum(map(sum, matrix))
total_modules = matrix_size ** 2
k = int(abs(dark_modules * 2 - total_modules) * 10 // total_modules)
return 10 * k | python | def score_n4(matrix, matrix_size):
"""\
Implements the penalty score feature 4.
ISO/IEC 18004:2015(E) -- 7.8.3 Evaluation of data masking results - Table 11 (page 54)
=========================================== ==================================== ======
Feature Evaluation condition Points
=========================================== ==================================== ======
Proportion of dark modules in entire symbol 50 × (5 × k)% to 50 × (5 × (k + 1))% N4 × k
=========================================== ==================================== ======
N4 = 10
:param matrix: The matrix to evaluate
:param matrix_size: The width (or height) of the matrix.
:return int: The penalty score (feature 4) of the matrix.
"""
dark_modules = sum(map(sum, matrix))
total_modules = matrix_size ** 2
k = int(abs(dark_modules * 2 - total_modules) * 10 // total_modules)
return 10 * k | [
"def",
"score_n4",
"(",
"matrix",
",",
"matrix_size",
")",
":",
"dark_modules",
"=",
"sum",
"(",
"map",
"(",
"sum",
",",
"matrix",
")",
")",
"total_modules",
"=",
"matrix_size",
"**",
"2",
"k",
"=",
"int",
"(",
"abs",
"(",
"dark_modules",
"*",
"2",
"... | \
Implements the penalty score feature 4.
ISO/IEC 18004:2015(E) -- 7.8.3 Evaluation of data masking results - Table 11 (page 54)
=========================================== ==================================== ======
Feature Evaluation condition Points
=========================================== ==================================== ======
Proportion of dark modules in entire symbol 50 × (5 × k)% to 50 × (5 × (k + 1))% N4 × k
=========================================== ==================================== ======
N4 = 10
:param matrix: The matrix to evaluate
:param matrix_size: The width (or height) of the matrix.
:return int: The penalty score (feature 4) of the matrix. | [
"\\",
"Implements",
"the",
"penalty",
"score",
"feature",
"4",
"."
] | 64d912a2bd17d0b5ff3e8b5d37098edfc663c2b3 | https://github.com/heuer/segno/blob/64d912a2bd17d0b5ff3e8b5d37098edfc663c2b3/segno/encoder.py#L880-L901 | train | 31,952 |
heuer/segno | segno/encoder.py | evaluate_micro_mask | def evaluate_micro_mask(matrix, matrix_size):
"""\
Evaluates the provided `matrix` of a Micro QR code.
ISO/IEC 18004:2015(E) -- 7.8.3.2 Evaluation of Micro QR Code symbols (page 54)
:param matrix: The matrix to evaluate
:param matrix_size: The width (or height) of the matrix.
:return int: The penalty score of the matrix.
"""
sum1 = sum(matrix[i][-1] == 0x1 for i in range(1, matrix_size))
sum2 = sum(matrix[-1][i] == 0x1 for i in range(1, matrix_size))
return sum1 * 16 + sum2 if sum1 <= sum2 else sum2 * 16 + sum1 | python | def evaluate_micro_mask(matrix, matrix_size):
"""\
Evaluates the provided `matrix` of a Micro QR code.
ISO/IEC 18004:2015(E) -- 7.8.3.2 Evaluation of Micro QR Code symbols (page 54)
:param matrix: The matrix to evaluate
:param matrix_size: The width (or height) of the matrix.
:return int: The penalty score of the matrix.
"""
sum1 = sum(matrix[i][-1] == 0x1 for i in range(1, matrix_size))
sum2 = sum(matrix[-1][i] == 0x1 for i in range(1, matrix_size))
return sum1 * 16 + sum2 if sum1 <= sum2 else sum2 * 16 + sum1 | [
"def",
"evaluate_micro_mask",
"(",
"matrix",
",",
"matrix_size",
")",
":",
"sum1",
"=",
"sum",
"(",
"matrix",
"[",
"i",
"]",
"[",
"-",
"1",
"]",
"==",
"0x1",
"for",
"i",
"in",
"range",
"(",
"1",
",",
"matrix_size",
")",
")",
"sum2",
"=",
"sum",
"... | \
Evaluates the provided `matrix` of a Micro QR code.
ISO/IEC 18004:2015(E) -- 7.8.3.2 Evaluation of Micro QR Code symbols (page 54)
:param matrix: The matrix to evaluate
:param matrix_size: The width (or height) of the matrix.
:return int: The penalty score of the matrix. | [
"\\",
"Evaluates",
"the",
"provided",
"matrix",
"of",
"a",
"Micro",
"QR",
"code",
"."
] | 64d912a2bd17d0b5ff3e8b5d37098edfc663c2b3 | https://github.com/heuer/segno/blob/64d912a2bd17d0b5ff3e8b5d37098edfc663c2b3/segno/encoder.py#L904-L916 | train | 31,953 |
heuer/segno | segno/encoder.py | calc_format_info | def calc_format_info(version, error, mask_pattern):
"""\
Returns the format information for the provided error level and mask patttern.
ISO/IEC 18004:2015(E) -- 7.9 Format information (page 55)
ISO/IEC 18004:2015(E) -- Table C.1 — Valid format information bit sequences (page 80)
:param int version: Version constant
:param int error: Error level constant.
:param int mask_pattern: Mask pattern number.
"""
fmt = mask_pattern
if version > 0:
if error == consts.ERROR_LEVEL_L:
fmt += 0x08
elif error == consts.ERROR_LEVEL_H:
fmt += 0x10
elif error == consts.ERROR_LEVEL_Q:
fmt += 0x18
format_info = consts.FORMAT_INFO[fmt]
else:
fmt += consts.ERROR_LEVEL_TO_MICRO_MAPPING[version][error] << 2
format_info = consts.FORMAT_INFO_MICRO[fmt]
return format_info | python | def calc_format_info(version, error, mask_pattern):
"""\
Returns the format information for the provided error level and mask patttern.
ISO/IEC 18004:2015(E) -- 7.9 Format information (page 55)
ISO/IEC 18004:2015(E) -- Table C.1 — Valid format information bit sequences (page 80)
:param int version: Version constant
:param int error: Error level constant.
:param int mask_pattern: Mask pattern number.
"""
fmt = mask_pattern
if version > 0:
if error == consts.ERROR_LEVEL_L:
fmt += 0x08
elif error == consts.ERROR_LEVEL_H:
fmt += 0x10
elif error == consts.ERROR_LEVEL_Q:
fmt += 0x18
format_info = consts.FORMAT_INFO[fmt]
else:
fmt += consts.ERROR_LEVEL_TO_MICRO_MAPPING[version][error] << 2
format_info = consts.FORMAT_INFO_MICRO[fmt]
return format_info | [
"def",
"calc_format_info",
"(",
"version",
",",
"error",
",",
"mask_pattern",
")",
":",
"fmt",
"=",
"mask_pattern",
"if",
"version",
">",
"0",
":",
"if",
"error",
"==",
"consts",
".",
"ERROR_LEVEL_L",
":",
"fmt",
"+=",
"0x08",
"elif",
"error",
"==",
"con... | \
Returns the format information for the provided error level and mask patttern.
ISO/IEC 18004:2015(E) -- 7.9 Format information (page 55)
ISO/IEC 18004:2015(E) -- Table C.1 — Valid format information bit sequences (page 80)
:param int version: Version constant
:param int error: Error level constant.
:param int mask_pattern: Mask pattern number. | [
"\\",
"Returns",
"the",
"format",
"information",
"for",
"the",
"provided",
"error",
"level",
"and",
"mask",
"patttern",
"."
] | 64d912a2bd17d0b5ff3e8b5d37098edfc663c2b3 | https://github.com/heuer/segno/blob/64d912a2bd17d0b5ff3e8b5d37098edfc663c2b3/segno/encoder.py#L919-L942 | train | 31,954 |
heuer/segno | segno/encoder.py | add_format_info | def add_format_info(matrix, version, error, mask_pattern):
"""\
Adds the format information into the provided matrix.
ISO/IEC 18004:2015(E) -- 7.9 Format information (page 55)
ISO/IEC 18004:2015(E) -- 7.9.1 QR Code symbols
ISO/IEC 18004:2015(E) -- 7.9.2 Micro QR Code symbols
:param matrix: The matrix.
:param int version: Version constant
:param int error: Error level constant.
:param int mask_pattern: Mask pattern number.
"""
# 14: most significant bit
# 0: least significant bit
#
# QR Code format info: Micro QR format info
# col 0 col 7 col matrix[-1] col 1
# 0 | | [ ]
# 1 0
# 2 1
# 3 2
# 4 3
# 5 4
# [ ] 5
# 6 6
# 14 13 12 11 10 9 [ ] 8 7 ... 7 6 5 4 3 2 1 0 14 13 12 11 10 9 8 7
#
# ...
# [ ] (dark module)
# 8
# 9
# 10
# 11
# 12
# 13
# 14
is_micro = version < 1
format_info = calc_format_info(version, error, mask_pattern)
offset = int(is_micro)
for i in range(8):
bit = (format_info >> i) & 0x01
if i == 6 and not is_micro: # Timing pattern
offset += 1
# vertical row, upper left corner
matrix[i + offset][8] = bit
if not is_micro:
# horizontal row, upper right corner
matrix[8][-1 - i] = bit
offset = int(is_micro)
for i in range(8):
bit = (format_info >> (14 - i)) & 0x01
if i == 6 and not is_micro: # Timing pattern
offset = 1
# horizontal row, upper left corner
matrix[8][i + offset] = bit
if not is_micro:
# vertical row, bottom left corner
matrix[-1 - i][8] = bit
if not is_micro:
# Dark module
matrix[-8][8] = 0x1 | python | def add_format_info(matrix, version, error, mask_pattern):
"""\
Adds the format information into the provided matrix.
ISO/IEC 18004:2015(E) -- 7.9 Format information (page 55)
ISO/IEC 18004:2015(E) -- 7.9.1 QR Code symbols
ISO/IEC 18004:2015(E) -- 7.9.2 Micro QR Code symbols
:param matrix: The matrix.
:param int version: Version constant
:param int error: Error level constant.
:param int mask_pattern: Mask pattern number.
"""
# 14: most significant bit
# 0: least significant bit
#
# QR Code format info: Micro QR format info
# col 0 col 7 col matrix[-1] col 1
# 0 | | [ ]
# 1 0
# 2 1
# 3 2
# 4 3
# 5 4
# [ ] 5
# 6 6
# 14 13 12 11 10 9 [ ] 8 7 ... 7 6 5 4 3 2 1 0 14 13 12 11 10 9 8 7
#
# ...
# [ ] (dark module)
# 8
# 9
# 10
# 11
# 12
# 13
# 14
is_micro = version < 1
format_info = calc_format_info(version, error, mask_pattern)
offset = int(is_micro)
for i in range(8):
bit = (format_info >> i) & 0x01
if i == 6 and not is_micro: # Timing pattern
offset += 1
# vertical row, upper left corner
matrix[i + offset][8] = bit
if not is_micro:
# horizontal row, upper right corner
matrix[8][-1 - i] = bit
offset = int(is_micro)
for i in range(8):
bit = (format_info >> (14 - i)) & 0x01
if i == 6 and not is_micro: # Timing pattern
offset = 1
# horizontal row, upper left corner
matrix[8][i + offset] = bit
if not is_micro:
# vertical row, bottom left corner
matrix[-1 - i][8] = bit
if not is_micro:
# Dark module
matrix[-8][8] = 0x1 | [
"def",
"add_format_info",
"(",
"matrix",
",",
"version",
",",
"error",
",",
"mask_pattern",
")",
":",
"# 14: most significant bit",
"# 0: least significant bit",
"#",
"# QR Code format info: Micro QR format info",
"# col 0 col ... | \
Adds the format information into the provided matrix.
ISO/IEC 18004:2015(E) -- 7.9 Format information (page 55)
ISO/IEC 18004:2015(E) -- 7.9.1 QR Code symbols
ISO/IEC 18004:2015(E) -- 7.9.2 Micro QR Code symbols
:param matrix: The matrix.
:param int version: Version constant
:param int error: Error level constant.
:param int mask_pattern: Mask pattern number. | [
"\\",
"Adds",
"the",
"format",
"information",
"into",
"the",
"provided",
"matrix",
"."
] | 64d912a2bd17d0b5ff3e8b5d37098edfc663c2b3 | https://github.com/heuer/segno/blob/64d912a2bd17d0b5ff3e8b5d37098edfc663c2b3/segno/encoder.py#L945-L1006 | train | 31,955 |
heuer/segno | segno/encoder.py | add_version_info | def add_version_info(matrix, version):
"""\
Adds the version information to the matrix, for versions < 7 this is a no-op.
ISO/IEC 18004:2015(E) -- 7.10 Version information (page 58)
"""
#
# module 0 = least significant bit
# module 17 = most significant bit
#
# Figure 27 — Version information positioning (page 58)
#
# Lower left Upper right
# ---------- -----------
# 0 3 6 9 12 15 0 1 2
# 1 4 7 10 13 16 3 4 5
# 2 5 8 11 14 17 6 7 8
# 9 10 11
# 12 13 14
# 15 16 17
#
if version < 7:
return
version_info = consts.VERSION_INFO[version - 7]
for i in range(6):
bit1 = (version_info >> (i * 3)) & 0x01
bit2 = (version_info >> ((i * 3) + 1)) & 0x01
bit3 = (version_info >> ((i * 3) + 2)) & 0x01
# Lower left
matrix[-11][i] = bit1
matrix[-10][i] = bit2
matrix[-9][i] = bit3
# Upper right
matrix[i][-11] = bit1
matrix[i][-10] = bit2
matrix[i][-9] = bit3 | python | def add_version_info(matrix, version):
"""\
Adds the version information to the matrix, for versions < 7 this is a no-op.
ISO/IEC 18004:2015(E) -- 7.10 Version information (page 58)
"""
#
# module 0 = least significant bit
# module 17 = most significant bit
#
# Figure 27 — Version information positioning (page 58)
#
# Lower left Upper right
# ---------- -----------
# 0 3 6 9 12 15 0 1 2
# 1 4 7 10 13 16 3 4 5
# 2 5 8 11 14 17 6 7 8
# 9 10 11
# 12 13 14
# 15 16 17
#
if version < 7:
return
version_info = consts.VERSION_INFO[version - 7]
for i in range(6):
bit1 = (version_info >> (i * 3)) & 0x01
bit2 = (version_info >> ((i * 3) + 1)) & 0x01
bit3 = (version_info >> ((i * 3) + 2)) & 0x01
# Lower left
matrix[-11][i] = bit1
matrix[-10][i] = bit2
matrix[-9][i] = bit3
# Upper right
matrix[i][-11] = bit1
matrix[i][-10] = bit2
matrix[i][-9] = bit3 | [
"def",
"add_version_info",
"(",
"matrix",
",",
"version",
")",
":",
"#",
"# module 0 = least significant bit",
"# module 17 = most significant bit",
"#",
"# Figure 27 — Version information positioning (page 58)",
"#",
"# Lower left Upper right",
"# ---------- ... | \
Adds the version information to the matrix, for versions < 7 this is a no-op.
ISO/IEC 18004:2015(E) -- 7.10 Version information (page 58) | [
"\\",
"Adds",
"the",
"version",
"information",
"to",
"the",
"matrix",
"for",
"versions",
"<",
"7",
"this",
"is",
"a",
"no",
"-",
"op",
"."
] | 64d912a2bd17d0b5ff3e8b5d37098edfc663c2b3 | https://github.com/heuer/segno/blob/64d912a2bd17d0b5ff3e8b5d37098edfc663c2b3/segno/encoder.py#L1009-L1044 | train | 31,956 |
heuer/segno | segno/encoder.py | prepare_data | def prepare_data(content, mode, encoding, version=None):
"""\
Returns an iterable of `Segment` instances.
If `content` is a string, an integer, or bytes, the returned tuple will
have a single item. If `content` is a list or a tuple, a tuple of
`Segment` instances of the same length is returned.
:param content: Either a string, bytes, an integer or an iterable.
:type content: str, bytes, int, tuple, list or any iterable
:param mode: The global mode. If `content` is list/tuple, the `Segment`
instances may have a different mode.
:param encoding: The global encoding. If `content` is a list or a tuple,
the `Segment` instances may have a different encoding.
:param int version: Version constant or ``None``. This refers to the version
which was provided by the user.
:rtype: Segments
"""
segments = Segments()
add_segment = segments.add_segment
if isinstance(content, (str_type, bytes, numeric)):
add_segment(make_segment(content, mode, encoding))
return segments
for item in content:
seg_content, seg_mode, seg_encoding = item, mode, encoding
if isinstance(item, tuple):
seg_content = item[0]
if len(item) > 1:
seg_mode = item[1] or mode # item[1] could be None
if len(item) > 2:
seg_encoding = item[2] or encoding # item[2] may be None
add_segment(make_segment(seg_content, seg_mode, seg_encoding))
return segments | python | def prepare_data(content, mode, encoding, version=None):
"""\
Returns an iterable of `Segment` instances.
If `content` is a string, an integer, or bytes, the returned tuple will
have a single item. If `content` is a list or a tuple, a tuple of
`Segment` instances of the same length is returned.
:param content: Either a string, bytes, an integer or an iterable.
:type content: str, bytes, int, tuple, list or any iterable
:param mode: The global mode. If `content` is list/tuple, the `Segment`
instances may have a different mode.
:param encoding: The global encoding. If `content` is a list or a tuple,
the `Segment` instances may have a different encoding.
:param int version: Version constant or ``None``. This refers to the version
which was provided by the user.
:rtype: Segments
"""
segments = Segments()
add_segment = segments.add_segment
if isinstance(content, (str_type, bytes, numeric)):
add_segment(make_segment(content, mode, encoding))
return segments
for item in content:
seg_content, seg_mode, seg_encoding = item, mode, encoding
if isinstance(item, tuple):
seg_content = item[0]
if len(item) > 1:
seg_mode = item[1] or mode # item[1] could be None
if len(item) > 2:
seg_encoding = item[2] or encoding # item[2] may be None
add_segment(make_segment(seg_content, seg_mode, seg_encoding))
return segments | [
"def",
"prepare_data",
"(",
"content",
",",
"mode",
",",
"encoding",
",",
"version",
"=",
"None",
")",
":",
"segments",
"=",
"Segments",
"(",
")",
"add_segment",
"=",
"segments",
".",
"add_segment",
"if",
"isinstance",
"(",
"content",
",",
"(",
"str_type",... | \
Returns an iterable of `Segment` instances.
If `content` is a string, an integer, or bytes, the returned tuple will
have a single item. If `content` is a list or a tuple, a tuple of
`Segment` instances of the same length is returned.
:param content: Either a string, bytes, an integer or an iterable.
:type content: str, bytes, int, tuple, list or any iterable
:param mode: The global mode. If `content` is list/tuple, the `Segment`
instances may have a different mode.
:param encoding: The global encoding. If `content` is a list or a tuple,
the `Segment` instances may have a different encoding.
:param int version: Version constant or ``None``. This refers to the version
which was provided by the user.
:rtype: Segments | [
"\\",
"Returns",
"an",
"iterable",
"of",
"Segment",
"instances",
"."
] | 64d912a2bd17d0b5ff3e8b5d37098edfc663c2b3 | https://github.com/heuer/segno/blob/64d912a2bd17d0b5ff3e8b5d37098edfc663c2b3/segno/encoder.py#L1047-L1079 | train | 31,957 |
heuer/segno | segno/encoder.py | data_to_bytes | def data_to_bytes(data, encoding):
"""\
Converts the provided data into bytes. If the data is already a byte
sequence, it will be left unchanged.
This function tries to use the provided `encoding` (if not ``None``)
or the default encoding (ISO/IEC 8859-1). It uses UTF-8 as fallback.
Returns the (byte) data, the data length and the encoding of the data.
:param data: The data to encode
:type data: str or bytes
:param encoding: str or ``None``
:rtype: tuple: data, data length, encoding
"""
if isinstance(data, bytes):
return data, len(data), encoding or consts.DEFAULT_BYTE_ENCODING
data = str(data)
if encoding is not None:
# Use the provided encoding; could raise an exception by intention
data = data.encode(encoding)
else:
try:
# Try to use the default byte encoding
encoding = consts.DEFAULT_BYTE_ENCODING
data = data.encode(encoding)
except UnicodeError:
try:
# Try Kanji / Shift_JIS
encoding = consts.KANJI_ENCODING
data = data.encode(encoding)
except UnicodeError:
# Use UTF-8
encoding = 'utf-8'
data = data.encode(encoding)
return data, len(data), encoding | python | def data_to_bytes(data, encoding):
"""\
Converts the provided data into bytes. If the data is already a byte
sequence, it will be left unchanged.
This function tries to use the provided `encoding` (if not ``None``)
or the default encoding (ISO/IEC 8859-1). It uses UTF-8 as fallback.
Returns the (byte) data, the data length and the encoding of the data.
:param data: The data to encode
:type data: str or bytes
:param encoding: str or ``None``
:rtype: tuple: data, data length, encoding
"""
if isinstance(data, bytes):
return data, len(data), encoding or consts.DEFAULT_BYTE_ENCODING
data = str(data)
if encoding is not None:
# Use the provided encoding; could raise an exception by intention
data = data.encode(encoding)
else:
try:
# Try to use the default byte encoding
encoding = consts.DEFAULT_BYTE_ENCODING
data = data.encode(encoding)
except UnicodeError:
try:
# Try Kanji / Shift_JIS
encoding = consts.KANJI_ENCODING
data = data.encode(encoding)
except UnicodeError:
# Use UTF-8
encoding = 'utf-8'
data = data.encode(encoding)
return data, len(data), encoding | [
"def",
"data_to_bytes",
"(",
"data",
",",
"encoding",
")",
":",
"if",
"isinstance",
"(",
"data",
",",
"bytes",
")",
":",
"return",
"data",
",",
"len",
"(",
"data",
")",
",",
"encoding",
"or",
"consts",
".",
"DEFAULT_BYTE_ENCODING",
"data",
"=",
"str",
... | \
Converts the provided data into bytes. If the data is already a byte
sequence, it will be left unchanged.
This function tries to use the provided `encoding` (if not ``None``)
or the default encoding (ISO/IEC 8859-1). It uses UTF-8 as fallback.
Returns the (byte) data, the data length and the encoding of the data.
:param data: The data to encode
:type data: str or bytes
:param encoding: str or ``None``
:rtype: tuple: data, data length, encoding | [
"\\",
"Converts",
"the",
"provided",
"data",
"into",
"bytes",
".",
"If",
"the",
"data",
"is",
"already",
"a",
"byte",
"sequence",
"it",
"will",
"be",
"left",
"unchanged",
"."
] | 64d912a2bd17d0b5ff3e8b5d37098edfc663c2b3 | https://github.com/heuer/segno/blob/64d912a2bd17d0b5ff3e8b5d37098edfc663c2b3/segno/encoder.py#L1082-L1117 | train | 31,958 |
heuer/segno | segno/encoder.py | normalize_version | def normalize_version(version):
"""\
Canonicalizes the provided `version`.
If the `version` is ``None``, this function returns ``None``. Otherwise
this function checks if `version` is an integer or a Micro QR Code version.
In case the string represents a Micro QR Code version, an uppercased
string identifier is returned.
If the `version` does not represent a valid version identifier (aside of
``None``, a VersionError is raised.
:param version: An integer, a string or ``None``.
:raises: VersionError: In case the version is not ``None`` and does not
represent a valid (Micro) QR Code version.
:rtype: int, str or ``None``
"""
if version is None:
return None
error = False
try:
version = int(version)
# Don't want Micro QR Code constants as input
error = version < 1
except (ValueError, TypeError):
try:
version = consts.MICRO_VERSION_MAPPING[version.upper()]
except (KeyError, AttributeError):
error = True
if error or not 0 < version < 41 and version not in consts.MICRO_VERSIONS:
raise VersionError('Unsupported version "{0}". '
'Supported: {1} and 1 .. 40'
.format(version, ', '.join(sorted(consts.MICRO_VERSION_MAPPING.keys()))))
return version | python | def normalize_version(version):
"""\
Canonicalizes the provided `version`.
If the `version` is ``None``, this function returns ``None``. Otherwise
this function checks if `version` is an integer or a Micro QR Code version.
In case the string represents a Micro QR Code version, an uppercased
string identifier is returned.
If the `version` does not represent a valid version identifier (aside of
``None``, a VersionError is raised.
:param version: An integer, a string or ``None``.
:raises: VersionError: In case the version is not ``None`` and does not
represent a valid (Micro) QR Code version.
:rtype: int, str or ``None``
"""
if version is None:
return None
error = False
try:
version = int(version)
# Don't want Micro QR Code constants as input
error = version < 1
except (ValueError, TypeError):
try:
version = consts.MICRO_VERSION_MAPPING[version.upper()]
except (KeyError, AttributeError):
error = True
if error or not 0 < version < 41 and version not in consts.MICRO_VERSIONS:
raise VersionError('Unsupported version "{0}". '
'Supported: {1} and 1 .. 40'
.format(version, ', '.join(sorted(consts.MICRO_VERSION_MAPPING.keys()))))
return version | [
"def",
"normalize_version",
"(",
"version",
")",
":",
"if",
"version",
"is",
"None",
":",
"return",
"None",
"error",
"=",
"False",
"try",
":",
"version",
"=",
"int",
"(",
"version",
")",
"# Don't want Micro QR Code constants as input",
"error",
"=",
"version",
... | \
Canonicalizes the provided `version`.
If the `version` is ``None``, this function returns ``None``. Otherwise
this function checks if `version` is an integer or a Micro QR Code version.
In case the string represents a Micro QR Code version, an uppercased
string identifier is returned.
If the `version` does not represent a valid version identifier (aside of
``None``, a VersionError is raised.
:param version: An integer, a string or ``None``.
:raises: VersionError: In case the version is not ``None`` and does not
represent a valid (Micro) QR Code version.
:rtype: int, str or ``None`` | [
"\\",
"Canonicalizes",
"the",
"provided",
"version",
"."
] | 64d912a2bd17d0b5ff3e8b5d37098edfc663c2b3 | https://github.com/heuer/segno/blob/64d912a2bd17d0b5ff3e8b5d37098edfc663c2b3/segno/encoder.py#L1245-L1278 | train | 31,959 |
heuer/segno | segno/encoder.py | normalize_errorlevel | def normalize_errorlevel(error, accept_none=False):
"""\
Returns a constant for the provided error level.
This function returns ``None`` if the provided parameter is ``None`` and
`accept_none` is set to ``True`` (default: ``False``). If `error` is ``None``
and `accept_none` is ``False`` or if the provided parameter cannot be
mapped to a valid QR Code error level, a ErrorLevelError is raised.
:param error: String or ``None``.
:param bool accept_none: Indicates if ``None`` is accepted as error level.
:rtype: int
"""
if error is None:
if not accept_none:
raise ErrorLevelError('The error level must be provided')
return error
try:
return consts.ERROR_MAPPING[error.upper()]
except: # KeyError or error.upper() fails
if error in consts.ERROR_MAPPING.values():
return error
raise ErrorLevelError('Illegal error correction level: "{0}".'
'Supported levels: {1}'
.format(error, ', '.join(sorted(consts.ERROR_MAPPING.keys())))) | python | def normalize_errorlevel(error, accept_none=False):
"""\
Returns a constant for the provided error level.
This function returns ``None`` if the provided parameter is ``None`` and
`accept_none` is set to ``True`` (default: ``False``). If `error` is ``None``
and `accept_none` is ``False`` or if the provided parameter cannot be
mapped to a valid QR Code error level, a ErrorLevelError is raised.
:param error: String or ``None``.
:param bool accept_none: Indicates if ``None`` is accepted as error level.
:rtype: int
"""
if error is None:
if not accept_none:
raise ErrorLevelError('The error level must be provided')
return error
try:
return consts.ERROR_MAPPING[error.upper()]
except: # KeyError or error.upper() fails
if error in consts.ERROR_MAPPING.values():
return error
raise ErrorLevelError('Illegal error correction level: "{0}".'
'Supported levels: {1}'
.format(error, ', '.join(sorted(consts.ERROR_MAPPING.keys())))) | [
"def",
"normalize_errorlevel",
"(",
"error",
",",
"accept_none",
"=",
"False",
")",
":",
"if",
"error",
"is",
"None",
":",
"if",
"not",
"accept_none",
":",
"raise",
"ErrorLevelError",
"(",
"'The error level must be provided'",
")",
"return",
"error",
"try",
":",... | \
Returns a constant for the provided error level.
This function returns ``None`` if the provided parameter is ``None`` and
`accept_none` is set to ``True`` (default: ``False``). If `error` is ``None``
and `accept_none` is ``False`` or if the provided parameter cannot be
mapped to a valid QR Code error level, a ErrorLevelError is raised.
:param error: String or ``None``.
:param bool accept_none: Indicates if ``None`` is accepted as error level.
:rtype: int | [
"\\",
"Returns",
"a",
"constant",
"for",
"the",
"provided",
"error",
"level",
"."
] | 64d912a2bd17d0b5ff3e8b5d37098edfc663c2b3 | https://github.com/heuer/segno/blob/64d912a2bd17d0b5ff3e8b5d37098edfc663c2b3/segno/encoder.py#L1329-L1353 | train | 31,960 |
heuer/segno | segno/encoder.py | get_mode_name | def get_mode_name(mode_const):
"""\
Returns the mode name for the provided mode constant.
:param int mode_const: The mode constant (see :py:module:`segno.consts`)
"""
for name, val in consts.MODE_MAPPING.items():
if val == mode_const:
return name
raise ModeError('Unknown mode "{0}"'.format(mode_const)) | python | def get_mode_name(mode_const):
"""\
Returns the mode name for the provided mode constant.
:param int mode_const: The mode constant (see :py:module:`segno.consts`)
"""
for name, val in consts.MODE_MAPPING.items():
if val == mode_const:
return name
raise ModeError('Unknown mode "{0}"'.format(mode_const)) | [
"def",
"get_mode_name",
"(",
"mode_const",
")",
":",
"for",
"name",
",",
"val",
"in",
"consts",
".",
"MODE_MAPPING",
".",
"items",
"(",
")",
":",
"if",
"val",
"==",
"mode_const",
":",
"return",
"name",
"raise",
"ModeError",
"(",
"'Unknown mode \"{0}\"'",
"... | \
Returns the mode name for the provided mode constant.
:param int mode_const: The mode constant (see :py:module:`segno.consts`) | [
"\\",
"Returns",
"the",
"mode",
"name",
"for",
"the",
"provided",
"mode",
"constant",
"."
] | 64d912a2bd17d0b5ff3e8b5d37098edfc663c2b3 | https://github.com/heuer/segno/blob/64d912a2bd17d0b5ff3e8b5d37098edfc663c2b3/segno/encoder.py#L1356-L1365 | train | 31,961 |
heuer/segno | segno/encoder.py | get_error_name | def get_error_name(error_const):
"""\
Returns the error name for the provided error constant.
:param int error_const: The error constant (see :py:module:`segno.consts`)
"""
for name, val in consts.ERROR_MAPPING.items():
if val == error_const:
return name
raise ErrorLevelError('Unknown error level "{0}"'.format(error_const)) | python | def get_error_name(error_const):
"""\
Returns the error name for the provided error constant.
:param int error_const: The error constant (see :py:module:`segno.consts`)
"""
for name, val in consts.ERROR_MAPPING.items():
if val == error_const:
return name
raise ErrorLevelError('Unknown error level "{0}"'.format(error_const)) | [
"def",
"get_error_name",
"(",
"error_const",
")",
":",
"for",
"name",
",",
"val",
"in",
"consts",
".",
"ERROR_MAPPING",
".",
"items",
"(",
")",
":",
"if",
"val",
"==",
"error_const",
":",
"return",
"name",
"raise",
"ErrorLevelError",
"(",
"'Unknown error lev... | \
Returns the error name for the provided error constant.
:param int error_const: The error constant (see :py:module:`segno.consts`) | [
"\\",
"Returns",
"the",
"error",
"name",
"for",
"the",
"provided",
"error",
"constant",
"."
] | 64d912a2bd17d0b5ff3e8b5d37098edfc663c2b3 | https://github.com/heuer/segno/blob/64d912a2bd17d0b5ff3e8b5d37098edfc663c2b3/segno/encoder.py#L1368-L1377 | train | 31,962 |
heuer/segno | segno/encoder.py | get_version_name | def get_version_name(version_const):
"""\
Returns the version name.
For version 1 .. 40 it returns the version as integer, for Micro QR Codes
it returns a string like ``M1`` etc.
:raises: VersionError: In case the `version_constant` is unknown.
"""
if 0 < version_const < 41:
return version_const
for name, v in consts.MICRO_VERSION_MAPPING.items():
if v == version_const:
return name
raise VersionError('Unknown version constant "{0}"'.format(version_const)) | python | def get_version_name(version_const):
"""\
Returns the version name.
For version 1 .. 40 it returns the version as integer, for Micro QR Codes
it returns a string like ``M1`` etc.
:raises: VersionError: In case the `version_constant` is unknown.
"""
if 0 < version_const < 41:
return version_const
for name, v in consts.MICRO_VERSION_MAPPING.items():
if v == version_const:
return name
raise VersionError('Unknown version constant "{0}"'.format(version_const)) | [
"def",
"get_version_name",
"(",
"version_const",
")",
":",
"if",
"0",
"<",
"version_const",
"<",
"41",
":",
"return",
"version_const",
"for",
"name",
",",
"v",
"in",
"consts",
".",
"MICRO_VERSION_MAPPING",
".",
"items",
"(",
")",
":",
"if",
"v",
"==",
"v... | \
Returns the version name.
For version 1 .. 40 it returns the version as integer, for Micro QR Codes
it returns a string like ``M1`` etc.
:raises: VersionError: In case the `version_constant` is unknown. | [
"\\",
"Returns",
"the",
"version",
"name",
"."
] | 64d912a2bd17d0b5ff3e8b5d37098edfc663c2b3 | https://github.com/heuer/segno/blob/64d912a2bd17d0b5ff3e8b5d37098edfc663c2b3/segno/encoder.py#L1380-L1394 | train | 31,963 |
heuer/segno | segno/encoder.py | is_kanji | def is_kanji(data):
"""\
Returns if the `data` can be encoded in "kanji" mode.
:param bytes data: The data to check.
:rtype: bool
"""
data_len = len(data)
if not data_len or data_len % 2:
return False
if _PY2:
data = (ord(c) for c in data)
data_iter = iter(data)
for i in range(0, data_len, 2):
code = (next(data_iter) << 8) | next(data_iter)
if not (0x8140 <= code <= 0x9ffc or 0xe040 <= code <= 0xebbf):
return False
return True | python | def is_kanji(data):
"""\
Returns if the `data` can be encoded in "kanji" mode.
:param bytes data: The data to check.
:rtype: bool
"""
data_len = len(data)
if not data_len or data_len % 2:
return False
if _PY2:
data = (ord(c) for c in data)
data_iter = iter(data)
for i in range(0, data_len, 2):
code = (next(data_iter) << 8) | next(data_iter)
if not (0x8140 <= code <= 0x9ffc or 0xe040 <= code <= 0xebbf):
return False
return True | [
"def",
"is_kanji",
"(",
"data",
")",
":",
"data_len",
"=",
"len",
"(",
"data",
")",
"if",
"not",
"data_len",
"or",
"data_len",
"%",
"2",
":",
"return",
"False",
"if",
"_PY2",
":",
"data",
"=",
"(",
"ord",
"(",
"c",
")",
"for",
"c",
"in",
"data",
... | \
Returns if the `data` can be encoded in "kanji" mode.
:param bytes data: The data to check.
:rtype: bool | [
"\\",
"Returns",
"if",
"the",
"data",
"can",
"be",
"encoded",
"in",
"kanji",
"mode",
"."
] | 64d912a2bd17d0b5ff3e8b5d37098edfc663c2b3 | https://github.com/heuer/segno/blob/64d912a2bd17d0b5ff3e8b5d37098edfc663c2b3/segno/encoder.py#L1409-L1426 | train | 31,964 |
heuer/segno | segno/encoder.py | calc_structured_append_parity | def calc_structured_append_parity(content):
"""\
Calculates the parity data for the Structured Append mode.
:param str content: The content.
:rtype: int
"""
if not isinstance(content, str_type):
content = str(content)
try:
data = content.encode('iso-8859-1')
except UnicodeError:
try:
data = content.encode('shift-jis')
except (LookupError, UnicodeError):
data = content.encode('utf-8')
if _PY2:
data = (ord(c) for c in data)
return reduce(xor, data) | python | def calc_structured_append_parity(content):
"""\
Calculates the parity data for the Structured Append mode.
:param str content: The content.
:rtype: int
"""
if not isinstance(content, str_type):
content = str(content)
try:
data = content.encode('iso-8859-1')
except UnicodeError:
try:
data = content.encode('shift-jis')
except (LookupError, UnicodeError):
data = content.encode('utf-8')
if _PY2:
data = (ord(c) for c in data)
return reduce(xor, data) | [
"def",
"calc_structured_append_parity",
"(",
"content",
")",
":",
"if",
"not",
"isinstance",
"(",
"content",
",",
"str_type",
")",
":",
"content",
"=",
"str",
"(",
"content",
")",
"try",
":",
"data",
"=",
"content",
".",
"encode",
"(",
"'iso-8859-1'",
")",... | \
Calculates the parity data for the Structured Append mode.
:param str content: The content.
:rtype: int | [
"\\",
"Calculates",
"the",
"parity",
"data",
"for",
"the",
"Structured",
"Append",
"mode",
"."
] | 64d912a2bd17d0b5ff3e8b5d37098edfc663c2b3 | https://github.com/heuer/segno/blob/64d912a2bd17d0b5ff3e8b5d37098edfc663c2b3/segno/encoder.py#L1490-L1508 | train | 31,965 |
heuer/segno | segno/encoder.py | is_mode_supported | def is_mode_supported(mode, ver):
"""\
Returns if `mode` is supported by `version`.
Note: This function does not check if `version` is actually a valid
(Micro) QR Code version. Invalid versions like ``41`` may return an illegal
value.
:param int mode: Canonicalized mode.
:param int or None ver: (Micro) QR Code version constant.
:rtype: bool
"""
ver = None if ver > 0 else ver
try:
return ver in consts.SUPPORTED_MODES[mode]
except KeyError:
raise ModeError('Unknown mode "{0}"'.format(mode)) | python | def is_mode_supported(mode, ver):
"""\
Returns if `mode` is supported by `version`.
Note: This function does not check if `version` is actually a valid
(Micro) QR Code version. Invalid versions like ``41`` may return an illegal
value.
:param int mode: Canonicalized mode.
:param int or None ver: (Micro) QR Code version constant.
:rtype: bool
"""
ver = None if ver > 0 else ver
try:
return ver in consts.SUPPORTED_MODES[mode]
except KeyError:
raise ModeError('Unknown mode "{0}"'.format(mode)) | [
"def",
"is_mode_supported",
"(",
"mode",
",",
"ver",
")",
":",
"ver",
"=",
"None",
"if",
"ver",
">",
"0",
"else",
"ver",
"try",
":",
"return",
"ver",
"in",
"consts",
".",
"SUPPORTED_MODES",
"[",
"mode",
"]",
"except",
"KeyError",
":",
"raise",
"ModeErr... | \
Returns if `mode` is supported by `version`.
Note: This function does not check if `version` is actually a valid
(Micro) QR Code version. Invalid versions like ``41`` may return an illegal
value.
:param int mode: Canonicalized mode.
:param int or None ver: (Micro) QR Code version constant.
:rtype: bool | [
"\\",
"Returns",
"if",
"mode",
"is",
"supported",
"by",
"version",
"."
] | 64d912a2bd17d0b5ff3e8b5d37098edfc663c2b3 | https://github.com/heuer/segno/blob/64d912a2bd17d0b5ff3e8b5d37098edfc663c2b3/segno/encoder.py#L1511-L1527 | train | 31,966 |
heuer/segno | segno/encoder.py | version_range | def version_range(version):
"""\
Returns the version range for the provided version. This applies to QR Code
versions, only.
:param int version: The QR Code version (1 .. 40)
:rtype: int
"""
# ISO/IEC 18004:2015(E)
# Table 3 — Number of bits in character count indicator for QR Code (page 23)
if 0 < version < 10:
return consts.VERSION_RANGE_01_09
elif 9 < version < 27:
return consts.VERSION_RANGE_10_26
elif 26 < version < 41:
return consts.VERSION_RANGE_27_40
raise VersionError('Unknown version "{0}"'.format(version)) | python | def version_range(version):
"""\
Returns the version range for the provided version. This applies to QR Code
versions, only.
:param int version: The QR Code version (1 .. 40)
:rtype: int
"""
# ISO/IEC 18004:2015(E)
# Table 3 — Number of bits in character count indicator for QR Code (page 23)
if 0 < version < 10:
return consts.VERSION_RANGE_01_09
elif 9 < version < 27:
return consts.VERSION_RANGE_10_26
elif 26 < version < 41:
return consts.VERSION_RANGE_27_40
raise VersionError('Unknown version "{0}"'.format(version)) | [
"def",
"version_range",
"(",
"version",
")",
":",
"# ISO/IEC 18004:2015(E)",
"# Table 3 — Number of bits in character count indicator for QR Code (page 23)",
"if",
"0",
"<",
"version",
"<",
"10",
":",
"return",
"consts",
".",
"VERSION_RANGE_01_09",
"elif",
"9",
"<",
"vers... | \
Returns the version range for the provided version. This applies to QR Code
versions, only.
:param int version: The QR Code version (1 .. 40)
:rtype: int | [
"\\",
"Returns",
"the",
"version",
"range",
"for",
"the",
"provided",
"version",
".",
"This",
"applies",
"to",
"QR",
"Code",
"versions",
"only",
"."
] | 64d912a2bd17d0b5ff3e8b5d37098edfc663c2b3 | https://github.com/heuer/segno/blob/64d912a2bd17d0b5ff3e8b5d37098edfc663c2b3/segno/encoder.py#L1543-L1559 | train | 31,967 |
heuer/segno | segno/encoder.py | get_eci_assignment_number | def get_eci_assignment_number(encoding):
"""\
Returns the ECI number for the provided encoding.
:param str encoding: A encoding name
:return str: The ECI number.
"""
try:
return consts.ECI_ASSIGNMENT_NUM[codecs.lookup(encoding).name]
except KeyError:
raise QRCodeError('Unknown ECI assignment number for encoding "{0}".'
.format(encoding)) | python | def get_eci_assignment_number(encoding):
"""\
Returns the ECI number for the provided encoding.
:param str encoding: A encoding name
:return str: The ECI number.
"""
try:
return consts.ECI_ASSIGNMENT_NUM[codecs.lookup(encoding).name]
except KeyError:
raise QRCodeError('Unknown ECI assignment number for encoding "{0}".'
.format(encoding)) | [
"def",
"get_eci_assignment_number",
"(",
"encoding",
")",
":",
"try",
":",
"return",
"consts",
".",
"ECI_ASSIGNMENT_NUM",
"[",
"codecs",
".",
"lookup",
"(",
"encoding",
")",
".",
"name",
"]",
"except",
"KeyError",
":",
"raise",
"QRCodeError",
"(",
"'Unknown EC... | \
Returns the ECI number for the provided encoding.
:param str encoding: A encoding name
:return str: The ECI number. | [
"\\",
"Returns",
"the",
"ECI",
"number",
"for",
"the",
"provided",
"encoding",
"."
] | 64d912a2bd17d0b5ff3e8b5d37098edfc663c2b3 | https://github.com/heuer/segno/blob/64d912a2bd17d0b5ff3e8b5d37098edfc663c2b3/segno/encoder.py#L1562-L1573 | train | 31,968 |
heuer/segno | segno/encoder.py | get_data_mask_functions | def get_data_mask_functions(is_micro):
"""
Returns the data mask functions.
ISO/IEC 18004:2015(E) -- 7.8.2 Data mask patterns (page 50)
Table 10 — Data mask pattern generation conditions (page 50)
=============== ===================== =====================================
QR Code Pattern Micro QR Code Pattern Condition
=============== ===================== =====================================
000 (i + j) mod 2 = 0
001 00 i mod 2 = 0
010 j mod 3 = 0
011 (i + j) mod 3 = 0
100 01 ((i div 2) + (j div 3)) mod 2 = 0
101 (i j) mod 2 + (i j) mod 3 = 0
110 10 ((i j) mod 2 + (i j) mod 3) mod 2 = 0
111 11 ((i+j) mod 2 + (i j) mod 3) mod 2 = 0
=============== ===================== =====================================
:param is_micro: Indicates if data mask functions for a Micro QR Code
should be returned
:return: A tuple of functions
"""
# i = row position, j = col position; (i, j) = (0, 0) = upper left corner
def fn0(i, j):
return (i + j) & 0x1 == 0
def fn1(i, j):
return i & 0x1 == 0
def fn2(i, j):
return j % 3 == 0
def fn3(i, j):
return (i + j) % 3 == 0
def fn4(i, j):
return (i // 2 + j // 3) & 0x1 == 0
def fn5(i, j):
tmp = i * j
return (tmp & 0x1) + (tmp % 3) == 0
def fn6(i, j):
tmp = i * j
return ((tmp & 0x1) + (tmp % 3)) & 0x1 == 0
def fn7(i, j):
return (((i + j) & 0x1) + (i * j) % 3) & 0x1 == 0
if is_micro:
return fn1, fn4, fn6, fn7
return fn0, fn1, fn2, fn3, fn4, fn5, fn6, fn7 | python | def get_data_mask_functions(is_micro):
"""
Returns the data mask functions.
ISO/IEC 18004:2015(E) -- 7.8.2 Data mask patterns (page 50)
Table 10 — Data mask pattern generation conditions (page 50)
=============== ===================== =====================================
QR Code Pattern Micro QR Code Pattern Condition
=============== ===================== =====================================
000 (i + j) mod 2 = 0
001 00 i mod 2 = 0
010 j mod 3 = 0
011 (i + j) mod 3 = 0
100 01 ((i div 2) + (j div 3)) mod 2 = 0
101 (i j) mod 2 + (i j) mod 3 = 0
110 10 ((i j) mod 2 + (i j) mod 3) mod 2 = 0
111 11 ((i+j) mod 2 + (i j) mod 3) mod 2 = 0
=============== ===================== =====================================
:param is_micro: Indicates if data mask functions for a Micro QR Code
should be returned
:return: A tuple of functions
"""
# i = row position, j = col position; (i, j) = (0, 0) = upper left corner
def fn0(i, j):
return (i + j) & 0x1 == 0
def fn1(i, j):
return i & 0x1 == 0
def fn2(i, j):
return j % 3 == 0
def fn3(i, j):
return (i + j) % 3 == 0
def fn4(i, j):
return (i // 2 + j // 3) & 0x1 == 0
def fn5(i, j):
tmp = i * j
return (tmp & 0x1) + (tmp % 3) == 0
def fn6(i, j):
tmp = i * j
return ((tmp & 0x1) + (tmp % 3)) & 0x1 == 0
def fn7(i, j):
return (((i + j) & 0x1) + (i * j) % 3) & 0x1 == 0
if is_micro:
return fn1, fn4, fn6, fn7
return fn0, fn1, fn2, fn3, fn4, fn5, fn6, fn7 | [
"def",
"get_data_mask_functions",
"(",
"is_micro",
")",
":",
"# i = row position, j = col position; (i, j) = (0, 0) = upper left corner",
"def",
"fn0",
"(",
"i",
",",
"j",
")",
":",
"return",
"(",
"i",
"+",
"j",
")",
"&",
"0x1",
"==",
"0",
"def",
"fn1",
"(",
"... | Returns the data mask functions.
ISO/IEC 18004:2015(E) -- 7.8.2 Data mask patterns (page 50)
Table 10 — Data mask pattern generation conditions (page 50)
=============== ===================== =====================================
QR Code Pattern Micro QR Code Pattern Condition
=============== ===================== =====================================
000 (i + j) mod 2 = 0
001 00 i mod 2 = 0
010 j mod 3 = 0
011 (i + j) mod 3 = 0
100 01 ((i div 2) + (j div 3)) mod 2 = 0
101 (i j) mod 2 + (i j) mod 3 = 0
110 10 ((i j) mod 2 + (i j) mod 3) mod 2 = 0
111 11 ((i+j) mod 2 + (i j) mod 3) mod 2 = 0
=============== ===================== =====================================
:param is_micro: Indicates if data mask functions for a Micro QR Code
should be returned
:return: A tuple of functions | [
"Returns",
"the",
"data",
"mask",
"functions",
"."
] | 64d912a2bd17d0b5ff3e8b5d37098edfc663c2b3 | https://github.com/heuer/segno/blob/64d912a2bd17d0b5ff3e8b5d37098edfc663c2b3/segno/encoder.py#L1576-L1629 | train | 31,969 |
heuer/segno | segno/encoder.py | Buffer.toints | def toints(self):
"""\
Returns an iterable of integers interpreting the content of `seq`
as sequence of binary numbers of length 8.
"""
def grouper(iterable, n, fillvalue=None):
"Collect data into fixed-length chunks or blocks"
# grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx
return zip_longest(*[iter(iterable)] * n, fillvalue=fillvalue)
return [int(''.join(map(str, group)), 2) for group in grouper(self._data, 8, 0)] | python | def toints(self):
"""\
Returns an iterable of integers interpreting the content of `seq`
as sequence of binary numbers of length 8.
"""
def grouper(iterable, n, fillvalue=None):
"Collect data into fixed-length chunks or blocks"
# grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx
return zip_longest(*[iter(iterable)] * n, fillvalue=fillvalue)
return [int(''.join(map(str, group)), 2) for group in grouper(self._data, 8, 0)] | [
"def",
"toints",
"(",
"self",
")",
":",
"def",
"grouper",
"(",
"iterable",
",",
"n",
",",
"fillvalue",
"=",
"None",
")",
":",
"\"Collect data into fixed-length chunks or blocks\"",
"# grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx",
"return",
"zip_longest",
"(",
"*",
"[",... | \
Returns an iterable of integers interpreting the content of `seq`
as sequence of binary numbers of length 8. | [
"\\",
"Returns",
"an",
"iterable",
"of",
"integers",
"interpreting",
"the",
"content",
"of",
"seq",
"as",
"sequence",
"of",
"binary",
"numbers",
"of",
"length",
"8",
"."
] | 64d912a2bd17d0b5ff3e8b5d37098edfc663c2b3 | https://github.com/heuer/segno/blob/64d912a2bd17d0b5ff3e8b5d37098edfc663c2b3/segno/encoder.py#L1735-L1744 | train | 31,970 |
heuer/segno | segno/colors.py | color_to_webcolor | def color_to_webcolor(color, allow_css3_colors=True, optimize=True):
"""\
Returns either a hexadecimal code or a color name.
:param color: A web color name (i.e. ``darkblue``) or a hexadecimal value
(``#RGB`` or ``#RRGGBB``) or a RGB(A) tuple (i.e. ``(R, G, B)`` or
``(R, G, B, A)``)
:param bool allow_css3_colors: Indicates if a CSS3 color value like
rgba(R G, B, A) is an acceptable result.
:param bool optimize: Inidcates if the shortest possible color value should
be returned (default: ``True``).
:rtype: str
:return: The provided color as web color: ``#RGB``, ``#RRGGBB``,
``rgba(R, G, B, A)``, or web color name.
"""
if color_is_black(color):
return '#000'
elif color_is_white(color):
return '#fff'
clr = color_to_rgb_or_rgba(color)
alpha_channel = None
if len(clr) == 4:
if allow_css3_colors:
return 'rgba({0},{1},{2},{3})'.format(*clr)
alpha_channel = clr[3]
clr = clr[:3]
hx = '#{0:02x}{1:02x}{2:02x}'.format(*clr)
if optimize:
if hx == '#d2b48c':
hx = 'tan' # shorter
elif hx == '#ff0000':
hx = 'red' # shorter
elif hx[1] == hx[2] and hx[3] == hx[4] and hx[5] == hx[6]:
hx = '#{0}{1}{2}'.format(hx[1], hx[3], hx[5])
return hx if alpha_channel is None else (hx, alpha_channel) | python | def color_to_webcolor(color, allow_css3_colors=True, optimize=True):
"""\
Returns either a hexadecimal code or a color name.
:param color: A web color name (i.e. ``darkblue``) or a hexadecimal value
(``#RGB`` or ``#RRGGBB``) or a RGB(A) tuple (i.e. ``(R, G, B)`` or
``(R, G, B, A)``)
:param bool allow_css3_colors: Indicates if a CSS3 color value like
rgba(R G, B, A) is an acceptable result.
:param bool optimize: Inidcates if the shortest possible color value should
be returned (default: ``True``).
:rtype: str
:return: The provided color as web color: ``#RGB``, ``#RRGGBB``,
``rgba(R, G, B, A)``, or web color name.
"""
if color_is_black(color):
return '#000'
elif color_is_white(color):
return '#fff'
clr = color_to_rgb_or_rgba(color)
alpha_channel = None
if len(clr) == 4:
if allow_css3_colors:
return 'rgba({0},{1},{2},{3})'.format(*clr)
alpha_channel = clr[3]
clr = clr[:3]
hx = '#{0:02x}{1:02x}{2:02x}'.format(*clr)
if optimize:
if hx == '#d2b48c':
hx = 'tan' # shorter
elif hx == '#ff0000':
hx = 'red' # shorter
elif hx[1] == hx[2] and hx[3] == hx[4] and hx[5] == hx[6]:
hx = '#{0}{1}{2}'.format(hx[1], hx[3], hx[5])
return hx if alpha_channel is None else (hx, alpha_channel) | [
"def",
"color_to_webcolor",
"(",
"color",
",",
"allow_css3_colors",
"=",
"True",
",",
"optimize",
"=",
"True",
")",
":",
"if",
"color_is_black",
"(",
"color",
")",
":",
"return",
"'#000'",
"elif",
"color_is_white",
"(",
"color",
")",
":",
"return",
"'#fff'",... | \
Returns either a hexadecimal code or a color name.
:param color: A web color name (i.e. ``darkblue``) or a hexadecimal value
(``#RGB`` or ``#RRGGBB``) or a RGB(A) tuple (i.e. ``(R, G, B)`` or
``(R, G, B, A)``)
:param bool allow_css3_colors: Indicates if a CSS3 color value like
rgba(R G, B, A) is an acceptable result.
:param bool optimize: Inidcates if the shortest possible color value should
be returned (default: ``True``).
:rtype: str
:return: The provided color as web color: ``#RGB``, ``#RRGGBB``,
``rgba(R, G, B, A)``, or web color name. | [
"\\",
"Returns",
"either",
"a",
"hexadecimal",
"code",
"or",
"a",
"color",
"name",
"."
] | 64d912a2bd17d0b5ff3e8b5d37098edfc663c2b3 | https://github.com/heuer/segno/blob/64d912a2bd17d0b5ff3e8b5d37098edfc663c2b3/segno/colors.py#L35-L69 | train | 31,971 |
heuer/segno | segno/utils.py | check_valid_border | def check_valid_border(border):
"""\
Raises a ValueError iff `border` is negative.
:param int border: Indicating the size of the quiet zone.
"""
if border is not None and (int(border) != border or border < 0):
raise ValueError('The border must not a non-negative integer value. '
'Got: "{0}"'.format(border)) | python | def check_valid_border(border):
"""\
Raises a ValueError iff `border` is negative.
:param int border: Indicating the size of the quiet zone.
"""
if border is not None and (int(border) != border or border < 0):
raise ValueError('The border must not a non-negative integer value. '
'Got: "{0}"'.format(border)) | [
"def",
"check_valid_border",
"(",
"border",
")",
":",
"if",
"border",
"is",
"not",
"None",
"and",
"(",
"int",
"(",
"border",
")",
"!=",
"border",
"or",
"border",
"<",
"0",
")",
":",
"raise",
"ValueError",
"(",
"'The border must not a non-negative integer value... | \
Raises a ValueError iff `border` is negative.
:param int border: Indicating the size of the quiet zone. | [
"\\",
"Raises",
"a",
"ValueError",
"iff",
"border",
"is",
"negative",
"."
] | 64d912a2bd17d0b5ff3e8b5d37098edfc663c2b3 | https://github.com/heuer/segno/blob/64d912a2bd17d0b5ff3e8b5d37098edfc663c2b3/segno/utils.py#L79-L87 | train | 31,972 |
CyberReboot/vent | vent/menu.py | VentApp.onStart | def onStart(self):
""" Override onStart method for npyscreen """
curses.mousemask(0)
self.paths.host_config()
version = Version()
# setup initial runtime stuff
if self.first_time[0] and self.first_time[1] != 'exists':
system = System()
thr = Thread(target=system.start, args=(), kwargs={})
thr.start()
countdown = 60
while thr.is_alive():
npyscreen.notify_wait('Completing initialization:...' + str(countdown),
title='Setting up things...')
time.sleep(1)
countdown -= 1
thr.join()
quit_s = '\t'*4 + '^Q to quit'
tab_esc = '\t'*4 + 'ESC to close menu popup'
self.addForm('MAIN',
MainForm,
name='Vent ' + version +
'\t\t\t\t\t^T for help' + quit_s + tab_esc,
color='IMPORTANT')
self.addForm('HELP',
HelpForm,
name='Help\t\t\t\t\t\t\t\t^T to toggle previous' +
quit_s,
color='DANGER')
self.addForm('TUTORIALINTRO',
TutorialIntroForm,
name='Vent Tutorial' + quit_s,
color='DANGER')
self.addForm('TUTORIALBACKGROUND',
TutorialBackgroundForm,
name='About Vent' + quit_s,
color='DANGER')
self.addForm('TUTORIALTERMINOLOGY',
TutorialTerminologyForm,
name='About Vent' + quit_s,
color='DANGER')
self.addForm('TUTORIALGETTINGSETUP',
TutorialGettingSetupForm,
name='About Vent' + quit_s,
color='DANGER')
self.addForm('TUTORIALSTARTINGCORES',
TutorialStartingCoresForm,
name='Working with Cores' + quit_s,
color='DANGER')
self.addForm('TUTORIALADDINGPLUGINS',
TutorialAddingPluginsForm,
name='Working with Plugins' + quit_s,
color='DANGER')
self.addForm('TUTORIALADDINGFILES',
TutorialAddingFilesForm,
name='Files' + quit_s,
color='DANGER')
self.addForm('TUTORIALTROUBLESHOOTING',
TutorialTroubleshootingForm,
name='Troubleshooting' + quit_s,
color='DANGER') | python | def onStart(self):
""" Override onStart method for npyscreen """
curses.mousemask(0)
self.paths.host_config()
version = Version()
# setup initial runtime stuff
if self.first_time[0] and self.first_time[1] != 'exists':
system = System()
thr = Thread(target=system.start, args=(), kwargs={})
thr.start()
countdown = 60
while thr.is_alive():
npyscreen.notify_wait('Completing initialization:...' + str(countdown),
title='Setting up things...')
time.sleep(1)
countdown -= 1
thr.join()
quit_s = '\t'*4 + '^Q to quit'
tab_esc = '\t'*4 + 'ESC to close menu popup'
self.addForm('MAIN',
MainForm,
name='Vent ' + version +
'\t\t\t\t\t^T for help' + quit_s + tab_esc,
color='IMPORTANT')
self.addForm('HELP',
HelpForm,
name='Help\t\t\t\t\t\t\t\t^T to toggle previous' +
quit_s,
color='DANGER')
self.addForm('TUTORIALINTRO',
TutorialIntroForm,
name='Vent Tutorial' + quit_s,
color='DANGER')
self.addForm('TUTORIALBACKGROUND',
TutorialBackgroundForm,
name='About Vent' + quit_s,
color='DANGER')
self.addForm('TUTORIALTERMINOLOGY',
TutorialTerminologyForm,
name='About Vent' + quit_s,
color='DANGER')
self.addForm('TUTORIALGETTINGSETUP',
TutorialGettingSetupForm,
name='About Vent' + quit_s,
color='DANGER')
self.addForm('TUTORIALSTARTINGCORES',
TutorialStartingCoresForm,
name='Working with Cores' + quit_s,
color='DANGER')
self.addForm('TUTORIALADDINGPLUGINS',
TutorialAddingPluginsForm,
name='Working with Plugins' + quit_s,
color='DANGER')
self.addForm('TUTORIALADDINGFILES',
TutorialAddingFilesForm,
name='Files' + quit_s,
color='DANGER')
self.addForm('TUTORIALTROUBLESHOOTING',
TutorialTroubleshootingForm,
name='Troubleshooting' + quit_s,
color='DANGER') | [
"def",
"onStart",
"(",
"self",
")",
":",
"curses",
".",
"mousemask",
"(",
"0",
")",
"self",
".",
"paths",
".",
"host_config",
"(",
")",
"version",
"=",
"Version",
"(",
")",
"# setup initial runtime stuff",
"if",
"self",
".",
"first_time",
"[",
"0",
"]",
... | Override onStart method for npyscreen | [
"Override",
"onStart",
"method",
"for",
"npyscreen"
] | 9956a09146b11a89a0eabab3bc7ce8906d124885 | https://github.com/CyberReboot/vent/blob/9956a09146b11a89a0eabab3bc7ce8906d124885/vent/menu.py#L35-L97 | train | 31,973 |
LettError/MutatorMath | Lib/mutatorMath/ufo/instance.py | InstanceWriter.setGroups | def setGroups(self, groups, kerningGroupConversionRenameMaps=None):
""" Copy the groups into our font. """
skipping = []
for name, members in groups.items():
checked = []
for m in members:
if m in self.font:
checked.append(m)
else:
skipping.append(m)
if checked:
self.font.groups[name] = checked
if skipping:
if self.verbose and self.logger:
self.logger.info("\tNote: some glyphnames were removed from groups: %s (unavailable in the font)", ", ".join(skipping))
if kerningGroupConversionRenameMaps:
# in case the sources were UFO2,
# and defcon upconverted them to UFO3
# and now we have to down convert them again,
# we don't want the UFO3 public prefixes in the group names
self.font.kerningGroupConversionRenameMaps = kerningGroupConversionRenameMaps | python | def setGroups(self, groups, kerningGroupConversionRenameMaps=None):
""" Copy the groups into our font. """
skipping = []
for name, members in groups.items():
checked = []
for m in members:
if m in self.font:
checked.append(m)
else:
skipping.append(m)
if checked:
self.font.groups[name] = checked
if skipping:
if self.verbose and self.logger:
self.logger.info("\tNote: some glyphnames were removed from groups: %s (unavailable in the font)", ", ".join(skipping))
if kerningGroupConversionRenameMaps:
# in case the sources were UFO2,
# and defcon upconverted them to UFO3
# and now we have to down convert them again,
# we don't want the UFO3 public prefixes in the group names
self.font.kerningGroupConversionRenameMaps = kerningGroupConversionRenameMaps | [
"def",
"setGroups",
"(",
"self",
",",
"groups",
",",
"kerningGroupConversionRenameMaps",
"=",
"None",
")",
":",
"skipping",
"=",
"[",
"]",
"for",
"name",
",",
"members",
"in",
"groups",
".",
"items",
"(",
")",
":",
"checked",
"=",
"[",
"]",
"for",
"m",... | Copy the groups into our font. | [
"Copy",
"the",
"groups",
"into",
"our",
"font",
"."
] | 10318fc4e7c9cee9df6130826829baea3054a42b | https://github.com/LettError/MutatorMath/blob/10318fc4e7c9cee9df6130826829baea3054a42b/Lib/mutatorMath/ufo/instance.py#L80-L100 | train | 31,974 |
LettError/MutatorMath | Lib/mutatorMath/ufo/instance.py | InstanceWriter.setLib | def setLib(self, lib):
""" Copy the lib items into our font. """
for name, item in lib.items():
self.font.lib[name] = item | python | def setLib(self, lib):
""" Copy the lib items into our font. """
for name, item in lib.items():
self.font.lib[name] = item | [
"def",
"setLib",
"(",
"self",
",",
"lib",
")",
":",
"for",
"name",
",",
"item",
"in",
"lib",
".",
"items",
"(",
")",
":",
"self",
".",
"font",
".",
"lib",
"[",
"name",
"]",
"=",
"item"
] | Copy the lib items into our font. | [
"Copy",
"the",
"lib",
"items",
"into",
"our",
"font",
"."
] | 10318fc4e7c9cee9df6130826829baea3054a42b | https://github.com/LettError/MutatorMath/blob/10318fc4e7c9cee9df6130826829baea3054a42b/Lib/mutatorMath/ufo/instance.py#L110-L113 | train | 31,975 |
LettError/MutatorMath | Lib/mutatorMath/ufo/instance.py | InstanceWriter.copyFeatures | def copyFeatures(self, featureSource):
""" Copy the features from this source """
if featureSource in self.sources:
src, loc = self.sources[featureSource]
if isinstance(src.features.text, str):
self.font.features.text = u""+src.features.text
elif isinstance(src.features.text, unicode):
self.font.features.text = src.features.text | python | def copyFeatures(self, featureSource):
""" Copy the features from this source """
if featureSource in self.sources:
src, loc = self.sources[featureSource]
if isinstance(src.features.text, str):
self.font.features.text = u""+src.features.text
elif isinstance(src.features.text, unicode):
self.font.features.text = src.features.text | [
"def",
"copyFeatures",
"(",
"self",
",",
"featureSource",
")",
":",
"if",
"featureSource",
"in",
"self",
".",
"sources",
":",
"src",
",",
"loc",
"=",
"self",
".",
"sources",
"[",
"featureSource",
"]",
"if",
"isinstance",
"(",
"src",
".",
"features",
".",... | Copy the features from this source | [
"Copy",
"the",
"features",
"from",
"this",
"source"
] | 10318fc4e7c9cee9df6130826829baea3054a42b | https://github.com/LettError/MutatorMath/blob/10318fc4e7c9cee9df6130826829baea3054a42b/Lib/mutatorMath/ufo/instance.py#L135-L142 | train | 31,976 |
LettError/MutatorMath | Lib/mutatorMath/ufo/instance.py | InstanceWriter.makeUnicodeMapFromSources | def makeUnicodeMapFromSources(self):
""" Create a dict with glyphName -> unicode value pairs
using the data in the sources.
If all master glyphs have the same unicode value
this value will be used in the map.
If master glyphs have conflicting value, a warning will be printed, no value will be used.
If only a single master has a value, that value will be used.
"""
values = {}
for locationName, (source, loc) in self.sources.items():
# this will be expensive in large fonts
for glyph in source:
if glyph.unicodes is not None:
if glyph.name not in values:
values[glyph.name] = {}
for u in glyph.unicodes:
values[glyph.name][u] = 1
for name, u in values.items():
if len(u) == 0:
# only report missing unicodes if the name has no extension
if "." not in name:
self._missingUnicodes.append(name)
continue
k = list(u.keys())
self.unicodeValues[name] = k
return self.unicodeValues | python | def makeUnicodeMapFromSources(self):
""" Create a dict with glyphName -> unicode value pairs
using the data in the sources.
If all master glyphs have the same unicode value
this value will be used in the map.
If master glyphs have conflicting value, a warning will be printed, no value will be used.
If only a single master has a value, that value will be used.
"""
values = {}
for locationName, (source, loc) in self.sources.items():
# this will be expensive in large fonts
for glyph in source:
if glyph.unicodes is not None:
if glyph.name not in values:
values[glyph.name] = {}
for u in glyph.unicodes:
values[glyph.name][u] = 1
for name, u in values.items():
if len(u) == 0:
# only report missing unicodes if the name has no extension
if "." not in name:
self._missingUnicodes.append(name)
continue
k = list(u.keys())
self.unicodeValues[name] = k
return self.unicodeValues | [
"def",
"makeUnicodeMapFromSources",
"(",
"self",
")",
":",
"values",
"=",
"{",
"}",
"for",
"locationName",
",",
"(",
"source",
",",
"loc",
")",
"in",
"self",
".",
"sources",
".",
"items",
"(",
")",
":",
"# this will be expensive in large fonts",
"for",
"glyp... | Create a dict with glyphName -> unicode value pairs
using the data in the sources.
If all master glyphs have the same unicode value
this value will be used in the map.
If master glyphs have conflicting value, a warning will be printed, no value will be used.
If only a single master has a value, that value will be used. | [
"Create",
"a",
"dict",
"with",
"glyphName",
"-",
">",
"unicode",
"value",
"pairs",
"using",
"the",
"data",
"in",
"the",
"sources",
".",
"If",
"all",
"master",
"glyphs",
"have",
"the",
"same",
"unicode",
"value",
"this",
"value",
"will",
"be",
"used",
"in... | 10318fc4e7c9cee9df6130826829baea3054a42b | https://github.com/LettError/MutatorMath/blob/10318fc4e7c9cee9df6130826829baea3054a42b/Lib/mutatorMath/ufo/instance.py#L144-L169 | train | 31,977 |
LettError/MutatorMath | Lib/mutatorMath/ufo/instance.py | InstanceWriter.getAvailableGlyphnames | def getAvailableGlyphnames(self):
""" Return a list of all glyphnames we have masters for."""
glyphNames = {}
for locationName, (source, loc) in self.sources.items():
for glyph in source:
glyphNames[glyph.name] = 1
names = sorted(glyphNames.keys())
return names | python | def getAvailableGlyphnames(self):
""" Return a list of all glyphnames we have masters for."""
glyphNames = {}
for locationName, (source, loc) in self.sources.items():
for glyph in source:
glyphNames[glyph.name] = 1
names = sorted(glyphNames.keys())
return names | [
"def",
"getAvailableGlyphnames",
"(",
"self",
")",
":",
"glyphNames",
"=",
"{",
"}",
"for",
"locationName",
",",
"(",
"source",
",",
"loc",
")",
"in",
"self",
".",
"sources",
".",
"items",
"(",
")",
":",
"for",
"glyph",
"in",
"source",
":",
"glyphNames... | Return a list of all glyphnames we have masters for. | [
"Return",
"a",
"list",
"of",
"all",
"glyphnames",
"we",
"have",
"masters",
"for",
"."
] | 10318fc4e7c9cee9df6130826829baea3054a42b | https://github.com/LettError/MutatorMath/blob/10318fc4e7c9cee9df6130826829baea3054a42b/Lib/mutatorMath/ufo/instance.py#L171-L178 | train | 31,978 |
LettError/MutatorMath | Lib/mutatorMath/ufo/instance.py | InstanceWriter.addInfo | def addInfo(self, instanceLocation=None, sources=None, copySourceName=None):
""" Add font info data. """
if instanceLocation is None:
instanceLocation = self.locationObject
infoObject = self.font.info
infoMasters = []
if sources is None:
sources = self.sources
items = []
for sourceName, (source, sourceLocation) in sources.items():
if sourceName in self.muted['info']:
# info in this master was muted, so do not add.
continue
items.append((sourceLocation, MathInfo(source.info)))
try:
bias, m = buildMutator(items, axes=self.axes)
except:
if self.logger:
self.logger.exception("Error processing font info. %s", items)
return
instanceObject = m.makeInstance(instanceLocation)
if self.roundGeometry:
try:
instanceObject = instanceObject.round()
except AttributeError:
warnings.warn("MathInfo object missing round() method.")
instanceObject.extractInfo(self.font.info)
# handle the copyable info fields
if copySourceName is not None:
if not copySourceName in sources:
if self.verbose and self.logger:
self.logger.info("Copy info source %s not found, skipping.", copySourceName)
return
copySourceObject, loc = sources[copySourceName]
self._copyFontInfo(self.font.info, copySourceObject.info) | python | def addInfo(self, instanceLocation=None, sources=None, copySourceName=None):
""" Add font info data. """
if instanceLocation is None:
instanceLocation = self.locationObject
infoObject = self.font.info
infoMasters = []
if sources is None:
sources = self.sources
items = []
for sourceName, (source, sourceLocation) in sources.items():
if sourceName in self.muted['info']:
# info in this master was muted, so do not add.
continue
items.append((sourceLocation, MathInfo(source.info)))
try:
bias, m = buildMutator(items, axes=self.axes)
except:
if self.logger:
self.logger.exception("Error processing font info. %s", items)
return
instanceObject = m.makeInstance(instanceLocation)
if self.roundGeometry:
try:
instanceObject = instanceObject.round()
except AttributeError:
warnings.warn("MathInfo object missing round() method.")
instanceObject.extractInfo(self.font.info)
# handle the copyable info fields
if copySourceName is not None:
if not copySourceName in sources:
if self.verbose and self.logger:
self.logger.info("Copy info source %s not found, skipping.", copySourceName)
return
copySourceObject, loc = sources[copySourceName]
self._copyFontInfo(self.font.info, copySourceObject.info) | [
"def",
"addInfo",
"(",
"self",
",",
"instanceLocation",
"=",
"None",
",",
"sources",
"=",
"None",
",",
"copySourceName",
"=",
"None",
")",
":",
"if",
"instanceLocation",
"is",
"None",
":",
"instanceLocation",
"=",
"self",
".",
"locationObject",
"infoObject",
... | Add font info data. | [
"Add",
"font",
"info",
"data",
"."
] | 10318fc4e7c9cee9df6130826829baea3054a42b | https://github.com/LettError/MutatorMath/blob/10318fc4e7c9cee9df6130826829baea3054a42b/Lib/mutatorMath/ufo/instance.py#L184-L219 | train | 31,979 |
LettError/MutatorMath | Lib/mutatorMath/ufo/instance.py | InstanceWriter._copyFontInfo | def _copyFontInfo(self, targetInfo, sourceInfo):
""" Copy the non-calculating fields from the source info.
"""
infoAttributes = [
"versionMajor",
"versionMinor",
"copyright",
"trademark",
"note",
"openTypeGaspRangeRecords",
"openTypeHeadCreated",
"openTypeHeadFlags",
"openTypeNameDesigner",
"openTypeNameDesignerURL",
"openTypeNameManufacturer",
"openTypeNameManufacturerURL",
"openTypeNameLicense",
"openTypeNameLicenseURL",
"openTypeNameVersion",
"openTypeNameUniqueID",
"openTypeNameDescription",
"#openTypeNamePreferredFamilyName",
"#openTypeNamePreferredSubfamilyName",
"#openTypeNameCompatibleFullName",
"openTypeNameSampleText",
"openTypeNameWWSFamilyName",
"openTypeNameWWSSubfamilyName",
"openTypeNameRecords",
"openTypeOS2Selection",
"openTypeOS2VendorID",
"openTypeOS2Panose",
"openTypeOS2FamilyClass",
"openTypeOS2UnicodeRanges",
"openTypeOS2CodePageRanges",
"openTypeOS2Type",
"postscriptIsFixedPitch",
"postscriptForceBold",
"postscriptDefaultCharacter",
"postscriptWindowsCharacterSet"
]
for infoAttribute in infoAttributes:
copy = False
if self.ufoVersion == 1 and infoAttribute in fontInfoAttributesVersion1:
copy = True
elif self.ufoVersion == 2 and infoAttribute in fontInfoAttributesVersion2:
copy = True
elif self.ufoVersion == 3 and infoAttribute in fontInfoAttributesVersion3:
copy = True
if copy:
value = getattr(sourceInfo, infoAttribute)
setattr(targetInfo, infoAttribute, value) | python | def _copyFontInfo(self, targetInfo, sourceInfo):
""" Copy the non-calculating fields from the source info.
"""
infoAttributes = [
"versionMajor",
"versionMinor",
"copyright",
"trademark",
"note",
"openTypeGaspRangeRecords",
"openTypeHeadCreated",
"openTypeHeadFlags",
"openTypeNameDesigner",
"openTypeNameDesignerURL",
"openTypeNameManufacturer",
"openTypeNameManufacturerURL",
"openTypeNameLicense",
"openTypeNameLicenseURL",
"openTypeNameVersion",
"openTypeNameUniqueID",
"openTypeNameDescription",
"#openTypeNamePreferredFamilyName",
"#openTypeNamePreferredSubfamilyName",
"#openTypeNameCompatibleFullName",
"openTypeNameSampleText",
"openTypeNameWWSFamilyName",
"openTypeNameWWSSubfamilyName",
"openTypeNameRecords",
"openTypeOS2Selection",
"openTypeOS2VendorID",
"openTypeOS2Panose",
"openTypeOS2FamilyClass",
"openTypeOS2UnicodeRanges",
"openTypeOS2CodePageRanges",
"openTypeOS2Type",
"postscriptIsFixedPitch",
"postscriptForceBold",
"postscriptDefaultCharacter",
"postscriptWindowsCharacterSet"
]
for infoAttribute in infoAttributes:
copy = False
if self.ufoVersion == 1 and infoAttribute in fontInfoAttributesVersion1:
copy = True
elif self.ufoVersion == 2 and infoAttribute in fontInfoAttributesVersion2:
copy = True
elif self.ufoVersion == 3 and infoAttribute in fontInfoAttributesVersion3:
copy = True
if copy:
value = getattr(sourceInfo, infoAttribute)
setattr(targetInfo, infoAttribute, value) | [
"def",
"_copyFontInfo",
"(",
"self",
",",
"targetInfo",
",",
"sourceInfo",
")",
":",
"infoAttributes",
"=",
"[",
"\"versionMajor\"",
",",
"\"versionMinor\"",
",",
"\"copyright\"",
",",
"\"trademark\"",
",",
"\"note\"",
",",
"\"openTypeGaspRangeRecords\"",
",",
"\"op... | Copy the non-calculating fields from the source info. | [
"Copy",
"the",
"non",
"-",
"calculating",
"fields",
"from",
"the",
"source",
"info",
"."
] | 10318fc4e7c9cee9df6130826829baea3054a42b | https://github.com/LettError/MutatorMath/blob/10318fc4e7c9cee9df6130826829baea3054a42b/Lib/mutatorMath/ufo/instance.py#L221-L271 | train | 31,980 |
LettError/MutatorMath | Lib/mutatorMath/ufo/instance.py | InstanceWriter._calculateGlyph | def _calculateGlyph(self, targetGlyphObject, instanceLocationObject, glyphMasters):
"""
Build a Mutator object for this glyph.
* name: glyphName
* location: Location object
* glyphMasters: dict with font objects.
"""
sources = None
items = []
for item in glyphMasters:
locationObject = item['location']
fontObject = item['font']
glyphName = item['glyphName']
if not glyphName in fontObject:
continue
glyphObject = MathGlyph(fontObject[glyphName])
items.append((locationObject, glyphObject))
bias, m = buildMutator(items, axes=self.axes)
instanceObject = m.makeInstance(instanceLocationObject)
if self.roundGeometry:
try:
instanceObject = instanceObject.round()
except AttributeError:
if self.verbose and self.logger:
self.logger.info("MathGlyph object missing round() method.")
try:
instanceObject.extractGlyph(targetGlyphObject, onlyGeometry=True)
except TypeError:
# this causes ruled glyphs to end up in the wrong glyphname
# but defcon2 objects don't support it
pPen = targetGlyphObject.getPointPen()
targetGlyphObject.clear()
instanceObject.drawPoints(pPen)
targetGlyphObject.width = instanceObject.width | python | def _calculateGlyph(self, targetGlyphObject, instanceLocationObject, glyphMasters):
"""
Build a Mutator object for this glyph.
* name: glyphName
* location: Location object
* glyphMasters: dict with font objects.
"""
sources = None
items = []
for item in glyphMasters:
locationObject = item['location']
fontObject = item['font']
glyphName = item['glyphName']
if not glyphName in fontObject:
continue
glyphObject = MathGlyph(fontObject[glyphName])
items.append((locationObject, glyphObject))
bias, m = buildMutator(items, axes=self.axes)
instanceObject = m.makeInstance(instanceLocationObject)
if self.roundGeometry:
try:
instanceObject = instanceObject.round()
except AttributeError:
if self.verbose and self.logger:
self.logger.info("MathGlyph object missing round() method.")
try:
instanceObject.extractGlyph(targetGlyphObject, onlyGeometry=True)
except TypeError:
# this causes ruled glyphs to end up in the wrong glyphname
# but defcon2 objects don't support it
pPen = targetGlyphObject.getPointPen()
targetGlyphObject.clear()
instanceObject.drawPoints(pPen)
targetGlyphObject.width = instanceObject.width | [
"def",
"_calculateGlyph",
"(",
"self",
",",
"targetGlyphObject",
",",
"instanceLocationObject",
",",
"glyphMasters",
")",
":",
"sources",
"=",
"None",
"items",
"=",
"[",
"]",
"for",
"item",
"in",
"glyphMasters",
":",
"locationObject",
"=",
"item",
"[",
"'locat... | Build a Mutator object for this glyph.
* name: glyphName
* location: Location object
* glyphMasters: dict with font objects. | [
"Build",
"a",
"Mutator",
"object",
"for",
"this",
"glyph",
"."
] | 10318fc4e7c9cee9df6130826829baea3054a42b | https://github.com/LettError/MutatorMath/blob/10318fc4e7c9cee9df6130826829baea3054a42b/Lib/mutatorMath/ufo/instance.py#L351-L388 | train | 31,981 |
LettError/MutatorMath | Lib/mutatorMath/ufo/instance.py | InstanceWriter.save | def save(self):
""" Save the UFO."""
# handle glyphs that were muted
for name in self.mutedGlyphsNames:
if name not in self.font: continue
if self.logger:
self.logger.info("removing muted glyph %s", name)
del self.font[name]
# XXX housekeeping:
# remove glyph from groups / kerning as well?
# remove components referencing this glyph?
# fontTools.ufoLib no longer calls os.makedirs for us if the
# parent directories of the Font we are saving do not exist.
# We want to keep backward compatibility with the previous
# MutatorMath behavior, so we create the instance' parent
# directories if they do not exist. We assume that the users
# knows what they are doing...
directory = os.path.dirname(os.path.normpath(self.path))
if directory and not os.path.exists(directory):
os.makedirs(directory)
try:
self.font.save(os.path.abspath(self.path), self.ufoVersion)
except defcon.DefconError as error:
if self.logger:
self.logger.exception("Error generating.")
return False, error.report
return True, None | python | def save(self):
""" Save the UFO."""
# handle glyphs that were muted
for name in self.mutedGlyphsNames:
if name not in self.font: continue
if self.logger:
self.logger.info("removing muted glyph %s", name)
del self.font[name]
# XXX housekeeping:
# remove glyph from groups / kerning as well?
# remove components referencing this glyph?
# fontTools.ufoLib no longer calls os.makedirs for us if the
# parent directories of the Font we are saving do not exist.
# We want to keep backward compatibility with the previous
# MutatorMath behavior, so we create the instance' parent
# directories if they do not exist. We assume that the users
# knows what they are doing...
directory = os.path.dirname(os.path.normpath(self.path))
if directory and not os.path.exists(directory):
os.makedirs(directory)
try:
self.font.save(os.path.abspath(self.path), self.ufoVersion)
except defcon.DefconError as error:
if self.logger:
self.logger.exception("Error generating.")
return False, error.report
return True, None | [
"def",
"save",
"(",
"self",
")",
":",
"# handle glyphs that were muted",
"for",
"name",
"in",
"self",
".",
"mutedGlyphsNames",
":",
"if",
"name",
"not",
"in",
"self",
".",
"font",
":",
"continue",
"if",
"self",
".",
"logger",
":",
"self",
".",
"logger",
... | Save the UFO. | [
"Save",
"the",
"UFO",
"."
] | 10318fc4e7c9cee9df6130826829baea3054a42b | https://github.com/LettError/MutatorMath/blob/10318fc4e7c9cee9df6130826829baea3054a42b/Lib/mutatorMath/ufo/instance.py#L390-L418 | train | 31,982 |
LettError/MutatorMath | Lib/mutatorMath/ufo/document.py | DesignSpaceDocumentWriter.save | def save(self, pretty=True):
""" Save the xml. Make pretty if necessary. """
self.endInstance()
if pretty:
_indent(self.root, whitespace=self._whiteSpace)
tree = ET.ElementTree(self.root)
tree.write(self.path, encoding="utf-8", method='xml', xml_declaration=True)
if self.logger:
self.logger.info("Writing %s", self.path) | python | def save(self, pretty=True):
""" Save the xml. Make pretty if necessary. """
self.endInstance()
if pretty:
_indent(self.root, whitespace=self._whiteSpace)
tree = ET.ElementTree(self.root)
tree.write(self.path, encoding="utf-8", method='xml', xml_declaration=True)
if self.logger:
self.logger.info("Writing %s", self.path) | [
"def",
"save",
"(",
"self",
",",
"pretty",
"=",
"True",
")",
":",
"self",
".",
"endInstance",
"(",
")",
"if",
"pretty",
":",
"_indent",
"(",
"self",
".",
"root",
",",
"whitespace",
"=",
"self",
".",
"_whiteSpace",
")",
"tree",
"=",
"ET",
".",
"Elem... | Save the xml. Make pretty if necessary. | [
"Save",
"the",
"xml",
".",
"Make",
"pretty",
"if",
"necessary",
"."
] | 10318fc4e7c9cee9df6130826829baea3054a42b | https://github.com/LettError/MutatorMath/blob/10318fc4e7c9cee9df6130826829baea3054a42b/Lib/mutatorMath/ufo/document.py#L73-L81 | train | 31,983 |
LettError/MutatorMath | Lib/mutatorMath/ufo/document.py | DesignSpaceDocumentWriter._makeLocationElement | def _makeLocationElement(self, locationObject, name=None):
""" Convert Location object to an locationElement."""
locElement = ET.Element("location")
if name is not None:
locElement.attrib['name'] = name
for dimensionName, dimensionValue in locationObject.items():
dimElement = ET.Element('dimension')
dimElement.attrib['name'] = dimensionName
if type(dimensionValue)==tuple:
dimElement.attrib['xvalue'] = "%f"%dimensionValue[0]
dimElement.attrib['yvalue'] = "%f"%dimensionValue[1]
else:
dimElement.attrib['xvalue'] = "%f"%dimensionValue
locElement.append(dimElement)
return locElement | python | def _makeLocationElement(self, locationObject, name=None):
""" Convert Location object to an locationElement."""
locElement = ET.Element("location")
if name is not None:
locElement.attrib['name'] = name
for dimensionName, dimensionValue in locationObject.items():
dimElement = ET.Element('dimension')
dimElement.attrib['name'] = dimensionName
if type(dimensionValue)==tuple:
dimElement.attrib['xvalue'] = "%f"%dimensionValue[0]
dimElement.attrib['yvalue'] = "%f"%dimensionValue[1]
else:
dimElement.attrib['xvalue'] = "%f"%dimensionValue
locElement.append(dimElement)
return locElement | [
"def",
"_makeLocationElement",
"(",
"self",
",",
"locationObject",
",",
"name",
"=",
"None",
")",
":",
"locElement",
"=",
"ET",
".",
"Element",
"(",
"\"location\"",
")",
"if",
"name",
"is",
"not",
"None",
":",
"locElement",
".",
"attrib",
"[",
"'name'",
... | Convert Location object to an locationElement. | [
"Convert",
"Location",
"object",
"to",
"an",
"locationElement",
"."
] | 10318fc4e7c9cee9df6130826829baea3054a42b | https://github.com/LettError/MutatorMath/blob/10318fc4e7c9cee9df6130826829baea3054a42b/Lib/mutatorMath/ufo/document.py#L83-L98 | train | 31,984 |
LettError/MutatorMath | Lib/mutatorMath/ufo/document.py | DesignSpaceDocumentReader.reportProgress | def reportProgress(self, state, action, text=None, tick=None):
""" If we want to keep other code updated about our progress.
state: 'prep' reading sources
'generate' making instances
'done' wrapping up
'error' reporting a problem
action: 'start' begin generating
'stop' end generating
'source' which ufo we're reading
text: <file.ufo> ufoname (for instance)
tick: a float between 0 and 1 indicating progress.
"""
if self.progressFunc is not None:
self.progressFunc(state=state, action=action, text=text, tick=tick) | python | def reportProgress(self, state, action, text=None, tick=None):
""" If we want to keep other code updated about our progress.
state: 'prep' reading sources
'generate' making instances
'done' wrapping up
'error' reporting a problem
action: 'start' begin generating
'stop' end generating
'source' which ufo we're reading
text: <file.ufo> ufoname (for instance)
tick: a float between 0 and 1 indicating progress.
"""
if self.progressFunc is not None:
self.progressFunc(state=state, action=action, text=text, tick=tick) | [
"def",
"reportProgress",
"(",
"self",
",",
"state",
",",
"action",
",",
"text",
"=",
"None",
",",
"tick",
"=",
"None",
")",
":",
"if",
"self",
".",
"progressFunc",
"is",
"not",
"None",
":",
"self",
".",
"progressFunc",
"(",
"state",
"=",
"state",
","... | If we want to keep other code updated about our progress.
state: 'prep' reading sources
'generate' making instances
'done' wrapping up
'error' reporting a problem
action: 'start' begin generating
'stop' end generating
'source' which ufo we're reading
text: <file.ufo> ufoname (for instance)
tick: a float between 0 and 1 indicating progress. | [
"If",
"we",
"want",
"to",
"keep",
"other",
"code",
"updated",
"about",
"our",
"progress",
"."
] | 10318fc4e7c9cee9df6130826829baea3054a42b | https://github.com/LettError/MutatorMath/blob/10318fc4e7c9cee9df6130826829baea3054a42b/Lib/mutatorMath/ufo/document.py#L411-L428 | train | 31,985 |
LettError/MutatorMath | Lib/mutatorMath/ufo/document.py | DesignSpaceDocumentReader.getSourcePaths | def getSourcePaths(self, makeGlyphs=True, makeKerning=True, makeInfo=True):
""" Return a list of paths referenced in the document."""
paths = []
for name in self.sources.keys():
paths.append(self.sources[name][0].path)
return paths | python | def getSourcePaths(self, makeGlyphs=True, makeKerning=True, makeInfo=True):
""" Return a list of paths referenced in the document."""
paths = []
for name in self.sources.keys():
paths.append(self.sources[name][0].path)
return paths | [
"def",
"getSourcePaths",
"(",
"self",
",",
"makeGlyphs",
"=",
"True",
",",
"makeKerning",
"=",
"True",
",",
"makeInfo",
"=",
"True",
")",
":",
"paths",
"=",
"[",
"]",
"for",
"name",
"in",
"self",
".",
"sources",
".",
"keys",
"(",
")",
":",
"paths",
... | Return a list of paths referenced in the document. | [
"Return",
"a",
"list",
"of",
"paths",
"referenced",
"in",
"the",
"document",
"."
] | 10318fc4e7c9cee9df6130826829baea3054a42b | https://github.com/LettError/MutatorMath/blob/10318fc4e7c9cee9df6130826829baea3054a42b/Lib/mutatorMath/ufo/document.py#L430-L435 | train | 31,986 |
LettError/MutatorMath | Lib/mutatorMath/ufo/document.py | DesignSpaceDocumentReader.process | def process(self, makeGlyphs=True, makeKerning=True, makeInfo=True):
""" Process the input file and generate the instances. """
if self.logger:
self.logger.info("Reading %s", self.path)
self.readInstances(makeGlyphs=makeGlyphs, makeKerning=makeKerning, makeInfo=makeInfo)
self.reportProgress("done", 'stop') | python | def process(self, makeGlyphs=True, makeKerning=True, makeInfo=True):
""" Process the input file and generate the instances. """
if self.logger:
self.logger.info("Reading %s", self.path)
self.readInstances(makeGlyphs=makeGlyphs, makeKerning=makeKerning, makeInfo=makeInfo)
self.reportProgress("done", 'stop') | [
"def",
"process",
"(",
"self",
",",
"makeGlyphs",
"=",
"True",
",",
"makeKerning",
"=",
"True",
",",
"makeInfo",
"=",
"True",
")",
":",
"if",
"self",
".",
"logger",
":",
"self",
".",
"logger",
".",
"info",
"(",
"\"Reading %s\"",
",",
"self",
".",
"pa... | Process the input file and generate the instances. | [
"Process",
"the",
"input",
"file",
"and",
"generate",
"the",
"instances",
"."
] | 10318fc4e7c9cee9df6130826829baea3054a42b | https://github.com/LettError/MutatorMath/blob/10318fc4e7c9cee9df6130826829baea3054a42b/Lib/mutatorMath/ufo/document.py#L437-L442 | train | 31,987 |
LettError/MutatorMath | Lib/mutatorMath/ufo/document.py | DesignSpaceDocumentReader.readWarp | def readWarp(self):
""" Read the warp element
::
<warp>
<axis name="weight">
<map input="0" output="0" />
<map input="500" output="200" />
<map input="1000" output="1000" />
</axis>
</warp>
"""
warpDict = {}
for warpAxisElement in self.root.findall(".warp/axis"):
axisName = warpAxisElement.attrib.get("name")
warpDict[axisName] = []
for warpPoint in warpAxisElement.findall(".map"):
inputValue = float(warpPoint.attrib.get("input"))
outputValue = float(warpPoint.attrib.get("output"))
warpDict[axisName].append((inputValue, outputValue))
self.warpDict = warpDict | python | def readWarp(self):
""" Read the warp element
::
<warp>
<axis name="weight">
<map input="0" output="0" />
<map input="500" output="200" />
<map input="1000" output="1000" />
</axis>
</warp>
"""
warpDict = {}
for warpAxisElement in self.root.findall(".warp/axis"):
axisName = warpAxisElement.attrib.get("name")
warpDict[axisName] = []
for warpPoint in warpAxisElement.findall(".map"):
inputValue = float(warpPoint.attrib.get("input"))
outputValue = float(warpPoint.attrib.get("output"))
warpDict[axisName].append((inputValue, outputValue))
self.warpDict = warpDict | [
"def",
"readWarp",
"(",
"self",
")",
":",
"warpDict",
"=",
"{",
"}",
"for",
"warpAxisElement",
"in",
"self",
".",
"root",
".",
"findall",
"(",
"\".warp/axis\"",
")",
":",
"axisName",
"=",
"warpAxisElement",
".",
"attrib",
".",
"get",
"(",
"\"name\"",
")"... | Read the warp element
::
<warp>
<axis name="weight">
<map input="0" output="0" />
<map input="500" output="200" />
<map input="1000" output="1000" />
</axis>
</warp> | [
"Read",
"the",
"warp",
"element"
] | 10318fc4e7c9cee9df6130826829baea3054a42b | https://github.com/LettError/MutatorMath/blob/10318fc4e7c9cee9df6130826829baea3054a42b/Lib/mutatorMath/ufo/document.py#L457-L478 | train | 31,988 |
LettError/MutatorMath | Lib/mutatorMath/ufo/document.py | DesignSpaceDocumentReader.readAxes | def readAxes(self):
""" Read the axes element.
"""
for axisElement in self.root.findall(".axes/axis"):
axis = {}
axis['name'] = name = axisElement.attrib.get("name")
axis['tag'] = axisElement.attrib.get("tag")
axis['minimum'] = float(axisElement.attrib.get("minimum"))
axis['maximum'] = float(axisElement.attrib.get("maximum"))
axis['default'] = float(axisElement.attrib.get("default"))
# we're not using the map for anything.
axis['map'] = []
for warpPoint in axisElement.findall(".map"):
inputValue = float(warpPoint.attrib.get("input"))
outputValue = float(warpPoint.attrib.get("output"))
axis['map'].append((inputValue, outputValue))
# there are labelnames in the element
# but we don't need them for building the fonts.
self.axes[name] = axis
self.axesOrder.append(axis['name']) | python | def readAxes(self):
""" Read the axes element.
"""
for axisElement in self.root.findall(".axes/axis"):
axis = {}
axis['name'] = name = axisElement.attrib.get("name")
axis['tag'] = axisElement.attrib.get("tag")
axis['minimum'] = float(axisElement.attrib.get("minimum"))
axis['maximum'] = float(axisElement.attrib.get("maximum"))
axis['default'] = float(axisElement.attrib.get("default"))
# we're not using the map for anything.
axis['map'] = []
for warpPoint in axisElement.findall(".map"):
inputValue = float(warpPoint.attrib.get("input"))
outputValue = float(warpPoint.attrib.get("output"))
axis['map'].append((inputValue, outputValue))
# there are labelnames in the element
# but we don't need them for building the fonts.
self.axes[name] = axis
self.axesOrder.append(axis['name']) | [
"def",
"readAxes",
"(",
"self",
")",
":",
"for",
"axisElement",
"in",
"self",
".",
"root",
".",
"findall",
"(",
"\".axes/axis\"",
")",
":",
"axis",
"=",
"{",
"}",
"axis",
"[",
"'name'",
"]",
"=",
"name",
"=",
"axisElement",
".",
"attrib",
".",
"get",... | Read the axes element. | [
"Read",
"the",
"axes",
"element",
"."
] | 10318fc4e7c9cee9df6130826829baea3054a42b | https://github.com/LettError/MutatorMath/blob/10318fc4e7c9cee9df6130826829baea3054a42b/Lib/mutatorMath/ufo/document.py#L480-L499 | train | 31,989 |
LettError/MutatorMath | Lib/mutatorMath/ufo/document.py | DesignSpaceDocumentReader.readSources | def readSources(self):
""" Read the source elements.
::
<source filename="LightCondensed.ufo" location="location-token-aaa" name="master-token-aaa1">
<info mute="1" copy="1"/>
<kerning mute="1"/>
<glyph mute="1" name="thirdGlyph"/>
</source>
"""
for sourceCount, sourceElement in enumerate(self.root.findall(".sources/source")):
# shall we just read the UFO here?
filename = sourceElement.attrib.get('filename')
# filename is a path relaive to the documentpath. resolve first.
sourcePath = os.path.abspath(os.path.join(os.path.dirname(self.path), filename))
sourceName = sourceElement.attrib.get('name')
if sourceName is None:
# if the source element has no name attribute
# (some authoring tools do not need them)
# then we should make a temporary one. We still need it for reference.
sourceName = "temp_master.%d"%(sourceCount)
self.reportProgress("prep", 'load', sourcePath)
if not os.path.exists(sourcePath):
raise MutatorError("Source not found at %s"%sourcePath)
sourceObject = self._instantiateFont(sourcePath)
# read the locations
sourceLocationObject = None
sourceLocationObject = self.locationFromElement(sourceElement)
if sourceLocationObject is None:
raise MutatorError("No location defined for source %s"%sourceName)
# read lib flag
for libElement in sourceElement.findall('.lib'):
if libElement.attrib.get('copy') == '1':
self.libSource = sourceName
# read the groups flag
for groupsElement in sourceElement.findall('.groups'):
if groupsElement.attrib.get('copy') == '1':
self.groupsSource = sourceName
# read the info flag
for infoElement in sourceElement.findall(".info"):
if infoElement.attrib.get('copy') == '1':
self.infoSource = sourceName
if infoElement.attrib.get('mute') == '1':
self.muted['info'].append(sourceName)
# read the features flag
for featuresElement in sourceElement.findall(".features"):
if featuresElement.attrib.get('copy') == '1':
if self.featuresSource is not None:
self.featuresSource = None
else:
self.featuresSource = sourceName
mutedGlyphs = []
for glyphElement in sourceElement.findall(".glyph"):
glyphName = glyphElement.attrib.get('name')
if glyphName is None:
continue
if glyphElement.attrib.get('mute') == '1':
if not sourceName in self.muted['glyphs']:
self.muted['glyphs'][sourceName] = []
self.muted['glyphs'][sourceName].append(glyphName)
for kerningElement in sourceElement.findall(".kerning"):
if kerningElement.attrib.get('mute') == '1':
self.muted['kerning'].append(sourceName)
# store
self.sources[sourceName] = sourceObject, sourceLocationObject
self.reportProgress("prep", 'done') | python | def readSources(self):
""" Read the source elements.
::
<source filename="LightCondensed.ufo" location="location-token-aaa" name="master-token-aaa1">
<info mute="1" copy="1"/>
<kerning mute="1"/>
<glyph mute="1" name="thirdGlyph"/>
</source>
"""
for sourceCount, sourceElement in enumerate(self.root.findall(".sources/source")):
# shall we just read the UFO here?
filename = sourceElement.attrib.get('filename')
# filename is a path relaive to the documentpath. resolve first.
sourcePath = os.path.abspath(os.path.join(os.path.dirname(self.path), filename))
sourceName = sourceElement.attrib.get('name')
if sourceName is None:
# if the source element has no name attribute
# (some authoring tools do not need them)
# then we should make a temporary one. We still need it for reference.
sourceName = "temp_master.%d"%(sourceCount)
self.reportProgress("prep", 'load', sourcePath)
if not os.path.exists(sourcePath):
raise MutatorError("Source not found at %s"%sourcePath)
sourceObject = self._instantiateFont(sourcePath)
# read the locations
sourceLocationObject = None
sourceLocationObject = self.locationFromElement(sourceElement)
if sourceLocationObject is None:
raise MutatorError("No location defined for source %s"%sourceName)
# read lib flag
for libElement in sourceElement.findall('.lib'):
if libElement.attrib.get('copy') == '1':
self.libSource = sourceName
# read the groups flag
for groupsElement in sourceElement.findall('.groups'):
if groupsElement.attrib.get('copy') == '1':
self.groupsSource = sourceName
# read the info flag
for infoElement in sourceElement.findall(".info"):
if infoElement.attrib.get('copy') == '1':
self.infoSource = sourceName
if infoElement.attrib.get('mute') == '1':
self.muted['info'].append(sourceName)
# read the features flag
for featuresElement in sourceElement.findall(".features"):
if featuresElement.attrib.get('copy') == '1':
if self.featuresSource is not None:
self.featuresSource = None
else:
self.featuresSource = sourceName
mutedGlyphs = []
for glyphElement in sourceElement.findall(".glyph"):
glyphName = glyphElement.attrib.get('name')
if glyphName is None:
continue
if glyphElement.attrib.get('mute') == '1':
if not sourceName in self.muted['glyphs']:
self.muted['glyphs'][sourceName] = []
self.muted['glyphs'][sourceName].append(glyphName)
for kerningElement in sourceElement.findall(".kerning"):
if kerningElement.attrib.get('mute') == '1':
self.muted['kerning'].append(sourceName)
# store
self.sources[sourceName] = sourceObject, sourceLocationObject
self.reportProgress("prep", 'done') | [
"def",
"readSources",
"(",
"self",
")",
":",
"for",
"sourceCount",
",",
"sourceElement",
"in",
"enumerate",
"(",
"self",
".",
"root",
".",
"findall",
"(",
"\".sources/source\"",
")",
")",
":",
"# shall we just read the UFO here?",
"filename",
"=",
"sourceElement",... | Read the source elements.
::
<source filename="LightCondensed.ufo" location="location-token-aaa" name="master-token-aaa1">
<info mute="1" copy="1"/>
<kerning mute="1"/>
<glyph mute="1" name="thirdGlyph"/>
</source> | [
"Read",
"the",
"source",
"elements",
"."
] | 10318fc4e7c9cee9df6130826829baea3054a42b | https://github.com/LettError/MutatorMath/blob/10318fc4e7c9cee9df6130826829baea3054a42b/Lib/mutatorMath/ufo/document.py#L501-L576 | train | 31,990 |
LettError/MutatorMath | Lib/mutatorMath/ufo/document.py | DesignSpaceDocumentReader.locationFromElement | def locationFromElement(self, element):
"""
Find the MutatorMath location of this element, either by name or from a child element.
"""
elementLocation = None
for locationElement in element.findall('.location'):
elementLocation = self.readLocationElement(locationElement)
break
return elementLocation | python | def locationFromElement(self, element):
"""
Find the MutatorMath location of this element, either by name or from a child element.
"""
elementLocation = None
for locationElement in element.findall('.location'):
elementLocation = self.readLocationElement(locationElement)
break
return elementLocation | [
"def",
"locationFromElement",
"(",
"self",
",",
"element",
")",
":",
"elementLocation",
"=",
"None",
"for",
"locationElement",
"in",
"element",
".",
"findall",
"(",
"'.location'",
")",
":",
"elementLocation",
"=",
"self",
".",
"readLocationElement",
"(",
"locati... | Find the MutatorMath location of this element, either by name or from a child element. | [
"Find",
"the",
"MutatorMath",
"location",
"of",
"this",
"element",
"either",
"by",
"name",
"or",
"from",
"a",
"child",
"element",
"."
] | 10318fc4e7c9cee9df6130826829baea3054a42b | https://github.com/LettError/MutatorMath/blob/10318fc4e7c9cee9df6130826829baea3054a42b/Lib/mutatorMath/ufo/document.py#L578-L586 | train | 31,991 |
LettError/MutatorMath | Lib/mutatorMath/ufo/document.py | DesignSpaceDocumentReader.readInstance | def readInstance(self, key, makeGlyphs=True, makeKerning=True, makeInfo=True):
""" Read a single instance element.
key: an (attribute, value) tuple used to find the requested instance.
::
<instance familyname="SuperFamily" filename="OutputNameInstance1.ufo" location="location-token-aaa" stylename="Regular">
"""
attrib, value = key
for instanceElement in self.root.findall('.instances/instance'):
if instanceElement.attrib.get(attrib) == value:
self._readSingleInstanceElement(instanceElement, makeGlyphs=makeGlyphs, makeKerning=makeKerning, makeInfo=makeInfo)
return
raise MutatorError("No instance found with key: (%s, %s)." % key) | python | def readInstance(self, key, makeGlyphs=True, makeKerning=True, makeInfo=True):
""" Read a single instance element.
key: an (attribute, value) tuple used to find the requested instance.
::
<instance familyname="SuperFamily" filename="OutputNameInstance1.ufo" location="location-token-aaa" stylename="Regular">
"""
attrib, value = key
for instanceElement in self.root.findall('.instances/instance'):
if instanceElement.attrib.get(attrib) == value:
self._readSingleInstanceElement(instanceElement, makeGlyphs=makeGlyphs, makeKerning=makeKerning, makeInfo=makeInfo)
return
raise MutatorError("No instance found with key: (%s, %s)." % key) | [
"def",
"readInstance",
"(",
"self",
",",
"key",
",",
"makeGlyphs",
"=",
"True",
",",
"makeKerning",
"=",
"True",
",",
"makeInfo",
"=",
"True",
")",
":",
"attrib",
",",
"value",
"=",
"key",
"for",
"instanceElement",
"in",
"self",
".",
"root",
".",
"find... | Read a single instance element.
key: an (attribute, value) tuple used to find the requested instance.
::
<instance familyname="SuperFamily" filename="OutputNameInstance1.ufo" location="location-token-aaa" stylename="Regular"> | [
"Read",
"a",
"single",
"instance",
"element",
"."
] | 10318fc4e7c9cee9df6130826829baea3054a42b | https://github.com/LettError/MutatorMath/blob/10318fc4e7c9cee9df6130826829baea3054a42b/Lib/mutatorMath/ufo/document.py#L612-L627 | train | 31,992 |
LettError/MutatorMath | Lib/mutatorMath/ufo/document.py | DesignSpaceDocumentReader.readInstances | def readInstances(self, makeGlyphs=True, makeKerning=True, makeInfo=True):
""" Read all instance elements.
::
<instance familyname="SuperFamily" filename="OutputNameInstance1.ufo" location="location-token-aaa" stylename="Regular">
"""
for instanceElement in self.root.findall('.instances/instance'):
self._readSingleInstanceElement(instanceElement, makeGlyphs=makeGlyphs, makeKerning=makeKerning, makeInfo=makeInfo) | python | def readInstances(self, makeGlyphs=True, makeKerning=True, makeInfo=True):
""" Read all instance elements.
::
<instance familyname="SuperFamily" filename="OutputNameInstance1.ufo" location="location-token-aaa" stylename="Regular">
"""
for instanceElement in self.root.findall('.instances/instance'):
self._readSingleInstanceElement(instanceElement, makeGlyphs=makeGlyphs, makeKerning=makeKerning, makeInfo=makeInfo) | [
"def",
"readInstances",
"(",
"self",
",",
"makeGlyphs",
"=",
"True",
",",
"makeKerning",
"=",
"True",
",",
"makeInfo",
"=",
"True",
")",
":",
"for",
"instanceElement",
"in",
"self",
".",
"root",
".",
"findall",
"(",
"'.instances/instance'",
")",
":",
"self... | Read all instance elements.
::
<instance familyname="SuperFamily" filename="OutputNameInstance1.ufo" location="location-token-aaa" stylename="Regular"> | [
"Read",
"all",
"instance",
"elements",
"."
] | 10318fc4e7c9cee9df6130826829baea3054a42b | https://github.com/LettError/MutatorMath/blob/10318fc4e7c9cee9df6130826829baea3054a42b/Lib/mutatorMath/ufo/document.py#L629-L638 | train | 31,993 |
LettError/MutatorMath | Lib/mutatorMath/ufo/document.py | DesignSpaceDocumentReader.readInfoElement | def readInfoElement(self, infoElement, instanceObject):
""" Read the info element.
::
<info/>
<info">
<location/>
</info>
"""
infoLocation = self.locationFromElement(infoElement)
instanceObject.addInfo(infoLocation, copySourceName=self.infoSource) | python | def readInfoElement(self, infoElement, instanceObject):
""" Read the info element.
::
<info/>
<info">
<location/>
</info>
"""
infoLocation = self.locationFromElement(infoElement)
instanceObject.addInfo(infoLocation, copySourceName=self.infoSource) | [
"def",
"readInfoElement",
"(",
"self",
",",
"infoElement",
",",
"instanceObject",
")",
":",
"infoLocation",
"=",
"self",
".",
"locationFromElement",
"(",
"infoElement",
")",
"instanceObject",
".",
"addInfo",
"(",
"infoLocation",
",",
"copySourceName",
"=",
"self",... | Read the info element.
::
<info/>
<info">
<location/>
</info> | [
"Read",
"the",
"info",
"element",
"."
] | 10318fc4e7c9cee9df6130826829baea3054a42b | https://github.com/LettError/MutatorMath/blob/10318fc4e7c9cee9df6130826829baea3054a42b/Lib/mutatorMath/ufo/document.py#L765-L778 | train | 31,994 |
LettError/MutatorMath | Lib/mutatorMath/ufo/document.py | DesignSpaceDocumentReader.readKerningElement | def readKerningElement(self, kerningElement, instanceObject):
""" Read the kerning element.
::
Make kerning at the location and with the masters specified at the instance level.
<kerning/>
"""
kerningLocation = self.locationFromElement(kerningElement)
instanceObject.addKerning(kerningLocation) | python | def readKerningElement(self, kerningElement, instanceObject):
""" Read the kerning element.
::
Make kerning at the location and with the masters specified at the instance level.
<kerning/>
"""
kerningLocation = self.locationFromElement(kerningElement)
instanceObject.addKerning(kerningLocation) | [
"def",
"readKerningElement",
"(",
"self",
",",
"kerningElement",
",",
"instanceObject",
")",
":",
"kerningLocation",
"=",
"self",
".",
"locationFromElement",
"(",
"kerningElement",
")",
"instanceObject",
".",
"addKerning",
"(",
"kerningLocation",
")"
] | Read the kerning element.
::
Make kerning at the location and with the masters specified at the instance level.
<kerning/> | [
"Read",
"the",
"kerning",
"element",
"."
] | 10318fc4e7c9cee9df6130826829baea3054a42b | https://github.com/LettError/MutatorMath/blob/10318fc4e7c9cee9df6130826829baea3054a42b/Lib/mutatorMath/ufo/document.py#L780-L790 | train | 31,995 |
LettError/MutatorMath | Lib/mutatorMath/ufo/document.py | DesignSpaceDocumentReader.readGlyphElement | def readGlyphElement(self, glyphElement, instanceObject):
"""
Read the glyph element.
::
<glyph name="b" unicode="0x62"/>
<glyph name="b"/>
<glyph name="b">
<master location="location-token-bbb" source="master-token-aaa2"/>
<master glyphname="b.alt1" location="location-token-ccc" source="master-token-aaa3"/>
<note>
This is an instance from an anisotropic interpolation.
</note>
</glyph>
"""
# name
glyphName = glyphElement.attrib.get('name')
if glyphName is None:
raise MutatorError("Glyph object without name attribute.")
# mute
mute = glyphElement.attrib.get("mute")
if mute == "1":
instanceObject.muteGlyph(glyphName)
# we do not need to stick around after this
return
# unicode
unicodes = glyphElement.attrib.get('unicode')
if unicodes == None:
unicodes = self.unicodeMap.get(glyphName, None)
else:
try:
unicodes = [int(u, 16) for u in unicodes.split(" ")]
except ValueError:
raise MutatorError("unicode values %s are not integers" % unicodes)
# note
note = None
for noteElement in glyphElement.findall('.note'):
note = noteElement.text
break
# location
instanceLocation = self.locationFromElement(glyphElement)
# masters
glyphSources = None
for masterElement in glyphElement.findall('.masters/master'):
fontSourceName = masterElement.attrib.get('source')
fontSource, fontLocation = self.sources.get(fontSourceName)
if fontSource is None:
raise MutatorError("Unknown glyph master: %s"%masterElement)
sourceLocation = self.locationFromElement(masterElement)
if sourceLocation is None:
# if we don't read a location, use the instance location
sourceLocation = fontLocation
masterGlyphName = masterElement.attrib.get('glyphname')
if masterGlyphName is None:
# if we don't read a glyphname, use the one we have
masterGlyphName = glyphName
d = dict( font=fontSource,
location=sourceLocation,
glyphName=masterGlyphName)
if glyphSources is None:
glyphSources = []
glyphSources.append(d)
# calculate the glyph
instanceObject.addGlyph(glyphName, unicodes, instanceLocation, glyphSources, note=note) | python | def readGlyphElement(self, glyphElement, instanceObject):
"""
Read the glyph element.
::
<glyph name="b" unicode="0x62"/>
<glyph name="b"/>
<glyph name="b">
<master location="location-token-bbb" source="master-token-aaa2"/>
<master glyphname="b.alt1" location="location-token-ccc" source="master-token-aaa3"/>
<note>
This is an instance from an anisotropic interpolation.
</note>
</glyph>
"""
# name
glyphName = glyphElement.attrib.get('name')
if glyphName is None:
raise MutatorError("Glyph object without name attribute.")
# mute
mute = glyphElement.attrib.get("mute")
if mute == "1":
instanceObject.muteGlyph(glyphName)
# we do not need to stick around after this
return
# unicode
unicodes = glyphElement.attrib.get('unicode')
if unicodes == None:
unicodes = self.unicodeMap.get(glyphName, None)
else:
try:
unicodes = [int(u, 16) for u in unicodes.split(" ")]
except ValueError:
raise MutatorError("unicode values %s are not integers" % unicodes)
# note
note = None
for noteElement in glyphElement.findall('.note'):
note = noteElement.text
break
# location
instanceLocation = self.locationFromElement(glyphElement)
# masters
glyphSources = None
for masterElement in glyphElement.findall('.masters/master'):
fontSourceName = masterElement.attrib.get('source')
fontSource, fontLocation = self.sources.get(fontSourceName)
if fontSource is None:
raise MutatorError("Unknown glyph master: %s"%masterElement)
sourceLocation = self.locationFromElement(masterElement)
if sourceLocation is None:
# if we don't read a location, use the instance location
sourceLocation = fontLocation
masterGlyphName = masterElement.attrib.get('glyphname')
if masterGlyphName is None:
# if we don't read a glyphname, use the one we have
masterGlyphName = glyphName
d = dict( font=fontSource,
location=sourceLocation,
glyphName=masterGlyphName)
if glyphSources is None:
glyphSources = []
glyphSources.append(d)
# calculate the glyph
instanceObject.addGlyph(glyphName, unicodes, instanceLocation, glyphSources, note=note) | [
"def",
"readGlyphElement",
"(",
"self",
",",
"glyphElement",
",",
"instanceObject",
")",
":",
"# name",
"glyphName",
"=",
"glyphElement",
".",
"attrib",
".",
"get",
"(",
"'name'",
")",
"if",
"glyphName",
"is",
"None",
":",
"raise",
"MutatorError",
"(",
"\"Gl... | Read the glyph element.
::
<glyph name="b" unicode="0x62"/>
<glyph name="b"/>
<glyph name="b">
<master location="location-token-bbb" source="master-token-aaa2"/>
<master glyphname="b.alt1" location="location-token-ccc" source="master-token-aaa3"/>
<note>
This is an instance from an anisotropic interpolation.
</note>
</glyph> | [
"Read",
"the",
"glyph",
"element",
"."
] | 10318fc4e7c9cee9df6130826829baea3054a42b | https://github.com/LettError/MutatorMath/blob/10318fc4e7c9cee9df6130826829baea3054a42b/Lib/mutatorMath/ufo/document.py#L792-L865 | train | 31,996 |
viralogic/py-enumerable | py_linq/py_linq.py | Enumerable.group_by | def group_by(self, key_names=[], key=lambda x: x, result_func=lambda x: x):
"""
Groups an enumerable on given key selector. Index of key name
corresponds to index of key lambda function.
Usage:
Enumerable([1,2,3]).group_by(key_names=['id'], key=lambda x: x) _
.to_list() -->
Enumerable object [
Grouping object {
key.id: 1,
_data: [1]
},
Grouping object {
key.id: 2,
_data: [2]
},
Grouping object {
key.id: 3,
_data: [3]
}
]
Thus the key names for each grouping object can be referenced
through the key property. Using the above example:
Enumerable([1,2,3]).group_by(key_names=['id'], key=lambda x: x) _
.select(lambda g: { 'key': g.key.id, 'count': g.count() }
:param key_names: list of key names
:param key: key selector as lambda expression
:param result_func: transformation function as lambda expression
:return: Enumerable of grouping objects
"""
result = []
ordered = sorted(self, key=key)
grouped = itertools.groupby(ordered, key)
for k, g in grouped:
can_enumerate = isinstance(k, list) or isinstance(k, tuple) \
and len(k) > 0
key_prop = {}
for i, prop in enumerate(key_names):
key_prop.setdefault(prop, k[i] if can_enumerate else k)
key_object = Key(key_prop)
result.append(Grouping(key_object, list(g)))
return Enumerable(result).select(result_func) | python | def group_by(self, key_names=[], key=lambda x: x, result_func=lambda x: x):
"""
Groups an enumerable on given key selector. Index of key name
corresponds to index of key lambda function.
Usage:
Enumerable([1,2,3]).group_by(key_names=['id'], key=lambda x: x) _
.to_list() -->
Enumerable object [
Grouping object {
key.id: 1,
_data: [1]
},
Grouping object {
key.id: 2,
_data: [2]
},
Grouping object {
key.id: 3,
_data: [3]
}
]
Thus the key names for each grouping object can be referenced
through the key property. Using the above example:
Enumerable([1,2,3]).group_by(key_names=['id'], key=lambda x: x) _
.select(lambda g: { 'key': g.key.id, 'count': g.count() }
:param key_names: list of key names
:param key: key selector as lambda expression
:param result_func: transformation function as lambda expression
:return: Enumerable of grouping objects
"""
result = []
ordered = sorted(self, key=key)
grouped = itertools.groupby(ordered, key)
for k, g in grouped:
can_enumerate = isinstance(k, list) or isinstance(k, tuple) \
and len(k) > 0
key_prop = {}
for i, prop in enumerate(key_names):
key_prop.setdefault(prop, k[i] if can_enumerate else k)
key_object = Key(key_prop)
result.append(Grouping(key_object, list(g)))
return Enumerable(result).select(result_func) | [
"def",
"group_by",
"(",
"self",
",",
"key_names",
"=",
"[",
"]",
",",
"key",
"=",
"lambda",
"x",
":",
"x",
",",
"result_func",
"=",
"lambda",
"x",
":",
"x",
")",
":",
"result",
"=",
"[",
"]",
"ordered",
"=",
"sorted",
"(",
"self",
",",
"key",
"... | Groups an enumerable on given key selector. Index of key name
corresponds to index of key lambda function.
Usage:
Enumerable([1,2,3]).group_by(key_names=['id'], key=lambda x: x) _
.to_list() -->
Enumerable object [
Grouping object {
key.id: 1,
_data: [1]
},
Grouping object {
key.id: 2,
_data: [2]
},
Grouping object {
key.id: 3,
_data: [3]
}
]
Thus the key names for each grouping object can be referenced
through the key property. Using the above example:
Enumerable([1,2,3]).group_by(key_names=['id'], key=lambda x: x) _
.select(lambda g: { 'key': g.key.id, 'count': g.count() }
:param key_names: list of key names
:param key: key selector as lambda expression
:param result_func: transformation function as lambda expression
:return: Enumerable of grouping objects | [
"Groups",
"an",
"enumerable",
"on",
"given",
"key",
"selector",
".",
"Index",
"of",
"key",
"name",
"corresponds",
"to",
"index",
"of",
"key",
"lambda",
"function",
"."
] | 63363649bccef223379e1e87056747240c83aa9d | https://github.com/viralogic/py-enumerable/blob/63363649bccef223379e1e87056747240c83aa9d/py_linq/py_linq.py#L287-L331 | train | 31,997 |
CyberReboot/vent | vent/api/tools.py | Tools.inventory | def inventory(self, choices=None):
""" Return a dictionary of the inventory items and status """
status = (True, None)
if not choices:
return (False, 'No choices made')
try:
# choices: repos, tools, images, built, running, enabled
items = {'repos': [], 'tools': {}, 'images': {},
'built': {}, 'running': {}, 'enabled': {}}
tools = Template(self.manifest).list_tools()
for choice in choices:
for tool in tools:
try:
if choice == 'repos':
if 'repo' in tool:
if (tool['repo'] and
tool['repo'] not in items[choice]):
items[choice].append(tool['repo'])
elif choice == 'tools':
items[choice][tool['section']] = tool['name']
elif choice == 'images':
# TODO also check against docker
items[choice][tool['section']] = tool['image_name']
elif choice == 'built':
items[choice][tool['section']] = tool['built']
elif choice == 'running':
containers = Containers()
status = 'not running'
for container in containers:
image_name = tool['image_name'] \
.rsplit(':' +
tool['version'], 1)[0]
image_name = image_name.replace(':', '-')
image_name = image_name.replace('/', '-')
self.logger.info('image_name: ' + image_name)
if container[0] == image_name:
status = container[1]
elif container[0] == image_name + \
'-' + tool['version']:
status = container[1]
items[choice][tool['section']] = status
elif choice == 'enabled':
items[choice][tool['section']] = tool['enabled']
else:
# unknown choice
pass
except Exception as e: # pragma: no cover
self.logger.error('Unable to grab info about tool: ' +
str(tool) + ' because: ' + str(e))
status = (True, items)
except Exception as e: # pragma: no cover
self.logger.error(
'Inventory failed with error: {0}'.format(str(e)))
status = (False, str(e))
return status | python | def inventory(self, choices=None):
""" Return a dictionary of the inventory items and status """
status = (True, None)
if not choices:
return (False, 'No choices made')
try:
# choices: repos, tools, images, built, running, enabled
items = {'repos': [], 'tools': {}, 'images': {},
'built': {}, 'running': {}, 'enabled': {}}
tools = Template(self.manifest).list_tools()
for choice in choices:
for tool in tools:
try:
if choice == 'repos':
if 'repo' in tool:
if (tool['repo'] and
tool['repo'] not in items[choice]):
items[choice].append(tool['repo'])
elif choice == 'tools':
items[choice][tool['section']] = tool['name']
elif choice == 'images':
# TODO also check against docker
items[choice][tool['section']] = tool['image_name']
elif choice == 'built':
items[choice][tool['section']] = tool['built']
elif choice == 'running':
containers = Containers()
status = 'not running'
for container in containers:
image_name = tool['image_name'] \
.rsplit(':' +
tool['version'], 1)[0]
image_name = image_name.replace(':', '-')
image_name = image_name.replace('/', '-')
self.logger.info('image_name: ' + image_name)
if container[0] == image_name:
status = container[1]
elif container[0] == image_name + \
'-' + tool['version']:
status = container[1]
items[choice][tool['section']] = status
elif choice == 'enabled':
items[choice][tool['section']] = tool['enabled']
else:
# unknown choice
pass
except Exception as e: # pragma: no cover
self.logger.error('Unable to grab info about tool: ' +
str(tool) + ' because: ' + str(e))
status = (True, items)
except Exception as e: # pragma: no cover
self.logger.error(
'Inventory failed with error: {0}'.format(str(e)))
status = (False, str(e))
return status | [
"def",
"inventory",
"(",
"self",
",",
"choices",
"=",
"None",
")",
":",
"status",
"=",
"(",
"True",
",",
"None",
")",
"if",
"not",
"choices",
":",
"return",
"(",
"False",
",",
"'No choices made'",
")",
"try",
":",
"# choices: repos, tools, images, built, run... | Return a dictionary of the inventory items and status | [
"Return",
"a",
"dictionary",
"of",
"the",
"inventory",
"items",
"and",
"status"
] | 9956a09146b11a89a0eabab3bc7ce8906d124885 | https://github.com/CyberReboot/vent/blob/9956a09146b11a89a0eabab3bc7ce8906d124885/vent/api/tools.py#L90-L145 | train | 31,998 |
CyberReboot/vent | vent/api/tools.py | Tools._start_priority_containers | def _start_priority_containers(self, groups, group_orders, tool_d):
""" Select containers based on priorities to start """
vent_cfg = Template(self.path_dirs.cfg_file)
cfg_groups = vent_cfg.option('groups', 'start_order')
if cfg_groups[0]:
cfg_groups = cfg_groups[1].split(',')
else:
cfg_groups = []
all_groups = sorted(set(groups))
s_conts = []
f_conts = []
# start tools in order of group defined in vent.cfg
for group in cfg_groups:
# remove from all_groups because already checked out
if group in all_groups:
all_groups.remove(group)
if group in group_orders:
for cont_t in sorted(group_orders[group]):
if cont_t[1] not in s_conts:
s_conts, f_conts = self._start_container(cont_t[1],
tool_d,
s_conts,
f_conts)
# start tools that haven't been specified in the vent.cfg, if any
for group in all_groups:
if group in group_orders:
for cont_t in sorted(group_orders[group]):
if cont_t[1] not in s_conts:
s_conts, f_conts = self._start_container(cont_t[1],
tool_d,
s_conts,
f_conts)
return (s_conts, f_conts) | python | def _start_priority_containers(self, groups, group_orders, tool_d):
""" Select containers based on priorities to start """
vent_cfg = Template(self.path_dirs.cfg_file)
cfg_groups = vent_cfg.option('groups', 'start_order')
if cfg_groups[0]:
cfg_groups = cfg_groups[1].split(',')
else:
cfg_groups = []
all_groups = sorted(set(groups))
s_conts = []
f_conts = []
# start tools in order of group defined in vent.cfg
for group in cfg_groups:
# remove from all_groups because already checked out
if group in all_groups:
all_groups.remove(group)
if group in group_orders:
for cont_t in sorted(group_orders[group]):
if cont_t[1] not in s_conts:
s_conts, f_conts = self._start_container(cont_t[1],
tool_d,
s_conts,
f_conts)
# start tools that haven't been specified in the vent.cfg, if any
for group in all_groups:
if group in group_orders:
for cont_t in sorted(group_orders[group]):
if cont_t[1] not in s_conts:
s_conts, f_conts = self._start_container(cont_t[1],
tool_d,
s_conts,
f_conts)
return (s_conts, f_conts) | [
"def",
"_start_priority_containers",
"(",
"self",
",",
"groups",
",",
"group_orders",
",",
"tool_d",
")",
":",
"vent_cfg",
"=",
"Template",
"(",
"self",
".",
"path_dirs",
".",
"cfg_file",
")",
"cfg_groups",
"=",
"vent_cfg",
".",
"option",
"(",
"'groups'",
",... | Select containers based on priorities to start | [
"Select",
"containers",
"based",
"on",
"priorities",
"to",
"start"
] | 9956a09146b11a89a0eabab3bc7ce8906d124885 | https://github.com/CyberReboot/vent/blob/9956a09146b11a89a0eabab3bc7ce8906d124885/vent/api/tools.py#L651-L683 | train | 31,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.