Search is not available for this dataset
text stringlengths 75 104k |
|---|
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.mol... |
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:
... |
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 wit... |
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 ex... |
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 ... |
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
... |
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 Charm... |
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())
... |
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
P... |
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_fi... |
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:
t... |
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, ForceF... |
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... |
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
... |
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... |
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... |
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:
se... |
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:
se... |
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
... |
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 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 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... |
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 Con... |
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_p... |
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
... |
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_pag... |
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 oth... |
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 _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.m... |
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 ... |
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(... |
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, s... |
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.con... |
def create(self, attributes=None, **kwargs):
"""
Creates a webhook with given attributes.
"""
return super(WebhooksProxy, self).create(resource_id=None, attributes=attributes) |
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
#... |
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 con... |
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 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 <cont... |
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.EnvironmentEntri... |
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.EnvironmentAssetsPro... |
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.EnvironmentLoca... |
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_pro... |
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 revoke(self, token_id, *args, **kwargs):
"""
Revokes a personal access token.
"""
return self.delete(token_id, *args, **kwargs) |
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... |
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)
... |
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 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(
... |
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._environ... |
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_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 ... |
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_ob... |
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:
... |
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 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['u... |
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... |
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
... |
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... |
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/foob... |
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(
... |
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 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 ''
),
'descript... |
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':... |
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[me... |
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}".form... |
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 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,
'fi... |
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_en... |
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... |
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:`ContentTypeSnapshotsP... |
def all(self, query=None, **kwargs):
"""
Gets all organizations.
"""
return super(OrganizationsProxy, self).all(query=query) |
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 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': at... |
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 delete(self):
"""
Deletes the space
"""
return self._client._delete(
self.__class__.base_url(
self.sys['id']
)
) |
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 all(self, query=None, **kwargs):
"""
Gets all spaces.
"""
return super(SpacesProxy, self).all(query=query) |
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 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(Space... |
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 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:`EditorInterface... |
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 <co... |
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_managem... |
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:`SnapshotsProx... |
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:
... |
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'] = {
'n... |
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}... |
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... |
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_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_put(self, url, data, **kwargs):
"""
Performs the HTTP PUT request.
"""
kwargs.update({'data': json.dumps(data)})
return self._http_request('put', url, kwargs) |
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 = geta... |
def _get(self, url, query=None, **kwargs):
"""
Wrapper for the HTTP GET request.
"""
return self._request('get', url, query, **kwargs) |
def _post(self, url, attributes=None, **kwargs):
"""
Wrapper for the HTTP POST request.
"""
return self._request('post', url, attributes, **kwargs) |
def _put(self, url, attributes=None, **kwargs):
"""
Wrapper for the HTTP PUT request.
"""
return self._request('put', url, attributes, **kwargs) |
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)
... |
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,
... |
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 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 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_pro... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.