code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
if override is True:
self.analysis_output = {}
if isinstance(frames, int):
analysed_frame = self._analysis_serial(frames, ncpus, **kwargs)
if frames not in self.analysis_output.keys():
self.analysis_output[frames] = analysed_frame
... | def analysis(self, frames='all', ncpus=1, override=False, **kwargs) | Perform structural analysis on a frame/ set of frames.
Depending on the passed parameters a frame, a list of particular
frames, a range of frames (from, to), or all frames can be analysed
with this function.
The analysis is performed on each frame and each discrete molecule in
... | 1.892152 | 1.787063 | 1.058805 |
self.trajectory_map = {}
with open(self.filepath, 'r') as trajectory_file:
with closing(
mmap(
trajectory_file.fileno(), 0,
access=ACCESS_READ)) as mapped_file:
progress = 0
line = 0
... | def _map_trajectory(self) | Return filepath as a class attribute | 4.608625 | 4.430395 | 1.040229 |
return cls(Input().load_rdkit_mol(mol), system_name, mol_id) | def load_rdkit_mol(cls, mol, system_name='rdkit', mol_id=0) | Create a :class:`Molecule` from :class:`rdkit.Chem.rdchem.Mol`.
To be used only by expert users.
Parameters
----------
mol : :class:`rdkit.Chem.rdchem.Mol`
An RDKit molecule object.
Returns
-------
:class:`pywindow.molecular.Molecule`
:cl... | 5.838239 | 11.109896 | 0.525499 |
self.molecular_weight()
self.calculate_centre_of_mass()
self.calculate_maximum_diameter()
self.calculate_average_diameter()
self.calculate_pore_diameter()
self.calculate_pore_volume()
self.calculate_pore_diameter_opt(**kwargs)
self.calculate_pore_... | def full_analysis(self, ncpus=1, **kwargs) | Perform a full structural analysis of a molecule.
This invokes other methods:
1. :attr:`molecular_weight()`
2. :attr:`calculate_centre_of_mass()`
3. :attr:`calculate_maximum_diameter()`
4. :attr:`calculate_average_diameter()`
5. :attr:`calculate_... | 3.763143 | 2.086465 | 1.803597 |
self.centre_of_mass = center_of_mass(self.elements, self.coordinates)
self.properties['centre_of_mass'] = self.centre_of_mass
return self.centre_of_mass | def calculate_centre_of_mass(self) | Return the xyz coordinates of the centre of mass of a molecule.
Returns
-------
:class:`numpy.array`
The centre of mass of the molecule. | 2.853543 | 3.313267 | 0.861247 |
self.maxd_atom_1, self.maxd_atom_2, self.maximum_diameter = max_dim(
self.elements, self.coordinates)
self.properties['maximum_diameter'] = {
'diameter': self.maximum_diameter,
'atom_1': int(self.maxd_atom_1),
'atom_2': int(self.maxd_atom_2),
... | def calculate_maximum_diameter(self) | Return the maximum diamension of a molecule.
Returns
-------
:class:`float`
The maximum dimension of the molecule. | 3.101069 | 3.076224 | 1.008076 |
self.average_diameter = find_average_diameter(
self.elements, self.coordinates, **kwargs)
return self.average_diameter | def calculate_average_diameter(self, **kwargs) | Return the average diamension of a molecule.
Returns
-------
:class:`float`
The average dimension of the molecule. | 4.381023 | 5.292956 | 0.827708 |
self.pore_diameter, self.pore_closest_atom = pore_diameter(
self.elements, self.coordinates)
self.properties['pore_diameter'] = {
'diameter': self.pore_diameter,
'atom': int(self.pore_closest_atom),
}
return self.pore_diameter | def calculate_pore_diameter(self) | Return the intrinsic pore diameter.
Returns
-------
:class:`float`
The intrinsic pore diameter. | 3.346476 | 3.910454 | 0.855777 |
self.pore_volume = sphere_volume(self.calculate_pore_diameter() / 2)
self.properties['pore_volume'] = self.pore_volume
return self.pore_volume | def calculate_pore_volume(self) | Return the intrinsic pore volume.
Returns
-------
:class:`float`
The intrinsic pore volume. | 3.273195 | 4.081054 | 0.802046 |
(self.pore_diameter_opt, self.pore_opt_closest_atom,
self.pore_opt_COM) = opt_pore_diameter(self.elements,
self.coordinates, **kwargs)
self.properties['pore_diameter_opt'] = {
'diameter': self.pore_diameter_opt,
'a... | def calculate_pore_diameter_opt(self, **kwargs) | Return the intrinsic pore diameter (for the optimised pore centre).
Similarly to :func:`calculate_pore_diameter` this method returns the
the intrinsic pore diameter, however, first a better approximation
of the pore centre is found with optimisation.
Returns
-------
:cl... | 3.044446 | 3.43656 | 0.885899 |
self.pore_volume_opt = sphere_volume(
self.calculate_pore_diameter_opt(**kwargs) / 2)
self.properties['pore_volume_opt'] = self.pore_volume_opt
return self.pore_volume_opt | def calculate_pore_volume_opt(self, **kwargs) | Return the intrinsic pore volume (for the optimised pore centre).
Similarly to :func:`calculate_pore_volume` this method returns the
the volume intrinsic pore diameter, however, for the
:func:`calculate_pore_diameter_opt` returned value.
Returns
-------
:class:`float`
... | 3.003338 | 3.675155 | 0.8172 |
windows = find_windows(self.elements, self.coordinates, **kwargs)
if windows:
self.properties.update(
{
'windows': {
'diameters': windows[0], 'centre_of_mass': windows[1],
}
}
... | def calculate_windows(self, **kwargs) | Return the diameters of all windows in a molecule.
This function first finds and then measures the diameters of all the
window in the molecule.
Returns
-------
:class:`numpy.array`
An array of windows' diameters.
:class:`NoneType`
If no windows ... | 3.672697 | 3.641795 | 1.008485 |
self.coordinates = shift_com(self.elements, self.coordinates, **kwargs)
self._update() | def shift_to_origin(self, **kwargs) | Shift a molecule to Origin.
This function takes the molecule's coordinates and adjust them so that
the centre of mass of the molecule coincides with the origin of the
coordinate system.
Returns
-------
None : :class:`NoneType` | 10.16515 | 10.539119 | 0.964516 |
# We pass a copy of the properties dictionary.
dict_obj = deepcopy(self.properties)
# If molecular data is also required we update the dictionary.
if molecular is True:
dict_obj.update(self.mol)
# If no filepath is provided we create one.
if filepath ... | def dump_properties_json(self, filepath=None, molecular=False, **kwargs) | Dump content of :attr:`Molecule.properties` to a JSON dictionary.
Parameters
----------
filepath : :class:`str`
The filepath for the dumped file. If :class:`None`, the file is
dumped localy with :attr:`molecule_id` as filename.
(defualt=None)
molecular ... | 5.165809 | 5.494297 | 0.940213 |
# If no filepath is provided we create one.
if filepath is None:
filepath = "_".join(
(str(self.parent_system), str(self.molecule_id)))
filepath = '/'.join((os.getcwd(), filepath))
filepath = '.'.join((filepath, 'pdb'))
# Check if ther... | def dump_molecule(self, filepath=None, include_coms=False, **kwargs) | Dump a :class:`Molecule` to a file (PDB or XYZ).
Kwargs are passed to :func:`pywindow.io_tools.Output.dump2file()`.
For validation purposes an overlay of window centres and COMs can also
be dumped as:
He - for the centre of mass
Ne - for the centre of the optimised cavity
... | 2.475053 | 2.26899 | 1.090817 |
obj = cls()
obj.system = obj._Input.load_file(filepath)
obj.filename = os.path.basename(filepath)
obj.system_id = obj.filename.split(".")[0]
obj.name, ext = os.path.splitext(obj.filename)
return obj | def load_file(cls, filepath) | Create a :class:`MolecularSystem` from an input file.
Recognized input file formats: XYZ, PDB and MOL (V3000).
Parameters
----------
filepath : :class:`str`
The input's filepath.
Returns
-------
:class:`pywindow.molecular.MolecularSystem`
... | 3.987577 | 4.030986 | 0.989231 |
obj = cls()
obj.system = obj._Input.load_rdkit_mol(mol)
return obj | def load_rdkit_mol(cls, mol) | Create a :class:`MolecularSystem` from :class:`rdkit.Chem.rdchem.Mol`.
Parameters
----------
mol : :class:`rdkit.Chem.rdchem.Mol`
An RDKit molecule object.
Returns
-------
:class:`pywindow.molecular.MolecularSystem`
:class:`MolecularSystem` | 9.888268 | 10.660494 | 0.927562 |
obj = cls()
obj.system = dict_
obj.system_id = system_id
return obj | def load_system(cls, dict_, system_id='system') | Create a :class:`MolecularSystem` from a python :class:`dict`.
As the loaded :class:`MolecularSystem` is storred as a :class:`dict` in
the :class:`MolecularSystem.system` it can also be loaded directly from
a :class:`dict` input. This feature is used by :mod:`trajectory` that
extracts t... | 4.551762 | 4.877484 | 0.933219 |
# First we create a 3x3x3 supercell with the initial unit cell in the
# centre and the 26 unit cell translations around to provide all the
# atom positions necessary for the molecules passing through periodic
# boundary reconstruction step.
supercell_333 = create_superce... | def rebuild_system(self, override=False, **kwargs) | Rebuild molecules in molecular system.
Parameters
----------
override : :class:`bool`, optional (default=False)
If False the rebuild molecular system is returned as a new
:class:`MolecularSystem`, if True, the current
:class:`MolecularSystem` is modified. | 4.725547 | 4.610458 | 1.024963 |
# Similar situation to the one from decipher_atom_keys function.
if 'atom_ids' not in self.system.keys():
dict_key = 'elements'
for atom_key in range(len(self.system[dict_key])):
for key in swap_dict.keys():
if self.system[dict_key][atom_key] == k... | def swap_atom_keys(self, swap_dict, dict_key='atom_ids') | Swap a force field atom id for another user-defined value.
This modified all values in :attr:`MolecularSystem.system['atom_ids']`
that match criteria.
This function can be used to decipher a whole forcefield if an
appropriate dictionary is passed to the function.
Example
... | 3.512843 | 3.17782 | 1.105425 |
# In case there is no 'atom_ids' key we try 'elements'. This is for
# XYZ and MOL files mostly. But, we keep the dict_key keyword for
# someone who would want to decipher 'elements' even if 'atom_ids' key
# is present in the system's dictionary.
if 'atom_ids' not in self... | def decipher_atom_keys(self, forcefield='DLF', dict_key='atom_ids') | Decipher force field atom ids.
This takes all values in :attr:`MolecularSystem.system['atom_ids']`
that match force field type criteria and creates
:attr:`MolecularSystem.system['elements']` with the corresponding
periodic table of elements equivalents.
If a forcefield is not s... | 6.276151 | 6.371865 | 0.984979 |
if rebuild is True:
supercell_333 = create_supercell(self.system)
else:
supercell_333 = None
dis = discrete_molecules(self.system, rebuild=supercell_333)
self.no_of_discrete_molecules = len(dis)
self.molecules = {}
for i in range(len(dis))... | def make_modular(self, rebuild=False) | Find and return all :class:`Molecule` s in :class:`MolecularSystem`.
This function populates :attr:`MolecularSystem.molecules` with
:class:`Molecule` s.
Parameters
----------
rebuild : :class:`bool`
If True, run first the :func:`rebuild_system()`. (default=False)
... | 4.688239 | 4.367863 | 1.073348 |
pores = []
for point in sampling_points:
pores.append(
Pore(
self.system['elements'],
self.system['coordinates'],
com=point))
return pores | def _get_pores(self, sampling_points) | Under development. | 6.817269 | 6.161947 | 1.10635 |
# If no filepath is provided we create one.
if filepath is None:
filepath = '/'.join((os.getcwd(), str(self.system_id)))
filepath = '.'.join((filepath, 'pdb'))
# If modular is True substitute the molecular data for modular one.
system_dict = deepcopy(self... | def dump_system(self, filepath=None, modular=False, **kwargs) | Dump a :class:`MolecularSystem` to a file (PDB or XYZ).
Kwargs are passed to :func:`pywindow.io_tools.Output.dump2file()`.
Parameters
----------
filepath : :class:`str`
The filepath for the dumped file. If :class:`None`, the file is
dumped localy with :attr:`syste... | 3.481061 | 3.339187 | 1.042488 |
# We pass a copy of the properties dictionary.
dict_obj = deepcopy(self.system)
# In case we want a modular system.
if modular is True:
try:
if self.molecules:
pass
except AttributeError:
raise _NotAModu... | def dump_system_json(self, filepath=None, modular=False, **kwargs) | Dump a :class:`MolecularSystem` to a JSON dictionary.
The dumped JSON dictionary, with :class:`MolecularSystem`, can then be
loaded through a JSON loader and then through :func:`load_system()`
to retrieve a :class:`MolecularSystem`.
Kwargs are passed to :func:`pywindow.io_tools.Output.... | 5.124029 | 4.814349 | 1.064324 |
for attr, column in list(sqlalchemy.inspect(instance.__class__).c.items()):
if column.name == name:
return attr | def get_attrname_by_colname(instance, name) | Get value from SQLAlchemy instance by column name
:Parameters:
- `instance`: SQLAlchemy model instance.
- `name`: Column name
:Examples:
>>> from sqlalchemy import Column, Integer
>>> from sqlalchemy.ext.declarative import declarative_base
>>> Base = declarative_base()
>>> cl... | 4.28146 | 8.006825 | 0.534726 |
instance_defaults_params = inspect.getargspec(table.__init__).args[1:]
# list like ['name', 'group', 'visible'] to dict with empty
# value as {'name': None, 'group': None, 'visible': None}
init = dict(
list(zip(instance_defaults_params, itertools.repeat(None)))
)
return table(**init... | def get_empty_instance(table) | Return empty instance of model. | 5.731306 | 5.446856 | 1.052223 |
if inspect.isclass(obj):
pk_list = sqlalchemy.inspect(obj).primary_key
else:
pk_list = obj.__mapper__.primary_key
return pk_list | def get_pk(obj) | Return primary key name by model class or instance.
:Parameters:
- `obj`: SQLAlchemy model instance or class.
:Examples:
>>> from sqlalchemy import Column, Integer
>>> from sqlalchemy.ext.declarative import declarative_base
>>> Base = declarative_base()
>>> class User(Base):
... ... | 3.152299 | 3.854407 | 0.817843 |
#The defaults are indicated below
myrule = {
"source": "",
"dest": "",
"messagetype": "request",
"headerpattern": "*",
"bodypattern": "*",
"delayprobability": 0.0,
"dela... | def add_rule(self, **args) | @param args keyword argument list, consisting of:
source: <source service name>,
dest: <destination service name>,
messagetype: <request|response|publish|subscribe|stream>
headerpattern: <regex to match against the value of the X-Gremlin-ID trackingheader present in HTTP headers>
... | 3.199423 | 2.257082 | 1.417504 |
self._queue = []
if self.debug:
print 'Clearing rules'
for service in self.app.get_services():
for instance in self.app.get_service_instances(service):
if self.debug:
print 'Clearing rules for %s - instance %s' % (servi... | def clear_rules_from_all_proxies(self) | Clear fault injection rules from all known service proxies. | 3.324228 | 3.287785 | 1.011084 |
rules = {}
for service in self.app.get_services():
rules[service] = {}
for instance in self.app.get_service_instances(service):
rules[service][instance] = {}
resp = requests.get("http://{}/gremlin/v1/rules/list".format(instance))
... | def list_rules(self, service=None) | List fault fault injection rules installed on instances of a given service (or all services)
returns a JSON dictionary | 3.244141 | 3.157172 | 1.027547 |
rule = args.copy()
assert 'source' in rule and 'dest' in rule
#assert 'srcprobability' in rule and 'dstprobability' in rule
assert rule['source'] != "" and rule['dest'] != ""
#check if the two services are connected
assert rule['dest'] in self.app.get_dependencie... | def partition_services(self, **args) | Partitions two connected services. Not two sets of services (TODO)
Expects usual arguments and srcprobability and dstprobability, that indicates probability of
terminating connections from source to dest and vice versa | 4.267594 | 3.567228 | 1.196334 |
assert scenario is not None and scenario in self.functiondict
self.functiondict[scenario](**args) | def setup_failure(self, scenario=None, **args) | Add a given failure scenario
@param scenario: string 'delayrequests' or 'crash' | 8.831114 | 8.668943 | 1.018707 |
assert isinstance(gremlins, dict) and 'gremlins' in gremlins
for gremlin in gremlins['gremlins']:
self.setup_failure(**gremlin)
self.push_rules() | def setup_failures(self, gremlins) | Add gremlins to environment | 4.585403 | 4.336895 | 1.057301 |
index = ' '.join(str(vertices[vn].index) for vn in self.vnames)
com = ' '.join(self.vnames) # for comment
return '({0:s}) // {1:s} ({2:s})'.format(index, self.name, com) | def format(self, vertices) | Format instance to dump
vertices is dict of name to Vertex | 6.100059 | 6.052805 | 1.007807 |
index = ' '.join(str(vertices[vn].index) for vn in self.vnames)
vcom = ' '.join(self.vnames) # for comment
return 'hex ({0:s}) {2:s} ({1[0]:d} {1[1]:d} {1[2]:d}) '\
'{4:s} // {2:s} ({3:s})'.format(
index, self.cells, self.name, vcom, self.grading.for... | def format(self, vertices) | Format instance to dump
vertices is dict of name to Vertex | 6.896743 | 6.912849 | 0.99767 |
kw_to_index = {
'w': 0, 'xm': 0, '-100': 0,
'e': 1, 'xp': 1, '100': 1,
's': 2, 'ym': 2, '0-10': 2,
'n': 3, 'yp': 3, '010': 3,
'b': 4, 'zm': 4, '00-1': 4,
't': 5, 'zp': 5, '001': 5}
index_to_vertex = [
(0, 4, 7, ... | def face(self, index, name=None) | Generate Face object
index is number or keyword to identify the face of Hex
0 = 'w' = 'xm' = '-100' = (0 4 7 3)
1 = 'e' = 'xp' = '100' = (1 2 5 6)
2 = 's' = 'ym' = '0-10' = (0 1 5 4)
3 = 'n' = 'yp' = '010' = (2 3 7 6)
4 = 'b' = 'zm' = '00-1' = (0 3 2 1... | 2.385479 | 1.68998 | 1.411543 |
index = ' '.join(str(vertices[vn].index) for vn in self.vnames)
vcom = ' '.join(self.vnames) # for comment
return 'arc {0:s} ({1.x:18.15g} {1.y:18.15g} {1.z:18.15g}) '\
'// {2:s} ({3:s})'.format(
index, self.interVertex, self.name, vcom) | def format(self, vertices) | Format instance to dump
vertices is dict of name to Vertex | 5.815659 | 5.78842 | 1.004706 |
index = ' '.join(str(vertices[vn].index) for vn in self.vnames)
vcom = ' '.join(self.vnames) # for comment
buf = io.StringIO()
buf.write('spline {0:s} '\
'// {1:s} ({2:s})'.format(
index,self.name, vcom))
buf... | def format(self, vertices) | Format instance to dump
vertices is dict of name to Vertex | 5.615753 | 5.640437 | 0.995624 |
buf = io.StringIO()
buf.write(self.name + '\n')
buf.write('{\n')
buf.write(' type {};\n'.format(self.type_))
buf.write(' faces\n')
buf.write(' (\n')
for f in self.faces:
s = f.format(vertices)
buf.write(' {}\n'.for... | def format(self, vertices) | Format instance to dump
vertices is dict of name to Vertex | 2.583711 | 2.622151 | 0.98534 |
self.vertices[name] = Vertex(x, y, z, name)
return self.vertices[name] | def add_vertex(self, x, y, z, name) | add vertex by coordinate and uniq name
x y z is coordinates of vertex
name is uniq name to refer the vertex
returns Vertex object whici is added. | 2.587204 | 2.35907 | 1.096705 |
v = self.vertices[name1]
for n in names:
w = self.vertices[n]
v.alias.update(w.alias)
# replace mapping from n w by to v
self.vertices[n] = v | def reduce_vertex(self, name1, *names) | treat name1, name2, ... as same point.
name2.alias, name3.alias, ... are merged with name1.alias
the key name2, name3, ... in self.vertices are kept and mapped to
same Vertex instance as name1 | 6.083643 | 4.913034 | 1.238266 |
# groupby expects sorted data
sorted_vertices = sorted(list(self.vertices.items()), key=lambda v: hash(v[1]))
groups = []
for k, g in groupby(sorted_vertices, lambda v: hash(v[1])):
groups.append(list(g))
for group in groups:
if len(group) == 1:
... | def merge_vertices(self) | call reduce_vertex on all vertices with identical values. | 3.383086 | 2.828011 | 1.196278 |
# gather 'uniq' names which are refferred by blocks
validvnames = set()
self.valid_vertices = []
for b in self.blocks.values():
for n in b.vnames:
v = self.vertices[n]
if v.name not in validvnames:
validvnames.upda... | def assign_vertexid(self) | 1. create list of Vertex which are referred by blocks only.
2. sort vertex according to (x, y, z)
3. assign sequence number for each Vertex
4. sorted list is saved as self.valid_vertices | 4.043347 | 3.245579 | 1.245802 |
buf = io.StringIO()
buf.write('vertices\n')
buf.write('(\n')
for v in self.valid_vertices:
buf.write(' ' + v.format() + '\n')
buf.write(');')
return buf.getvalue() | def format_vertices_section(self) | format vertices section.
assign_vertexid() should be called before this method, because
self.valid_vetices should be available and member self.valid_vertices
should have valid index. | 3.160572 | 2.633675 | 1.200061 |
buf = io.StringIO()
buf.write('blocks\n')
buf.write('(\n')
for b in self.blocks.values():
buf.write(' ' + b.format(self.vertices) + '\n')
buf.write(');')
return buf.getvalue() | def format_blocks_section(self) | format blocks section.
assign_vertexid() should be called before this method, because
vertices reffered by blocks should have valid index. | 3.523793 | 2.975941 | 1.184094 |
buf = io.StringIO()
buf.write('edges\n')
buf.write('(\n')
for e in self.edges.values():
buf.write(' ' + e.format(self.vertices) + '\n')
buf.write(');')
return buf.getvalue() | def format_edges_section(self) | format edges section.
assign_vertexid() should be called before this method, because
vertices reffered by blocks should have valid index. | 3.084866 | 2.870081 | 1.074836 |
buf = io.StringIO()
buf.write('boundary\n')
buf.write('(\n')
for b in self.boundaries.values():
# format Boundary instance and add indent
indent = ' ' * 4
s = b.format(self.vertices).replace('\n', '\n'+indent)
buf.write(indent + s ... | def format_boundary_section(self) | format boundary section.
assign_vertexid() should be called before this method, because
vertices reffered by faces should have valid index. | 4.299565 | 4.066453 | 1.057326 |
Archive(path, ext=ext).extract(to_path, **kwargs) | def extract(path, to_path='', ext='', **kwargs) | Unpack the tar or zip file at the specified path to the directory
specified by to_path. | 5.863644 | 6.175491 | 0.949502 |
cls = None
filename = None
if is_string(file):
filename = file
else:
try:
filename = file.name
except AttributeError:
raise UnrecognizedArchiveFormat(
"File object not a recognized archive fo... | def _archive_cls(file, ext='') | Return the proper Archive implementation class, based on the file type. | 3.240051 | 3.102826 | 1.044226 |
if to_path:
target_path = os.path.normpath(os.path.realpath(to_path))
else:
target_path = os.getcwd()
for filename in self.filenames():
extract_path = os.path.join(target_path, filename)
extract_path = os.path.normpath(os.path.realpath(ext... | def check_files(self, to_path=None) | Check that all of the files contained in the archive are within the
target directory. | 2.980487 | 2.663538 | 1.118996 |
infn = Path(infn).expanduser()
# %% parse indicies to load
if isinstance(Navg, slice):
key = Navg
elif isinstance(Navg, int):
key = slice(0, Navg)
elif len(Navg) == 1:
key = slice(0, Navg[0])
elif len(Navg) == 2:
key = slice(Navg[0], Navg[1])
else:
raise ... | def meanstack(infn: Path, Navg: int, ut1: Optional[datetime]=None,
method: str='mean') -> Tuple[np.ndarray, Optional[datetime]] | some methods handled individually to improve efficiency with huge files | 3.181103 | 3.101237 | 1.025753 |
not_done = True
while not_done:
response_object = self._run_search_page_request(
protocol_request, object_name, protocol_response_class)
value_list = getattr(
response_object,
protocol.getValueListName(protocol_response_cla... | def _run_search_request(
self, protocol_request, object_name, protocol_response_class) | Runs the specified request at the specified object_name and
instantiates an object of the specified class. We yield each object in
listAttr. If pages of results are present, repeat this process
until the pageToken is null. | 3.245091 | 2.90835 | 1.115784 |
request = protocol.ListReferenceBasesRequest()
request.start = pb.int(start)
request.end = pb.int(end)
request.reference_id = id_
not_done = True
# TODO We should probably use a StringIO here to make string buffering
# a bit more efficient.
bases_... | def list_reference_bases(self, id_, start=0, end=None) | Returns an iterator over the bases from the server in the form
of consecutive strings. This command does not conform to the
patterns of the other search and get requests, and is implemented
differently. | 3.93879 | 3.766449 | 1.045757 |
request = protocol.SearchVariantsRequest()
request.reference_name = pb.string(reference_name)
request.start = pb.int(start)
request.end = pb.int(end)
request.variant_set_id = variant_set_id
request.call_set_ids.extend(pb.string(call_set_ids))
request.page... | def search_variants(
self, variant_set_id, start=None, end=None, reference_name=None,
call_set_ids=None) | Returns an iterator over the Variants fulfilling the specified
conditions from the specified VariantSet.
:param str variant_set_id: The ID of the
:class:`ga4gh.protocol.VariantSet` of interest.
:param int start: Required. The beginning of the window (0-based,
inclusive) ... | 2.191835 | 2.589131 | 0.846552 |
request = protocol.SearchVariantAnnotationsRequest()
request.variant_annotation_set_id = variant_annotation_set_id
request.reference_name = reference_name
request.reference_id = reference_id
request.start = start
request.end = end
for effect in effects:
... | def search_variant_annotations(
self, variant_annotation_set_id, reference_name="",
reference_id="", start=0, end=0, effects=[]) | Returns an iterator over the Variant Annotations fulfilling
the specified conditions from the specified VariantSet.
:param str variant_annotation_set_id: The ID of the
:class:`ga4gh.protocol.VariantAnnotationSet` of interest.
:param int start: Required. The beginning of the window (... | 2.872007 | 3.817328 | 0.75236 |
request = protocol.SearchFeaturesRequest()
request.feature_set_id = feature_set_id
request.parent_id = parent_id
request.reference_name = reference_name
request.name = name
request.gene_symbol = gene_symbol
request.start = start
request.end = end
... | def search_features(
self, feature_set_id=None, parent_id="", reference_name="",
start=0, end=0, feature_types=[], name="", gene_symbol="") | Returns the result of running a search_features method
on a request with the passed-in parameters.
:param str feature_set_id: ID of the feature Set being searched
:param str parent_id: ID (optional) of the parent feature
:param str reference_name: name of the reference to search
... | 2.170454 | 2.383343 | 0.910676 |
request = protocol.SearchContinuousRequest()
request.continuous_set_id = continuous_set_id
request.reference_name = reference_name
request.start = start
request.end = end
request.page_size = pb.int(self._page_size)
return self._run_search_request(
... | def search_continuous(
self, continuous_set_id=None, reference_name="", start=0, end=0) | Returns the result of running a search_continuous method
on a request with the passed-in parameters.
:param str continuous_set_id: ID of the ContinuousSet being searched
:param str reference_name: name of the reference to search
(ex: "chr1")
:param int start: search start po... | 2.790828 | 3.224258 | 0.865572 |
request = protocol.SearchDatasetsRequest()
request.page_size = pb.int(self._page_size)
return self._run_search_request(
request, "datasets", protocol.SearchDatasetsResponse) | def search_datasets(self) | Returns an iterator over the Datasets on the server.
:return: An iterator over the :class:`ga4gh.protocol.Dataset`
objects on the server. | 6.058875 | 6.206339 | 0.97624 |
request = protocol.SearchVariantSetsRequest()
request.dataset_id = dataset_id
request.page_size = pb.int(self._page_size)
return self._run_search_request(
request, "variantsets", protocol.SearchVariantSetsResponse) | def search_variant_sets(self, dataset_id) | Returns an iterator over the VariantSets fulfilling the specified
conditions from the specified Dataset.
:param str dataset_id: The ID of the :class:`ga4gh.protocol.Dataset`
of interest.
:return: An iterator over the :class:`ga4gh.protocol.VariantSet`
objects defined by ... | 3.831393 | 4.675923 | 0.819388 |
request = protocol.SearchVariantAnnotationSetsRequest()
request.variant_set_id = variant_set_id
request.page_size = pb.int(self._page_size)
return self._run_search_request(
request, "variantannotationsets",
protocol.SearchVariantAnnotationSetsResponse) | def search_variant_annotation_sets(self, variant_set_id) | Returns an iterator over the Annotation Sets fulfilling the specified
conditions from the specified variant set.
:param str variant_set_id: The ID of the
:class:`ga4gh.protocol.VariantSet` of interest.
:return: An iterator over the :class:`ga4gh.protocol.AnnotationSet`
o... | 3.504425 | 4.189491 | 0.83648 |
request = protocol.SearchFeatureSetsRequest()
request.dataset_id = dataset_id
request.page_size = pb.int(self._page_size)
return self._run_search_request(
request, "featuresets", protocol.SearchFeatureSetsResponse) | def search_feature_sets(self, dataset_id) | Returns an iterator over the FeatureSets fulfilling the specified
conditions from the specified Dataset.
:param str dataset_id: The ID of the
:class:`ga4gh.protocol.Dataset` of interest.
:return: An iterator over the :class:`ga4gh.protocol.FeatureSet`
objects defined by ... | 4.020631 | 4.666806 | 0.861538 |
request = protocol.SearchContinuousSetsRequest()
request.dataset_id = dataset_id
request.page_size = pb.int(self._page_size)
return self._run_search_request(
request, "continuoussets", protocol.SearchContinuousSetsResponse) | def search_continuous_sets(self, dataset_id) | Returns an iterator over the ContinuousSets fulfilling the specified
conditions from the specified Dataset.
:param str dataset_id: The ID of the
:class:`ga4gh.protocol.Dataset` of interest.
:return: An iterator over the :class:`ga4gh.protocol.ContinuousSet`
objects defin... | 4.342905 | 4.633037 | 0.937378 |
request = protocol.SearchReferenceSetsRequest()
request.accession = pb.string(accession)
request.md5checksum = pb.string(md5checksum)
request.assembly_id = pb.string(assembly_id)
request.page_size = pb.int(self._page_size)
return self._run_search_request(
... | def search_reference_sets(
self, accession=None, md5checksum=None, assembly_id=None) | Returns an iterator over the ReferenceSets fulfilling the specified
conditions.
:param str accession: If not null, return the reference sets for which
the `accession` matches this string (case-sensitive, exact match).
:param str md5checksum: If not null, return the reference sets fo... | 2.556741 | 2.703556 | 0.945696 |
request = protocol.SearchReferencesRequest()
request.reference_set_id = reference_set_id
request.accession = pb.string(accession)
request.md5checksum = pb.string(md5checksum)
request.page_size = pb.int(self._page_size)
return self._run_search_request(
... | def search_references(
self, reference_set_id, accession=None, md5checksum=None) | Returns an iterator over the References fulfilling the specified
conditions from the specified Dataset.
:param str reference_set_id: The ReferenceSet to search.
:param str accession: If not None, return the references for which the
`accession` matches this string (case-sensitive, ex... | 2.684579 | 2.866346 | 0.936586 |
request = protocol.SearchCallSetsRequest()
request.variant_set_id = variant_set_id
request.name = pb.string(name)
request.biosample_id = pb.string(biosample_id)
request.page_size = pb.int(self._page_size)
return self._run_search_request(
request, "cal... | def search_call_sets(self, variant_set_id, name=None, biosample_id=None) | Returns an iterator over the CallSets fulfilling the specified
conditions from the specified VariantSet.
:param str variant_set_id: Find callsets belonging to the
provided variant set.
:param str name: Only CallSets matching the specified name will
be returned.
:... | 2.614922 | 2.895678 | 0.903043 |
request = protocol.SearchBiosamplesRequest()
request.dataset_id = dataset_id
request.name = pb.string(name)
request.individual_id = pb.string(individual_id)
request.page_size = pb.int(self._page_size)
return self._run_search_request(
request, "biosamp... | def search_biosamples(self, dataset_id, name=None, individual_id=None) | Returns an iterator over the Biosamples fulfilling the specified
conditions.
:param str dataset_id: The dataset to search within.
:param str name: Only Biosamples matching the specified name will
be returned.
:param str individual_id: Only Biosamples matching matching this
... | 2.756244 | 2.892117 | 0.953019 |
request = protocol.SearchIndividualsRequest()
request.dataset_id = dataset_id
request.name = pb.string(name)
request.page_size = pb.int(self._page_size)
return self._run_search_request(
request, "individuals", protocol.SearchIndividualsResponse) | def search_individuals(self, dataset_id, name=None) | Returns an iterator over the Individuals fulfilling the specified
conditions.
:param str dataset_id: The dataset to search within.
:param str name: Only Individuals matching the specified name will
be returned.
:return: An iterator over the :class:`ga4gh.protocol.Biosample`
... | 3.354186 | 3.84817 | 0.871631 |
request = protocol.SearchReadGroupSetsRequest()
request.dataset_id = dataset_id
request.name = pb.string(name)
request.biosample_id = pb.string(biosample_id)
request.page_size = pb.int(self._page_size)
return self._run_search_request(
request, "readgr... | def search_read_group_sets(
self, dataset_id, name=None, biosample_id=None) | Returns an iterator over the ReadGroupSets fulfilling the specified
conditions from the specified Dataset.
:param str name: Only ReadGroupSets matching the specified name
will be returned.
:param str biosample_id: Only ReadGroups matching the specified
biosample will be ... | 2.620038 | 3.038194 | 0.862367 |
request = protocol.SearchReadsRequest()
request.read_group_ids.extend(read_group_ids)
request.reference_id = pb.string(reference_id)
request.start = pb.int(start)
request.end = pb.int(end)
request.page_size = pb.int(self._page_size)
return self._run_searc... | def search_reads(
self, read_group_ids, reference_id=None, start=None, end=None) | Returns an iterator over the Reads fulfilling the specified
conditions from the specified read_group_ids.
:param str read_group_ids: The IDs of the
:class:`ga4gh.protocol.ReadGroup` of interest.
:param str reference_id: The name of the
:class:`ga4gh.protocol.Reference` w... | 2.331856 | 2.724487 | 0.855888 |
request = protocol.SearchPhenotypeAssociationSetsRequest()
request.dataset_id = dataset_id
request.page_size = pb.int(self._page_size)
return self._run_search_request(
request, "phenotypeassociationsets",
protocol.SearchPhenotypeAssociationSetsResponse) | def search_phenotype_association_sets(self, dataset_id) | Returns an iterator over the PhenotypeAssociationSets on the server. | 3.323579 | 3.142675 | 1.057563 |
request = protocol.SearchGenotypePhenotypeRequest()
request.phenotype_association_set_id = phenotype_association_set_id
if feature_ids:
request.feature_ids.extend(feature_ids)
if phenotype_ids:
request.phenotype_ids.extend(phenotype_ids)
if eviden... | def search_genotype_phenotype(
self, phenotype_association_set_id=None, feature_ids=None,
phenotype_ids=None, evidence=None) | Returns an iterator over the GeneotypePhenotype associations from
the server | 2.1215 | 2.16723 | 0.978899 |
request = protocol.SearchPhenotypesRequest()
request.phenotype_association_set_id = phenotype_association_set_id
if phenotype_id:
request.id = phenotype_id
if description:
request.description = description
if type_:
request.type.mergeF... | def search_phenotype(
self, phenotype_association_set_id=None, phenotype_id=None,
description=None, type_=None, age_of_onset=None) | Returns an iterator over the Phenotypes from the server | 2.32438 | 2.388292 | 0.973239 |
request = protocol.SearchRnaQuantificationSetsRequest()
request.dataset_id = dataset_id
request.page_size = pb.int(self._page_size)
return self._run_search_request(
request, "rnaquantificationsets",
protocol.SearchRnaQuantificationSetsResponse) | def search_rna_quantification_sets(self, dataset_id) | Returns an iterator over the RnaQuantificationSet objects from the
server | 3.267874 | 3.649135 | 0.89552 |
request = protocol.SearchRnaQuantificationsRequest()
request.rna_quantification_set_id = rna_quantification_set_id
request.page_size = pb.int(self._page_size)
return self._run_search_request(
request, "rnaquantifications",
protocol.SearchRnaQuantification... | def search_rna_quantifications(self, rna_quantification_set_id="") | Returns an iterator over the RnaQuantification objects from the server
:param str rna_quantification_set_id: The ID of the
:class:`ga4gh.protocol.RnaQuantificationSet` of interest. | 3.042038 | 3.157734 | 0.963361 |
request = protocol.SearchExpressionLevelsRequest()
request.rna_quantification_id = rna_quantification_id
request.names.extend(names)
request.threshold = threshold
request.page_size = pb.int(self._page_size)
return self._run_search_request(
request, "e... | def search_expression_levels(
self, rna_quantification_id="", names=[], threshold=0.0) | Returns an iterator over the ExpressionLevel objects from the server
:param str feature_ids: The IDs of the
:class:`ga4gh.protocol.Feature` of interest.
:param str rna_quantification_id: The ID of the
:class:`ga4gh.protocol.RnaQuantification` of interest.
:param float th... | 3.092842 | 3.508869 | 0.881435 |
headers = {"Content-type": "application/json"}
if (self._id_token):
headers.update({"authorization": "Bearer {}".format(
self._id_token)})
self._session.headers.update(headers)
# TODO is this unsafe????
self._session.verify = False | def _setup_http_session(self) | Sets up the common HTTP session parameters used by requests. | 4.654263 | 4.408275 | 1.055802 |
if response.status_code != requests.codes.ok:
self._logger.error("%s %s", response.status_code, response.text)
raise exceptions.RequestNonSuccessException(
"Url {0} had status_code {1}".format(
response.url, response.status_code)) | def _check_response_status(self, response) | Checks the speficied HTTP response from the requests package and
raises an exception if a non-200 HTTP code was returned by the
server. | 3.73807 | 3.5809 | 1.043891 |
self.enabled = app.config.get("CAPTCHA_ENABLE", True)
self.digits = app.config.get("CAPTCHA_LENGTH", 4)
self.max = 10**self.digits
self.image_generator = ImageCaptcha()
self.rand = SystemRandom()
def _generate():
if not self.enabled:
... | def init_app(self, app) | Initialize the captcha extension to the given app object. | 5.29619 | 5.128141 | 1.03277 |
answer = self.rand.randrange(self.max)
answer = str(answer).zfill(self.digits)
image_data = self.image_generator.generate(answer)
base64_captcha = base64.b64encode(image_data.getvalue()).decode("ascii")
logging.debug('Generated captcha with answer... | def generate(self) | Generates and returns a numeric captcha image in base64 format.
Saves the correct answer in `session['captcha_answer']`
Use later as:
src = captcha.generate()
<img src="{{src}}"> | 4.572512 | 3.701984 | 1.235152 |
if not self.enabled:
return True
session_value = session.get('captcha_answer', None)
if not session_value:
return False
if not value and form_key in request.form:
value = request.form[form_key].strip()
# invalidate the answe... | def validate(self, form_key="captcha", value=None) | Validate a captcha answer (taken from request.form) against the answer saved in the session.
Returns always true if CAPTCHA_ENABLE is set to False. Otherwise return true only if it is the correct answer. | 4.215672 | 3.511715 | 1.20046 |
url = self.baseurl + '/_status?format=xml'
response = self.s.get(url)
response.raise_for_status()
from xml.etree.ElementTree import XML
root = XML(response.text)
for serv_el in root.iter('service'):
serv = Monit.Service(self, serv_el)
self... | def update(self) | Update Monit deamon and services status. | 5.14945 | 4.415377 | 1.166254 |
packet = Packet()
self.packets.append(packet)
packet.add_payload(payloads.SA())
packet.add_payload(payloads.KE(diffie_hellman=self.diffie_hellman))
packet.add_payload(payloads.Nonce(nonce=self.Ni))
packet.iSPI = self.iSPI = packet.payloads[0].spi
self.sta... | def init_send(self) | Generates the first (IKE_INIT) packet for Initiator
:return: bytes() containing a valid IKE_INIT packet | 6.360217 | 5.686428 | 1.118491 |
assert len(self.packets) == 2
packet = Packet(exchange_type=const.ExchangeType.IKE_AUTH, iSPI=self.iSPI, rSPI=self.rSPI)
# Add IDi (35)
id_payload = payloads.IDi()
packet.add_payload(id_payload)
# Add AUTH (39)
signed_octets = bytes(self.packets[0]) + s... | def auth_send(self) | Generates the second (IKE_AUTH) packet for Initiator
:return: bytes() containing a valid IKE_INIT packet | 6.10883 | 5.796551 | 1.053873 |
assert len(self.packets) == 2
packet = self.packets[-1]
for p in packet.payloads:
if p._type == payloads.Type.Nr:
self.Nr = p._data
logger.debug(u"Responder nonce {}".format(binascii.hexlify(self.Nr)))
elif p._type == payloads.Type... | def init_recv(self) | Parses the IKE_INIT response packet received from Responder.
Assigns the correct values of rSPI and Nr
Calculates Diffie-Hellman exchange and assigns all keys to self. | 4.301696 | 4.036415 | 1.065722 |
logger.debug('message: {}'.format(dump(message)))
signed_octets = message + self.Ni + prf(self.SK_pr, peer_id._data)
auth_type = const.AuthenticationType(struct.unpack(const.AUTH_HEADER, auth_data[:4])[0])
assert auth_type == const.AuthenticationType.RSA
logger.debug(dum... | def authenticate_peer(self, auth_data, peer_id, message) | Verifies the peers authentication. | 9.021185 | 8.959955 | 1.006834 |
id_r = auth_data = None
for p in self.packets[-1].payloads:
if p._type == payloads.Type.IDr:
id_r = p
logger.debug('Got responder ID: {}'.format(dump(bytes(p))))
if p._type == payloads.Type.AUTH:
auth_data = p._data
... | def auth_recv(self) | Handle peer's IKE_AUTH response. | 8.75632 | 7.940469 | 1.102746 |
final = Packet(exchange_type=packet.exchange_type, iSPI=packet.iSPI, rSPI=packet.rSPI, message_id=1)
# Set up crypto
iv = os.urandom(16)
ikecrypto = Camellia(self.SK_ei, iv)
ikehash = HMAC(self.SK_ai, digestmod=sha256)
logger.debug('IV: {}'.format(dump(iv)))
... | def encrypt_and_hmac(self, packet) | Encrypts and signs a Packet() using self.SK_ei and self.SK_ai
:param packet: Unecrypted Packet() with one or more payloads.
:return: Encrypted and signed Packet() with a single payloads.SK | 6.058641 | 5.090234 | 1.190248 |
next_payload, is_critical, payload_len = const.PAYLOAD_HEADER.unpack(data[:const.PAYLOAD_HEADER.size])
next_payload = payloads.Type(next_payload)
logger.debug("next payload: {!r}".format(next_payload))
try:
iv_len = 16
iv = bytes(data[const.PAYLOAD_HEADER... | def decrypt(self, data) | Decrypts an encrypted (SK, 46) IKE payload using self.SK_er
:param data: Encrypted IKE payload including headers (payloads.SK())
:return: next_payload, data_containing_payloads
:raise IkeError: If packet is corrupted. | 4.273249 | 3.441942 | 1.241523 |
hmac = HMAC(self.SK_ar, digestmod=sha256)
hmac_theirs = data[-MACLEN:]
hmac.update(data[:-MACLEN])
hmac_ours = hmac.digest()[:MACLEN]
logger.debug('HMAC verify (ours){} (theirs){}'.format(
binascii.hexlify(hmac_ours), binascii.hexlify(hmac_theirs)))
i... | def verify_hmac(self, data) | Verifies the HMAC signature of an encrypted (SK, 46) payload using self.SK_ar
:param data: bytes(payloads.SK())
:raise IkeError: if calculated signature does not match the one in the payload | 4.083619 | 3.12029 | 1.308731 |
packet = Packet(data=data)
packet.header = data[0:const.IKE_HEADER.size]
(packet.iSPI, packet.rSPI, next_payload, packet.version, exchange_type, packet.flags,
packet.message_id, packet.length) = const.IKE_HEADER.unpack(packet.header)
packet.exchange_type = const.Exchang... | def parse_packet(self, data) | Parses a received packet in to Packet() with corresponding payloads.
Will decrypt encrypted packets when needed.
:param data: bytes() IKE packet from wire.
:return: Packet() instance
:raise IkeError: on malformed packet | 3.281665 | 3.245765 | 1.01106 |
if self.payloads:
self.payloads[-1].next_payload = payload._type
self.payloads.append(payload) | def add_payload(self, payload) | Adds a payload to packet, updating last payload's next_payload field | 4.862217 | 3.205956 | 1.51662 |
stack = inspect.stack()
assert len(stack) > 1
caller = stack[2][0]
return caller.f_globals['__name__'] | def get_caller_module() | Returns the name of the caller's module as a string.
>>> get_caller_module()
'__main__' | 3.002496 | 4.14873 | 0.723715 |
cls_dict = {}
cls_dict.update(
# Provide a nice, clean, self-documenting __repr__
__repr__=lambda self: name,
# Provide a copy and deepcopy implementation which simply return the
# same exact instance.
__deepcopy__=lambda self, _memo: self,
__copy__=lambda ... | def create(name, mro=(object,), extra_methods={}, *args, **kwargs) | create(name, mro=(object,), extra_methods={}, ...) -> Sentinel instance
Creates a new sentinel instance. This is a singleton instance kind
of like the builtin None, and Ellipsis.
Method resolution order (MRO) for the anonymous class can be
specified (i.e., it can be a subclass). Provide the mro as tup... | 5.888533 | 5.716809 | 1.030038 |
if hasattr(key, "encode"):
key = key.encode('ascii')
value = (zlib.crc32(key, self.seed) & MAX_VALUE)
return value * INV_MAX_VALUE | def _random(self, key) | Generates a pseudorandom value between 0 and 1 (inclusive) | 8.157248 | 6.293232 | 1.296194 |
return min_value + self._random(key) * (max_value - min_value) | def uniform(self, key, min_value=0., max_value=1.) | Returns a random number between min_value and max_value | 4.139987 | 4.376748 | 0.945905 |
total = sum(x[0] for x in probabilities)
choice = total * self._random(key)
for probability, option in probabilities:
choice -= probability
if choice <= 0:
return option | def weighted_choice(self, probabilities, key) | Makes a weighted choice between several options.
Probabilities is a list of 2-tuples, (probability, option). The
probabilties don't need to add up to anything, they are automatically
scaled. | 4.62947 | 3.664183 | 1.263439 |
if hasattr(key, "encode"):
key = key.encode('ascii')
value = zlib.adler32(key, self.seed)
return PerlinNoise(value, **kwargs) | def perlin(self, key, **kwargs) | Return perlin noise seede with the specified key.
For parameters, check the PerlinNoise class. | 4.983057 | 4.684494 | 1.063734 |
try:
choice = self.values[key].lower()
except KeyError:
# override not set.
result = super(OverridableParameters, self)\
.weighted_choice(probabilities, key)
if hasattr(result, "__call__"):
self.results[key] = resu... | def weighted_choice(self, probabilities, key) | Makes a weighted choice between several options.
Probabilities is a list of 2-tuples, (probability, option). The
probabilties don't need to add up to anything, they are automatically
scaled. | 4.177461 | 4.078146 | 1.024353 |
try:
choice = self.values[key].lower()
except KeyError:
# override not set.
return super(RecordingParameters, self)\
.weighted_choice(probabilities, key)
# Find the matching key (case insensitive)
for probability, option in p... | def weighted_choice(self, probabilities, key) | Makes a weighted choice between several options.
Probabilities is a list of 2-tuples, (probability, option). The
probabilties don't need to add up to anything, they are automatically
scaled. | 6.349428 | 5.909691 | 1.074409 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.