repository_name
stringlengths
7
55
func_path_in_repository
stringlengths
4
223
func_name
stringlengths
1
134
whole_func_string
stringlengths
75
104k
language
stringclasses
1 value
func_code_string
stringlengths
75
104k
func_code_tokens
listlengths
19
28.4k
func_documentation_string
stringlengths
1
46.9k
func_documentation_tokens
listlengths
1
1.97k
split_name
stringclasses
1 value
func_code_url
stringlengths
87
315
insilichem/ommprotocol
ommprotocol/io.py
process_forcefield
def process_forcefield(*forcefields): """ Given a list of filenames, check which ones are `frcmods`. If so, convert them to ffxml. Else, just return them. """ for forcefield in forcefields: if forcefield.endswith('.frcmod'): gaffmol2 = os.path.splitext(forcefield)[0] + '.gaff.mol2' yield create_ffxml_file([gaffmol2], [forcefield]) else: yield forcefield
python
def process_forcefield(*forcefields): """ Given a list of filenames, check which ones are `frcmods`. If so, convert them to ffxml. Else, just return them. """ for forcefield in forcefields: if forcefield.endswith('.frcmod'): gaffmol2 = os.path.splitext(forcefield)[0] + '.gaff.mol2' yield create_ffxml_file([gaffmol2], [forcefield]) else: yield forcefield
[ "def", "process_forcefield", "(", "*", "forcefields", ")", ":", "for", "forcefield", "in", "forcefields", ":", "if", "forcefield", ".", "endswith", "(", "'.frcmod'", ")", ":", "gaffmol2", "=", "os", ".", "path", ".", "splitext", "(", "forcefield", ")", "[", "0", "]", "+", "'.gaff.mol2'", "yield", "create_ffxml_file", "(", "[", "gaffmol2", "]", ",", "[", "forcefield", "]", ")", "else", ":", "yield", "forcefield" ]
Given a list of filenames, check which ones are `frcmods`. If so, convert them to ffxml. Else, just return them.
[ "Given", "a", "list", "of", "filenames", "check", "which", "ones", "are", "frcmods", ".", "If", "so", "convert", "them", "to", "ffxml", ".", "Else", "just", "return", "them", "." ]
train
https://github.com/insilichem/ommprotocol/blob/7283fddba7203e5ac3542fdab41fc1279d3b444e/ommprotocol/io.py#L981-L991
insilichem/ommprotocol
ommprotocol/io.py
statexml2pdb
def statexml2pdb(topology, state, output=None): """ Given an OpenMM xml file containing the state of the simulation, generate a PDB snapshot for easy visualization. """ state = Restart.from_xml(state) system = SystemHandler.load(topology, positions=state.positions) if output is None: output = topology + '.pdb' system.write_pdb(output)
python
def statexml2pdb(topology, state, output=None): """ Given an OpenMM xml file containing the state of the simulation, generate a PDB snapshot for easy visualization. """ state = Restart.from_xml(state) system = SystemHandler.load(topology, positions=state.positions) if output is None: output = topology + '.pdb' system.write_pdb(output)
[ "def", "statexml2pdb", "(", "topology", ",", "state", ",", "output", "=", "None", ")", ":", "state", "=", "Restart", ".", "from_xml", "(", "state", ")", "system", "=", "SystemHandler", ".", "load", "(", "topology", ",", "positions", "=", "state", ".", "positions", ")", "if", "output", "is", "None", ":", "output", "=", "topology", "+", "'.pdb'", "system", ".", "write_pdb", "(", "output", ")" ]
Given an OpenMM xml file containing the state of the simulation, generate a PDB snapshot for easy visualization.
[ "Given", "an", "OpenMM", "xml", "file", "containing", "the", "state", "of", "the", "simulation", "generate", "a", "PDB", "snapshot", "for", "easy", "visualization", "." ]
train
https://github.com/insilichem/ommprotocol/blob/7283fddba7203e5ac3542fdab41fc1279d3b444e/ommprotocol/io.py#L994-L1003
insilichem/ommprotocol
ommprotocol/io.py
export_frame_coordinates
def export_frame_coordinates(topology, trajectory, nframe, output=None): """ Extract a single frame structure from a trajectory. """ if output is None: basename, ext = os.path.splitext(trajectory) output = '{}.frame{}.inpcrd'.format(basename, nframe) # ParmEd sometimes struggles with certain PRMTOP files if os.path.splitext(topology)[1] in ('.top', '.prmtop'): top = AmberPrmtopFile(topology) mdtop = mdtraj.Topology.from_openmm(top.topology) traj = mdtraj.load_frame(trajectory, int(nframe), top=mdtop) structure = parmed.openmm.load_topology(top.topology, system=top.createSystem()) structure.box_vectors = top.topology.getPeriodicBoxVectors() else: # standard protocol (the topology is loaded twice, though) traj = mdtraj.load_frame(trajectory, int(nframe), top=topology) structure = parmed.load_file(topology) structure.positions = traj.openmm_positions(0) if traj.unitcell_vectors is not None: # if frame provides box vectors, use those structure.box_vectors = traj.openmm_boxes(0) structure.save(output, overwrite=True)
python
def export_frame_coordinates(topology, trajectory, nframe, output=None): """ Extract a single frame structure from a trajectory. """ if output is None: basename, ext = os.path.splitext(trajectory) output = '{}.frame{}.inpcrd'.format(basename, nframe) # ParmEd sometimes struggles with certain PRMTOP files if os.path.splitext(topology)[1] in ('.top', '.prmtop'): top = AmberPrmtopFile(topology) mdtop = mdtraj.Topology.from_openmm(top.topology) traj = mdtraj.load_frame(trajectory, int(nframe), top=mdtop) structure = parmed.openmm.load_topology(top.topology, system=top.createSystem()) structure.box_vectors = top.topology.getPeriodicBoxVectors() else: # standard protocol (the topology is loaded twice, though) traj = mdtraj.load_frame(trajectory, int(nframe), top=topology) structure = parmed.load_file(topology) structure.positions = traj.openmm_positions(0) if traj.unitcell_vectors is not None: # if frame provides box vectors, use those structure.box_vectors = traj.openmm_boxes(0) structure.save(output, overwrite=True)
[ "def", "export_frame_coordinates", "(", "topology", ",", "trajectory", ",", "nframe", ",", "output", "=", "None", ")", ":", "if", "output", "is", "None", ":", "basename", ",", "ext", "=", "os", ".", "path", ".", "splitext", "(", "trajectory", ")", "output", "=", "'{}.frame{}.inpcrd'", ".", "format", "(", "basename", ",", "nframe", ")", "# ParmEd sometimes struggles with certain PRMTOP files", "if", "os", ".", "path", ".", "splitext", "(", "topology", ")", "[", "1", "]", "in", "(", "'.top'", ",", "'.prmtop'", ")", ":", "top", "=", "AmberPrmtopFile", "(", "topology", ")", "mdtop", "=", "mdtraj", ".", "Topology", ".", "from_openmm", "(", "top", ".", "topology", ")", "traj", "=", "mdtraj", ".", "load_frame", "(", "trajectory", ",", "int", "(", "nframe", ")", ",", "top", "=", "mdtop", ")", "structure", "=", "parmed", ".", "openmm", ".", "load_topology", "(", "top", ".", "topology", ",", "system", "=", "top", ".", "createSystem", "(", ")", ")", "structure", ".", "box_vectors", "=", "top", ".", "topology", ".", "getPeriodicBoxVectors", "(", ")", "else", ":", "# standard protocol (the topology is loaded twice, though)", "traj", "=", "mdtraj", ".", "load_frame", "(", "trajectory", ",", "int", "(", "nframe", ")", ",", "top", "=", "topology", ")", "structure", "=", "parmed", ".", "load_file", "(", "topology", ")", "structure", ".", "positions", "=", "traj", ".", "openmm_positions", "(", "0", ")", "if", "traj", ".", "unitcell_vectors", "is", "not", "None", ":", "# if frame provides box vectors, use those", "structure", ".", "box_vectors", "=", "traj", ".", "openmm_boxes", "(", "0", ")", "structure", ".", "save", "(", "output", ",", "overwrite", "=", "True", ")" ]
Extract a single frame structure from a trajectory.
[ "Extract", "a", "single", "frame", "structure", "from", "a", "trajectory", "." ]
train
https://github.com/insilichem/ommprotocol/blob/7283fddba7203e5ac3542fdab41fc1279d3b444e/ommprotocol/io.py#L1006-L1031
insilichem/ommprotocol
ommprotocol/io.py
YamlLoader.construct_include
def construct_include(self, node): """Include file referenced at node.""" filename = os.path.join(self._root, self.construct_scalar(node)) filename = os.path.abspath(filename) extension = os.path.splitext(filename)[1].lstrip('.') with open(filename, 'r') as f: if extension in ('yaml', 'yml'): return yaml.load(f, Loader=self) else: return ''.join(f.readlines())
python
def construct_include(self, node): """Include file referenced at node.""" filename = os.path.join(self._root, self.construct_scalar(node)) filename = os.path.abspath(filename) extension = os.path.splitext(filename)[1].lstrip('.') with open(filename, 'r') as f: if extension in ('yaml', 'yml'): return yaml.load(f, Loader=self) else: return ''.join(f.readlines())
[ "def", "construct_include", "(", "self", ",", "node", ")", ":", "filename", "=", "os", ".", "path", ".", "join", "(", "self", ".", "_root", ",", "self", ".", "construct_scalar", "(", "node", ")", ")", "filename", "=", "os", ".", "path", ".", "abspath", "(", "filename", ")", "extension", "=", "os", ".", "path", ".", "splitext", "(", "filename", ")", "[", "1", "]", ".", "lstrip", "(", "'.'", ")", "with", "open", "(", "filename", ",", "'r'", ")", "as", "f", ":", "if", "extension", "in", "(", "'yaml'", ",", "'yml'", ")", ":", "return", "yaml", ".", "load", "(", "f", ",", "Loader", "=", "self", ")", "else", ":", "return", "''", ".", "join", "(", "f", ".", "readlines", "(", ")", ")" ]
Include file referenced at node.
[ "Include", "file", "referenced", "at", "node", "." ]
train
https://github.com/insilichem/ommprotocol/blob/7283fddba7203e5ac3542fdab41fc1279d3b444e/ommprotocol/io.py#L81-L92
insilichem/ommprotocol
ommprotocol/io.py
SystemHandler.from_pdb
def from_pdb(cls, path, forcefield=None, loader=PDBFile, strict=True, **kwargs): """ Loads topology, positions and, potentially, velocities and vectors, from a PDB or PDBx file Parameters ---------- path : str Path to PDB/PDBx file forcefields : list of str Paths to FFXML and/or FRCMOD forcefields. REQUIRED. Returns ------- pdb : SystemHandler SystemHandler with topology, positions, and, potentially, velocities and box vectors. Forcefields are embedded in the `master` attribute. """ pdb = loader(path) box = kwargs.pop('box', pdb.topology.getPeriodicBoxVectors()) positions = kwargs.pop('positions', pdb.positions) velocities = kwargs.pop('velocities', getattr(pdb, 'velocities', None)) if strict and not forcefield: from .md import FORCEFIELDS as forcefield logger.info('! Forcefields for PDB not specified. Using default: %s', ', '.join(forcefield)) pdb.forcefield = ForceField(*list(process_forcefield(*forcefield))) return cls(master=pdb.forcefield, topology=pdb.topology, positions=positions, velocities=velocities, box=box, path=path, **kwargs)
python
def from_pdb(cls, path, forcefield=None, loader=PDBFile, strict=True, **kwargs): """ Loads topology, positions and, potentially, velocities and vectors, from a PDB or PDBx file Parameters ---------- path : str Path to PDB/PDBx file forcefields : list of str Paths to FFXML and/or FRCMOD forcefields. REQUIRED. Returns ------- pdb : SystemHandler SystemHandler with topology, positions, and, potentially, velocities and box vectors. Forcefields are embedded in the `master` attribute. """ pdb = loader(path) box = kwargs.pop('box', pdb.topology.getPeriodicBoxVectors()) positions = kwargs.pop('positions', pdb.positions) velocities = kwargs.pop('velocities', getattr(pdb, 'velocities', None)) if strict and not forcefield: from .md import FORCEFIELDS as forcefield logger.info('! Forcefields for PDB not specified. Using default: %s', ', '.join(forcefield)) pdb.forcefield = ForceField(*list(process_forcefield(*forcefield))) return cls(master=pdb.forcefield, topology=pdb.topology, positions=positions, velocities=velocities, box=box, path=path, **kwargs)
[ "def", "from_pdb", "(", "cls", ",", "path", ",", "forcefield", "=", "None", ",", "loader", "=", "PDBFile", ",", "strict", "=", "True", ",", "*", "*", "kwargs", ")", ":", "pdb", "=", "loader", "(", "path", ")", "box", "=", "kwargs", ".", "pop", "(", "'box'", ",", "pdb", ".", "topology", ".", "getPeriodicBoxVectors", "(", ")", ")", "positions", "=", "kwargs", ".", "pop", "(", "'positions'", ",", "pdb", ".", "positions", ")", "velocities", "=", "kwargs", ".", "pop", "(", "'velocities'", ",", "getattr", "(", "pdb", ",", "'velocities'", ",", "None", ")", ")", "if", "strict", "and", "not", "forcefield", ":", "from", ".", "md", "import", "FORCEFIELDS", "as", "forcefield", "logger", ".", "info", "(", "'! Forcefields for PDB not specified. Using default: %s'", ",", "', '", ".", "join", "(", "forcefield", ")", ")", "pdb", ".", "forcefield", "=", "ForceField", "(", "*", "list", "(", "process_forcefield", "(", "*", "forcefield", ")", ")", ")", "return", "cls", "(", "master", "=", "pdb", ".", "forcefield", ",", "topology", "=", "pdb", ".", "topology", ",", "positions", "=", "positions", ",", "velocities", "=", "velocities", ",", "box", "=", "box", ",", "path", "=", "path", ",", "*", "*", "kwargs", ")" ]
Loads topology, positions and, potentially, velocities and vectors, from a PDB or PDBx file Parameters ---------- path : str Path to PDB/PDBx file forcefields : list of str Paths to FFXML and/or FRCMOD forcefields. REQUIRED. Returns ------- pdb : SystemHandler SystemHandler with topology, positions, and, potentially, velocities and box vectors. Forcefields are embedded in the `master` attribute.
[ "Loads", "topology", "positions", "and", "potentially", "velocities", "and", "vectors", "from", "a", "PDB", "or", "PDBx", "file" ]
train
https://github.com/insilichem/ommprotocol/blob/7283fddba7203e5ac3542fdab41fc1279d3b444e/ommprotocol/io.py#L222-L252
insilichem/ommprotocol
ommprotocol/io.py
SystemHandler.from_amber
def from_amber(cls, path, positions=None, strict=True, **kwargs): """ Loads Amber Parm7 parameters and topology file Parameters ---------- path : str Path to *.prmtop or *.top file positions : simtk.unit.Quantity Atomic positions Returns ------- prmtop : SystemHandler SystemHandler with topology """ if strict and positions is None: raise ValueError('Amber TOP/PRMTOP files require initial positions.') prmtop = AmberPrmtopFile(path) box = kwargs.pop('box', prmtop.topology.getPeriodicBoxVectors()) return cls(master=prmtop, topology=prmtop.topology, positions=positions, box=box, path=path, **kwargs)
python
def from_amber(cls, path, positions=None, strict=True, **kwargs): """ Loads Amber Parm7 parameters and topology file Parameters ---------- path : str Path to *.prmtop or *.top file positions : simtk.unit.Quantity Atomic positions Returns ------- prmtop : SystemHandler SystemHandler with topology """ if strict and positions is None: raise ValueError('Amber TOP/PRMTOP files require initial positions.') prmtop = AmberPrmtopFile(path) box = kwargs.pop('box', prmtop.topology.getPeriodicBoxVectors()) return cls(master=prmtop, topology=prmtop.topology, positions=positions, box=box, path=path, **kwargs)
[ "def", "from_amber", "(", "cls", ",", "path", ",", "positions", "=", "None", ",", "strict", "=", "True", ",", "*", "*", "kwargs", ")", ":", "if", "strict", "and", "positions", "is", "None", ":", "raise", "ValueError", "(", "'Amber TOP/PRMTOP files require initial positions.'", ")", "prmtop", "=", "AmberPrmtopFile", "(", "path", ")", "box", "=", "kwargs", ".", "pop", "(", "'box'", ",", "prmtop", ".", "topology", ".", "getPeriodicBoxVectors", "(", ")", ")", "return", "cls", "(", "master", "=", "prmtop", ",", "topology", "=", "prmtop", ".", "topology", ",", "positions", "=", "positions", ",", "box", "=", "box", ",", "path", "=", "path", ",", "*", "*", "kwargs", ")" ]
Loads Amber Parm7 parameters and topology file Parameters ---------- path : str Path to *.prmtop or *.top file positions : simtk.unit.Quantity Atomic positions Returns ------- prmtop : SystemHandler SystemHandler with topology
[ "Loads", "Amber", "Parm7", "parameters", "and", "topology", "file" ]
train
https://github.com/insilichem/ommprotocol/blob/7283fddba7203e5ac3542fdab41fc1279d3b444e/ommprotocol/io.py#L260-L281
insilichem/ommprotocol
ommprotocol/io.py
SystemHandler.from_charmm
def from_charmm(cls, path, positions=None, forcefield=None, strict=True, **kwargs): """ Loads PSF Charmm structure from `path`. Requires `charmm_parameters`. Parameters ---------- path : str Path to PSF file forcefield : list of str Paths to Charmm parameters files, such as *.par or *.str. REQUIRED Returns ------- psf : SystemHandler SystemHandler with topology. Charmm parameters are embedded in the `master` attribute. """ psf = CharmmPsfFile(path) if strict and forcefield is None: raise ValueError('PSF files require key `forcefield`.') if strict and positions is None: raise ValueError('PSF files require key `positions`.') psf.parmset = CharmmParameterSet(*forcefield) psf.loadParameters(psf.parmset) return cls(master=psf, topology=psf.topology, positions=positions, path=path, **kwargs)
python
def from_charmm(cls, path, positions=None, forcefield=None, strict=True, **kwargs): """ Loads PSF Charmm structure from `path`. Requires `charmm_parameters`. Parameters ---------- path : str Path to PSF file forcefield : list of str Paths to Charmm parameters files, such as *.par or *.str. REQUIRED Returns ------- psf : SystemHandler SystemHandler with topology. Charmm parameters are embedded in the `master` attribute. """ psf = CharmmPsfFile(path) if strict and forcefield is None: raise ValueError('PSF files require key `forcefield`.') if strict and positions is None: raise ValueError('PSF files require key `positions`.') psf.parmset = CharmmParameterSet(*forcefield) psf.loadParameters(psf.parmset) return cls(master=psf, topology=psf.topology, positions=positions, path=path, **kwargs)
[ "def", "from_charmm", "(", "cls", ",", "path", ",", "positions", "=", "None", ",", "forcefield", "=", "None", ",", "strict", "=", "True", ",", "*", "*", "kwargs", ")", ":", "psf", "=", "CharmmPsfFile", "(", "path", ")", "if", "strict", "and", "forcefield", "is", "None", ":", "raise", "ValueError", "(", "'PSF files require key `forcefield`.'", ")", "if", "strict", "and", "positions", "is", "None", ":", "raise", "ValueError", "(", "'PSF files require key `positions`.'", ")", "psf", ".", "parmset", "=", "CharmmParameterSet", "(", "*", "forcefield", ")", "psf", ".", "loadParameters", "(", "psf", ".", "parmset", ")", "return", "cls", "(", "master", "=", "psf", ",", "topology", "=", "psf", ".", "topology", ",", "positions", "=", "positions", ",", "path", "=", "path", ",", "*", "*", "kwargs", ")" ]
Loads PSF Charmm structure from `path`. Requires `charmm_parameters`. Parameters ---------- path : str Path to PSF file forcefield : list of str Paths to Charmm parameters files, such as *.par or *.str. REQUIRED Returns ------- psf : SystemHandler SystemHandler with topology. Charmm parameters are embedded in the `master` attribute.
[ "Loads", "PSF", "Charmm", "structure", "from", "path", ".", "Requires", "charmm_parameters", "." ]
train
https://github.com/insilichem/ommprotocol/blob/7283fddba7203e5ac3542fdab41fc1279d3b444e/ommprotocol/io.py#L284-L309
insilichem/ommprotocol
ommprotocol/io.py
SystemHandler.from_desmond
def from_desmond(cls, path, **kwargs): """ Loads a topology from a Desmond DMS file located at `path`. Arguments --------- path : str Path to a Desmond DMS file """ dms = DesmondDMSFile(path) pos = kwargs.pop('positions', dms.getPositions()) return cls(master=dms, topology=dms.getTopology(), positions=pos, path=path, **kwargs)
python
def from_desmond(cls, path, **kwargs): """ Loads a topology from a Desmond DMS file located at `path`. Arguments --------- path : str Path to a Desmond DMS file """ dms = DesmondDMSFile(path) pos = kwargs.pop('positions', dms.getPositions()) return cls(master=dms, topology=dms.getTopology(), positions=pos, path=path, **kwargs)
[ "def", "from_desmond", "(", "cls", ",", "path", ",", "*", "*", "kwargs", ")", ":", "dms", "=", "DesmondDMSFile", "(", "path", ")", "pos", "=", "kwargs", ".", "pop", "(", "'positions'", ",", "dms", ".", "getPositions", "(", ")", ")", "return", "cls", "(", "master", "=", "dms", ",", "topology", "=", "dms", ".", "getTopology", "(", ")", ",", "positions", "=", "pos", ",", "path", "=", "path", ",", "*", "*", "kwargs", ")" ]
Loads a topology from a Desmond DMS file located at `path`. Arguments --------- path : str Path to a Desmond DMS file
[ "Loads", "a", "topology", "from", "a", "Desmond", "DMS", "file", "located", "at", "path", "." ]
train
https://github.com/insilichem/ommprotocol/blob/7283fddba7203e5ac3542fdab41fc1279d3b444e/ommprotocol/io.py#L312-L324
insilichem/ommprotocol
ommprotocol/io.py
SystemHandler.from_gromacs
def from_gromacs(cls, path, positions=None, forcefield=None, strict=True, **kwargs): """ Loads a topology from a Gromacs TOP file located at `path`. Additional root directory for parameters can be specified with `forcefield`. Arguments --------- path : str Path to a Gromacs TOP file positions : simtk.unit.Quantity Atomic positions forcefield : str, optional Root directory for parameter files """ if strict and positions is None: raise ValueError('Gromacs TOP files require initial positions.') box = kwargs.pop('box', None) top = GromacsTopFile(path, includeDir=forcefield, periodicBoxVectors=box) return cls(master=top, topology=top.topology, positions=positions, box=box, path=path, **kwargs)
python
def from_gromacs(cls, path, positions=None, forcefield=None, strict=True, **kwargs): """ Loads a topology from a Gromacs TOP file located at `path`. Additional root directory for parameters can be specified with `forcefield`. Arguments --------- path : str Path to a Gromacs TOP file positions : simtk.unit.Quantity Atomic positions forcefield : str, optional Root directory for parameter files """ if strict and positions is None: raise ValueError('Gromacs TOP files require initial positions.') box = kwargs.pop('box', None) top = GromacsTopFile(path, includeDir=forcefield, periodicBoxVectors=box) return cls(master=top, topology=top.topology, positions=positions, box=box, path=path, **kwargs)
[ "def", "from_gromacs", "(", "cls", ",", "path", ",", "positions", "=", "None", ",", "forcefield", "=", "None", ",", "strict", "=", "True", ",", "*", "*", "kwargs", ")", ":", "if", "strict", "and", "positions", "is", "None", ":", "raise", "ValueError", "(", "'Gromacs TOP files require initial positions.'", ")", "box", "=", "kwargs", ".", "pop", "(", "'box'", ",", "None", ")", "top", "=", "GromacsTopFile", "(", "path", ",", "includeDir", "=", "forcefield", ",", "periodicBoxVectors", "=", "box", ")", "return", "cls", "(", "master", "=", "top", ",", "topology", "=", "top", ".", "topology", ",", "positions", "=", "positions", ",", "box", "=", "box", ",", "path", "=", "path", ",", "*", "*", "kwargs", ")" ]
Loads a topology from a Gromacs TOP file located at `path`. Additional root directory for parameters can be specified with `forcefield`. Arguments --------- path : str Path to a Gromacs TOP file positions : simtk.unit.Quantity Atomic positions forcefield : str, optional Root directory for parameter files
[ "Loads", "a", "topology", "from", "a", "Gromacs", "TOP", "file", "located", "at", "path", "." ]
train
https://github.com/insilichem/ommprotocol/blob/7283fddba7203e5ac3542fdab41fc1279d3b444e/ommprotocol/io.py#L327-L347
insilichem/ommprotocol
ommprotocol/io.py
SystemHandler.from_parmed
def from_parmed(cls, path, *args, **kwargs): """ Try to load a file automatically with ParmEd. Not guaranteed to work, but might be useful if it succeeds. Arguments --------- path : str Path to file that ParmEd can load """ st = parmed.load_file(path, structure=True, *args, **kwargs) box = kwargs.pop('box', getattr(st, 'box', None)) velocities = kwargs.pop('velocities', getattr(st, 'velocities', None)) positions = kwargs.pop('positions', getattr(st, 'positions', None)) return cls(master=st, topology=st.topology, positions=positions, box=box, velocities=velocities, path=path, **kwargs)
python
def from_parmed(cls, path, *args, **kwargs): """ Try to load a file automatically with ParmEd. Not guaranteed to work, but might be useful if it succeeds. Arguments --------- path : str Path to file that ParmEd can load """ st = parmed.load_file(path, structure=True, *args, **kwargs) box = kwargs.pop('box', getattr(st, 'box', None)) velocities = kwargs.pop('velocities', getattr(st, 'velocities', None)) positions = kwargs.pop('positions', getattr(st, 'positions', None)) return cls(master=st, topology=st.topology, positions=positions, box=box, velocities=velocities, path=path, **kwargs)
[ "def", "from_parmed", "(", "cls", ",", "path", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "st", "=", "parmed", ".", "load_file", "(", "path", ",", "structure", "=", "True", ",", "*", "args", ",", "*", "*", "kwargs", ")", "box", "=", "kwargs", ".", "pop", "(", "'box'", ",", "getattr", "(", "st", ",", "'box'", ",", "None", ")", ")", "velocities", "=", "kwargs", ".", "pop", "(", "'velocities'", ",", "getattr", "(", "st", ",", "'velocities'", ",", "None", ")", ")", "positions", "=", "kwargs", ".", "pop", "(", "'positions'", ",", "getattr", "(", "st", ",", "'positions'", ",", "None", ")", ")", "return", "cls", "(", "master", "=", "st", ",", "topology", "=", "st", ".", "topology", ",", "positions", "=", "positions", ",", "box", "=", "box", ",", "velocities", "=", "velocities", ",", "path", "=", "path", ",", "*", "*", "kwargs", ")" ]
Try to load a file automatically with ParmEd. Not guaranteed to work, but might be useful if it succeeds. Arguments --------- path : str Path to file that ParmEd can load
[ "Try", "to", "load", "a", "file", "automatically", "with", "ParmEd", ".", "Not", "guaranteed", "to", "work", "but", "might", "be", "useful", "if", "it", "succeeds", "." ]
train
https://github.com/insilichem/ommprotocol/blob/7283fddba7203e5ac3542fdab41fc1279d3b444e/ommprotocol/io.py#L350-L365
insilichem/ommprotocol
ommprotocol/io.py
SystemHandler._pickle_load
def _pickle_load(path): """ Loads pickled topology. Careful with Python versions though! """ _, ext = os.path.splitext(path) topology = None if sys.version_info.major == 2: if ext == '.pickle2': with open(path, 'rb') as f: topology = pickle.load(f) elif ext in ('.pickle3', '.pickle'): with open(path, 'rb') as f: topology = pickle.load(f, protocol=3) elif sys.version_info.major == 3: if ext == '.pickle2': with open(path, 'rb') as f: topology = pickle.load(f) elif ext in ('.pickle3', '.pickle'): with open(path, 'rb') as f: topology = pickle.load(f) if topology is None: raise ValueError('File {} is not compatible with this version'.format(path)) return topology
python
def _pickle_load(path): """ Loads pickled topology. Careful with Python versions though! """ _, ext = os.path.splitext(path) topology = None if sys.version_info.major == 2: if ext == '.pickle2': with open(path, 'rb') as f: topology = pickle.load(f) elif ext in ('.pickle3', '.pickle'): with open(path, 'rb') as f: topology = pickle.load(f, protocol=3) elif sys.version_info.major == 3: if ext == '.pickle2': with open(path, 'rb') as f: topology = pickle.load(f) elif ext in ('.pickle3', '.pickle'): with open(path, 'rb') as f: topology = pickle.load(f) if topology is None: raise ValueError('File {} is not compatible with this version'.format(path)) return topology
[ "def", "_pickle_load", "(", "path", ")", ":", "_", ",", "ext", "=", "os", ".", "path", ".", "splitext", "(", "path", ")", "topology", "=", "None", "if", "sys", ".", "version_info", ".", "major", "==", "2", ":", "if", "ext", "==", "'.pickle2'", ":", "with", "open", "(", "path", ",", "'rb'", ")", "as", "f", ":", "topology", "=", "pickle", ".", "load", "(", "f", ")", "elif", "ext", "in", "(", "'.pickle3'", ",", "'.pickle'", ")", ":", "with", "open", "(", "path", ",", "'rb'", ")", "as", "f", ":", "topology", "=", "pickle", ".", "load", "(", "f", ",", "protocol", "=", "3", ")", "elif", "sys", ".", "version_info", ".", "major", "==", "3", ":", "if", "ext", "==", "'.pickle2'", ":", "with", "open", "(", "path", ",", "'rb'", ")", "as", "f", ":", "topology", "=", "pickle", ".", "load", "(", "f", ")", "elif", "ext", "in", "(", "'.pickle3'", ",", "'.pickle'", ")", ":", "with", "open", "(", "path", ",", "'rb'", ")", "as", "f", ":", "topology", "=", "pickle", ".", "load", "(", "f", ")", "if", "topology", "is", "None", ":", "raise", "ValueError", "(", "'File {} is not compatible with this version'", ".", "format", "(", "path", ")", ")", "return", "topology" ]
Loads pickled topology. Careful with Python versions though!
[ "Loads", "pickled", "topology", ".", "Careful", "with", "Python", "versions", "though!" ]
train
https://github.com/insilichem/ommprotocol/blob/7283fddba7203e5ac3542fdab41fc1279d3b444e/ommprotocol/io.py#L380-L402
insilichem/ommprotocol
ommprotocol/io.py
SystemHandler.create_system
def create_system(self, **system_options): """ Create an OpenMM system for every supported topology file with given system options """ if self.master is None: raise ValueError('Handler {} is not able to create systems.'.format(self)) if isinstance(self.master, ForceField): system = self.master.createSystem(self.topology, **system_options) elif isinstance(self.master, (AmberPrmtopFile, GromacsTopFile, DesmondDMSFile)): system = self.master.createSystem(**system_options) elif isinstance(self.master, CharmmPsfFile): if not hasattr(self.master, 'parmset'): raise ValueError('PSF topology files require Charmm parameters.') system = self.master.createSystem(self.master.parmset, **system_options) else: raise NotImplementedError('Handler {} is not able to create systems.'.format(self)) if self.has_box: system.setDefaultPeriodicBoxVectors(*self.box) return system
python
def create_system(self, **system_options): """ Create an OpenMM system for every supported topology file with given system options """ if self.master is None: raise ValueError('Handler {} is not able to create systems.'.format(self)) if isinstance(self.master, ForceField): system = self.master.createSystem(self.topology, **system_options) elif isinstance(self.master, (AmberPrmtopFile, GromacsTopFile, DesmondDMSFile)): system = self.master.createSystem(**system_options) elif isinstance(self.master, CharmmPsfFile): if not hasattr(self.master, 'parmset'): raise ValueError('PSF topology files require Charmm parameters.') system = self.master.createSystem(self.master.parmset, **system_options) else: raise NotImplementedError('Handler {} is not able to create systems.'.format(self)) if self.has_box: system.setDefaultPeriodicBoxVectors(*self.box) return system
[ "def", "create_system", "(", "self", ",", "*", "*", "system_options", ")", ":", "if", "self", ".", "master", "is", "None", ":", "raise", "ValueError", "(", "'Handler {} is not able to create systems.'", ".", "format", "(", "self", ")", ")", "if", "isinstance", "(", "self", ".", "master", ",", "ForceField", ")", ":", "system", "=", "self", ".", "master", ".", "createSystem", "(", "self", ".", "topology", ",", "*", "*", "system_options", ")", "elif", "isinstance", "(", "self", ".", "master", ",", "(", "AmberPrmtopFile", ",", "GromacsTopFile", ",", "DesmondDMSFile", ")", ")", ":", "system", "=", "self", ".", "master", ".", "createSystem", "(", "*", "*", "system_options", ")", "elif", "isinstance", "(", "self", ".", "master", ",", "CharmmPsfFile", ")", ":", "if", "not", "hasattr", "(", "self", ".", "master", ",", "'parmset'", ")", ":", "raise", "ValueError", "(", "'PSF topology files require Charmm parameters.'", ")", "system", "=", "self", ".", "master", ".", "createSystem", "(", "self", ".", "master", ".", "parmset", ",", "*", "*", "system_options", ")", "else", ":", "raise", "NotImplementedError", "(", "'Handler {} is not able to create systems.'", ".", "format", "(", "self", ")", ")", "if", "self", ".", "has_box", ":", "system", ".", "setDefaultPeriodicBoxVectors", "(", "*", "self", ".", "box", ")", "return", "system" ]
Create an OpenMM system for every supported topology file with given system options
[ "Create", "an", "OpenMM", "system", "for", "every", "supported", "topology", "file", "with", "given", "system", "options" ]
train
https://github.com/insilichem/ommprotocol/blob/7283fddba7203e5ac3542fdab41fc1279d3b444e/ommprotocol/io.py#L412-L432
insilichem/ommprotocol
ommprotocol/io.py
SystemHandler.write_pdb
def write_pdb(self, path): """ Outputs a PDB file with the current contents of the system """ if self.master is None and self.positions is None: raise ValueError('Topology and positions are needed to write output files.') with open(path, 'w') as f: PDBFile.writeFile(self.topology, self.positions, f)
python
def write_pdb(self, path): """ Outputs a PDB file with the current contents of the system """ if self.master is None and self.positions is None: raise ValueError('Topology and positions are needed to write output files.') with open(path, 'w') as f: PDBFile.writeFile(self.topology, self.positions, f)
[ "def", "write_pdb", "(", "self", ",", "path", ")", ":", "if", "self", ".", "master", "is", "None", "and", "self", ".", "positions", "is", "None", ":", "raise", "ValueError", "(", "'Topology and positions are needed to write output files.'", ")", "with", "open", "(", "path", ",", "'w'", ")", "as", "f", ":", "PDBFile", ".", "writeFile", "(", "self", ".", "topology", ",", "self", ".", "positions", ",", "f", ")" ]
Outputs a PDB file with the current contents of the system
[ "Outputs", "a", "PDB", "file", "with", "the", "current", "contents", "of", "the", "system" ]
train
https://github.com/insilichem/ommprotocol/blob/7283fddba7203e5ac3542fdab41fc1279d3b444e/ommprotocol/io.py#L434-L441
insilichem/ommprotocol
ommprotocol/io.py
BoxVectors.from_xsc
def from_xsc(cls, path): """ Returns u.Quantity with box vectors from XSC file """ def parse(path): """ Open and parses an XSC file into its fields Parameters ---------- path : str Path to XSC file Returns ------- namedxsc : namedtuple A namedtuple with XSC fields as names """ with open(path) as f: lines = f.readlines() NamedXsc = namedtuple('NamedXsc', lines[1].split()[1:]) return NamedXsc(*map(float, lines[2].split())) xsc = parse(path) return u.Quantity([[xsc.a_x, xsc.a_y, xsc.a_z], [xsc.b_x, xsc.b_y, xsc.b_z], [xsc.c_x, xsc.c_y, xsc.c_z]], unit=u.angstroms)
python
def from_xsc(cls, path): """ Returns u.Quantity with box vectors from XSC file """ def parse(path): """ Open and parses an XSC file into its fields Parameters ---------- path : str Path to XSC file Returns ------- namedxsc : namedtuple A namedtuple with XSC fields as names """ with open(path) as f: lines = f.readlines() NamedXsc = namedtuple('NamedXsc', lines[1].split()[1:]) return NamedXsc(*map(float, lines[2].split())) xsc = parse(path) return u.Quantity([[xsc.a_x, xsc.a_y, xsc.a_z], [xsc.b_x, xsc.b_y, xsc.b_z], [xsc.c_x, xsc.c_y, xsc.c_z]], unit=u.angstroms)
[ "def", "from_xsc", "(", "cls", ",", "path", ")", ":", "def", "parse", "(", "path", ")", ":", "\"\"\"\n Open and parses an XSC file into its fields\n\n Parameters\n ----------\n path : str\n Path to XSC file\n\n Returns\n -------\n namedxsc : namedtuple\n A namedtuple with XSC fields as names\n \"\"\"", "with", "open", "(", "path", ")", "as", "f", ":", "lines", "=", "f", ".", "readlines", "(", ")", "NamedXsc", "=", "namedtuple", "(", "'NamedXsc'", ",", "lines", "[", "1", "]", ".", "split", "(", ")", "[", "1", ":", "]", ")", "return", "NamedXsc", "(", "*", "map", "(", "float", ",", "lines", "[", "2", "]", ".", "split", "(", ")", ")", ")", "xsc", "=", "parse", "(", "path", ")", "return", "u", ".", "Quantity", "(", "[", "[", "xsc", ".", "a_x", ",", "xsc", ".", "a_y", ",", "xsc", ".", "a_z", "]", ",", "[", "xsc", ".", "b_x", ",", "xsc", ".", "b_y", ",", "xsc", ".", "b_z", "]", ",", "[", "xsc", ".", "c_x", ",", "xsc", ".", "c_y", ",", "xsc", ".", "c_z", "]", "]", ",", "unit", "=", "u", ".", "angstroms", ")" ]
Returns u.Quantity with box vectors from XSC file
[ "Returns", "u", ".", "Quantity", "with", "box", "vectors", "from", "XSC", "file" ]
train
https://github.com/insilichem/ommprotocol/blob/7283fddba7203e5ac3542fdab41fc1279d3b444e/ommprotocol/io.py#L554-L579
insilichem/ommprotocol
ommprotocol/io.py
BoxVectors.from_csv
def from_csv(cls, path): """ Get box vectors from comma-separated values in file `path`. The csv file must containt only one line, which in turn can contain three values (orthogonal vectors) or nine values (triclinic box). The values should be in nanometers. Parameters ---------- path : str Path to CSV file Returns ------- vectors : simtk.unit.Quantity([3, 3], unit=nanometers """ with open(path) as f: fields = map(float, next(f).split(',')) if len(fields) == 3: return u.Quantity([[fields[0], 0, 0], [0, fields[1], 0], [0, 0, fields[2]]], unit=u.nanometers) elif len(fields) == 9: return u.Quantity([fields[0:3], fields[3:6], fields[6:9]], unit=u.nanometers) else: raise ValueError('This type of CSV is not supported. Please ' 'provide a comma-separated list of three or nine ' 'floats in a single-line file.')
python
def from_csv(cls, path): """ Get box vectors from comma-separated values in file `path`. The csv file must containt only one line, which in turn can contain three values (orthogonal vectors) or nine values (triclinic box). The values should be in nanometers. Parameters ---------- path : str Path to CSV file Returns ------- vectors : simtk.unit.Quantity([3, 3], unit=nanometers """ with open(path) as f: fields = map(float, next(f).split(',')) if len(fields) == 3: return u.Quantity([[fields[0], 0, 0], [0, fields[1], 0], [0, 0, fields[2]]], unit=u.nanometers) elif len(fields) == 9: return u.Quantity([fields[0:3], fields[3:6], fields[6:9]], unit=u.nanometers) else: raise ValueError('This type of CSV is not supported. Please ' 'provide a comma-separated list of three or nine ' 'floats in a single-line file.')
[ "def", "from_csv", "(", "cls", ",", "path", ")", ":", "with", "open", "(", "path", ")", "as", "f", ":", "fields", "=", "map", "(", "float", ",", "next", "(", "f", ")", ".", "split", "(", "','", ")", ")", "if", "len", "(", "fields", ")", "==", "3", ":", "return", "u", ".", "Quantity", "(", "[", "[", "fields", "[", "0", "]", ",", "0", ",", "0", "]", ",", "[", "0", ",", "fields", "[", "1", "]", ",", "0", "]", ",", "[", "0", ",", "0", ",", "fields", "[", "2", "]", "]", "]", ",", "unit", "=", "u", ".", "nanometers", ")", "elif", "len", "(", "fields", ")", "==", "9", ":", "return", "u", ".", "Quantity", "(", "[", "fields", "[", "0", ":", "3", "]", ",", "fields", "[", "3", ":", "6", "]", ",", "fields", "[", "6", ":", "9", "]", "]", ",", "unit", "=", "u", ".", "nanometers", ")", "else", ":", "raise", "ValueError", "(", "'This type of CSV is not supported. Please '", "'provide a comma-separated list of three or nine '", "'floats in a single-line file.'", ")" ]
Get box vectors from comma-separated values in file `path`. The csv file must containt only one line, which in turn can contain three values (orthogonal vectors) or nine values (triclinic box). The values should be in nanometers. Parameters ---------- path : str Path to CSV file Returns ------- vectors : simtk.unit.Quantity([3, 3], unit=nanometers
[ "Get", "box", "vectors", "from", "comma", "-", "separated", "values", "in", "file", "path", "." ]
train
https://github.com/insilichem/ommprotocol/blob/7283fddba7203e5ac3542fdab41fc1279d3b444e/ommprotocol/io.py#L582-L613
insilichem/ommprotocol
ommprotocol/io.py
ProgressBarReporter.describeNextReport
def describeNextReport(self, simulation): """Get information about the next report this object will generate. Parameters ---------- simulation : Simulation The Simulation to generate a report for Returns ------- tuple A five element tuple. The first element is the number of steps until the next report. The remaining elements specify whether that report will require positions, velocities, forces, and energies respectively. """ steps = self.interval - simulation.currentStep % self.interval return steps, False, False, False, False
python
def describeNextReport(self, simulation): """Get information about the next report this object will generate. Parameters ---------- simulation : Simulation The Simulation to generate a report for Returns ------- tuple A five element tuple. The first element is the number of steps until the next report. The remaining elements specify whether that report will require positions, velocities, forces, and energies respectively. """ steps = self.interval - simulation.currentStep % self.interval return steps, False, False, False, False
[ "def", "describeNextReport", "(", "self", ",", "simulation", ")", ":", "steps", "=", "self", ".", "interval", "-", "simulation", ".", "currentStep", "%", "self", ".", "interval", "return", "steps", ",", "False", ",", "False", ",", "False", ",", "False" ]
Get information about the next report this object will generate. Parameters ---------- simulation : Simulation The Simulation to generate a report for Returns ------- tuple A five element tuple. The first element is the number of steps until the next report. The remaining elements specify whether that report will require positions, velocities, forces, and energies respectively.
[ "Get", "information", "about", "the", "next", "report", "this", "object", "will", "generate", "." ]
train
https://github.com/insilichem/ommprotocol/blob/7283fddba7203e5ac3542fdab41fc1279d3b444e/ommprotocol/io.py#L720-L737
insilichem/ommprotocol
ommprotocol/io.py
ProgressBarReporter.report
def report(self, simulation, state): """Generate a report. Parameters ---------- simulation : Simulation The Simulation to generate a report for state : State The current state of the simulation """ if not self._initialized: self._initial_clock_time = datetime.now() self._initial_simulation_time = state.getTime() self._initial_steps = simulation.currentStep self._initialized = True steps = simulation.currentStep time = datetime.now() - self._initial_clock_time days = time.total_seconds()/86400.0 ns = (state.getTime()-self._initial_simulation_time).value_in_unit(u.nanosecond) margin = ' ' * self.margin ns_day = ns/days delta = ((self.total_steps-steps)*time.total_seconds())/steps # remove microseconds to have cleaner output remaining = timedelta(seconds=int(delta)) percentage = 100.0*steps/self.total_steps if ns_day: template = '{}{}/{} steps ({:.1f}%) - {} left @ {:.1f} ns/day \r' else: template = '{}{}/{} steps ({:.1f}%) \r' report = template.format(margin, steps, self.total_steps, percentage, remaining, ns_day) self._out.write(report) if hasattr(self._out, 'flush'): self._out.flush()
python
def report(self, simulation, state): """Generate a report. Parameters ---------- simulation : Simulation The Simulation to generate a report for state : State The current state of the simulation """ if not self._initialized: self._initial_clock_time = datetime.now() self._initial_simulation_time = state.getTime() self._initial_steps = simulation.currentStep self._initialized = True steps = simulation.currentStep time = datetime.now() - self._initial_clock_time days = time.total_seconds()/86400.0 ns = (state.getTime()-self._initial_simulation_time).value_in_unit(u.nanosecond) margin = ' ' * self.margin ns_day = ns/days delta = ((self.total_steps-steps)*time.total_seconds())/steps # remove microseconds to have cleaner output remaining = timedelta(seconds=int(delta)) percentage = 100.0*steps/self.total_steps if ns_day: template = '{}{}/{} steps ({:.1f}%) - {} left @ {:.1f} ns/day \r' else: template = '{}{}/{} steps ({:.1f}%) \r' report = template.format(margin, steps, self.total_steps, percentage, remaining, ns_day) self._out.write(report) if hasattr(self._out, 'flush'): self._out.flush()
[ "def", "report", "(", "self", ",", "simulation", ",", "state", ")", ":", "if", "not", "self", ".", "_initialized", ":", "self", ".", "_initial_clock_time", "=", "datetime", ".", "now", "(", ")", "self", ".", "_initial_simulation_time", "=", "state", ".", "getTime", "(", ")", "self", ".", "_initial_steps", "=", "simulation", ".", "currentStep", "self", ".", "_initialized", "=", "True", "steps", "=", "simulation", ".", "currentStep", "time", "=", "datetime", ".", "now", "(", ")", "-", "self", ".", "_initial_clock_time", "days", "=", "time", ".", "total_seconds", "(", ")", "/", "86400.0", "ns", "=", "(", "state", ".", "getTime", "(", ")", "-", "self", ".", "_initial_simulation_time", ")", ".", "value_in_unit", "(", "u", ".", "nanosecond", ")", "margin", "=", "' '", "*", "self", ".", "margin", "ns_day", "=", "ns", "/", "days", "delta", "=", "(", "(", "self", ".", "total_steps", "-", "steps", ")", "*", "time", ".", "total_seconds", "(", ")", ")", "/", "steps", "# remove microseconds to have cleaner output", "remaining", "=", "timedelta", "(", "seconds", "=", "int", "(", "delta", ")", ")", "percentage", "=", "100.0", "*", "steps", "/", "self", ".", "total_steps", "if", "ns_day", ":", "template", "=", "'{}{}/{} steps ({:.1f}%) - {} left @ {:.1f} ns/day \\r'", "else", ":", "template", "=", "'{}{}/{} steps ({:.1f}%) \\r'", "report", "=", "template", ".", "format", "(", "margin", ",", "steps", ",", "self", ".", "total_steps", ",", "percentage", ",", "remaining", ",", "ns_day", ")", "self", ".", "_out", ".", "write", "(", "report", ")", "if", "hasattr", "(", "self", ".", "_out", ",", "'flush'", ")", ":", "self", ".", "_out", ".", "flush", "(", ")" ]
Generate a report. Parameters ---------- simulation : Simulation The Simulation to generate a report for state : State The current state of the simulation
[ "Generate", "a", "report", "." ]
train
https://github.com/insilichem/ommprotocol/blob/7283fddba7203e5ac3542fdab41fc1279d3b444e/ommprotocol/io.py#L739-L773
insilichem/ommprotocol
ommprotocol/io.py
SerializedReporter.report
def report(self, simulation, state): """Generate a report. Parameters ---------- simulation : Simulation The Simulation to generate a report for state : State The current state of the simulation """ if not self._initialized: self._initialized = True self._steps[0] += self.interval positions = state.getPositions() # Serialize self._out.write(b''.join([b'\nSTARTOFCHUNK\n', pickle.dumps([self._steps[0], positions._value]), b'\nENDOFCHUNK\n'])) if hasattr(self._out, 'flush'): self._out.flush()
python
def report(self, simulation, state): """Generate a report. Parameters ---------- simulation : Simulation The Simulation to generate a report for state : State The current state of the simulation """ if not self._initialized: self._initialized = True self._steps[0] += self.interval positions = state.getPositions() # Serialize self._out.write(b''.join([b'\nSTARTOFCHUNK\n', pickle.dumps([self._steps[0], positions._value]), b'\nENDOFCHUNK\n'])) if hasattr(self._out, 'flush'): self._out.flush()
[ "def", "report", "(", "self", ",", "simulation", ",", "state", ")", ":", "if", "not", "self", ".", "_initialized", ":", "self", ".", "_initialized", "=", "True", "self", ".", "_steps", "[", "0", "]", "+=", "self", ".", "interval", "positions", "=", "state", ".", "getPositions", "(", ")", "# Serialize", "self", ".", "_out", ".", "write", "(", "b''", ".", "join", "(", "[", "b'\\nSTARTOFCHUNK\\n'", ",", "pickle", ".", "dumps", "(", "[", "self", ".", "_steps", "[", "0", "]", ",", "positions", ".", "_value", "]", ")", ",", "b'\\nENDOFCHUNK\\n'", "]", ")", ")", "if", "hasattr", "(", "self", ".", "_out", ",", "'flush'", ")", ":", "self", ".", "_out", ".", "flush", "(", ")" ]
Generate a report. Parameters ---------- simulation : Simulation The Simulation to generate a report for state : State The current state of the simulation
[ "Generate", "a", "report", "." ]
train
https://github.com/insilichem/ommprotocol/blob/7283fddba7203e5ac3542fdab41fc1279d3b444e/ommprotocol/io.py#L827-L848
insilichem/ommprotocol
ommprotocol/utils.py
assert_not_exists
def assert_not_exists(path, sep='.'): """ If path exists, modify to add a counter in the filename. Useful for preventing accidental overrides. For example, if `file.txt` exists, check if `file.1.txt` also exists. Repeat until we find a non-existing version, such as `file.12.txt`. Parameters ---------- path : str Path to be checked Returns ------- newpath : str A modified version of path with a counter right before the extension. """ name, ext = os.path.splitext(path) i = 1 while os.path.exists(path): path = '{}{}{}{}'.format(name, sep, i, ext) i += 1 return path
python
def assert_not_exists(path, sep='.'): """ If path exists, modify to add a counter in the filename. Useful for preventing accidental overrides. For example, if `file.txt` exists, check if `file.1.txt` also exists. Repeat until we find a non-existing version, such as `file.12.txt`. Parameters ---------- path : str Path to be checked Returns ------- newpath : str A modified version of path with a counter right before the extension. """ name, ext = os.path.splitext(path) i = 1 while os.path.exists(path): path = '{}{}{}{}'.format(name, sep, i, ext) i += 1 return path
[ "def", "assert_not_exists", "(", "path", ",", "sep", "=", "'.'", ")", ":", "name", ",", "ext", "=", "os", ".", "path", ".", "splitext", "(", "path", ")", "i", "=", "1", "while", "os", ".", "path", ".", "exists", "(", "path", ")", ":", "path", "=", "'{}{}{}{}'", ".", "format", "(", "name", ",", "sep", ",", "i", ",", "ext", ")", "i", "+=", "1", "return", "path" ]
If path exists, modify to add a counter in the filename. Useful for preventing accidental overrides. For example, if `file.txt` exists, check if `file.1.txt` also exists. Repeat until we find a non-existing version, such as `file.12.txt`. Parameters ---------- path : str Path to be checked Returns ------- newpath : str A modified version of path with a counter right before the extension.
[ "If", "path", "exists", "modify", "to", "add", "a", "counter", "in", "the", "filename", ".", "Useful", "for", "preventing", "accidental", "overrides", ".", "For", "example", "if", "file", ".", "txt", "exists", "check", "if", "file", ".", "1", ".", "txt", "also", "exists", ".", "Repeat", "until", "we", "find", "a", "non", "-", "existing", "version", "such", "as", "file", ".", "12", ".", "txt", "." ]
train
https://github.com/insilichem/ommprotocol/blob/7283fddba7203e5ac3542fdab41fc1279d3b444e/ommprotocol/utils.py#L34-L56
insilichem/ommprotocol
ommprotocol/utils.py
assertinstance
def assertinstance(obj, types): """ Make sure object `obj` is of type `types`. Else, raise TypeError. """ if isinstance(obj, types): return obj raise TypeError('{} must be instance of {}'.format(obj, types))
python
def assertinstance(obj, types): """ Make sure object `obj` is of type `types`. Else, raise TypeError. """ if isinstance(obj, types): return obj raise TypeError('{} must be instance of {}'.format(obj, types))
[ "def", "assertinstance", "(", "obj", ",", "types", ")", ":", "if", "isinstance", "(", "obj", ",", "types", ")", ":", "return", "obj", "raise", "TypeError", "(", "'{} must be instance of {}'", ".", "format", "(", "obj", ",", "types", ")", ")" ]
Make sure object `obj` is of type `types`. Else, raise TypeError.
[ "Make", "sure", "object", "obj", "is", "of", "type", "types", ".", "Else", "raise", "TypeError", "." ]
train
https://github.com/insilichem/ommprotocol/blob/7283fddba7203e5ac3542fdab41fc1279d3b444e/ommprotocol/utils.py#L59-L65
insilichem/ommprotocol
ommprotocol/utils.py
extant_file
def extant_file(path): """ Check if file exists with argparse """ if not os.path.exists(path): raise argparse.ArgumentTypeError("{} does not exist".format(path)) return path
python
def extant_file(path): """ Check if file exists with argparse """ if not os.path.exists(path): raise argparse.ArgumentTypeError("{} does not exist".format(path)) return path
[ "def", "extant_file", "(", "path", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "path", ")", ":", "raise", "argparse", ".", "ArgumentTypeError", "(", "\"{} does not exist\"", ".", "format", "(", "path", ")", ")", "return", "path" ]
Check if file exists with argparse
[ "Check", "if", "file", "exists", "with", "argparse" ]
train
https://github.com/insilichem/ommprotocol/blob/7283fddba7203e5ac3542fdab41fc1279d3b444e/ommprotocol/utils.py#L89-L95
insilichem/ommprotocol
ommprotocol/utils.py
sort_key_for_numeric_suffixes
def sort_key_for_numeric_suffixes(path, sep='.', suffix_index=-2): """ Sort files taking into account potentially absent suffixes like somefile.dcd somefile.1000.dcd somefile.2000.dcd To be used with sorted(..., key=callable). """ chunks = path.split(sep) # Remove suffix from path and convert to int if chunks[suffix_index].isdigit(): return sep.join(chunks[:suffix_index] + chunks[suffix_index+1:]), int(chunks[suffix_index]) return path, 0
python
def sort_key_for_numeric_suffixes(path, sep='.', suffix_index=-2): """ Sort files taking into account potentially absent suffixes like somefile.dcd somefile.1000.dcd somefile.2000.dcd To be used with sorted(..., key=callable). """ chunks = path.split(sep) # Remove suffix from path and convert to int if chunks[suffix_index].isdigit(): return sep.join(chunks[:suffix_index] + chunks[suffix_index+1:]), int(chunks[suffix_index]) return path, 0
[ "def", "sort_key_for_numeric_suffixes", "(", "path", ",", "sep", "=", "'.'", ",", "suffix_index", "=", "-", "2", ")", ":", "chunks", "=", "path", ".", "split", "(", "sep", ")", "# Remove suffix from path and convert to int", "if", "chunks", "[", "suffix_index", "]", ".", "isdigit", "(", ")", ":", "return", "sep", ".", "join", "(", "chunks", "[", ":", "suffix_index", "]", "+", "chunks", "[", "suffix_index", "+", "1", ":", "]", ")", ",", "int", "(", "chunks", "[", "suffix_index", "]", ")", "return", "path", ",", "0" ]
Sort files taking into account potentially absent suffixes like somefile.dcd somefile.1000.dcd somefile.2000.dcd To be used with sorted(..., key=callable).
[ "Sort", "files", "taking", "into", "account", "potentially", "absent", "suffixes", "like", "somefile", ".", "dcd", "somefile", ".", "1000", ".", "dcd", "somefile", ".", "2000", ".", "dcd" ]
train
https://github.com/insilichem/ommprotocol/blob/7283fddba7203e5ac3542fdab41fc1279d3b444e/ommprotocol/utils.py#L123-L136
joestump/django-ajax
ajax/decorators.py
json_response
def json_response(f, *args, **kwargs): """Wrap a view in JSON. This decorator runs the given function and looks out for ajax.AJAXError's, which it encodes into a proper HttpResponse object. If an unknown error is thrown it's encoded as a 500. All errors are then packaged up with an appropriate Content-Type and a JSON body that you can inspect in JavaScript on the client. They look like: { "message": "Error message here.", "code": 500 } Please keep in mind that raw exception messages could very well be exposed to the client if a non-AJAXError is thrown. """ try: result = f(*args, **kwargs) if isinstance(result, AJAXError): raise result except AJAXError as e: result = e.get_response() request = args[0] logger.warn('AJAXError: %d %s - %s', e.code, request.path, e.msg, exc_info=True, extra={ 'status_code': e.code, 'request': request } ) except Http404 as e: result = AJAXError(404, e.__str__()).get_response() except Exception as e: import sys exc_info = sys.exc_info() type, message, trace = exc_info if settings.DEBUG: import traceback tb = [{'file': l[0], 'line': l[1], 'in': l[2], 'code': l[3]} for l in traceback.extract_tb(trace)] result = AJAXError(500, message, traceback=tb).get_response() else: result = AJAXError(500, "Internal server error.").get_response() request = args[0] logger.error('Internal Server Error: %s' % request.path, exc_info=exc_info, extra={ 'status_code': 500, 'request': request } ) result['Content-Type'] = 'application/json' return result
python
def json_response(f, *args, **kwargs): """Wrap a view in JSON. This decorator runs the given function and looks out for ajax.AJAXError's, which it encodes into a proper HttpResponse object. If an unknown error is thrown it's encoded as a 500. All errors are then packaged up with an appropriate Content-Type and a JSON body that you can inspect in JavaScript on the client. They look like: { "message": "Error message here.", "code": 500 } Please keep in mind that raw exception messages could very well be exposed to the client if a non-AJAXError is thrown. """ try: result = f(*args, **kwargs) if isinstance(result, AJAXError): raise result except AJAXError as e: result = e.get_response() request = args[0] logger.warn('AJAXError: %d %s - %s', e.code, request.path, e.msg, exc_info=True, extra={ 'status_code': e.code, 'request': request } ) except Http404 as e: result = AJAXError(404, e.__str__()).get_response() except Exception as e: import sys exc_info = sys.exc_info() type, message, trace = exc_info if settings.DEBUG: import traceback tb = [{'file': l[0], 'line': l[1], 'in': l[2], 'code': l[3]} for l in traceback.extract_tb(trace)] result = AJAXError(500, message, traceback=tb).get_response() else: result = AJAXError(500, "Internal server error.").get_response() request = args[0] logger.error('Internal Server Error: %s' % request.path, exc_info=exc_info, extra={ 'status_code': 500, 'request': request } ) result['Content-Type'] = 'application/json' return result
[ "def", "json_response", "(", "f", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "try", ":", "result", "=", "f", "(", "*", "args", ",", "*", "*", "kwargs", ")", "if", "isinstance", "(", "result", ",", "AJAXError", ")", ":", "raise", "result", "except", "AJAXError", "as", "e", ":", "result", "=", "e", ".", "get_response", "(", ")", "request", "=", "args", "[", "0", "]", "logger", ".", "warn", "(", "'AJAXError: %d %s - %s'", ",", "e", ".", "code", ",", "request", ".", "path", ",", "e", ".", "msg", ",", "exc_info", "=", "True", ",", "extra", "=", "{", "'status_code'", ":", "e", ".", "code", ",", "'request'", ":", "request", "}", ")", "except", "Http404", "as", "e", ":", "result", "=", "AJAXError", "(", "404", ",", "e", ".", "__str__", "(", ")", ")", ".", "get_response", "(", ")", "except", "Exception", "as", "e", ":", "import", "sys", "exc_info", "=", "sys", ".", "exc_info", "(", ")", "type", ",", "message", ",", "trace", "=", "exc_info", "if", "settings", ".", "DEBUG", ":", "import", "traceback", "tb", "=", "[", "{", "'file'", ":", "l", "[", "0", "]", ",", "'line'", ":", "l", "[", "1", "]", ",", "'in'", ":", "l", "[", "2", "]", ",", "'code'", ":", "l", "[", "3", "]", "}", "for", "l", "in", "traceback", ".", "extract_tb", "(", "trace", ")", "]", "result", "=", "AJAXError", "(", "500", ",", "message", ",", "traceback", "=", "tb", ")", ".", "get_response", "(", ")", "else", ":", "result", "=", "AJAXError", "(", "500", ",", "\"Internal server error.\"", ")", ".", "get_response", "(", ")", "request", "=", "args", "[", "0", "]", "logger", ".", "error", "(", "'Internal Server Error: %s'", "%", "request", ".", "path", ",", "exc_info", "=", "exc_info", ",", "extra", "=", "{", "'status_code'", ":", "500", ",", "'request'", ":", "request", "}", ")", "result", "[", "'Content-Type'", "]", "=", "'application/json'", "return", "result" ]
Wrap a view in JSON. This decorator runs the given function and looks out for ajax.AJAXError's, which it encodes into a proper HttpResponse object. If an unknown error is thrown it's encoded as a 500. All errors are then packaged up with an appropriate Content-Type and a JSON body that you can inspect in JavaScript on the client. They look like: { "message": "Error message here.", "code": 500 } Please keep in mind that raw exception messages could very well be exposed to the client if a non-AJAXError is thrown.
[ "Wrap", "a", "view", "in", "JSON", "." ]
train
https://github.com/joestump/django-ajax/blob/b71619d5c00d8e0bb990ddbea2c93cf303dc2c80/ajax/decorators.py#L43-L100
joestump/django-ajax
ajax/utils.py
import_by_path
def import_by_path(dotted_path, error_prefix=''): """ Import a dotted module path and return the attribute/class designated by the last name in the path. Raise ImproperlyConfigured if something goes wrong. This has come straight from Django 1.6 """ try: module_path, class_name = dotted_path.rsplit('.', 1) except ValueError: raise ImproperlyConfigured("%s%s doesn't look like a module path" % ( error_prefix, dotted_path)) try: module = import_module(module_path) except ImportError as e: raise ImproperlyConfigured('%sError importing module %s: "%s"' % ( error_prefix, module_path, e)) try: attr = getattr(module, class_name) except AttributeError: raise ImproperlyConfigured( '%sModule "%s" does not define a "%s" attribute/class' % ( error_prefix, module_path, class_name ) ) return attr
python
def import_by_path(dotted_path, error_prefix=''): """ Import a dotted module path and return the attribute/class designated by the last name in the path. Raise ImproperlyConfigured if something goes wrong. This has come straight from Django 1.6 """ try: module_path, class_name = dotted_path.rsplit('.', 1) except ValueError: raise ImproperlyConfigured("%s%s doesn't look like a module path" % ( error_prefix, dotted_path)) try: module = import_module(module_path) except ImportError as e: raise ImproperlyConfigured('%sError importing module %s: "%s"' % ( error_prefix, module_path, e)) try: attr = getattr(module, class_name) except AttributeError: raise ImproperlyConfigured( '%sModule "%s" does not define a "%s" attribute/class' % ( error_prefix, module_path, class_name ) ) return attr
[ "def", "import_by_path", "(", "dotted_path", ",", "error_prefix", "=", "''", ")", ":", "try", ":", "module_path", ",", "class_name", "=", "dotted_path", ".", "rsplit", "(", "'.'", ",", "1", ")", "except", "ValueError", ":", "raise", "ImproperlyConfigured", "(", "\"%s%s doesn't look like a module path\"", "%", "(", "error_prefix", ",", "dotted_path", ")", ")", "try", ":", "module", "=", "import_module", "(", "module_path", ")", "except", "ImportError", "as", "e", ":", "raise", "ImproperlyConfigured", "(", "'%sError importing module %s: \"%s\"'", "%", "(", "error_prefix", ",", "module_path", ",", "e", ")", ")", "try", ":", "attr", "=", "getattr", "(", "module", ",", "class_name", ")", "except", "AttributeError", ":", "raise", "ImproperlyConfigured", "(", "'%sModule \"%s\" does not define a \"%s\" attribute/class'", "%", "(", "error_prefix", ",", "module_path", ",", "class_name", ")", ")", "return", "attr" ]
Import a dotted module path and return the attribute/class designated by the last name in the path. Raise ImproperlyConfigured if something goes wrong. This has come straight from Django 1.6
[ "Import", "a", "dotted", "module", "path", "and", "return", "the", "attribute", "/", "class", "designated", "by", "the", "last", "name", "in", "the", "path", ".", "Raise", "ImproperlyConfigured", "if", "something", "goes", "wrong", ".", "This", "has", "come", "straight", "from", "Django", "1", ".", "6" ]
train
https://github.com/joestump/django-ajax/blob/b71619d5c00d8e0bb990ddbea2c93cf303dc2c80/ajax/utils.py#L8-L32
joestump/django-ajax
ajax/views.py
endpoint_loader
def endpoint_loader(request, application, model, **kwargs): """Load an AJAX endpoint. This will load either an ad-hoc endpoint or it will load up a model endpoint depending on what it finds. It first attempts to load ``model`` as if it were an ad-hoc endpoint. Alternatively, it will attempt to see if there is a ``ModelEndpoint`` for the given ``model``. """ if request.method != "POST": raise AJAXError(400, _('Invalid HTTP method used.')) try: module = import_module('%s.endpoints' % application) except ImportError as e: if settings.DEBUG: raise e else: raise AJAXError(404, _('AJAX endpoint does not exist.')) if hasattr(module, model): # This is an ad-hoc endpoint endpoint = getattr(module, model) else: # This is a model endpoint method = kwargs.get('method', 'create').lower() try: del kwargs['method'] except: pass try: model_endpoint = ajax.endpoint.load(model, application, method, **kwargs) if not model_endpoint.authenticate(request, application, method): raise AJAXError(403, _('User is not authorized.')) endpoint = getattr(model_endpoint, method, False) if not endpoint: raise AJAXError(404, _('Invalid method.')) except NotRegistered: raise AJAXError(500, _('Invalid model.')) data = endpoint(request) if isinstance(data, HttpResponse): return data if isinstance(data, EnvelopedResponse): envelope = data.metadata payload = data.data else: envelope = {} payload = data envelope.update({ 'success': True, 'data': payload, }) return HttpResponse(json.dumps(envelope, cls=DjangoJSONEncoder, separators=(',', ':')))
python
def endpoint_loader(request, application, model, **kwargs): """Load an AJAX endpoint. This will load either an ad-hoc endpoint or it will load up a model endpoint depending on what it finds. It first attempts to load ``model`` as if it were an ad-hoc endpoint. Alternatively, it will attempt to see if there is a ``ModelEndpoint`` for the given ``model``. """ if request.method != "POST": raise AJAXError(400, _('Invalid HTTP method used.')) try: module = import_module('%s.endpoints' % application) except ImportError as e: if settings.DEBUG: raise e else: raise AJAXError(404, _('AJAX endpoint does not exist.')) if hasattr(module, model): # This is an ad-hoc endpoint endpoint = getattr(module, model) else: # This is a model endpoint method = kwargs.get('method', 'create').lower() try: del kwargs['method'] except: pass try: model_endpoint = ajax.endpoint.load(model, application, method, **kwargs) if not model_endpoint.authenticate(request, application, method): raise AJAXError(403, _('User is not authorized.')) endpoint = getattr(model_endpoint, method, False) if not endpoint: raise AJAXError(404, _('Invalid method.')) except NotRegistered: raise AJAXError(500, _('Invalid model.')) data = endpoint(request) if isinstance(data, HttpResponse): return data if isinstance(data, EnvelopedResponse): envelope = data.metadata payload = data.data else: envelope = {} payload = data envelope.update({ 'success': True, 'data': payload, }) return HttpResponse(json.dumps(envelope, cls=DjangoJSONEncoder, separators=(',', ':')))
[ "def", "endpoint_loader", "(", "request", ",", "application", ",", "model", ",", "*", "*", "kwargs", ")", ":", "if", "request", ".", "method", "!=", "\"POST\"", ":", "raise", "AJAXError", "(", "400", ",", "_", "(", "'Invalid HTTP method used.'", ")", ")", "try", ":", "module", "=", "import_module", "(", "'%s.endpoints'", "%", "application", ")", "except", "ImportError", "as", "e", ":", "if", "settings", ".", "DEBUG", ":", "raise", "e", "else", ":", "raise", "AJAXError", "(", "404", ",", "_", "(", "'AJAX endpoint does not exist.'", ")", ")", "if", "hasattr", "(", "module", ",", "model", ")", ":", "# This is an ad-hoc endpoint", "endpoint", "=", "getattr", "(", "module", ",", "model", ")", "else", ":", "# This is a model endpoint", "method", "=", "kwargs", ".", "get", "(", "'method'", ",", "'create'", ")", ".", "lower", "(", ")", "try", ":", "del", "kwargs", "[", "'method'", "]", "except", ":", "pass", "try", ":", "model_endpoint", "=", "ajax", ".", "endpoint", ".", "load", "(", "model", ",", "application", ",", "method", ",", "*", "*", "kwargs", ")", "if", "not", "model_endpoint", ".", "authenticate", "(", "request", ",", "application", ",", "method", ")", ":", "raise", "AJAXError", "(", "403", ",", "_", "(", "'User is not authorized.'", ")", ")", "endpoint", "=", "getattr", "(", "model_endpoint", ",", "method", ",", "False", ")", "if", "not", "endpoint", ":", "raise", "AJAXError", "(", "404", ",", "_", "(", "'Invalid method.'", ")", ")", "except", "NotRegistered", ":", "raise", "AJAXError", "(", "500", ",", "_", "(", "'Invalid model.'", ")", ")", "data", "=", "endpoint", "(", "request", ")", "if", "isinstance", "(", "data", ",", "HttpResponse", ")", ":", "return", "data", "if", "isinstance", "(", "data", ",", "EnvelopedResponse", ")", ":", "envelope", "=", "data", ".", "metadata", "payload", "=", "data", ".", "data", "else", ":", "envelope", "=", "{", "}", "payload", "=", "data", "envelope", ".", "update", "(", "{", "'success'", ":", "True", ",", "'data'", ":", "payload", ",", "}", ")", "return", "HttpResponse", "(", "json", ".", "dumps", "(", "envelope", ",", "cls", "=", "DjangoJSONEncoder", ",", "separators", "=", "(", "','", ",", "':'", ")", ")", ")" ]
Load an AJAX endpoint. This will load either an ad-hoc endpoint or it will load up a model endpoint depending on what it finds. It first attempts to load ``model`` as if it were an ad-hoc endpoint. Alternatively, it will attempt to see if there is a ``ModelEndpoint`` for the given ``model``.
[ "Load", "an", "AJAX", "endpoint", "." ]
train
https://github.com/joestump/django-ajax/blob/b71619d5c00d8e0bb990ddbea2c93cf303dc2c80/ajax/views.py#L32-L92
joestump/django-ajax
ajax/endpoints.py
ModelEndpoint.list
def list(self, request): """ List objects of a model. By default will show page 1 with 20 objects on it. **Usage**:: params = {"items_per_page":10,"page":2} //all params are optional $.post("/ajax/{app}/{model}/list.json"),params) """ max_items_per_page = getattr(self, 'max_per_page', getattr(settings, 'AJAX_MAX_PER_PAGE', 100)) requested_items_per_page = request.POST.get("items_per_page", 20) items_per_page = min(max_items_per_page, requested_items_per_page) current_page = request.POST.get("current_page", 1) if not self.can_list(request.user): raise AJAXError(403, _("Access to this endpoint is forbidden")) objects = self.get_queryset(request) paginator = Paginator(objects, items_per_page) try: page = paginator.page(current_page) except PageNotAnInteger: # If page is not an integer, deliver first page. page = paginator.page(1) except EmptyPage: # If page is out of range (e.g. 9999), return empty list. page = EmptyPageResult() data = [encoder.encode(record) for record in page.object_list] return EnvelopedResponse(data=data, metadata={'total': paginator.count})
python
def list(self, request): """ List objects of a model. By default will show page 1 with 20 objects on it. **Usage**:: params = {"items_per_page":10,"page":2} //all params are optional $.post("/ajax/{app}/{model}/list.json"),params) """ max_items_per_page = getattr(self, 'max_per_page', getattr(settings, 'AJAX_MAX_PER_PAGE', 100)) requested_items_per_page = request.POST.get("items_per_page", 20) items_per_page = min(max_items_per_page, requested_items_per_page) current_page = request.POST.get("current_page", 1) if not self.can_list(request.user): raise AJAXError(403, _("Access to this endpoint is forbidden")) objects = self.get_queryset(request) paginator = Paginator(objects, items_per_page) try: page = paginator.page(current_page) except PageNotAnInteger: # If page is not an integer, deliver first page. page = paginator.page(1) except EmptyPage: # If page is out of range (e.g. 9999), return empty list. page = EmptyPageResult() data = [encoder.encode(record) for record in page.object_list] return EnvelopedResponse(data=data, metadata={'total': paginator.count})
[ "def", "list", "(", "self", ",", "request", ")", ":", "max_items_per_page", "=", "getattr", "(", "self", ",", "'max_per_page'", ",", "getattr", "(", "settings", ",", "'AJAX_MAX_PER_PAGE'", ",", "100", ")", ")", "requested_items_per_page", "=", "request", ".", "POST", ".", "get", "(", "\"items_per_page\"", ",", "20", ")", "items_per_page", "=", "min", "(", "max_items_per_page", ",", "requested_items_per_page", ")", "current_page", "=", "request", ".", "POST", ".", "get", "(", "\"current_page\"", ",", "1", ")", "if", "not", "self", ".", "can_list", "(", "request", ".", "user", ")", ":", "raise", "AJAXError", "(", "403", ",", "_", "(", "\"Access to this endpoint is forbidden\"", ")", ")", "objects", "=", "self", ".", "get_queryset", "(", "request", ")", "paginator", "=", "Paginator", "(", "objects", ",", "items_per_page", ")", "try", ":", "page", "=", "paginator", ".", "page", "(", "current_page", ")", "except", "PageNotAnInteger", ":", "# If page is not an integer, deliver first page.", "page", "=", "paginator", ".", "page", "(", "1", ")", "except", "EmptyPage", ":", "# If page is out of range (e.g. 9999), return empty list.", "page", "=", "EmptyPageResult", "(", ")", "data", "=", "[", "encoder", ".", "encode", "(", "record", ")", "for", "record", "in", "page", ".", "object_list", "]", "return", "EnvelopedResponse", "(", "data", "=", "data", ",", "metadata", "=", "{", "'total'", ":", "paginator", ".", "count", "}", ")" ]
List objects of a model. By default will show page 1 with 20 objects on it. **Usage**:: params = {"items_per_page":10,"page":2} //all params are optional $.post("/ajax/{app}/{model}/list.json"),params)
[ "List", "objects", "of", "a", "model", ".", "By", "default", "will", "show", "page", "1", "with", "20", "objects", "on", "it", "." ]
train
https://github.com/joestump/django-ajax/blob/b71619d5c00d8e0bb990ddbea2c93cf303dc2c80/ajax/endpoints.py#L84-L118
joestump/django-ajax
ajax/endpoints.py
ModelEndpoint._extract_data
def _extract_data(self, request): """Extract data from POST. Handles extracting a vanilla Python dict of values that are present in the given model. This also handles instances of ``ForeignKey`` and will convert those to the appropriate object instances from the database. In other words, it will see that user is a ``ForeignKey`` to Django's ``User`` class, assume the value is an appropriate pk, and load up that record. """ data = {} for field, val in six.iteritems(request.POST): if field in self.immutable_fields: continue # Ignore immutable fields silently. if field in self.fields: field_obj = self.model._meta.get_field(field) val = self._extract_value(val) if isinstance(field_obj, models.ForeignKey): if field_obj.null and not val: clean_value = None else: clean_value = field_obj.rel.to.objects.get(pk=val) else: clean_value = field_obj.to_python(val) data[smart_str(field)] = clean_value return data
python
def _extract_data(self, request): """Extract data from POST. Handles extracting a vanilla Python dict of values that are present in the given model. This also handles instances of ``ForeignKey`` and will convert those to the appropriate object instances from the database. In other words, it will see that user is a ``ForeignKey`` to Django's ``User`` class, assume the value is an appropriate pk, and load up that record. """ data = {} for field, val in six.iteritems(request.POST): if field in self.immutable_fields: continue # Ignore immutable fields silently. if field in self.fields: field_obj = self.model._meta.get_field(field) val = self._extract_value(val) if isinstance(field_obj, models.ForeignKey): if field_obj.null and not val: clean_value = None else: clean_value = field_obj.rel.to.objects.get(pk=val) else: clean_value = field_obj.to_python(val) data[smart_str(field)] = clean_value return data
[ "def", "_extract_data", "(", "self", ",", "request", ")", ":", "data", "=", "{", "}", "for", "field", ",", "val", "in", "six", ".", "iteritems", "(", "request", ".", "POST", ")", ":", "if", "field", "in", "self", ".", "immutable_fields", ":", "continue", "# Ignore immutable fields silently.", "if", "field", "in", "self", ".", "fields", ":", "field_obj", "=", "self", ".", "model", ".", "_meta", ".", "get_field", "(", "field", ")", "val", "=", "self", ".", "_extract_value", "(", "val", ")", "if", "isinstance", "(", "field_obj", ",", "models", ".", "ForeignKey", ")", ":", "if", "field_obj", ".", "null", "and", "not", "val", ":", "clean_value", "=", "None", "else", ":", "clean_value", "=", "field_obj", ".", "rel", ".", "to", ".", "objects", ".", "get", "(", "pk", "=", "val", ")", "else", ":", "clean_value", "=", "field_obj", ".", "to_python", "(", "val", ")", "data", "[", "smart_str", "(", "field", ")", "]", "=", "clean_value", "return", "data" ]
Extract data from POST. Handles extracting a vanilla Python dict of values that are present in the given model. This also handles instances of ``ForeignKey`` and will convert those to the appropriate object instances from the database. In other words, it will see that user is a ``ForeignKey`` to Django's ``User`` class, assume the value is an appropriate pk, and load up that record.
[ "Extract", "data", "from", "POST", "." ]
train
https://github.com/joestump/django-ajax/blob/b71619d5c00d8e0bb990ddbea2c93cf303dc2c80/ajax/endpoints.py#L202-L229
joestump/django-ajax
ajax/endpoints.py
ModelEndpoint._extract_value
def _extract_value(self, value): """If the value is true/false/null replace with Python equivalent.""" return ModelEndpoint._value_map.get(smart_str(value).lower(), value)
python
def _extract_value(self, value): """If the value is true/false/null replace with Python equivalent.""" return ModelEndpoint._value_map.get(smart_str(value).lower(), value)
[ "def", "_extract_value", "(", "self", ",", "value", ")", ":", "return", "ModelEndpoint", ".", "_value_map", ".", "get", "(", "smart_str", "(", "value", ")", ".", "lower", "(", ")", ",", "value", ")" ]
If the value is true/false/null replace with Python equivalent.
[ "If", "the", "value", "is", "true", "/", "false", "/", "null", "replace", "with", "Python", "equivalent", "." ]
train
https://github.com/joestump/django-ajax/blob/b71619d5c00d8e0bb990ddbea2c93cf303dc2c80/ajax/endpoints.py#L231-L233
joestump/django-ajax
ajax/endpoints.py
ModelEndpoint._get_record
def _get_record(self): """Fetch a given record. Handles fetching a record from the database along with throwing an appropriate instance of ``AJAXError`. """ if not self.pk: raise AJAXError(400, _('Invalid request for record.')) try: return self.model.objects.get(pk=self.pk) except self.model.DoesNotExist: raise AJAXError(404, _('%s with id of "%s" not found.') % ( self.model.__name__, self.pk))
python
def _get_record(self): """Fetch a given record. Handles fetching a record from the database along with throwing an appropriate instance of ``AJAXError`. """ if not self.pk: raise AJAXError(400, _('Invalid request for record.')) try: return self.model.objects.get(pk=self.pk) except self.model.DoesNotExist: raise AJAXError(404, _('%s with id of "%s" not found.') % ( self.model.__name__, self.pk))
[ "def", "_get_record", "(", "self", ")", ":", "if", "not", "self", ".", "pk", ":", "raise", "AJAXError", "(", "400", ",", "_", "(", "'Invalid request for record.'", ")", ")", "try", ":", "return", "self", ".", "model", ".", "objects", ".", "get", "(", "pk", "=", "self", ".", "pk", ")", "except", "self", ".", "model", ".", "DoesNotExist", ":", "raise", "AJAXError", "(", "404", ",", "_", "(", "'%s with id of \"%s\" not found.'", ")", "%", "(", "self", ".", "model", ".", "__name__", ",", "self", ".", "pk", ")", ")" ]
Fetch a given record. Handles fetching a record from the database along with throwing an appropriate instance of ``AJAXError`.
[ "Fetch", "a", "given", "record", "." ]
train
https://github.com/joestump/django-ajax/blob/b71619d5c00d8e0bb990ddbea2c93cf303dc2c80/ajax/endpoints.py#L235-L248
joestump/django-ajax
ajax/endpoints.py
ModelEndpoint.authenticate
def authenticate(self, request, application, method): """Authenticate the AJAX request. By default any request to fetch a model is allowed for any user, including anonymous users. All other methods minimally require that the user is already logged in. Most likely you will want to lock down who can edit and delete various models. To do this, just override this method in your child class. """ return self.authentication.is_authenticated(request, application, method)
python
def authenticate(self, request, application, method): """Authenticate the AJAX request. By default any request to fetch a model is allowed for any user, including anonymous users. All other methods minimally require that the user is already logged in. Most likely you will want to lock down who can edit and delete various models. To do this, just override this method in your child class. """ return self.authentication.is_authenticated(request, application, method)
[ "def", "authenticate", "(", "self", ",", "request", ",", "application", ",", "method", ")", ":", "return", "self", ".", "authentication", ".", "is_authenticated", "(", "request", ",", "application", ",", "method", ")" ]
Authenticate the AJAX request. By default any request to fetch a model is allowed for any user, including anonymous users. All other methods minimally require that the user is already logged in. Most likely you will want to lock down who can edit and delete various models. To do this, just override this method in your child class.
[ "Authenticate", "the", "AJAX", "request", "." ]
train
https://github.com/joestump/django-ajax/blob/b71619d5c00d8e0bb990ddbea2c93cf303dc2c80/ajax/endpoints.py#L261-L271
contentful/contentful-management.py
contentful_management/entries_proxy.py
EntriesProxy.all
def all(self, query=None): """ Gets all entries of a space. """ if query is None: query = {} if self.content_type_id is not None: query['content_type'] = self.content_type_id normalize_select(query) return super(EntriesProxy, self).all(query=query)
python
def all(self, query=None): """ Gets all entries of a space. """ if query is None: query = {} if self.content_type_id is not None: query['content_type'] = self.content_type_id normalize_select(query) return super(EntriesProxy, self).all(query=query)
[ "def", "all", "(", "self", ",", "query", "=", "None", ")", ":", "if", "query", "is", "None", ":", "query", "=", "{", "}", "if", "self", ".", "content_type_id", "is", "not", "None", ":", "query", "[", "'content_type'", "]", "=", "self", ".", "content_type_id", "normalize_select", "(", "query", ")", "return", "super", "(", "EntriesProxy", ",", "self", ")", ".", "all", "(", "query", "=", "query", ")" ]
Gets all entries of a space.
[ "Gets", "all", "entries", "of", "a", "space", "." ]
train
https://github.com/contentful/contentful-management.py/blob/707dd30883b98a10c7ff0f7f5bdb8edbdc1d8df0/contentful_management/entries_proxy.py#L32-L45
contentful/contentful-management.py
contentful_management/entries_proxy.py
EntriesProxy.find
def find(self, entry_id, query=None): """ Gets a single entry by ID. """ if query is None: query = {} if self.content_type_id is not None: query['content_type'] = self.content_type_id normalize_select(query) return super(EntriesProxy, self).find(entry_id, query=query)
python
def find(self, entry_id, query=None): """ Gets a single entry by ID. """ if query is None: query = {} if self.content_type_id is not None: query['content_type'] = self.content_type_id normalize_select(query) return super(EntriesProxy, self).find(entry_id, query=query)
[ "def", "find", "(", "self", ",", "entry_id", ",", "query", "=", "None", ")", ":", "if", "query", "is", "None", ":", "query", "=", "{", "}", "if", "self", ".", "content_type_id", "is", "not", "None", ":", "query", "[", "'content_type'", "]", "=", "self", ".", "content_type_id", "normalize_select", "(", "query", ")", "return", "super", "(", "EntriesProxy", ",", "self", ")", ".", "find", "(", "entry_id", ",", "query", "=", "query", ")" ]
Gets a single entry by ID.
[ "Gets", "a", "single", "entry", "by", "ID", "." ]
train
https://github.com/contentful/contentful-management.py/blob/707dd30883b98a10c7ff0f7f5bdb8edbdc1d8df0/contentful_management/entries_proxy.py#L47-L60
contentful/contentful-management.py
contentful_management/entries_proxy.py
EntriesProxy.create
def create(self, resource_id=None, attributes=None, **kwargs): """ Creates an entry with a given ID (optional) and attributes. """ if self.content_type_id is not None: if attributes is None: attributes = {} attributes['content_type_id'] = self.content_type_id return super(EntriesProxy, self).create(resource_id=resource_id, attributes=attributes)
python
def create(self, resource_id=None, attributes=None, **kwargs): """ Creates an entry with a given ID (optional) and attributes. """ if self.content_type_id is not None: if attributes is None: attributes = {} attributes['content_type_id'] = self.content_type_id return super(EntriesProxy, self).create(resource_id=resource_id, attributes=attributes)
[ "def", "create", "(", "self", ",", "resource_id", "=", "None", ",", "attributes", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "self", ".", "content_type_id", "is", "not", "None", ":", "if", "attributes", "is", "None", ":", "attributes", "=", "{", "}", "attributes", "[", "'content_type_id'", "]", "=", "self", ".", "content_type_id", "return", "super", "(", "EntriesProxy", ",", "self", ")", ".", "create", "(", "resource_id", "=", "resource_id", ",", "attributes", "=", "attributes", ")" ]
Creates an entry with a given ID (optional) and attributes.
[ "Creates", "an", "entry", "with", "a", "given", "ID", "(", "optional", ")", "and", "attributes", "." ]
train
https://github.com/contentful/contentful-management.py/blob/707dd30883b98a10c7ff0f7f5bdb8edbdc1d8df0/contentful_management/entries_proxy.py#L62-L72
contentful/contentful-management.py
contentful_management/webhooks_proxy.py
WebhooksProxy.create
def create(self, attributes=None, **kwargs): """ Creates a webhook with given attributes. """ return super(WebhooksProxy, self).create(resource_id=None, attributes=attributes)
python
def create(self, attributes=None, **kwargs): """ Creates a webhook with given attributes. """ return super(WebhooksProxy, self).create(resource_id=None, attributes=attributes)
[ "def", "create", "(", "self", ",", "attributes", "=", "None", ",", "*", "*", "kwargs", ")", ":", "return", "super", "(", "WebhooksProxy", ",", "self", ")", ".", "create", "(", "resource_id", "=", "None", ",", "attributes", "=", "attributes", ")" ]
Creates a webhook with given attributes.
[ "Creates", "a", "webhook", "with", "given", "attributes", "." ]
train
https://github.com/contentful/contentful-management.py/blob/707dd30883b98a10c7ff0f7f5bdb8edbdc1d8df0/contentful_management/webhooks_proxy.py#L27-L32
contentful/contentful-management.py
contentful_management/utils.py
camel_case
def camel_case(snake_str): """ Returns a camel-cased version of a string. :param a_string: any :class:`str` object. Usage: >>> camel_case('foo_bar') "fooBar" """ components = snake_str.split('_') # We capitalize the first letter of each component except the first one # with the 'title' method and join them together. return components[0] + "".join(x.title() for x in components[1:])
python
def camel_case(snake_str): """ Returns a camel-cased version of a string. :param a_string: any :class:`str` object. Usage: >>> camel_case('foo_bar') "fooBar" """ components = snake_str.split('_') # We capitalize the first letter of each component except the first one # with the 'title' method and join them together. return components[0] + "".join(x.title() for x in components[1:])
[ "def", "camel_case", "(", "snake_str", ")", ":", "components", "=", "snake_str", ".", "split", "(", "'_'", ")", "# We capitalize the first letter of each component except the first one", "# with the 'title' method and join them together.", "return", "components", "[", "0", "]", "+", "\"\"", ".", "join", "(", "x", ".", "title", "(", ")", "for", "x", "in", "components", "[", "1", ":", "]", ")" ]
Returns a camel-cased version of a string. :param a_string: any :class:`str` object. Usage: >>> camel_case('foo_bar') "fooBar"
[ "Returns", "a", "camel", "-", "cased", "version", "of", "a", "string", "." ]
train
https://github.com/contentful/contentful-management.py/blob/707dd30883b98a10c7ff0f7f5bdb8edbdc1d8df0/contentful_management/utils.py#L73-L87
contentful/contentful-management.py
contentful_management/utils.py
normalize_select
def normalize_select(query): """ If the query contains the :select operator, we enforce :sys properties. The SDK requires sys.type to function properly, but as other of our SDKs require more parts of the :sys properties, we decided that every SDK should include the complete :sys block to provide consistency accross our SDKs. """ if 'select' not in query: return if isinstance( query['select'], str_type()): query['select'] = [s.strip() for s in query['select'].split(',')] query['select'] = [s for s in query['select'] if not s.startswith('sys.')] if 'sys' not in query['select']: query['select'].append('sys')
python
def normalize_select(query): """ If the query contains the :select operator, we enforce :sys properties. The SDK requires sys.type to function properly, but as other of our SDKs require more parts of the :sys properties, we decided that every SDK should include the complete :sys block to provide consistency accross our SDKs. """ if 'select' not in query: return if isinstance( query['select'], str_type()): query['select'] = [s.strip() for s in query['select'].split(',')] query['select'] = [s for s in query['select'] if not s.startswith('sys.')] if 'sys' not in query['select']: query['select'].append('sys')
[ "def", "normalize_select", "(", "query", ")", ":", "if", "'select'", "not", "in", "query", ":", "return", "if", "isinstance", "(", "query", "[", "'select'", "]", ",", "str_type", "(", ")", ")", ":", "query", "[", "'select'", "]", "=", "[", "s", ".", "strip", "(", ")", "for", "s", "in", "query", "[", "'select'", "]", ".", "split", "(", "','", ")", "]", "query", "[", "'select'", "]", "=", "[", "s", "for", "s", "in", "query", "[", "'select'", "]", "if", "not", "s", ".", "startswith", "(", "'sys.'", ")", "]", "if", "'sys'", "not", "in", "query", "[", "'select'", "]", ":", "query", "[", "'select'", "]", ".", "append", "(", "'sys'", ")" ]
If the query contains the :select operator, we enforce :sys properties. The SDK requires sys.type to function properly, but as other of our SDKs require more parts of the :sys properties, we decided that every SDK should include the complete :sys block to provide consistency accross our SDKs.
[ "If", "the", "query", "contains", "the", ":", "select", "operator", "we", "enforce", ":", "sys", "properties", ".", "The", "SDK", "requires", "sys", ".", "type", "to", "function", "properly", "but", "as", "other", "of", "our", "SDKs", "require", "more", "parts", "of", "the", ":", "sys", "properties", "we", "decided", "that", "every", "SDK", "should", "include", "the", "complete", ":", "sys", "block", "to", "provide", "consistency", "accross", "our", "SDKs", "." ]
train
https://github.com/contentful/contentful-management.py/blob/707dd30883b98a10c7ff0f7f5bdb8edbdc1d8df0/contentful_management/utils.py#L154-L176
contentful/contentful-management.py
contentful_management/environment.py
Environment.to_json
def to_json(self): """ Returns the JSON representation of the environment. """ result = super(Environment, self).to_json() result.update({ 'name': self.name }) return result
python
def to_json(self): """ Returns the JSON representation of the environment. """ result = super(Environment, self).to_json() result.update({ 'name': self.name }) return result
[ "def", "to_json", "(", "self", ")", ":", "result", "=", "super", "(", "Environment", ",", "self", ")", ".", "to_json", "(", ")", "result", ".", "update", "(", "{", "'name'", ":", "self", ".", "name", "}", ")", "return", "result" ]
Returns the JSON representation of the environment.
[ "Returns", "the", "JSON", "representation", "of", "the", "environment", "." ]
train
https://github.com/contentful/contentful-management.py/blob/707dd30883b98a10c7ff0f7f5bdb8edbdc1d8df0/contentful_management/environment.py#L56-L66
contentful/contentful-management.py
contentful_management/environment.py
Environment.content_types
def content_types(self): """ Provides access to content type management methods for content types of an environment. API reference: https://www.contentful.com/developers/docs/references/content-management-api/#/reference/content-types :return: :class:`EnvironmentContentTypesProxy <contentful_management.space_content_types_proxy.EnvironmentContentTypesProxy>` object. :rtype: contentful.space_content_types_proxy.EnvironmentContentTypesProxy Usage: >>> space_content_types_proxy = environment.content_types() <EnvironmentContentTypesProxy space_id="cfexampleapi" environment_id="master"> """ return EnvironmentContentTypesProxy(self._client, self.space.id, self.id)
python
def content_types(self): """ Provides access to content type management methods for content types of an environment. API reference: https://www.contentful.com/developers/docs/references/content-management-api/#/reference/content-types :return: :class:`EnvironmentContentTypesProxy <contentful_management.space_content_types_proxy.EnvironmentContentTypesProxy>` object. :rtype: contentful.space_content_types_proxy.EnvironmentContentTypesProxy Usage: >>> space_content_types_proxy = environment.content_types() <EnvironmentContentTypesProxy space_id="cfexampleapi" environment_id="master"> """ return EnvironmentContentTypesProxy(self._client, self.space.id, self.id)
[ "def", "content_types", "(", "self", ")", ":", "return", "EnvironmentContentTypesProxy", "(", "self", ".", "_client", ",", "self", ".", "space", ".", "id", ",", "self", ".", "id", ")" ]
Provides access to content type management methods for content types of an environment. API reference: https://www.contentful.com/developers/docs/references/content-management-api/#/reference/content-types :return: :class:`EnvironmentContentTypesProxy <contentful_management.space_content_types_proxy.EnvironmentContentTypesProxy>` object. :rtype: contentful.space_content_types_proxy.EnvironmentContentTypesProxy Usage: >>> space_content_types_proxy = environment.content_types() <EnvironmentContentTypesProxy space_id="cfexampleapi" environment_id="master">
[ "Provides", "access", "to", "content", "type", "management", "methods", "for", "content", "types", "of", "an", "environment", "." ]
train
https://github.com/contentful/contentful-management.py/blob/707dd30883b98a10c7ff0f7f5bdb8edbdc1d8df0/contentful_management/environment.py#L68-L83
contentful/contentful-management.py
contentful_management/environment.py
Environment.entries
def entries(self): """ Provides access to entry management methods. API reference: https://www.contentful.com/developers/docs/references/content-management-api/#/reference/entries :return: :class:`EnvironmentEntriesProxy <contentful_management.environment_entries_proxy.EnvironmentEntriesProxy>` object. :rtype: contentful.environment_entries_proxy.EnvironmentEntriesProxy Usage: >>> environment_entries_proxy = environment.entries() <EnvironmentEntriesProxy space_id="cfexampleapi" environment_id="master"> """ return EnvironmentEntriesProxy(self._client, self.space.id, self.id)
python
def entries(self): """ Provides access to entry management methods. API reference: https://www.contentful.com/developers/docs/references/content-management-api/#/reference/entries :return: :class:`EnvironmentEntriesProxy <contentful_management.environment_entries_proxy.EnvironmentEntriesProxy>` object. :rtype: contentful.environment_entries_proxy.EnvironmentEntriesProxy Usage: >>> environment_entries_proxy = environment.entries() <EnvironmentEntriesProxy space_id="cfexampleapi" environment_id="master"> """ return EnvironmentEntriesProxy(self._client, self.space.id, self.id)
[ "def", "entries", "(", "self", ")", ":", "return", "EnvironmentEntriesProxy", "(", "self", ".", "_client", ",", "self", ".", "space", ".", "id", ",", "self", ".", "id", ")" ]
Provides access to entry management methods. API reference: https://www.contentful.com/developers/docs/references/content-management-api/#/reference/entries :return: :class:`EnvironmentEntriesProxy <contentful_management.environment_entries_proxy.EnvironmentEntriesProxy>` object. :rtype: contentful.environment_entries_proxy.EnvironmentEntriesProxy Usage: >>> environment_entries_proxy = environment.entries() <EnvironmentEntriesProxy space_id="cfexampleapi" environment_id="master">
[ "Provides", "access", "to", "entry", "management", "methods", "." ]
train
https://github.com/contentful/contentful-management.py/blob/707dd30883b98a10c7ff0f7f5bdb8edbdc1d8df0/contentful_management/environment.py#L85-L100
contentful/contentful-management.py
contentful_management/environment.py
Environment.assets
def assets(self): """ Provides access to asset management methods. API reference: https://www.contentful.com/developers/docs/references/content-management-api/#/reference/assets :return: :class:`EnvironmentAssetsProxy <contentful_management.environment_assets_proxy.EnvironmentAssetsProxy>` object. :rtype: contentful.environment_assets_proxy.EnvironmentAssetsProxy Usage: >>> environment_assets_proxy = environment.assets() <EnvironmentAssetsProxy space_id="cfexampleapi" environment_id="master"> """ return EnvironmentAssetsProxy(self._client, self.space.id, self.id)
python
def assets(self): """ Provides access to asset management methods. API reference: https://www.contentful.com/developers/docs/references/content-management-api/#/reference/assets :return: :class:`EnvironmentAssetsProxy <contentful_management.environment_assets_proxy.EnvironmentAssetsProxy>` object. :rtype: contentful.environment_assets_proxy.EnvironmentAssetsProxy Usage: >>> environment_assets_proxy = environment.assets() <EnvironmentAssetsProxy space_id="cfexampleapi" environment_id="master"> """ return EnvironmentAssetsProxy(self._client, self.space.id, self.id)
[ "def", "assets", "(", "self", ")", ":", "return", "EnvironmentAssetsProxy", "(", "self", ".", "_client", ",", "self", ".", "space", ".", "id", ",", "self", ".", "id", ")" ]
Provides access to asset management methods. API reference: https://www.contentful.com/developers/docs/references/content-management-api/#/reference/assets :return: :class:`EnvironmentAssetsProxy <contentful_management.environment_assets_proxy.EnvironmentAssetsProxy>` object. :rtype: contentful.environment_assets_proxy.EnvironmentAssetsProxy Usage: >>> environment_assets_proxy = environment.assets() <EnvironmentAssetsProxy space_id="cfexampleapi" environment_id="master">
[ "Provides", "access", "to", "asset", "management", "methods", "." ]
train
https://github.com/contentful/contentful-management.py/blob/707dd30883b98a10c7ff0f7f5bdb8edbdc1d8df0/contentful_management/environment.py#L102-L117
contentful/contentful-management.py
contentful_management/environment.py
Environment.locales
def locales(self): """ Provides access to locale management methods. API reference: https://www.contentful.com/developers/docs/references/content-management-api/#/reference/locales :return: :class:`EnvironmentLocalesProxy <contentful_management.environment_locales_proxy.EnvironmentLocalesProxy>` object. :rtype: contentful.environment_locales_proxy.EnvironmentLocalesProxy Usage: >>> environment_locales_proxy = environment.locales() <EnvironmentLocalesProxy space_id="cfexampleapi" environment_id="master"> """ return EnvironmentLocalesProxy(self._client, self.space.id, self.id)
python
def locales(self): """ Provides access to locale management methods. API reference: https://www.contentful.com/developers/docs/references/content-management-api/#/reference/locales :return: :class:`EnvironmentLocalesProxy <contentful_management.environment_locales_proxy.EnvironmentLocalesProxy>` object. :rtype: contentful.environment_locales_proxy.EnvironmentLocalesProxy Usage: >>> environment_locales_proxy = environment.locales() <EnvironmentLocalesProxy space_id="cfexampleapi" environment_id="master"> """ return EnvironmentLocalesProxy(self._client, self.space.id, self.id)
[ "def", "locales", "(", "self", ")", ":", "return", "EnvironmentLocalesProxy", "(", "self", ".", "_client", ",", "self", ".", "space", ".", "id", ",", "self", ".", "id", ")" ]
Provides access to locale management methods. API reference: https://www.contentful.com/developers/docs/references/content-management-api/#/reference/locales :return: :class:`EnvironmentLocalesProxy <contentful_management.environment_locales_proxy.EnvironmentLocalesProxy>` object. :rtype: contentful.environment_locales_proxy.EnvironmentLocalesProxy Usage: >>> environment_locales_proxy = environment.locales() <EnvironmentLocalesProxy space_id="cfexampleapi" environment_id="master">
[ "Provides", "access", "to", "locale", "management", "methods", "." ]
train
https://github.com/contentful/contentful-management.py/blob/707dd30883b98a10c7ff0f7f5bdb8edbdc1d8df0/contentful_management/environment.py#L119-L134
contentful/contentful-management.py
contentful_management/environment.py
Environment.ui_extensions
def ui_extensions(self): """ Provides access to UI extensions management methods. API reference: https://www.contentful.com/developers/docs/references/content-management-api/#/reference/ui-extensions :return: :class:`EnvironmentUIExtensionsProxy <contentful_management.ui_extensions_proxy.EnvironmentUIExtensionsProxy>` object. :rtype: contentful.ui_extensions_proxy.EnvironmentUIExtensionsProxy Usage: >>> ui_extensions_proxy = environment.ui_extensions() <EnvironmentUIExtensionsProxy space_id="cfexampleapi" environment_id="master"> """ return EnvironmentUIExtensionsProxy(self._client, self.space.id, self.id)
python
def ui_extensions(self): """ Provides access to UI extensions management methods. API reference: https://www.contentful.com/developers/docs/references/content-management-api/#/reference/ui-extensions :return: :class:`EnvironmentUIExtensionsProxy <contentful_management.ui_extensions_proxy.EnvironmentUIExtensionsProxy>` object. :rtype: contentful.ui_extensions_proxy.EnvironmentUIExtensionsProxy Usage: >>> ui_extensions_proxy = environment.ui_extensions() <EnvironmentUIExtensionsProxy space_id="cfexampleapi" environment_id="master"> """ return EnvironmentUIExtensionsProxy(self._client, self.space.id, self.id)
[ "def", "ui_extensions", "(", "self", ")", ":", "return", "EnvironmentUIExtensionsProxy", "(", "self", ".", "_client", ",", "self", ".", "space", ".", "id", ",", "self", ".", "id", ")" ]
Provides access to UI extensions management methods. API reference: https://www.contentful.com/developers/docs/references/content-management-api/#/reference/ui-extensions :return: :class:`EnvironmentUIExtensionsProxy <contentful_management.ui_extensions_proxy.EnvironmentUIExtensionsProxy>` object. :rtype: contentful.ui_extensions_proxy.EnvironmentUIExtensionsProxy Usage: >>> ui_extensions_proxy = environment.ui_extensions() <EnvironmentUIExtensionsProxy space_id="cfexampleapi" environment_id="master">
[ "Provides", "access", "to", "UI", "extensions", "management", "methods", "." ]
train
https://github.com/contentful/contentful-management.py/blob/707dd30883b98a10c7ff0f7f5bdb8edbdc1d8df0/contentful_management/environment.py#L136-L151
contentful/contentful-management.py
contentful_management/personal_access_tokens_proxy.py
PersonalAccessTokensProxy.delete
def delete(self, token_id, *args, **kwargs): """ Revokes a personal access token. """ return self.client._put( "{0}/revoked".format( self._url(token_id) ), None, *args, **kwargs )
python
def delete(self, token_id, *args, **kwargs): """ Revokes a personal access token. """ return self.client._put( "{0}/revoked".format( self._url(token_id) ), None, *args, **kwargs )
[ "def", "delete", "(", "self", ",", "token_id", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "client", ".", "_put", "(", "\"{0}/revoked\"", ".", "format", "(", "self", ".", "_url", "(", "token_id", ")", ")", ",", "None", ",", "*", "args", ",", "*", "*", "kwargs", ")" ]
Revokes a personal access token.
[ "Revokes", "a", "personal", "access", "token", "." ]
train
https://github.com/contentful/contentful-management.py/blob/707dd30883b98a10c7ff0f7f5bdb8edbdc1d8df0/contentful_management/personal_access_tokens_proxy.py#L39-L51
contentful/contentful-management.py
contentful_management/personal_access_tokens_proxy.py
PersonalAccessTokensProxy.revoke
def revoke(self, token_id, *args, **kwargs): """ Revokes a personal access token. """ return self.delete(token_id, *args, **kwargs)
python
def revoke(self, token_id, *args, **kwargs): """ Revokes a personal access token. """ return self.delete(token_id, *args, **kwargs)
[ "def", "revoke", "(", "self", ",", "token_id", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "delete", "(", "token_id", ",", "*", "args", ",", "*", "*", "kwargs", ")" ]
Revokes a personal access token.
[ "Revokes", "a", "personal", "access", "token", "." ]
train
https://github.com/contentful/contentful-management.py/blob/707dd30883b98a10c7ff0f7f5bdb8edbdc1d8df0/contentful_management/personal_access_tokens_proxy.py#L53-L58
contentful/contentful-management.py
contentful_management/resource.py
Resource.base_url
def base_url(klass, space_id='', resource_id=None, environment_id=None, **kwargs): """ Returns the URI for the resource. """ url = "spaces/{0}".format( space_id) if environment_id is not None: url = url = "{0}/environments/{1}".format(url, environment_id) url = "{0}/{1}".format( url, base_path_for(klass.__name__) ) if resource_id: url = "{0}/{1}".format(url, resource_id) return url
python
def base_url(klass, space_id='', resource_id=None, environment_id=None, **kwargs): """ Returns the URI for the resource. """ url = "spaces/{0}".format( space_id) if environment_id is not None: url = url = "{0}/environments/{1}".format(url, environment_id) url = "{0}/{1}".format( url, base_path_for(klass.__name__) ) if resource_id: url = "{0}/{1}".format(url, resource_id) return url
[ "def", "base_url", "(", "klass", ",", "space_id", "=", "''", ",", "resource_id", "=", "None", ",", "environment_id", "=", "None", ",", "*", "*", "kwargs", ")", ":", "url", "=", "\"spaces/{0}\"", ".", "format", "(", "space_id", ")", "if", "environment_id", "is", "not", "None", ":", "url", "=", "url", "=", "\"{0}/environments/{1}\"", ".", "format", "(", "url", ",", "environment_id", ")", "url", "=", "\"{0}/{1}\"", ".", "format", "(", "url", ",", "base_path_for", "(", "klass", ".", "__name__", ")", ")", "if", "resource_id", ":", "url", "=", "\"{0}/{1}\"", ".", "format", "(", "url", ",", "resource_id", ")", "return", "url" ]
Returns the URI for the resource.
[ "Returns", "the", "URI", "for", "the", "resource", "." ]
train
https://github.com/contentful/contentful-management.py/blob/707dd30883b98a10c7ff0f7f5bdb8edbdc1d8df0/contentful_management/resource.py#L37-L56
contentful/contentful-management.py
contentful_management/resource.py
Resource.create_attributes
def create_attributes(klass, attributes, previous_object=None): """ Attributes for resource creation. """ result = {} if previous_object is not None: result = {k: v for k, v in previous_object.to_json().items() if k != 'sys'} result.update(attributes) return result
python
def create_attributes(klass, attributes, previous_object=None): """ Attributes for resource creation. """ result = {} if previous_object is not None: result = {k: v for k, v in previous_object.to_json().items() if k != 'sys'} result.update(attributes) return result
[ "def", "create_attributes", "(", "klass", ",", "attributes", ",", "previous_object", "=", "None", ")", ":", "result", "=", "{", "}", "if", "previous_object", "is", "not", "None", ":", "result", "=", "{", "k", ":", "v", "for", "k", ",", "v", "in", "previous_object", ".", "to_json", "(", ")", ".", "items", "(", ")", "if", "k", "!=", "'sys'", "}", "result", ".", "update", "(", "attributes", ")", "return", "result" ]
Attributes for resource creation.
[ "Attributes", "for", "resource", "creation", "." ]
train
https://github.com/contentful/contentful-management.py/blob/707dd30883b98a10c7ff0f7f5bdb8edbdc1d8df0/contentful_management/resource.py#L59-L71
contentful/contentful-management.py
contentful_management/resource.py
Resource.delete
def delete(self): """ Deletes the resource. """ return self._client._delete( self.__class__.base_url( self.sys['space'].id, self.sys['id'], environment_id=self._environment_id ) )
python
def delete(self): """ Deletes the resource. """ return self._client._delete( self.__class__.base_url( self.sys['space'].id, self.sys['id'], environment_id=self._environment_id ) )
[ "def", "delete", "(", "self", ")", ":", "return", "self", ".", "_client", ".", "_delete", "(", "self", ".", "__class__", ".", "base_url", "(", "self", ".", "sys", "[", "'space'", "]", ".", "id", ",", "self", ".", "sys", "[", "'id'", "]", ",", "environment_id", "=", "self", ".", "_environment_id", ")", ")" ]
Deletes the resource.
[ "Deletes", "the", "resource", "." ]
train
https://github.com/contentful/contentful-management.py/blob/707dd30883b98a10c7ff0f7f5bdb8edbdc1d8df0/contentful_management/resource.py#L89-L100
contentful/contentful-management.py
contentful_management/resource.py
Resource.update
def update(self, attributes=None): """ Updates the resource with attributes. """ if attributes is None: attributes = {} headers = self.__class__.create_headers(attributes) headers.update(self._update_headers()) result = self._client._put( self._update_url(), self.__class__.create_attributes(attributes, self), headers=headers ) self._update_from_resource(result) return self
python
def update(self, attributes=None): """ Updates the resource with attributes. """ if attributes is None: attributes = {} headers = self.__class__.create_headers(attributes) headers.update(self._update_headers()) result = self._client._put( self._update_url(), self.__class__.create_attributes(attributes, self), headers=headers ) self._update_from_resource(result) return self
[ "def", "update", "(", "self", ",", "attributes", "=", "None", ")", ":", "if", "attributes", "is", "None", ":", "attributes", "=", "{", "}", "headers", "=", "self", ".", "__class__", ".", "create_headers", "(", "attributes", ")", "headers", ".", "update", "(", "self", ".", "_update_headers", "(", ")", ")", "result", "=", "self", ".", "_client", ".", "_put", "(", "self", ".", "_update_url", "(", ")", ",", "self", ".", "__class__", ".", "create_attributes", "(", "attributes", ",", "self", ")", ",", "headers", "=", "headers", ")", "self", ".", "_update_from_resource", "(", "result", ")", "return", "self" ]
Updates the resource with attributes.
[ "Updates", "the", "resource", "with", "attributes", "." ]
train
https://github.com/contentful/contentful-management.py/blob/707dd30883b98a10c7ff0f7f5bdb8edbdc1d8df0/contentful_management/resource.py#L102-L121
contentful/contentful-management.py
contentful_management/resource.py
Resource.reload
def reload(self, result=None): """ Reloads the resource. """ if result is None: result = self._client._get( self.__class__.base_url( self.sys['space'].id, self.sys['id'], environment_id=self._environment_id ) ) self._update_from_resource(result) return self
python
def reload(self, result=None): """ Reloads the resource. """ if result is None: result = self._client._get( self.__class__.base_url( self.sys['space'].id, self.sys['id'], environment_id=self._environment_id ) ) self._update_from_resource(result) return self
[ "def", "reload", "(", "self", ",", "result", "=", "None", ")", ":", "if", "result", "is", "None", ":", "result", "=", "self", ".", "_client", ".", "_get", "(", "self", ".", "__class__", ".", "base_url", "(", "self", ".", "sys", "[", "'space'", "]", ".", "id", ",", "self", ".", "sys", "[", "'id'", "]", ",", "environment_id", "=", "self", ".", "_environment_id", ")", ")", "self", ".", "_update_from_resource", "(", "result", ")", "return", "self" ]
Reloads the resource.
[ "Reloads", "the", "resource", "." ]
train
https://github.com/contentful/contentful-management.py/blob/707dd30883b98a10c7ff0f7f5bdb8edbdc1d8df0/contentful_management/resource.py#L130-L146
contentful/contentful-management.py
contentful_management/resource.py
Resource.to_link
def to_link(self): """ Returns a link for the resource. """ link_type = self.link_type if self.type == 'Link' else self.type return Link({'sys': {'linkType': link_type, 'id': self.sys.get('id')}}, client=self._client)
python
def to_link(self): """ Returns a link for the resource. """ link_type = self.link_type if self.type == 'Link' else self.type return Link({'sys': {'linkType': link_type, 'id': self.sys.get('id')}}, client=self._client)
[ "def", "to_link", "(", "self", ")", ":", "link_type", "=", "self", ".", "link_type", "if", "self", ".", "type", "==", "'Link'", "else", "self", ".", "type", "return", "Link", "(", "{", "'sys'", ":", "{", "'linkType'", ":", "link_type", ",", "'id'", ":", "self", ".", "sys", ".", "get", "(", "'id'", ")", "}", "}", ",", "client", "=", "self", ".", "_client", ")" ]
Returns a link for the resource.
[ "Returns", "a", "link", "for", "the", "resource", "." ]
train
https://github.com/contentful/contentful-management.py/blob/707dd30883b98a10c7ff0f7f5bdb8edbdc1d8df0/contentful_management/resource.py#L148-L155
contentful/contentful-management.py
contentful_management/resource.py
Resource.to_json
def to_json(self): """ Returns the JSON representation of the resource. """ result = { 'sys': {} } for k, v in self.sys.items(): if k in ['space', 'content_type', 'created_by', 'updated_by', 'published_by']: v = v.to_json() if k in ['created_at', 'updated_at', 'deleted_at', 'first_published_at', 'published_at', 'expires_at']: v = v.isoformat() result['sys'][camel_case(k)] = v return result
python
def to_json(self): """ Returns the JSON representation of the resource. """ result = { 'sys': {} } for k, v in self.sys.items(): if k in ['space', 'content_type', 'created_by', 'updated_by', 'published_by']: v = v.to_json() if k in ['created_at', 'updated_at', 'deleted_at', 'first_published_at', 'published_at', 'expires_at']: v = v.isoformat() result['sys'][camel_case(k)] = v return result
[ "def", "to_json", "(", "self", ")", ":", "result", "=", "{", "'sys'", ":", "{", "}", "}", "for", "k", ",", "v", "in", "self", ".", "sys", ".", "items", "(", ")", ":", "if", "k", "in", "[", "'space'", ",", "'content_type'", ",", "'created_by'", ",", "'updated_by'", ",", "'published_by'", "]", ":", "v", "=", "v", ".", "to_json", "(", ")", "if", "k", "in", "[", "'created_at'", ",", "'updated_at'", ",", "'deleted_at'", ",", "'first_published_at'", ",", "'published_at'", ",", "'expires_at'", "]", ":", "v", "=", "v", ".", "isoformat", "(", ")", "result", "[", "'sys'", "]", "[", "camel_case", "(", "k", ")", "]", "=", "v", "return", "result" ]
Returns the JSON representation of the resource.
[ "Returns", "the", "JSON", "representation", "of", "the", "resource", "." ]
train
https://github.com/contentful/contentful-management.py/blob/707dd30883b98a10c7ff0f7f5bdb8edbdc1d8df0/contentful_management/resource.py#L157-L174
contentful/contentful-management.py
contentful_management/resource.py
FieldsResource.create_attributes
def create_attributes(klass, attributes, previous_object=None): """ Attributes for resource creation. """ if 'fields' not in attributes: if previous_object is None: attributes['fields'] = {} else: attributes['fields'] = previous_object.to_json()['fields'] return {'fields': attributes['fields']}
python
def create_attributes(klass, attributes, previous_object=None): """ Attributes for resource creation. """ if 'fields' not in attributes: if previous_object is None: attributes['fields'] = {} else: attributes['fields'] = previous_object.to_json()['fields'] return {'fields': attributes['fields']}
[ "def", "create_attributes", "(", "klass", ",", "attributes", ",", "previous_object", "=", "None", ")", ":", "if", "'fields'", "not", "in", "attributes", ":", "if", "previous_object", "is", "None", ":", "attributes", "[", "'fields'", "]", "=", "{", "}", "else", ":", "attributes", "[", "'fields'", "]", "=", "previous_object", ".", "to_json", "(", ")", "[", "'fields'", "]", "return", "{", "'fields'", ":", "attributes", "[", "'fields'", "]", "}" ]
Attributes for resource creation.
[ "Attributes", "for", "resource", "creation", "." ]
train
https://github.com/contentful/contentful-management.py/blob/707dd30883b98a10c7ff0f7f5bdb8edbdc1d8df0/contentful_management/resource.py#L249-L259
contentful/contentful-management.py
contentful_management/resource.py
FieldsResource.fields_with_locales
def fields_with_locales(self): """ Get fields with locales per field. """ result = {} for locale, fields in self._fields.items(): for k, v in fields.items(): real_field_id = self._real_field_id_for(k) if real_field_id not in result: result[real_field_id] = {} result[real_field_id][locale] = self._serialize_value(v) return result
python
def fields_with_locales(self): """ Get fields with locales per field. """ result = {} for locale, fields in self._fields.items(): for k, v in fields.items(): real_field_id = self._real_field_id_for(k) if real_field_id not in result: result[real_field_id] = {} result[real_field_id][locale] = self._serialize_value(v) return result
[ "def", "fields_with_locales", "(", "self", ")", ":", "result", "=", "{", "}", "for", "locale", ",", "fields", "in", "self", ".", "_fields", ".", "items", "(", ")", ":", "for", "k", ",", "v", "in", "fields", ".", "items", "(", ")", ":", "real_field_id", "=", "self", ".", "_real_field_id_for", "(", "k", ")", "if", "real_field_id", "not", "in", "result", ":", "result", "[", "real_field_id", "]", "=", "{", "}", "result", "[", "real_field_id", "]", "[", "locale", "]", "=", "self", ".", "_serialize_value", "(", "v", ")", "return", "result" ]
Get fields with locales per field.
[ "Get", "fields", "with", "locales", "per", "field", "." ]
train
https://github.com/contentful/contentful-management.py/blob/707dd30883b98a10c7ff0f7f5bdb8edbdc1d8df0/contentful_management/resource.py#L276-L288
contentful/contentful-management.py
contentful_management/resource.py
FieldsResource.to_json
def to_json(self): """ Returns the JSON Representation of the resource. """ result = super(FieldsResource, self).to_json() result['fields'] = self.fields_with_locales() return result
python
def to_json(self): """ Returns the JSON Representation of the resource. """ result = super(FieldsResource, self).to_json() result['fields'] = self.fields_with_locales() return result
[ "def", "to_json", "(", "self", ")", ":", "result", "=", "super", "(", "FieldsResource", ",", "self", ")", ".", "to_json", "(", ")", "result", "[", "'fields'", "]", "=", "self", ".", "fields_with_locales", "(", ")", "return", "result" ]
Returns the JSON Representation of the resource.
[ "Returns", "the", "JSON", "Representation", "of", "the", "resource", "." ]
train
https://github.com/contentful/contentful-management.py/blob/707dd30883b98a10c7ff0f7f5bdb8edbdc1d8df0/contentful_management/resource.py#L290-L297
contentful/contentful-management.py
contentful_management/resource.py
PublishResource.is_updated
def is_updated(self): """ Checks if a resource has been updated since last publish. Returns False if resource has not been published before. """ if not self.is_published: return False return sanitize_date(self.sys['published_at']) < sanitize_date(self.sys['updated_at'])
python
def is_updated(self): """ Checks if a resource has been updated since last publish. Returns False if resource has not been published before. """ if not self.is_published: return False return sanitize_date(self.sys['published_at']) < sanitize_date(self.sys['updated_at'])
[ "def", "is_updated", "(", "self", ")", ":", "if", "not", "self", ".", "is_published", ":", "return", "False", "return", "sanitize_date", "(", "self", ".", "sys", "[", "'published_at'", "]", ")", "<", "sanitize_date", "(", "self", ".", "sys", "[", "'updated_at'", "]", ")" ]
Checks if a resource has been updated since last publish. Returns False if resource has not been published before.
[ "Checks", "if", "a", "resource", "has", "been", "updated", "since", "last", "publish", ".", "Returns", "False", "if", "resource", "has", "not", "been", "published", "before", "." ]
train
https://github.com/contentful/contentful-management.py/blob/707dd30883b98a10c7ff0f7f5bdb8edbdc1d8df0/contentful_management/resource.py#L392-L401
contentful/contentful-management.py
contentful_management/resource.py
PublishResource.unpublish
def unpublish(self): """ Unpublishes the resource. """ self._client._delete( "{0}/published".format( self.__class__.base_url( self.sys['space'].id, self.sys['id'], environment_id=self._environment_id ), ), headers=self._update_headers() ) return self.reload()
python
def unpublish(self): """ Unpublishes the resource. """ self._client._delete( "{0}/published".format( self.__class__.base_url( self.sys['space'].id, self.sys['id'], environment_id=self._environment_id ), ), headers=self._update_headers() ) return self.reload()
[ "def", "unpublish", "(", "self", ")", ":", "self", ".", "_client", ".", "_delete", "(", "\"{0}/published\"", ".", "format", "(", "self", ".", "__class__", ".", "base_url", "(", "self", ".", "sys", "[", "'space'", "]", ".", "id", ",", "self", ".", "sys", "[", "'id'", "]", ",", "environment_id", "=", "self", ".", "_environment_id", ")", ",", ")", ",", "headers", "=", "self", ".", "_update_headers", "(", ")", ")", "return", "self", ".", "reload", "(", ")" ]
Unpublishes the resource.
[ "Unpublishes", "the", "resource", "." ]
train
https://github.com/contentful/contentful-management.py/blob/707dd30883b98a10c7ff0f7f5bdb8edbdc1d8df0/contentful_management/resource.py#L422-L438
contentful/contentful-management.py
contentful_management/resource.py
ArchiveResource.archive
def archive(self): """ Archives the resource. """ self._client._put( "{0}/archived".format( self.__class__.base_url( self.sys['space'].id, self.sys['id'], environment_id=self._environment_id ), ), {}, headers=self._update_headers() ) return self.reload()
python
def archive(self): """ Archives the resource. """ self._client._put( "{0}/archived".format( self.__class__.base_url( self.sys['space'].id, self.sys['id'], environment_id=self._environment_id ), ), {}, headers=self._update_headers() ) return self.reload()
[ "def", "archive", "(", "self", ")", ":", "self", ".", "_client", ".", "_put", "(", "\"{0}/archived\"", ".", "format", "(", "self", ".", "__class__", ".", "base_url", "(", "self", ".", "sys", "[", "'space'", "]", ".", "id", ",", "self", ".", "sys", "[", "'id'", "]", ",", "environment_id", "=", "self", ".", "_environment_id", ")", ",", ")", ",", "{", "}", ",", "headers", "=", "self", ".", "_update_headers", "(", ")", ")", "return", "self", ".", "reload", "(", ")" ]
Archives the resource.
[ "Archives", "the", "resource", "." ]
train
https://github.com/contentful/contentful-management.py/blob/707dd30883b98a10c7ff0f7f5bdb8edbdc1d8df0/contentful_management/resource.py#L454-L471
contentful/contentful-management.py
contentful_management/resource.py
Link.resolve
def resolve(self, space_id=None, environment_id=None): """ Resolves link to a specific resource. """ proxy_method = getattr( self._client, base_path_for(self.link_type) ) if self.link_type == 'Space': return proxy_method().find(self.id) elif environment_id is not None: return proxy_method(space_id, environment_id).find(self.id) else: return proxy_method(space_id).find(self.id)
python
def resolve(self, space_id=None, environment_id=None): """ Resolves link to a specific resource. """ proxy_method = getattr( self._client, base_path_for(self.link_type) ) if self.link_type == 'Space': return proxy_method().find(self.id) elif environment_id is not None: return proxy_method(space_id, environment_id).find(self.id) else: return proxy_method(space_id).find(self.id)
[ "def", "resolve", "(", "self", ",", "space_id", "=", "None", ",", "environment_id", "=", "None", ")", ":", "proxy_method", "=", "getattr", "(", "self", ".", "_client", ",", "base_path_for", "(", "self", ".", "link_type", ")", ")", "if", "self", ".", "link_type", "==", "'Space'", ":", "return", "proxy_method", "(", ")", ".", "find", "(", "self", ".", "id", ")", "elif", "environment_id", "is", "not", "None", ":", "return", "proxy_method", "(", "space_id", ",", "environment_id", ")", ".", "find", "(", "self", ".", "id", ")", "else", ":", "return", "proxy_method", "(", "space_id", ")", ".", "find", "(", "self", ".", "id", ")" ]
Resolves link to a specific resource.
[ "Resolves", "link", "to", "a", "specific", "resource", "." ]
train
https://github.com/contentful/contentful-management.py/blob/707dd30883b98a10c7ff0f7f5bdb8edbdc1d8df0/contentful_management/resource.py#L517-L531
contentful/contentful-management.py
contentful_management/asset.py
Asset.url
def url(self, **kwargs): """ Returns a formatted URL for the asset's File with serialized parameters. Usage: >>> my_asset.url() "//images.contentful.com/spaces/foobar/..." >>> my_asset.url(w=120, h=160) "//images.contentful.com/spaces/foobar/...?w=120&h=160" """ url = self.fields(self._locale()).get('file', {}).get('url', '') args = ['{0}={1}'.format(k, v) for k, v in kwargs.items()] if args: url += '?{0}'.format('&'.join(args)) return url
python
def url(self, **kwargs): """ Returns a formatted URL for the asset's File with serialized parameters. Usage: >>> my_asset.url() "//images.contentful.com/spaces/foobar/..." >>> my_asset.url(w=120, h=160) "//images.contentful.com/spaces/foobar/...?w=120&h=160" """ url = self.fields(self._locale()).get('file', {}).get('url', '') args = ['{0}={1}'.format(k, v) for k, v in kwargs.items()] if args: url += '?{0}'.format('&'.join(args)) return url
[ "def", "url", "(", "self", ",", "*", "*", "kwargs", ")", ":", "url", "=", "self", ".", "fields", "(", "self", ".", "_locale", "(", ")", ")", ".", "get", "(", "'file'", ",", "{", "}", ")", ".", "get", "(", "'url'", ",", "''", ")", "args", "=", "[", "'{0}={1}'", ".", "format", "(", "k", ",", "v", ")", "for", "k", ",", "v", "in", "kwargs", ".", "items", "(", ")", "]", "if", "args", ":", "url", "+=", "'?{0}'", ".", "format", "(", "'&'", ".", "join", "(", "args", ")", ")", "return", "url" ]
Returns a formatted URL for the asset's File with serialized parameters. Usage: >>> my_asset.url() "//images.contentful.com/spaces/foobar/..." >>> my_asset.url(w=120, h=160) "//images.contentful.com/spaces/foobar/...?w=120&h=160"
[ "Returns", "a", "formatted", "URL", "for", "the", "asset", "s", "File", "with", "serialized", "parameters", "." ]
train
https://github.com/contentful/contentful-management.py/blob/707dd30883b98a10c7ff0f7f5bdb8edbdc1d8df0/contentful_management/asset.py#L22-L40
contentful/contentful-management.py
contentful_management/asset.py
Asset.process
def process(self): """ Calls the process endpoint for all locales of the asset. API reference: https://www.contentful.com/developers/docs/references/content-management-api/#/reference/assets/asset-processing """ for locale in self._fields.keys(): self._client._put( "{0}/files/{1}/process".format( self.__class__.base_url( self.space.id, self.id, environment_id=self._environment_id ), locale ), {}, headers=self._update_headers() ) return self.reload()
python
def process(self): """ Calls the process endpoint for all locales of the asset. API reference: https://www.contentful.com/developers/docs/references/content-management-api/#/reference/assets/asset-processing """ for locale in self._fields.keys(): self._client._put( "{0}/files/{1}/process".format( self.__class__.base_url( self.space.id, self.id, environment_id=self._environment_id ), locale ), {}, headers=self._update_headers() ) return self.reload()
[ "def", "process", "(", "self", ")", ":", "for", "locale", "in", "self", ".", "_fields", ".", "keys", "(", ")", ":", "self", ".", "_client", ".", "_put", "(", "\"{0}/files/{1}/process\"", ".", "format", "(", "self", ".", "__class__", ".", "base_url", "(", "self", ".", "space", ".", "id", ",", "self", ".", "id", ",", "environment_id", "=", "self", ".", "_environment_id", ")", ",", "locale", ")", ",", "{", "}", ",", "headers", "=", "self", ".", "_update_headers", "(", ")", ")", "return", "self", ".", "reload", "(", ")" ]
Calls the process endpoint for all locales of the asset. API reference: https://www.contentful.com/developers/docs/references/content-management-api/#/reference/assets/asset-processing
[ "Calls", "the", "process", "endpoint", "for", "all", "locales", "of", "the", "asset", "." ]
train
https://github.com/contentful/contentful-management.py/blob/707dd30883b98a10c7ff0f7f5bdb8edbdc1d8df0/contentful_management/asset.py#L42-L62
contentful/contentful-management.py
contentful_management/ui_extension.py
UIExtension.to_json
def to_json(self): """ Returns the JSON Representation of the UI extension. """ result = super(UIExtension, self).to_json() result.update({ 'extension': self.extension }) return result
python
def to_json(self): """ Returns the JSON Representation of the UI extension. """ result = super(UIExtension, self).to_json() result.update({ 'extension': self.extension }) return result
[ "def", "to_json", "(", "self", ")", ":", "result", "=", "super", "(", "UIExtension", ",", "self", ")", ".", "to_json", "(", ")", "result", ".", "update", "(", "{", "'extension'", ":", "self", ".", "extension", "}", ")", "return", "result" ]
Returns the JSON Representation of the UI extension.
[ "Returns", "the", "JSON", "Representation", "of", "the", "UI", "extension", "." ]
train
https://github.com/contentful/contentful-management.py/blob/707dd30883b98a10c7ff0f7f5bdb8edbdc1d8df0/contentful_management/ui_extension.py#L78-L88
contentful/contentful-management.py
contentful_management/api_key.py
ApiKey.create_attributes
def create_attributes(klass, attributes, previous_object=None): """ Attributes for resource creation. """ return { 'name': attributes.get( 'name', previous_object.name if previous_object is not None else '' ), 'description': attributes.get( 'description', previous_object.description if previous_object is not None else '' ), 'environments': attributes.get( 'environments', [e.to_json() for e in previous_object.environments] if previous_object is not None else [] # Will default to master if empty ) }
python
def create_attributes(klass, attributes, previous_object=None): """ Attributes for resource creation. """ return { 'name': attributes.get( 'name', previous_object.name if previous_object is not None else '' ), 'description': attributes.get( 'description', previous_object.description if previous_object is not None else '' ), 'environments': attributes.get( 'environments', [e.to_json() for e in previous_object.environments] if previous_object is not None else [] # Will default to master if empty ) }
[ "def", "create_attributes", "(", "klass", ",", "attributes", ",", "previous_object", "=", "None", ")", ":", "return", "{", "'name'", ":", "attributes", ".", "get", "(", "'name'", ",", "previous_object", ".", "name", "if", "previous_object", "is", "not", "None", "else", "''", ")", ",", "'description'", ":", "attributes", ".", "get", "(", "'description'", ",", "previous_object", ".", "description", "if", "previous_object", "is", "not", "None", "else", "''", ")", ",", "'environments'", ":", "attributes", ".", "get", "(", "'environments'", ",", "[", "e", ".", "to_json", "(", ")", "for", "e", "in", "previous_object", ".", "environments", "]", "if", "previous_object", "is", "not", "None", "else", "[", "]", "# Will default to master if empty", ")", "}" ]
Attributes for resource creation.
[ "Attributes", "for", "resource", "creation", "." ]
train
https://github.com/contentful/contentful-management.py/blob/707dd30883b98a10c7ff0f7f5bdb8edbdc1d8df0/contentful_management/api_key.py#L34-L52
contentful/contentful-management.py
contentful_management/api_key.py
ApiKey.to_json
def to_json(self): """ Returns the JSON representation of the API key. """ result = super(ApiKey, self).to_json() result.update({ 'name': self.name, 'description': self.description, 'accessToken': self.access_token, 'environments': [e.to_json() for e in self.environments] }) return result
python
def to_json(self): """ Returns the JSON representation of the API key. """ result = super(ApiKey, self).to_json() result.update({ 'name': self.name, 'description': self.description, 'accessToken': self.access_token, 'environments': [e.to_json() for e in self.environments] }) return result
[ "def", "to_json", "(", "self", ")", ":", "result", "=", "super", "(", "ApiKey", ",", "self", ")", ".", "to_json", "(", ")", "result", ".", "update", "(", "{", "'name'", ":", "self", ".", "name", ",", "'description'", ":", "self", ".", "description", ",", "'accessToken'", ":", "self", ".", "access_token", ",", "'environments'", ":", "[", "e", ".", "to_json", "(", ")", "for", "e", "in", "self", ".", "environments", "]", "}", ")", "return", "result" ]
Returns the JSON representation of the API key.
[ "Returns", "the", "JSON", "representation", "of", "the", "API", "key", "." ]
train
https://github.com/contentful/contentful-management.py/blob/707dd30883b98a10c7ff0f7f5bdb8edbdc1d8df0/contentful_management/api_key.py#L70-L82
contentful/contentful-management.py
contentful_management/api_usages_proxy.py
ApiUsagesProxy.all
def all(self, usage_type, usage_period_id, api, query=None, *args, **kwargs): """ Gets all api usages by type for a given period an api. """ if query is None: query = {} mandatory_query = { 'filters[usagePeriod]': usage_period_id, 'filters[metric]': api } mandatory_query.update(query) return self.client._get( self._url(usage_type), mandatory_query, headers={ 'x-contentful-enable-alpha-feature': 'usage-insights' } )
python
def all(self, usage_type, usage_period_id, api, query=None, *args, **kwargs): """ Gets all api usages by type for a given period an api. """ if query is None: query = {} mandatory_query = { 'filters[usagePeriod]': usage_period_id, 'filters[metric]': api } mandatory_query.update(query) return self.client._get( self._url(usage_type), mandatory_query, headers={ 'x-contentful-enable-alpha-feature': 'usage-insights' } )
[ "def", "all", "(", "self", ",", "usage_type", ",", "usage_period_id", ",", "api", ",", "query", "=", "None", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "query", "is", "None", ":", "query", "=", "{", "}", "mandatory_query", "=", "{", "'filters[usagePeriod]'", ":", "usage_period_id", ",", "'filters[metric]'", ":", "api", "}", "mandatory_query", ".", "update", "(", "query", ")", "return", "self", ".", "client", ".", "_get", "(", "self", ".", "_url", "(", "usage_type", ")", ",", "mandatory_query", ",", "headers", "=", "{", "'x-contentful-enable-alpha-feature'", ":", "'usage-insights'", "}", ")" ]
Gets all api usages by type for a given period an api.
[ "Gets", "all", "api", "usages", "by", "type", "for", "a", "given", "period", "an", "api", "." ]
train
https://github.com/contentful/contentful-management.py/blob/707dd30883b98a10c7ff0f7f5bdb8edbdc1d8df0/contentful_management/api_usages_proxy.py#L31-L52
contentful/contentful-management.py
contentful_management/content_type.py
ContentType.base_url
def base_url(klass, space_id, resource_id=None, public=False, environment_id=None, **kwargs): """ Returns the URI for the content type. """ if public: environment_slug = "" if environment_id is not None: environment_slug = "/environments/{0}".format(environment_id) return "spaces/{0}{1}/public/content_types".format(space_id, environment_slug) return super(ContentType, klass).base_url( space_id, resource_id=resource_id, environment_id=environment_id, **kwargs )
python
def base_url(klass, space_id, resource_id=None, public=False, environment_id=None, **kwargs): """ Returns the URI for the content type. """ if public: environment_slug = "" if environment_id is not None: environment_slug = "/environments/{0}".format(environment_id) return "spaces/{0}{1}/public/content_types".format(space_id, environment_slug) return super(ContentType, klass).base_url( space_id, resource_id=resource_id, environment_id=environment_id, **kwargs )
[ "def", "base_url", "(", "klass", ",", "space_id", ",", "resource_id", "=", "None", ",", "public", "=", "False", ",", "environment_id", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "public", ":", "environment_slug", "=", "\"\"", "if", "environment_id", "is", "not", "None", ":", "environment_slug", "=", "\"/environments/{0}\"", ".", "format", "(", "environment_id", ")", "return", "\"spaces/{0}{1}/public/content_types\"", ".", "format", "(", "space_id", ",", "environment_slug", ")", "return", "super", "(", "ContentType", ",", "klass", ")", ".", "base_url", "(", "space_id", ",", "resource_id", "=", "resource_id", ",", "environment_id", "=", "environment_id", ",", "*", "*", "kwargs", ")" ]
Returns the URI for the content type.
[ "Returns", "the", "URI", "for", "the", "content", "type", "." ]
train
https://github.com/contentful/contentful-management.py/blob/707dd30883b98a10c7ff0f7f5bdb8edbdc1d8df0/contentful_management/content_type.py#L35-L50
contentful/contentful-management.py
contentful_management/content_type.py
ContentType.create_attributes
def create_attributes(klass, attributes, previous_object=None): """ Attributes for content type creation. """ result = super(ContentType, klass).create_attributes(attributes, previous_object) if 'fields' not in result: result['fields'] = [] return result
python
def create_attributes(klass, attributes, previous_object=None): """ Attributes for content type creation. """ result = super(ContentType, klass).create_attributes(attributes, previous_object) if 'fields' not in result: result['fields'] = [] return result
[ "def", "create_attributes", "(", "klass", ",", "attributes", ",", "previous_object", "=", "None", ")", ":", "result", "=", "super", "(", "ContentType", ",", "klass", ")", ".", "create_attributes", "(", "attributes", ",", "previous_object", ")", "if", "'fields'", "not", "in", "result", ":", "result", "[", "'fields'", "]", "=", "[", "]", "return", "result" ]
Attributes for content type creation.
[ "Attributes", "for", "content", "type", "creation", "." ]
train
https://github.com/contentful/contentful-management.py/blob/707dd30883b98a10c7ff0f7f5bdb8edbdc1d8df0/contentful_management/content_type.py#L53-L62
contentful/contentful-management.py
contentful_management/content_type.py
ContentType.to_json
def to_json(self): """ Returns the JSON representation of the content type. """ result = super(ContentType, self).to_json() result.update({ 'name': self.name, 'description': self.description, 'displayField': self.display_field, 'fields': [f.to_json() for f in self.fields] }) return result
python
def to_json(self): """ Returns the JSON representation of the content type. """ result = super(ContentType, self).to_json() result.update({ 'name': self.name, 'description': self.description, 'displayField': self.display_field, 'fields': [f.to_json() for f in self.fields] }) return result
[ "def", "to_json", "(", "self", ")", ":", "result", "=", "super", "(", "ContentType", ",", "self", ")", ".", "to_json", "(", ")", "result", ".", "update", "(", "{", "'name'", ":", "self", ".", "name", ",", "'description'", ":", "self", ".", "description", ",", "'displayField'", ":", "self", ".", "display_field", ",", "'fields'", ":", "[", "f", ".", "to_json", "(", ")", "for", "f", "in", "self", ".", "fields", "]", "}", ")", "return", "result" ]
Returns the JSON representation of the content type.
[ "Returns", "the", "JSON", "representation", "of", "the", "content", "type", "." ]
train
https://github.com/contentful/contentful-management.py/blob/707dd30883b98a10c7ff0f7f5bdb8edbdc1d8df0/contentful_management/content_type.py#L77-L89
contentful/contentful-management.py
contentful_management/content_type.py
ContentType.entries
def entries(self): """ Provides access to entry management methods for the given content type. API reference: https://www.contentful.com/developers/docs/references/content-management-api/#/reference/entries :return: :class:`ContentTypeEntriesProxy <contentful_management.content_type_entries_proxy.ContentTypeEntriesProxy>` object. :rtype: contentful.content_type_entries_proxy.ContentTypeEntriesProxy Usage: >>> content_type_entries_proxy = content_type.entries() <ContentTypeEntriesProxy space_id="cfexampleapi" environment_id="master" content_type_id="cat"> """ return ContentTypeEntriesProxy(self._client, self.space.id, self._environment_id, self.id)
python
def entries(self): """ Provides access to entry management methods for the given content type. API reference: https://www.contentful.com/developers/docs/references/content-management-api/#/reference/entries :return: :class:`ContentTypeEntriesProxy <contentful_management.content_type_entries_proxy.ContentTypeEntriesProxy>` object. :rtype: contentful.content_type_entries_proxy.ContentTypeEntriesProxy Usage: >>> content_type_entries_proxy = content_type.entries() <ContentTypeEntriesProxy space_id="cfexampleapi" environment_id="master" content_type_id="cat"> """ return ContentTypeEntriesProxy(self._client, self.space.id, self._environment_id, self.id)
[ "def", "entries", "(", "self", ")", ":", "return", "ContentTypeEntriesProxy", "(", "self", ".", "_client", ",", "self", ".", "space", ".", "id", ",", "self", ".", "_environment_id", ",", "self", ".", "id", ")" ]
Provides access to entry management methods for the given content type. API reference: https://www.contentful.com/developers/docs/references/content-management-api/#/reference/entries :return: :class:`ContentTypeEntriesProxy <contentful_management.content_type_entries_proxy.ContentTypeEntriesProxy>` object. :rtype: contentful.content_type_entries_proxy.ContentTypeEntriesProxy Usage: >>> content_type_entries_proxy = content_type.entries() <ContentTypeEntriesProxy space_id="cfexampleapi" environment_id="master" content_type_id="cat">
[ "Provides", "access", "to", "entry", "management", "methods", "for", "the", "given", "content", "type", "." ]
train
https://github.com/contentful/contentful-management.py/blob/707dd30883b98a10c7ff0f7f5bdb8edbdc1d8df0/contentful_management/content_type.py#L91-L105
contentful/contentful-management.py
contentful_management/content_type.py
ContentType.editor_interfaces
def editor_interfaces(self): """ Provides access to editor interface management methods for the given content type. API reference: https://www.contentful.com/developers/docs/references/content-management-api/#/reference/editor-interface :return: :class:`ContentTypeEditorInterfacesProxy <contentful_management.content_type_editor_interfaces_proxy.ContentTypeEditorInterfacesProxy>` object. :rtype: contentful.content_type_editor_interfaces_proxy.ContentTypeEditorInterfacesProxy Usage: >>> content_type_editor_interfaces_proxy = content_type.editor_interfaces() <ContentTypeEditorInterfacesProxy space_id="cfexampleapi" environment_id="master" content_type_id="cat"> """ return ContentTypeEditorInterfacesProxy(self._client, self.space.id, self._environment_id, self.id)
python
def editor_interfaces(self): """ Provides access to editor interface management methods for the given content type. API reference: https://www.contentful.com/developers/docs/references/content-management-api/#/reference/editor-interface :return: :class:`ContentTypeEditorInterfacesProxy <contentful_management.content_type_editor_interfaces_proxy.ContentTypeEditorInterfacesProxy>` object. :rtype: contentful.content_type_editor_interfaces_proxy.ContentTypeEditorInterfacesProxy Usage: >>> content_type_editor_interfaces_proxy = content_type.editor_interfaces() <ContentTypeEditorInterfacesProxy space_id="cfexampleapi" environment_id="master" content_type_id="cat"> """ return ContentTypeEditorInterfacesProxy(self._client, self.space.id, self._environment_id, self.id)
[ "def", "editor_interfaces", "(", "self", ")", ":", "return", "ContentTypeEditorInterfacesProxy", "(", "self", ".", "_client", ",", "self", ".", "space", ".", "id", ",", "self", ".", "_environment_id", ",", "self", ".", "id", ")" ]
Provides access to editor interface management methods for the given content type. API reference: https://www.contentful.com/developers/docs/references/content-management-api/#/reference/editor-interface :return: :class:`ContentTypeEditorInterfacesProxy <contentful_management.content_type_editor_interfaces_proxy.ContentTypeEditorInterfacesProxy>` object. :rtype: contentful.content_type_editor_interfaces_proxy.ContentTypeEditorInterfacesProxy Usage: >>> content_type_editor_interfaces_proxy = content_type.editor_interfaces() <ContentTypeEditorInterfacesProxy space_id="cfexampleapi" environment_id="master" content_type_id="cat">
[ "Provides", "access", "to", "editor", "interface", "management", "methods", "for", "the", "given", "content", "type", "." ]
train
https://github.com/contentful/contentful-management.py/blob/707dd30883b98a10c7ff0f7f5bdb8edbdc1d8df0/contentful_management/content_type.py#L107-L121
contentful/contentful-management.py
contentful_management/content_type.py
ContentType.snapshots
def snapshots(self): """ Provides access to snapshot management methods for the given content type. API reference: https://www.contentful.com/developers/docs/references/content-management-api/#/reference/snapshots/content-type-snapshots-collection :return: :class:`ContentTypeSnapshotsProxy <contentful_management.content_type_snapshots_proxy.ContentTypeSnapshotsProxy>` object. :rtype: contentful.content_type_snapshots_proxy.ContentTypeSnapshotsProxy Usage: >>> content_type_snapshots_proxy = content_type.entries() <ContentTypeSnapshotsProxy space_id="cfexampleapi" environment_id="master" content_type_id="cat"> """ return ContentTypeSnapshotsProxy(self._client, self.space.id, self._environment_id, self.id)
python
def snapshots(self): """ Provides access to snapshot management methods for the given content type. API reference: https://www.contentful.com/developers/docs/references/content-management-api/#/reference/snapshots/content-type-snapshots-collection :return: :class:`ContentTypeSnapshotsProxy <contentful_management.content_type_snapshots_proxy.ContentTypeSnapshotsProxy>` object. :rtype: contentful.content_type_snapshots_proxy.ContentTypeSnapshotsProxy Usage: >>> content_type_snapshots_proxy = content_type.entries() <ContentTypeSnapshotsProxy space_id="cfexampleapi" environment_id="master" content_type_id="cat"> """ return ContentTypeSnapshotsProxy(self._client, self.space.id, self._environment_id, self.id)
[ "def", "snapshots", "(", "self", ")", ":", "return", "ContentTypeSnapshotsProxy", "(", "self", ".", "_client", ",", "self", ".", "space", ".", "id", ",", "self", ".", "_environment_id", ",", "self", ".", "id", ")" ]
Provides access to snapshot management methods for the given content type. API reference: https://www.contentful.com/developers/docs/references/content-management-api/#/reference/snapshots/content-type-snapshots-collection :return: :class:`ContentTypeSnapshotsProxy <contentful_management.content_type_snapshots_proxy.ContentTypeSnapshotsProxy>` object. :rtype: contentful.content_type_snapshots_proxy.ContentTypeSnapshotsProxy Usage: >>> content_type_snapshots_proxy = content_type.entries() <ContentTypeSnapshotsProxy space_id="cfexampleapi" environment_id="master" content_type_id="cat">
[ "Provides", "access", "to", "snapshot", "management", "methods", "for", "the", "given", "content", "type", "." ]
train
https://github.com/contentful/contentful-management.py/blob/707dd30883b98a10c7ff0f7f5bdb8edbdc1d8df0/contentful_management/content_type.py#L123-L137
contentful/contentful-management.py
contentful_management/organizations_proxy.py
OrganizationsProxy.all
def all(self, query=None, **kwargs): """ Gets all organizations. """ return super(OrganizationsProxy, self).all(query=query)
python
def all(self, query=None, **kwargs): """ Gets all organizations. """ return super(OrganizationsProxy, self).all(query=query)
[ "def", "all", "(", "self", ",", "query", "=", "None", ",", "*", "*", "kwargs", ")", ":", "return", "super", "(", "OrganizationsProxy", ",", "self", ")", ".", "all", "(", "query", "=", "query", ")" ]
Gets all organizations.
[ "Gets", "all", "organizations", "." ]
train
https://github.com/contentful/contentful-management.py/blob/707dd30883b98a10c7ff0f7f5bdb8edbdc1d8df0/contentful_management/organizations_proxy.py#L33-L38
contentful/contentful-management.py
contentful_management/webhook_call.py
WebhookCall.base_url
def base_url(klass, space_id, webhook_id, resource_id=None): """ Returns the URI for the webhook call. """ return "spaces/{0}/webhooks/{1}/calls/{2}".format( space_id, webhook_id, resource_id if resource_id is not None else '' )
python
def base_url(klass, space_id, webhook_id, resource_id=None): """ Returns the URI for the webhook call. """ return "spaces/{0}/webhooks/{1}/calls/{2}".format( space_id, webhook_id, resource_id if resource_id is not None else '' )
[ "def", "base_url", "(", "klass", ",", "space_id", ",", "webhook_id", ",", "resource_id", "=", "None", ")", ":", "return", "\"spaces/{0}/webhooks/{1}/calls/{2}\"", ".", "format", "(", "space_id", ",", "webhook_id", ",", "resource_id", "if", "resource_id", "is", "not", "None", "else", "''", ")" ]
Returns the URI for the webhook call.
[ "Returns", "the", "URI", "for", "the", "webhook", "call", "." ]
train
https://github.com/contentful/contentful-management.py/blob/707dd30883b98a10c7ff0f7f5bdb8edbdc1d8df0/contentful_management/webhook_call.py#L42-L51
contentful/contentful-management.py
contentful_management/space.py
Space.create_attributes
def create_attributes(klass, attributes, previous_object=None): """Attributes for space creation.""" if previous_object is not None: return {'name': attributes.get('name', previous_object.name)} return { 'name': attributes.get('name', ''), 'defaultLocale': attributes['default_locale'] }
python
def create_attributes(klass, attributes, previous_object=None): """Attributes for space creation.""" if previous_object is not None: return {'name': attributes.get('name', previous_object.name)} return { 'name': attributes.get('name', ''), 'defaultLocale': attributes['default_locale'] }
[ "def", "create_attributes", "(", "klass", ",", "attributes", ",", "previous_object", "=", "None", ")", ":", "if", "previous_object", "is", "not", "None", ":", "return", "{", "'name'", ":", "attributes", ".", "get", "(", "'name'", ",", "previous_object", ".", "name", ")", "}", "return", "{", "'name'", ":", "attributes", ".", "get", "(", "'name'", ",", "''", ")", ",", "'defaultLocale'", ":", "attributes", "[", "'default_locale'", "]", "}" ]
Attributes for space creation.
[ "Attributes", "for", "space", "creation", "." ]
train
https://github.com/contentful/contentful-management.py/blob/707dd30883b98a10c7ff0f7f5bdb8edbdc1d8df0/contentful_management/space.py#L54-L62
contentful/contentful-management.py
contentful_management/space.py
Space.reload
def reload(self): """ Reloads the space. """ result = self._client._get( self.__class__.base_url( self.sys['id'] ) ) self._update_from_resource(result) return self
python
def reload(self): """ Reloads the space. """ result = self._client._get( self.__class__.base_url( self.sys['id'] ) ) self._update_from_resource(result) return self
[ "def", "reload", "(", "self", ")", ":", "result", "=", "self", ".", "_client", ".", "_get", "(", "self", ".", "__class__", ".", "base_url", "(", "self", ".", "sys", "[", "'id'", "]", ")", ")", "self", ".", "_update_from_resource", "(", "result", ")", "return", "self" ]
Reloads the space.
[ "Reloads", "the", "space", "." ]
train
https://github.com/contentful/contentful-management.py/blob/707dd30883b98a10c7ff0f7f5bdb8edbdc1d8df0/contentful_management/space.py#L96-L109
contentful/contentful-management.py
contentful_management/space.py
Space.delete
def delete(self): """ Deletes the space """ return self._client._delete( self.__class__.base_url( self.sys['id'] ) )
python
def delete(self): """ Deletes the space """ return self._client._delete( self.__class__.base_url( self.sys['id'] ) )
[ "def", "delete", "(", "self", ")", ":", "return", "self", ".", "_client", ".", "_delete", "(", "self", ".", "__class__", ".", "base_url", "(", "self", ".", "sys", "[", "'id'", "]", ")", ")" ]
Deletes the space
[ "Deletes", "the", "space" ]
train
https://github.com/contentful/contentful-management.py/blob/707dd30883b98a10c7ff0f7f5bdb8edbdc1d8df0/contentful_management/space.py#L111-L120
contentful/contentful-management.py
contentful_management/space.py
Space.to_json
def to_json(self): """ Returns the JSON representation of the space. """ result = super(Space, self).to_json() result.update({'name': self.name}) return result
python
def to_json(self): """ Returns the JSON representation of the space. """ result = super(Space, self).to_json() result.update({'name': self.name}) return result
[ "def", "to_json", "(", "self", ")", ":", "result", "=", "super", "(", "Space", ",", "self", ")", ".", "to_json", "(", ")", "result", ".", "update", "(", "{", "'name'", ":", "self", ".", "name", "}", ")", "return", "result" ]
Returns the JSON representation of the space.
[ "Returns", "the", "JSON", "representation", "of", "the", "space", "." ]
train
https://github.com/contentful/contentful-management.py/blob/707dd30883b98a10c7ff0f7f5bdb8edbdc1d8df0/contentful_management/space.py#L122-L129
contentful/contentful-management.py
contentful_management/spaces_proxy.py
SpacesProxy.all
def all(self, query=None, **kwargs): """ Gets all spaces. """ return super(SpacesProxy, self).all(query=query)
python
def all(self, query=None, **kwargs): """ Gets all spaces. """ return super(SpacesProxy, self).all(query=query)
[ "def", "all", "(", "self", ",", "query", "=", "None", ",", "*", "*", "kwargs", ")", ":", "return", "super", "(", "SpacesProxy", ",", "self", ")", ".", "all", "(", "query", "=", "query", ")" ]
Gets all spaces.
[ "Gets", "all", "spaces", "." ]
train
https://github.com/contentful/contentful-management.py/blob/707dd30883b98a10c7ff0f7f5bdb8edbdc1d8df0/contentful_management/spaces_proxy.py#L33-L38
contentful/contentful-management.py
contentful_management/spaces_proxy.py
SpacesProxy.find
def find(self, space_id, query=None, **kwargs): """ Gets a space by ID. """ try: self.space_id = space_id return super(SpacesProxy, self).find(space_id, query=query) finally: self.space_id = None
python
def find(self, space_id, query=None, **kwargs): """ Gets a space by ID. """ try: self.space_id = space_id return super(SpacesProxy, self).find(space_id, query=query) finally: self.space_id = None
[ "def", "find", "(", "self", ",", "space_id", ",", "query", "=", "None", ",", "*", "*", "kwargs", ")", ":", "try", ":", "self", ".", "space_id", "=", "space_id", "return", "super", "(", "SpacesProxy", ",", "self", ")", ".", "find", "(", "space_id", ",", "query", "=", "query", ")", "finally", ":", "self", ".", "space_id", "=", "None" ]
Gets a space by ID.
[ "Gets", "a", "space", "by", "ID", "." ]
train
https://github.com/contentful/contentful-management.py/blob/707dd30883b98a10c7ff0f7f5bdb8edbdc1d8df0/contentful_management/spaces_proxy.py#L40-L49
contentful/contentful-management.py
contentful_management/spaces_proxy.py
SpacesProxy.create
def create(self, attributes=None, **kwargs): """ Creates a space with given attributes. """ if attributes is None: attributes = {} if 'default_locale' not in attributes: attributes['default_locale'] = self.client.default_locale return super(SpacesProxy, self).create(resource_id=None, attributes=attributes)
python
def create(self, attributes=None, **kwargs): """ Creates a space with given attributes. """ if attributes is None: attributes = {} if 'default_locale' not in attributes: attributes['default_locale'] = self.client.default_locale return super(SpacesProxy, self).create(resource_id=None, attributes=attributes)
[ "def", "create", "(", "self", ",", "attributes", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "attributes", "is", "None", ":", "attributes", "=", "{", "}", "if", "'default_locale'", "not", "in", "attributes", ":", "attributes", "[", "'default_locale'", "]", "=", "self", ".", "client", ".", "default_locale", "return", "super", "(", "SpacesProxy", ",", "self", ")", ".", "create", "(", "resource_id", "=", "None", ",", "attributes", "=", "attributes", ")" ]
Creates a space with given attributes.
[ "Creates", "a", "space", "with", "given", "attributes", "." ]
train
https://github.com/contentful/contentful-management.py/blob/707dd30883b98a10c7ff0f7f5bdb8edbdc1d8df0/contentful_management/spaces_proxy.py#L51-L61
contentful/contentful-management.py
contentful_management/spaces_proxy.py
SpacesProxy.delete
def delete(self, space_id): """ Deletes a space by ID. """ try: self.space_id = space_id return super(SpacesProxy, self).delete(space_id) finally: self.space_id = None
python
def delete(self, space_id): """ Deletes a space by ID. """ try: self.space_id = space_id return super(SpacesProxy, self).delete(space_id) finally: self.space_id = None
[ "def", "delete", "(", "self", ",", "space_id", ")", ":", "try", ":", "self", ".", "space_id", "=", "space_id", "return", "super", "(", "SpacesProxy", ",", "self", ")", ".", "delete", "(", "space_id", ")", "finally", ":", "self", ".", "space_id", "=", "None" ]
Deletes a space by ID.
[ "Deletes", "a", "space", "by", "ID", "." ]
train
https://github.com/contentful/contentful-management.py/blob/707dd30883b98a10c7ff0f7f5bdb8edbdc1d8df0/contentful_management/spaces_proxy.py#L63-L72
contentful/contentful-management.py
contentful_management/client.py
Client.editor_interfaces
def editor_interfaces(self, space_id, environment_id, content_type_id): """ Provides access to editor interfaces management methods. API reference: https://www.contentful.com/developers/docs/references/content-management-api/#/reference/editor-interface :return: :class:`EditorInterfacesProxy <contentful_management.editor_interfaces_proxy.EditorInterfacesProxy>` object. :rtype: contentful.editor_interfaces_proxy.EditorInterfacesProxy Usage: >>> editor_interfaces_proxy = client.editor_interfaces('cfexampleapi', 'master', 'cat') <EditorInterfacesProxy space_id="cfexampleapi" environment_id="master" content_type_id="cat"> """ return EditorInterfacesProxy(self, space_id, environment_id, content_type_id)
python
def editor_interfaces(self, space_id, environment_id, content_type_id): """ Provides access to editor interfaces management methods. API reference: https://www.contentful.com/developers/docs/references/content-management-api/#/reference/editor-interface :return: :class:`EditorInterfacesProxy <contentful_management.editor_interfaces_proxy.EditorInterfacesProxy>` object. :rtype: contentful.editor_interfaces_proxy.EditorInterfacesProxy Usage: >>> editor_interfaces_proxy = client.editor_interfaces('cfexampleapi', 'master', 'cat') <EditorInterfacesProxy space_id="cfexampleapi" environment_id="master" content_type_id="cat"> """ return EditorInterfacesProxy(self, space_id, environment_id, content_type_id)
[ "def", "editor_interfaces", "(", "self", ",", "space_id", ",", "environment_id", ",", "content_type_id", ")", ":", "return", "EditorInterfacesProxy", "(", "self", ",", "space_id", ",", "environment_id", ",", "content_type_id", ")" ]
Provides access to editor interfaces management methods. API reference: https://www.contentful.com/developers/docs/references/content-management-api/#/reference/editor-interface :return: :class:`EditorInterfacesProxy <contentful_management.editor_interfaces_proxy.EditorInterfacesProxy>` object. :rtype: contentful.editor_interfaces_proxy.EditorInterfacesProxy Usage: >>> editor_interfaces_proxy = client.editor_interfaces('cfexampleapi', 'master', 'cat') <EditorInterfacesProxy space_id="cfexampleapi" environment_id="master" content_type_id="cat">
[ "Provides", "access", "to", "editor", "interfaces", "management", "methods", "." ]
train
https://github.com/contentful/contentful-management.py/blob/707dd30883b98a10c7ff0f7f5bdb8edbdc1d8df0/contentful_management/client.py#L444-L459
contentful/contentful-management.py
contentful_management/client.py
Client.snapshots
def snapshots(self, space_id, environment_id, resource_id, resource_kind='entries'): """ Provides access to snapshot management methods. API reference: https://www.contentful.com/developers/docs/references/content-management-api/#/reference/snapshots :return: :class:`SnapshotsProxy <contentful_management.snapshots_proxy.SnapshotsProxy>` object. :rtype: contentful.snapshots_proxy.SnapshotsProxy Usage: >>> entry_snapshots_proxy = client.snapshots('cfexampleapi', 'master', 'nyancat') <SnapshotsProxy[entries] space_id="cfexampleapi" environment_id="master" parent_resource_id="nyancat"> >>> content_type_snapshots_proxy = client.snapshots('cfexampleapi', 'master', 'cat', 'content_types') <SnapshotsProxy[content_types] space_id="cfexampleapi" environment_id="master" parent_resource_id="cat"> """ return SnapshotsProxy(self, space_id, environment_id, resource_id, resource_kind)
python
def snapshots(self, space_id, environment_id, resource_id, resource_kind='entries'): """ Provides access to snapshot management methods. API reference: https://www.contentful.com/developers/docs/references/content-management-api/#/reference/snapshots :return: :class:`SnapshotsProxy <contentful_management.snapshots_proxy.SnapshotsProxy>` object. :rtype: contentful.snapshots_proxy.SnapshotsProxy Usage: >>> entry_snapshots_proxy = client.snapshots('cfexampleapi', 'master', 'nyancat') <SnapshotsProxy[entries] space_id="cfexampleapi" environment_id="master" parent_resource_id="nyancat"> >>> content_type_snapshots_proxy = client.snapshots('cfexampleapi', 'master', 'cat', 'content_types') <SnapshotsProxy[content_types] space_id="cfexampleapi" environment_id="master" parent_resource_id="cat"> """ return SnapshotsProxy(self, space_id, environment_id, resource_id, resource_kind)
[ "def", "snapshots", "(", "self", ",", "space_id", ",", "environment_id", ",", "resource_id", ",", "resource_kind", "=", "'entries'", ")", ":", "return", "SnapshotsProxy", "(", "self", ",", "space_id", ",", "environment_id", ",", "resource_id", ",", "resource_kind", ")" ]
Provides access to snapshot management methods. API reference: https://www.contentful.com/developers/docs/references/content-management-api/#/reference/snapshots :return: :class:`SnapshotsProxy <contentful_management.snapshots_proxy.SnapshotsProxy>` object. :rtype: contentful.snapshots_proxy.SnapshotsProxy Usage: >>> entry_snapshots_proxy = client.snapshots('cfexampleapi', 'master', 'nyancat') <SnapshotsProxy[entries] space_id="cfexampleapi" environment_id="master" parent_resource_id="nyancat"> >>> content_type_snapshots_proxy = client.snapshots('cfexampleapi', 'master', 'cat', 'content_types') <SnapshotsProxy[content_types] space_id="cfexampleapi" environment_id="master" parent_resource_id="cat">
[ "Provides", "access", "to", "snapshot", "management", "methods", "." ]
train
https://github.com/contentful/contentful-management.py/blob/707dd30883b98a10c7ff0f7f5bdb8edbdc1d8df0/contentful_management/client.py#L461-L479
contentful/contentful-management.py
contentful_management/client.py
Client.entry_snapshots
def entry_snapshots(self, space_id, environment_id, entry_id): """ Provides access to entry snapshot management methods. API reference: https://www.contentful.com/developers/docs/references/content-management-api/#/reference/snapshots :return: :class:`SnapshotsProxy <contentful_management.snapshots_proxy.SnapshotsProxy>` object. :rtype: contentful.snapshots_proxy.SnapshotsProxy Usage: >>> entry_snapshots_proxy = client.entry_snapshots('cfexampleapi', 'master', 'nyancat') <SnapshotsProxy[entries] space_id="cfexampleapi" environment_id="master" parent_resource_id="nyancat"> """ return SnapshotsProxy(self, space_id, environment_id, entry_id, 'entries')
python
def entry_snapshots(self, space_id, environment_id, entry_id): """ Provides access to entry snapshot management methods. API reference: https://www.contentful.com/developers/docs/references/content-management-api/#/reference/snapshots :return: :class:`SnapshotsProxy <contentful_management.snapshots_proxy.SnapshotsProxy>` object. :rtype: contentful.snapshots_proxy.SnapshotsProxy Usage: >>> entry_snapshots_proxy = client.entry_snapshots('cfexampleapi', 'master', 'nyancat') <SnapshotsProxy[entries] space_id="cfexampleapi" environment_id="master" parent_resource_id="nyancat"> """ return SnapshotsProxy(self, space_id, environment_id, entry_id, 'entries')
[ "def", "entry_snapshots", "(", "self", ",", "space_id", ",", "environment_id", ",", "entry_id", ")", ":", "return", "SnapshotsProxy", "(", "self", ",", "space_id", ",", "environment_id", ",", "entry_id", ",", "'entries'", ")" ]
Provides access to entry snapshot management methods. API reference: https://www.contentful.com/developers/docs/references/content-management-api/#/reference/snapshots :return: :class:`SnapshotsProxy <contentful_management.snapshots_proxy.SnapshotsProxy>` object. :rtype: contentful.snapshots_proxy.SnapshotsProxy Usage: >>> entry_snapshots_proxy = client.entry_snapshots('cfexampleapi', 'master', 'nyancat') <SnapshotsProxy[entries] space_id="cfexampleapi" environment_id="master" parent_resource_id="nyancat">
[ "Provides", "access", "to", "entry", "snapshot", "management", "methods", "." ]
train
https://github.com/contentful/contentful-management.py/blob/707dd30883b98a10c7ff0f7f5bdb8edbdc1d8df0/contentful_management/client.py#L481-L496
contentful/contentful-management.py
contentful_management/client.py
Client.content_type_snapshots
def content_type_snapshots(self, space_id, environment_id, content_type_id): """ Provides access to content type snapshot management methods. API reference: https://www.contentful.com/developers/docs/references/content-management-api/#/reference/snapshots :return: :class:`SnapshotsProxy <contentful_management.snapshots_proxy.SnapshotsProxy>` object. :rtype: contentful.snapshots_proxy.SnapshotsProxy Usage: >>> content_type_snapshots_proxy = client.content_type_snapshots('cfexampleapi', 'master', 'cat') <SnapshotsProxy[content_types] space_id="cfexampleapi" environment_id="master" parent_resource_id="cat"> """ return SnapshotsProxy(self, space_id, environment_id, content_type_id, 'content_types')
python
def content_type_snapshots(self, space_id, environment_id, content_type_id): """ Provides access to content type snapshot management methods. API reference: https://www.contentful.com/developers/docs/references/content-management-api/#/reference/snapshots :return: :class:`SnapshotsProxy <contentful_management.snapshots_proxy.SnapshotsProxy>` object. :rtype: contentful.snapshots_proxy.SnapshotsProxy Usage: >>> content_type_snapshots_proxy = client.content_type_snapshots('cfexampleapi', 'master', 'cat') <SnapshotsProxy[content_types] space_id="cfexampleapi" environment_id="master" parent_resource_id="cat"> """ return SnapshotsProxy(self, space_id, environment_id, content_type_id, 'content_types')
[ "def", "content_type_snapshots", "(", "self", ",", "space_id", ",", "environment_id", ",", "content_type_id", ")", ":", "return", "SnapshotsProxy", "(", "self", ",", "space_id", ",", "environment_id", ",", "content_type_id", ",", "'content_types'", ")" ]
Provides access to content type snapshot management methods. API reference: https://www.contentful.com/developers/docs/references/content-management-api/#/reference/snapshots :return: :class:`SnapshotsProxy <contentful_management.snapshots_proxy.SnapshotsProxy>` object. :rtype: contentful.snapshots_proxy.SnapshotsProxy Usage: >>> content_type_snapshots_proxy = client.content_type_snapshots('cfexampleapi', 'master', 'cat') <SnapshotsProxy[content_types] space_id="cfexampleapi" environment_id="master" parent_resource_id="cat">
[ "Provides", "access", "to", "content", "type", "snapshot", "management", "methods", "." ]
train
https://github.com/contentful/contentful-management.py/blob/707dd30883b98a10c7ff0f7f5bdb8edbdc1d8df0/contentful_management/client.py#L498-L513
contentful/contentful-management.py
contentful_management/client.py
Client._validate_configuration
def _validate_configuration(self): """ Validates that required parameters are present. """ if not self.access_token: raise ConfigurationException( 'You will need to initialize a client with an Access Token' ) if not self.api_url: raise ConfigurationException( 'The client configuration needs to contain an API URL' ) if not self.default_locale: raise ConfigurationException( 'The client configuration needs to contain a Default Locale' ) if not self.api_version or self.api_version < 1: raise ConfigurationException( 'The API Version must be a positive number' )
python
def _validate_configuration(self): """ Validates that required parameters are present. """ if not self.access_token: raise ConfigurationException( 'You will need to initialize a client with an Access Token' ) if not self.api_url: raise ConfigurationException( 'The client configuration needs to contain an API URL' ) if not self.default_locale: raise ConfigurationException( 'The client configuration needs to contain a Default Locale' ) if not self.api_version or self.api_version < 1: raise ConfigurationException( 'The API Version must be a positive number' )
[ "def", "_validate_configuration", "(", "self", ")", ":", "if", "not", "self", ".", "access_token", ":", "raise", "ConfigurationException", "(", "'You will need to initialize a client with an Access Token'", ")", "if", "not", "self", ".", "api_url", ":", "raise", "ConfigurationException", "(", "'The client configuration needs to contain an API URL'", ")", "if", "not", "self", ".", "default_locale", ":", "raise", "ConfigurationException", "(", "'The client configuration needs to contain a Default Locale'", ")", "if", "not", "self", ".", "api_version", "or", "self", ".", "api_version", "<", "1", ":", "raise", "ConfigurationException", "(", "'The API Version must be a positive number'", ")" ]
Validates that required parameters are present.
[ "Validates", "that", "required", "parameters", "are", "present", "." ]
train
https://github.com/contentful/contentful-management.py/blob/707dd30883b98a10c7ff0f7f5bdb8edbdc1d8df0/contentful_management/client.py#L549-L569
contentful/contentful-management.py
contentful_management/client.py
Client._contentful_user_agent
def _contentful_user_agent(self): """ Sets the X-Contentful-User-Agent header. """ header = {} from . import __version__ header['sdk'] = { 'name': 'contentful-management.py', 'version': __version__ } header['app'] = { 'name': self.application_name, 'version': self.application_version } header['integration'] = { 'name': self.integration_name, 'version': self.integration_version } header['platform'] = { 'name': 'python', 'version': platform.python_version() } os_name = platform.system() if os_name == 'Darwin': os_name = 'macOS' elif not os_name or os_name == 'Java': os_name = None elif os_name and os_name not in ['macOS', 'Windows']: os_name = 'Linux' header['os'] = { 'name': os_name, 'version': platform.release() } def format_header(key, values): header = "{0} {1}".format(key, values['name']) if values['version'] is not None: header = "{0}/{1}".format(header, values['version']) return "{0};".format(header) result = [] for k, values in header.items(): if not values['name']: continue result.append(format_header(k, values)) return ' '.join(result)
python
def _contentful_user_agent(self): """ Sets the X-Contentful-User-Agent header. """ header = {} from . import __version__ header['sdk'] = { 'name': 'contentful-management.py', 'version': __version__ } header['app'] = { 'name': self.application_name, 'version': self.application_version } header['integration'] = { 'name': self.integration_name, 'version': self.integration_version } header['platform'] = { 'name': 'python', 'version': platform.python_version() } os_name = platform.system() if os_name == 'Darwin': os_name = 'macOS' elif not os_name or os_name == 'Java': os_name = None elif os_name and os_name not in ['macOS', 'Windows']: os_name = 'Linux' header['os'] = { 'name': os_name, 'version': platform.release() } def format_header(key, values): header = "{0} {1}".format(key, values['name']) if values['version'] is not None: header = "{0}/{1}".format(header, values['version']) return "{0};".format(header) result = [] for k, values in header.items(): if not values['name']: continue result.append(format_header(k, values)) return ' '.join(result)
[ "def", "_contentful_user_agent", "(", "self", ")", ":", "header", "=", "{", "}", "from", ".", "import", "__version__", "header", "[", "'sdk'", "]", "=", "{", "'name'", ":", "'contentful-management.py'", ",", "'version'", ":", "__version__", "}", "header", "[", "'app'", "]", "=", "{", "'name'", ":", "self", ".", "application_name", ",", "'version'", ":", "self", ".", "application_version", "}", "header", "[", "'integration'", "]", "=", "{", "'name'", ":", "self", ".", "integration_name", ",", "'version'", ":", "self", ".", "integration_version", "}", "header", "[", "'platform'", "]", "=", "{", "'name'", ":", "'python'", ",", "'version'", ":", "platform", ".", "python_version", "(", ")", "}", "os_name", "=", "platform", ".", "system", "(", ")", "if", "os_name", "==", "'Darwin'", ":", "os_name", "=", "'macOS'", "elif", "not", "os_name", "or", "os_name", "==", "'Java'", ":", "os_name", "=", "None", "elif", "os_name", "and", "os_name", "not", "in", "[", "'macOS'", ",", "'Windows'", "]", ":", "os_name", "=", "'Linux'", "header", "[", "'os'", "]", "=", "{", "'name'", ":", "os_name", ",", "'version'", ":", "platform", ".", "release", "(", ")", "}", "def", "format_header", "(", "key", ",", "values", ")", ":", "header", "=", "\"{0} {1}\"", ".", "format", "(", "key", ",", "values", "[", "'name'", "]", ")", "if", "values", "[", "'version'", "]", "is", "not", "None", ":", "header", "=", "\"{0}/{1}\"", ".", "format", "(", "header", ",", "values", "[", "'version'", "]", ")", "return", "\"{0};\"", ".", "format", "(", "header", ")", "result", "=", "[", "]", "for", "k", ",", "values", "in", "header", ".", "items", "(", ")", ":", "if", "not", "values", "[", "'name'", "]", ":", "continue", "result", ".", "append", "(", "format_header", "(", "k", ",", "values", ")", ")", "return", "' '", ".", "join", "(", "result", ")" ]
Sets the X-Contentful-User-Agent header.
[ "Sets", "the", "X", "-", "Contentful", "-", "User", "-", "Agent", "header", "." ]
train
https://github.com/contentful/contentful-management.py/blob/707dd30883b98a10c7ff0f7f5bdb8edbdc1d8df0/contentful_management/client.py#L571-L618
contentful/contentful-management.py
contentful_management/client.py
Client._url
def _url(self, url, file_upload=False): """ Creates the request URL. """ host = self.api_url if file_upload: host = self.uploads_api_url protocol = 'https' if self.https else 'http' if url.endswith('/'): url = url[:-1] return '{0}://{1}/{2}'.format( protocol, host, url )
python
def _url(self, url, file_upload=False): """ Creates the request URL. """ host = self.api_url if file_upload: host = self.uploads_api_url protocol = 'https' if self.https else 'http' if url.endswith('/'): url = url[:-1] return '{0}://{1}/{2}'.format( protocol, host, url )
[ "def", "_url", "(", "self", ",", "url", ",", "file_upload", "=", "False", ")", ":", "host", "=", "self", ".", "api_url", "if", "file_upload", ":", "host", "=", "self", ".", "uploads_api_url", "protocol", "=", "'https'", "if", "self", ".", "https", "else", "'http'", "if", "url", ".", "endswith", "(", "'/'", ")", ":", "url", "=", "url", "[", ":", "-", "1", "]", "return", "'{0}://{1}/{2}'", ".", "format", "(", "protocol", ",", "host", ",", "url", ")" ]
Creates the request URL.
[ "Creates", "the", "request", "URL", "." ]
train
https://github.com/contentful/contentful-management.py/blob/707dd30883b98a10c7ff0f7f5bdb8edbdc1d8df0/contentful_management/client.py#L641-L657
contentful/contentful-management.py
contentful_management/client.py
Client._http_request
def _http_request(self, method, url, request_kwargs=None): """ Performs the requested HTTP request. """ kwargs = request_kwargs if request_kwargs is not None else {} headers = self._request_headers() headers.update(self.additional_headers) if 'headers' in kwargs: headers.update(kwargs['headers']) kwargs['headers'] = headers if self._has_proxy(): kwargs['proxies'] = self._proxy_parameters() request_url = self._url( url, file_upload=kwargs.pop('file_upload', False) ) request_method = getattr(requests, method) response = request_method(request_url, **kwargs) if response.status_code == 429: raise RateLimitExceededError(response) return response
python
def _http_request(self, method, url, request_kwargs=None): """ Performs the requested HTTP request. """ kwargs = request_kwargs if request_kwargs is not None else {} headers = self._request_headers() headers.update(self.additional_headers) if 'headers' in kwargs: headers.update(kwargs['headers']) kwargs['headers'] = headers if self._has_proxy(): kwargs['proxies'] = self._proxy_parameters() request_url = self._url( url, file_upload=kwargs.pop('file_upload', False) ) request_method = getattr(requests, method) response = request_method(request_url, **kwargs) if response.status_code == 429: raise RateLimitExceededError(response) return response
[ "def", "_http_request", "(", "self", ",", "method", ",", "url", ",", "request_kwargs", "=", "None", ")", ":", "kwargs", "=", "request_kwargs", "if", "request_kwargs", "is", "not", "None", "else", "{", "}", "headers", "=", "self", ".", "_request_headers", "(", ")", "headers", ".", "update", "(", "self", ".", "additional_headers", ")", "if", "'headers'", "in", "kwargs", ":", "headers", ".", "update", "(", "kwargs", "[", "'headers'", "]", ")", "kwargs", "[", "'headers'", "]", "=", "headers", "if", "self", ".", "_has_proxy", "(", ")", ":", "kwargs", "[", "'proxies'", "]", "=", "self", ".", "_proxy_parameters", "(", ")", "request_url", "=", "self", ".", "_url", "(", "url", ",", "file_upload", "=", "kwargs", ".", "pop", "(", "'file_upload'", ",", "False", ")", ")", "request_method", "=", "getattr", "(", "requests", ",", "method", ")", "response", "=", "request_method", "(", "request_url", ",", "*", "*", "kwargs", ")", "if", "response", ".", "status_code", "==", "429", ":", "raise", "RateLimitExceededError", "(", "response", ")", "return", "response" ]
Performs the requested HTTP request.
[ "Performs", "the", "requested", "HTTP", "request", "." ]
train
https://github.com/contentful/contentful-management.py/blob/707dd30883b98a10c7ff0f7f5bdb8edbdc1d8df0/contentful_management/client.py#L669-L696
contentful/contentful-management.py
contentful_management/client.py
Client._http_get
def _http_get(self, url, query, **kwargs): """ Performs the HTTP GET request. """ self._normalize_query(query) kwargs.update({'params': query}) return self._http_request('get', url, kwargs)
python
def _http_get(self, url, query, **kwargs): """ Performs the HTTP GET request. """ self._normalize_query(query) kwargs.update({'params': query}) return self._http_request('get', url, kwargs)
[ "def", "_http_get", "(", "self", ",", "url", ",", "query", ",", "*", "*", "kwargs", ")", ":", "self", ".", "_normalize_query", "(", "query", ")", "kwargs", ".", "update", "(", "{", "'params'", ":", "query", "}", ")", "return", "self", ".", "_http_request", "(", "'get'", ",", "url", ",", "kwargs", ")" ]
Performs the HTTP GET request.
[ "Performs", "the", "HTTP", "GET", "request", "." ]
train
https://github.com/contentful/contentful-management.py/blob/707dd30883b98a10c7ff0f7f5bdb8edbdc1d8df0/contentful_management/client.py#L698-L707
contentful/contentful-management.py
contentful_management/client.py
Client._http_post
def _http_post(self, url, data, **kwargs): """ Performs the HTTP POST request. """ if not kwargs.get('file_upload', False): data = json.dumps(data) kwargs.update({'data': data}) return self._http_request('post', url, kwargs)
python
def _http_post(self, url, data, **kwargs): """ Performs the HTTP POST request. """ if not kwargs.get('file_upload', False): data = json.dumps(data) kwargs.update({'data': data}) return self._http_request('post', url, kwargs)
[ "def", "_http_post", "(", "self", ",", "url", ",", "data", ",", "*", "*", "kwargs", ")", ":", "if", "not", "kwargs", ".", "get", "(", "'file_upload'", ",", "False", ")", ":", "data", "=", "json", ".", "dumps", "(", "data", ")", "kwargs", ".", "update", "(", "{", "'data'", ":", "data", "}", ")", "return", "self", ".", "_http_request", "(", "'post'", ",", "url", ",", "kwargs", ")" ]
Performs the HTTP POST request.
[ "Performs", "the", "HTTP", "POST", "request", "." ]
train
https://github.com/contentful/contentful-management.py/blob/707dd30883b98a10c7ff0f7f5bdb8edbdc1d8df0/contentful_management/client.py#L709-L719
contentful/contentful-management.py
contentful_management/client.py
Client._http_put
def _http_put(self, url, data, **kwargs): """ Performs the HTTP PUT request. """ kwargs.update({'data': json.dumps(data)}) return self._http_request('put', url, kwargs)
python
def _http_put(self, url, data, **kwargs): """ Performs the HTTP PUT request. """ kwargs.update({'data': json.dumps(data)}) return self._http_request('put', url, kwargs)
[ "def", "_http_put", "(", "self", ",", "url", ",", "data", ",", "*", "*", "kwargs", ")", ":", "kwargs", ".", "update", "(", "{", "'data'", ":", "json", ".", "dumps", "(", "data", ")", "}", ")", "return", "self", ".", "_http_request", "(", "'put'", ",", "url", ",", "kwargs", ")" ]
Performs the HTTP PUT request.
[ "Performs", "the", "HTTP", "PUT", "request", "." ]
train
https://github.com/contentful/contentful-management.py/blob/707dd30883b98a10c7ff0f7f5bdb8edbdc1d8df0/contentful_management/client.py#L721-L728
contentful/contentful-management.py
contentful_management/client.py
Client._request
def _request(self, method, url, query_or_data=None, **kwargs): """ Wrapper for the HTTP requests, rate limit backoff is handled here, responses are processed with ResourceBuilder. """ if query_or_data is None: query_or_data = {} request_method = getattr(self, '_http_{0}'.format(method)) response = retry_request(self)(request_method)(url, query_or_data, **kwargs) if self.raw_mode: return response if response.status_code >= 300: error = get_error(response) if self.raise_errors: raise error return error # Return response object on NoContent if response.status_code == 204 or not response.text: return response return ResourceBuilder( self, self.default_locale, response.json() ).build()
python
def _request(self, method, url, query_or_data=None, **kwargs): """ Wrapper for the HTTP requests, rate limit backoff is handled here, responses are processed with ResourceBuilder. """ if query_or_data is None: query_or_data = {} request_method = getattr(self, '_http_{0}'.format(method)) response = retry_request(self)(request_method)(url, query_or_data, **kwargs) if self.raw_mode: return response if response.status_code >= 300: error = get_error(response) if self.raise_errors: raise error return error # Return response object on NoContent if response.status_code == 204 or not response.text: return response return ResourceBuilder( self, self.default_locale, response.json() ).build()
[ "def", "_request", "(", "self", ",", "method", ",", "url", ",", "query_or_data", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "query_or_data", "is", "None", ":", "query_or_data", "=", "{", "}", "request_method", "=", "getattr", "(", "self", ",", "'_http_{0}'", ".", "format", "(", "method", ")", ")", "response", "=", "retry_request", "(", "self", ")", "(", "request_method", ")", "(", "url", ",", "query_or_data", ",", "*", "*", "kwargs", ")", "if", "self", ".", "raw_mode", ":", "return", "response", "if", "response", ".", "status_code", ">=", "300", ":", "error", "=", "get_error", "(", "response", ")", "if", "self", ".", "raise_errors", ":", "raise", "error", "return", "error", "# Return response object on NoContent", "if", "response", ".", "status_code", "==", "204", "or", "not", "response", ".", "text", ":", "return", "response", "return", "ResourceBuilder", "(", "self", ",", "self", ".", "default_locale", ",", "response", ".", "json", "(", ")", ")", ".", "build", "(", ")" ]
Wrapper for the HTTP requests, rate limit backoff is handled here, responses are processed with ResourceBuilder.
[ "Wrapper", "for", "the", "HTTP", "requests", "rate", "limit", "backoff", "is", "handled", "here", "responses", "are", "processed", "with", "ResourceBuilder", "." ]
train
https://github.com/contentful/contentful-management.py/blob/707dd30883b98a10c7ff0f7f5bdb8edbdc1d8df0/contentful_management/client.py#L737-L767
contentful/contentful-management.py
contentful_management/client.py
Client._get
def _get(self, url, query=None, **kwargs): """ Wrapper for the HTTP GET request. """ return self._request('get', url, query, **kwargs)
python
def _get(self, url, query=None, **kwargs): """ Wrapper for the HTTP GET request. """ return self._request('get', url, query, **kwargs)
[ "def", "_get", "(", "self", ",", "url", ",", "query", "=", "None", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "_request", "(", "'get'", ",", "url", ",", "query", ",", "*", "*", "kwargs", ")" ]
Wrapper for the HTTP GET request.
[ "Wrapper", "for", "the", "HTTP", "GET", "request", "." ]
train
https://github.com/contentful/contentful-management.py/blob/707dd30883b98a10c7ff0f7f5bdb8edbdc1d8df0/contentful_management/client.py#L769-L774
contentful/contentful-management.py
contentful_management/client.py
Client._post
def _post(self, url, attributes=None, **kwargs): """ Wrapper for the HTTP POST request. """ return self._request('post', url, attributes, **kwargs)
python
def _post(self, url, attributes=None, **kwargs): """ Wrapper for the HTTP POST request. """ return self._request('post', url, attributes, **kwargs)
[ "def", "_post", "(", "self", ",", "url", ",", "attributes", "=", "None", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "_request", "(", "'post'", ",", "url", ",", "attributes", ",", "*", "*", "kwargs", ")" ]
Wrapper for the HTTP POST request.
[ "Wrapper", "for", "the", "HTTP", "POST", "request", "." ]
train
https://github.com/contentful/contentful-management.py/blob/707dd30883b98a10c7ff0f7f5bdb8edbdc1d8df0/contentful_management/client.py#L776-L781
contentful/contentful-management.py
contentful_management/client.py
Client._put
def _put(self, url, attributes=None, **kwargs): """ Wrapper for the HTTP PUT request. """ return self._request('put', url, attributes, **kwargs)
python
def _put(self, url, attributes=None, **kwargs): """ Wrapper for the HTTP PUT request. """ return self._request('put', url, attributes, **kwargs)
[ "def", "_put", "(", "self", ",", "url", ",", "attributes", "=", "None", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "_request", "(", "'put'", ",", "url", ",", "attributes", ",", "*", "*", "kwargs", ")" ]
Wrapper for the HTTP PUT request.
[ "Wrapper", "for", "the", "HTTP", "PUT", "request", "." ]
train
https://github.com/contentful/contentful-management.py/blob/707dd30883b98a10c7ff0f7f5bdb8edbdc1d8df0/contentful_management/client.py#L783-L788
contentful/contentful-management.py
contentful_management/client.py
Client._delete
def _delete(self, url, **kwargs): """ Wrapper for the HTTP DELETE request. """ response = retry_request(self)(self._http_delete)(url, **kwargs) if self.raw_mode: return response if response.status_code >= 300: error = get_error(response) if self.raise_errors: raise error return error return response
python
def _delete(self, url, **kwargs): """ Wrapper for the HTTP DELETE request. """ response = retry_request(self)(self._http_delete)(url, **kwargs) if self.raw_mode: return response if response.status_code >= 300: error = get_error(response) if self.raise_errors: raise error return error return response
[ "def", "_delete", "(", "self", ",", "url", ",", "*", "*", "kwargs", ")", ":", "response", "=", "retry_request", "(", "self", ")", "(", "self", ".", "_http_delete", ")", "(", "url", ",", "*", "*", "kwargs", ")", "if", "self", ".", "raw_mode", ":", "return", "response", "if", "response", ".", "status_code", ">=", "300", ":", "error", "=", "get_error", "(", "response", ")", "if", "self", ".", "raise_errors", ":", "raise", "error", "return", "error", "return", "response" ]
Wrapper for the HTTP DELETE request.
[ "Wrapper", "for", "the", "HTTP", "DELETE", "request", "." ]
train
https://github.com/contentful/contentful-management.py/blob/707dd30883b98a10c7ff0f7f5bdb8edbdc1d8df0/contentful_management/client.py#L790-L806
contentful/contentful-management.py
contentful_management/locale.py
Locale.to_json
def to_json(self): """ Returns the JSON representation of the locale. """ result = super(Locale, self).to_json() result.update({ 'code': self.code, 'name': self.name, 'fallbackCode': self.fallback_code, 'optional': self.optional, 'contentDeliveryApi': self.content_delivery_api, 'contentManagementApi': self.content_management_api }) return result
python
def to_json(self): """ Returns the JSON representation of the locale. """ result = super(Locale, self).to_json() result.update({ 'code': self.code, 'name': self.name, 'fallbackCode': self.fallback_code, 'optional': self.optional, 'contentDeliveryApi': self.content_delivery_api, 'contentManagementApi': self.content_management_api }) return result
[ "def", "to_json", "(", "self", ")", ":", "result", "=", "super", "(", "Locale", ",", "self", ")", ".", "to_json", "(", ")", "result", ".", "update", "(", "{", "'code'", ":", "self", ".", "code", ",", "'name'", ":", "self", ".", "name", ",", "'fallbackCode'", ":", "self", ".", "fallback_code", ",", "'optional'", ":", "self", ".", "optional", ",", "'contentDeliveryApi'", ":", "self", ".", "content_delivery_api", ",", "'contentManagementApi'", ":", "self", ".", "content_management_api", "}", ")", "return", "result" ]
Returns the JSON representation of the locale.
[ "Returns", "the", "JSON", "representation", "of", "the", "locale", "." ]
train
https://github.com/contentful/contentful-management.py/blob/707dd30883b98a10c7ff0f7f5bdb8edbdc1d8df0/contentful_management/locale.py#L48-L62
contentful/contentful-management.py
contentful_management/assets_proxy.py
AssetsProxy.all
def all(self, query=None, **kwargs): """ Gets all assets of a space. """ if query is None: query = {} normalize_select(query) return super(AssetsProxy, self).all(query, **kwargs)
python
def all(self, query=None, **kwargs): """ Gets all assets of a space. """ if query is None: query = {} normalize_select(query) return super(AssetsProxy, self).all(query, **kwargs)
[ "def", "all", "(", "self", ",", "query", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "query", "is", "None", ":", "query", "=", "{", "}", "normalize_select", "(", "query", ")", "return", "super", "(", "AssetsProxy", ",", "self", ")", ".", "all", "(", "query", ",", "*", "*", "kwargs", ")" ]
Gets all assets of a space.
[ "Gets", "all", "assets", "of", "a", "space", "." ]
train
https://github.com/contentful/contentful-management.py/blob/707dd30883b98a10c7ff0f7f5bdb8edbdc1d8df0/contentful_management/assets_proxy.py#L28-L38
contentful/contentful-management.py
contentful_management/assets_proxy.py
AssetsProxy.find
def find(self, asset_id, query=None, **kwargs): """ Gets a single asset by ID. """ if query is None: query = {} normalize_select(query) return super(AssetsProxy, self).find(asset_id, query=query, **kwargs)
python
def find(self, asset_id, query=None, **kwargs): """ Gets a single asset by ID. """ if query is None: query = {} normalize_select(query) return super(AssetsProxy, self).find(asset_id, query=query, **kwargs)
[ "def", "find", "(", "self", ",", "asset_id", ",", "query", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "query", "is", "None", ":", "query", "=", "{", "}", "normalize_select", "(", "query", ")", "return", "super", "(", "AssetsProxy", ",", "self", ")", ".", "find", "(", "asset_id", ",", "query", "=", "query", ",", "*", "*", "kwargs", ")" ]
Gets a single asset by ID.
[ "Gets", "a", "single", "asset", "by", "ID", "." ]
train
https://github.com/contentful/contentful-management.py/blob/707dd30883b98a10c7ff0f7f5bdb8edbdc1d8df0/contentful_management/assets_proxy.py#L40-L50
contentful/contentful-management.py
contentful_management/entry.py
Entry.snapshots
def snapshots(self): """ Provides access to snapshot management methods for the given entry. API reference: https://www.contentful.com/developers/docs/references/content-management-api/#/reference/snapshots :return: :class:`EntrySnapshotsProxy <contentful_management.entry_snapshots_proxy.EntrySnapshotsProxy>` object. :rtype: contentful.entry_snapshots_proxy.EntrySnapshotsProxy Usage: >>> entry_snapshots_proxy = entry.snapshots() <EntrySnapshotsProxy space_id="cfexampleapi" environment_id="master" entry_id="nyancat"> """ return EntrySnapshotsProxy(self._client, self.sys['space'].id, self._environment_id, self.sys['id'])
python
def snapshots(self): """ Provides access to snapshot management methods for the given entry. API reference: https://www.contentful.com/developers/docs/references/content-management-api/#/reference/snapshots :return: :class:`EntrySnapshotsProxy <contentful_management.entry_snapshots_proxy.EntrySnapshotsProxy>` object. :rtype: contentful.entry_snapshots_proxy.EntrySnapshotsProxy Usage: >>> entry_snapshots_proxy = entry.snapshots() <EntrySnapshotsProxy space_id="cfexampleapi" environment_id="master" entry_id="nyancat"> """ return EntrySnapshotsProxy(self._client, self.sys['space'].id, self._environment_id, self.sys['id'])
[ "def", "snapshots", "(", "self", ")", ":", "return", "EntrySnapshotsProxy", "(", "self", ".", "_client", ",", "self", ".", "sys", "[", "'space'", "]", ".", "id", ",", "self", ".", "_environment_id", ",", "self", ".", "sys", "[", "'id'", "]", ")" ]
Provides access to snapshot management methods for the given entry. API reference: https://www.contentful.com/developers/docs/references/content-management-api/#/reference/snapshots :return: :class:`EntrySnapshotsProxy <contentful_management.entry_snapshots_proxy.EntrySnapshotsProxy>` object. :rtype: contentful.entry_snapshots_proxy.EntrySnapshotsProxy Usage: >>> entry_snapshots_proxy = entry.snapshots() <EntrySnapshotsProxy space_id="cfexampleapi" environment_id="master" entry_id="nyancat">
[ "Provides", "access", "to", "snapshot", "management", "methods", "for", "the", "given", "entry", "." ]
train
https://github.com/contentful/contentful-management.py/blob/707dd30883b98a10c7ff0f7f5bdb8edbdc1d8df0/contentful_management/entry.py#L38-L52