INSTRUCTION stringlengths 1 46.3k | RESPONSE stringlengths 75 80.2k |
|---|---|
Returns (args, kwargs) to be used when deserializing this parameter. | def serialize_args(self):
"""Returns (args, kwargs) to be used when deserializing this parameter."""
args, kwargs = super(MultiParameter, self).serialize_args()
args.insert(0, [[t.id, t.serialize_args()] for t in self.types])
return args, kwargs |
Cleans and returns the given value, or raises a ParameterNotValidError exception | def clean(self, value):
"""Cleans and returns the given value, or raises a ParameterNotValidError exception"""
if not isinstance(value, (list, tuple, set, GeneratorType)):
value = [value]
gen = (self.param_type.clean(x) for x in value)
if isinstance(value, GeneratorType):
... |
Returns (args, kwargs) to be used when deserializing this parameter. | def serialize_args(self):
"""Returns (args, kwargs) to be used when deserializing this parameter."""
args, kwargs = super(ListParameter, self).serialize_args()
args.insert(0, [self.param_type.id, self.param_type.serialize_args()]) |
Cleans and returns the given value, or raises a ParameterNotValidError exception | def clean(self, value):
"""Cleans and returns the given value, or raises a ParameterNotValidError exception"""
if isinstance(value, six.string_types):
return value
elif isinstance(value, numbers.Number):
return str(value)
raise ParameterNotValidError |
Cleans and returns the given value, or raises a ParameterNotValidError exception | def clean(self, value):
"""Cleans and returns the given value, or raises a ParameterNotValidError exception"""
if isinstance(value, numbers.Number):
return value
elif isinstance(value, six.string_types):
try:
value = float(value)
return in... |
Cleans and returns the given value, or raises a ParameterNotValidError exception | def clean(self, value):
"""Cleans and returns the given value, or raises a ParameterNotValidError exception"""
if isinstance(value, six.string_types) and value.lower() == 'false':
return False
return bool(value) |
Cleans and returns the given value, or raises a ParameterNotValidError exception | def clean(self, value):
"""Cleans and returns the given value, or raises a ParameterNotValidError exception"""
if isinstance(value, numpy.ndarray):
return value
elif isinstance(value, (list, tuple)):
return numpy.array(value)
raise ParameterNotValidError |
Cleans and returns the given value, or raises a ParameterNotValidError exception | def clean(self, value):
"""Cleans and returns the given value, or raises a ParameterNotValidError exception"""
if isinstance(value, (list, tuple)):
return [super(FeatureCollectionParameter, self).clean(x) for x in value]
raise ParameterNotValidError |
Cleans and returns the given value, or raises a ParameterNotValidError exception | def clean(self, value):
"""Cleans and returns the given value, or raises a ParameterNotValidError exception"""
if not isinstance(value, six.string_types):
raise ParameterNotValidError
try:
source, value = value.split('://', 1)
except ValueError:
rais... |
Encode an item write command | def _encode_write(dynamizer, data, action, key):
""" Encode an item write command """
# Strip null values out of data
data = dict(((k, dynamizer.encode(v)) for k, v in six.iteritems(data) if
not is_null(v)))
return {
action: {
key: data,
}
} |
Encode query constraints in Dynamo format | def encode_query_kwargs(dynamizer, kwargs):
""" Encode query constraints in Dynamo format """
ret = {}
for k, v in six.iteritems(kwargs):
if '__' not in k:
raise TypeError("Invalid query argument '%s'" % k)
name, condition_key = k.split('__')
# Convert ==None to IS_NULL
... |
Get the attributes for the update | def attrs(self, dynamizer):
""" Get the attributes for the update """
ret = {
self.key: {
'Action': self.action,
}
}
if not is_null(self.value):
ret[self.key]['Value'] = dynamizer.encode(self.value)
return ret |
Get the expected values for the update | def expected(self, dynamizer):
""" Get the expected values for the update """
if self._expect_kwargs:
return encode_query_kwargs(dynamizer, self._expect_kwargs)
if self._expected is not NO_ARG:
ret = {}
if is_null(self._expected):
ret['Exists']... |
Write an item (will overwrite existing data)
Parameters
----------
data : dict
Item data | def put(self, data):
"""
Write an item (will overwrite existing data)
Parameters
----------
data : dict
Item data
"""
self._to_put.append(data)
if self.should_flush():
self.flush() |
Delete an item
Parameters
----------
kwargs : dict
The primary key of the item to delete | def delete(self, kwargs):
"""
Delete an item
Parameters
----------
kwargs : dict
The primary key of the item to delete
"""
self._to_delete.append(kwargs)
if self.should_flush():
self.flush() |
Flush pending items to Dynamo | def flush(self):
""" Flush pending items to Dynamo """
items = []
for data in self._to_put:
items.append(encode_put(self.connection.dynamizer, data))
for data in self._to_delete:
items.append(encode_delete(self.connection.dynamizer, data))
self._write(it... |
Perform a batch write and handle the response | def _write(self, items):
""" Perform a batch write and handle the response """
response = self._batch_write_item(items)
if 'consumed_capacity' in response:
# Comes back as a list from BatchWriteItem
self.consumed_capacity = \
sum(response['consumed_capacit... |
Resend all unprocessed items | def resend_unprocessed(self):
""" Resend all unprocessed items """
LOG.info("Re-sending %d unprocessed items.", len(self._unprocessed))
while self._unprocessed:
to_resend = self._unprocessed[:MAX_WRITE_BATCH]
self._unprocessed = self._unprocessed[MAX_WRITE_BATCH:]
... |
Make a BatchWriteItem call to Dynamo | def _batch_write_item(self, items):
""" Make a BatchWriteItem call to Dynamo """
kwargs = {
'RequestItems': {
self.tablename: items,
},
'ReturnConsumedCapacity': self.return_capacity,
'ReturnItemCollectionMetrics': self.return_item_collecti... |
This method is used to build the menu tree. | def get_nodes(self, request):
"""
This method is used to build the menu tree.
"""
nodes = []
for term in Term.objects.only('pk', 'name', 'url'):
try:
url = term.get_absolute_url()
except NoReverseMatch:
continue
... |
Get the entity_id as a string if it is a Reference.
@param entity_id The ID either a reference or a string of the entity
to get.
@return entity_id as a string | def _get_path(entity_id):
'''Get the entity_id as a string if it is a Reference.
@param entity_id The ID either a reference or a string of the entity
to get.
@return entity_id as a string
'''
try:
path = entity_id.path()
except AttributeError:
path = entity_id
if p... |
Make a get request against the charmstore.
This method is used by other API methods to standardize querying.
@param url The full url to query
(e.g. https://api.jujucharms.com/charmstore/v4/macaroon) | def _get(self, url):
"""Make a get request against the charmstore.
This method is used by other API methods to standardize querying.
@param url The full url to query
(e.g. https://api.jujucharms.com/charmstore/v4/macaroon)
"""
try:
response = requests.get... |
Retrieve metadata about an entity in the charmstore.
@param entity_id The ID either a reference or a string of the entity
to get.
@param includes Which metadata fields to include in the response.
@param channel Optional channel name, e.g. `stable`. | def _meta(self, entity_id, includes, channel=None):
'''Retrieve metadata about an entity in the charmstore.
@param entity_id The ID either a reference or a string of the entity
to get.
@param includes Which metadata fields to include in the response.
@param channel Option... |
Get the default data for any entity (e.g. bundle or charm).
@param entity_id The entity's id either as a reference or a string
@param get_files Whether to fetch the files for the charm or not.
@param channel Optional channel name.
@param include_stats Optionally disable stats collection... | def entity(self, entity_id, get_files=False, channel=None,
include_stats=True, includes=None):
'''Get the default data for any entity (e.g. bundle or charm).
@param entity_id The entity's id either as a reference or a string
@param get_files Whether to fetch the files for the cha... |
Get the default data for entities.
@param entity_ids A list of entity ids either as strings or references. | def entities(self, entity_ids):
'''Get the default data for entities.
@param entity_ids A list of entity ids either as strings or references.
'''
url = '%s/meta/any?include=id&' % self.url
for entity_id in entity_ids:
url += 'id=%s&' % _get_path(entity_id)
# ... |
Get the default data for a bundle.
@param bundle_id The bundle's id.
@param channel Optional channel name. | def bundle(self, bundle_id, channel=None):
'''Get the default data for a bundle.
@param bundle_id The bundle's id.
@param channel Optional channel name.
'''
return self.entity(bundle_id, get_files=True, channel=channel) |
Get the default data for a charm.
@param charm_id The charm's id.
@param channel Optional channel name. | def charm(self, charm_id, channel=None):
'''Get the default data for a charm.
@param charm_id The charm's id.
@param channel Optional channel name.
'''
return self.entity(charm_id, get_files=True, channel=channel) |
Generate the path to the icon for charms.
@param charm_id The ID of the charm.
@param channel Optional channel name.
@return The url to the icon. | def charm_icon_url(self, charm_id, channel=None):
'''Generate the path to the icon for charms.
@param charm_id The ID of the charm.
@param channel Optional channel name.
@return The url to the icon.
'''
url = '{}/{}/icon.svg'.format(self.url, _get_path(charm_id))
... |
Get the charm icon.
@param charm_id The ID of the charm.
@param channel Optional channel name. | def charm_icon(self, charm_id, channel=None):
'''Get the charm icon.
@param charm_id The ID of the charm.
@param channel Optional channel name.
'''
url = self.charm_icon_url(charm_id, channel=channel)
response = self._get(url)
return response.content |
Get the bundle visualization.
@param bundle_id The ID of the bundle.
@param channel Optional channel name. | def bundle_visualization(self, bundle_id, channel=None):
'''Get the bundle visualization.
@param bundle_id The ID of the bundle.
@param channel Optional channel name.
'''
url = self.bundle_visualization_url(bundle_id, channel=channel)
response = self._get(url)
re... |
Generate the path to the visualization for bundles.
@param charm_id The ID of the bundle.
@param channel Optional channel name.
@return The url to the visualization. | def bundle_visualization_url(self, bundle_id, channel=None):
'''Generate the path to the visualization for bundles.
@param charm_id The ID of the bundle.
@param channel Optional channel name.
@return The url to the visualization.
'''
url = '{}/{}/diagram.svg'.format(self... |
Generate the url path for the readme of an entity.
@entity_id The id of the entity (i.e. charm, bundle).
@param channel Optional channel name. | def entity_readme_url(self, entity_id, channel=None):
'''Generate the url path for the readme of an entity.
@entity_id The id of the entity (i.e. charm, bundle).
@param channel Optional channel name.
'''
url = '{}/{}/readme'.format(self.url, _get_path(entity_id))
return ... |
Get the readme for an entity.
@entity_id The id of the entity (i.e. charm, bundle).
@param channel Optional channel name. | def entity_readme_content(self, entity_id, channel=None):
'''Get the readme for an entity.
@entity_id The id of the entity (i.e. charm, bundle).
@param channel Optional channel name.
'''
readme_url = self.entity_readme_url(entity_id, channel=channel)
response = self._get... |
Generate a URL for the archive of an entity..
@param entity_id The ID of the entity to look up as a string
or reference.
@param channel Optional channel name. | def archive_url(self, entity_id, channel=None):
'''Generate a URL for the archive of an entity..
@param entity_id The ID of the entity to look up as a string
or reference.
@param channel Optional channel name.
'''
url = '{}/{}/archive'.format(self.url, _get_path(e... |
Generate a URL for a file in an archive without requesting it.
@param entity_id The ID of the entity to look up.
@param filename The name of the file in the archive.
@param channel Optional channel name. | def file_url(self, entity_id, filename, channel=None):
'''Generate a URL for a file in an archive without requesting it.
@param entity_id The ID of the entity to look up.
@param filename The name of the file in the archive.
@param channel Optional channel name.
'''
url =... |
Get the files or file contents of a file for an entity.
If all files are requested, a dictionary of filenames and urls for the
files in the archive are returned.
If filename is provided, the url of just that file is returned, if it
exists.
If filename is provided and read_file... | def files(self, entity_id, manifest=None, filename=None,
read_file=False, channel=None):
'''
Get the files or file contents of a file for an entity.
If all files are requested, a dictionary of filenames and urls for the
files in the archive are returned.
If filena... |
Return the resource url for a given resource on an entity.
@param entity_id The id of the entity to get resource for.
@param name The name of the resource.
@param revision The revision of the resource. | def resource_url(self, entity_id, name, revision):
'''
Return the resource url for a given resource on an entity.
@param entity_id The id of the entity to get resource for.
@param name The name of the resource.
@param revision The revision of the resource.
'''
re... |
Get the config data for a charm.
@param charm_id The charm's id.
@param channel Optional channel name. | def config(self, charm_id, channel=None):
'''Get the config data for a charm.
@param charm_id The charm's id.
@param channel Optional channel name.
'''
url = '{}/{}/meta/charm-config'.format(self.url, _get_path(charm_id))
data = self._get(_add_channel(url, channel))
... |
Get an entity's full id provided a partial one.
Raises EntityNotFound if partial cannot be resolved.
@param partial The partial id (e.g. mysql, precise/mysql).
@param channel Optional channel name. | def entityId(self, partial, channel=None):
'''Get an entity's full id provided a partial one.
Raises EntityNotFound if partial cannot be resolved.
@param partial The partial id (e.g. mysql, precise/mysql).
@param channel Optional channel name.
'''
url = '{}/{}/meta/any'.... |
Search for entities in the charmstore.
@param text The text to search for.
@param includes What metadata to return in results (e.g. charm-config).
@param doc_type Filter to this type: bundle or charm.
@param limit Maximum number of results to return.
@param autocomplete Whether ... | def search(self, text, includes=None, doc_type=None, limit=None,
autocomplete=False, promulgated_only=False, tags=None,
sort=None, owner=None, series=None):
'''
Search for entities in the charmstore.
@param text The text to search for.
@param includes What ... |
List entities in the charmstore.
@param includes What metadata to return in results (e.g. charm-config).
@param doc_type Filter to this type: bundle or charm.
@param promulgated_only Whether to filter to only promulgated charms.
@param sort Sorting the result based on the sort string pr... | def list(self, includes=None, doc_type=None, promulgated_only=False,
sort=None, owner=None, series=None):
'''
List entities in the charmstore.
@param includes What metadata to return in results (e.g. charm-config).
@param doc_type Filter to this type: bundle or charm.
... |
Extract common query parameters between search and list into slice.
@param includes What metadata to return in results (e.g. charm-config).
@param doc_type Filter to this type: bundle or charm.
@param promulgated_only Whether to filter to only promulgated charms.
@param sort Sorting the... | def _common_query_parameters(self, doc_type, includes, owner,
promulgated_only, series, sort):
'''
Extract common query parameters between search and list into slice.
@param includes What metadata to return in results (e.g. charm-config).
@param doc_type... |
Fetch related entity information.
Fetches metadata, stats and extra-info for the supplied entities.
@param ids The entity ids to fetch related information for. A list of
entity id dicts from the charmstore. | def fetch_related(self, ids):
"""Fetch related entity information.
Fetches metadata, stats and extra-info for the supplied entities.
@param ids The entity ids to fetch related information for. A list of
entity id dicts from the charmstore.
"""
if not ids:
... |
Get the list of charms that provides or requires this interface.
@param interface The interface for the charm relation.
@param way The type of relation, either "provides" or "requires".
@return List of charms | def fetch_interfaces(self, interface, way):
"""Get the list of charms that provides or requires this interface.
@param interface The interface for the charm relation.
@param way The type of relation, either "provides" or "requires".
@return List of charms
"""
if not inte... |
Retrieve the debug information from the charmstore. | def debug(self):
'''Retrieve the debug information from the charmstore.'''
url = '{}/debug/status'.format(self.url)
data = self._get(url)
return data.json() |
Server query for the isochrone file.
Parameters:
-----------
outfile : name of output isochrone file
age : isochrone age
metallicity : isochrone metallicity
Returns:
--------
outfile : name of output isochrone file | def query_server(self,outfile,age,metallicity):
""" Server query for the isochrone file.
Parameters:
-----------
outfile : name of output isochrone file
age : isochrone age
metallicity : isochrone metallicity
Returns:
--------
... |
Run the likelihood grid search | def run(self, coords=None, debug=False):
"""
Run the likelihood grid search
"""
#self.grid.precompute()
self.grid.search(coords=coords)
return self.grid |
DEPRECATED: ADW 20170627
Precompute color probabilities for background ('u_background')
and signal ('u_color') for each star in catalog. Precompute
observable fraction in each ROI pixel. # Precompute still
operates over the full ROI, not just the likelihood region
Parameters:... | def precompute(self, distance_modulus_array=None):
"""
DEPRECATED: ADW 20170627
Precompute color probabilities for background ('u_background')
and signal ('u_color') for each star in catalog. Precompute
observable fraction in each ROI pixel. # Precompute still
operates... |
Organize a grid search over ROI target pixels and distance moduli in distance_modulus_array
coords: (lon,lat)
distance_modulus: scalar | def search(self, coords=None, distance_modulus=None, tolerance=1.e-2):
"""
Organize a grid search over ROI target pixels and distance moduli in distance_modulus_array
coords: (lon,lat)
distance_modulus: scalar
"""
nmoduli = len(self.distance_modulus_array)
npixels... |
A few rough approximations of the fit uncertainty. These
values shouldn't be trusted for anything real (use MCMC instead). | def err(self):
"""
A few rough approximations of the fit uncertainty. These
values shouldn't be trusted for anything real (use MCMC instead).
"""
# Initiallize error to nan
err = odict(self.mle())
err.update([(k,np.nan*np.ones(2)) for k in err.keys()])
# ... |
Save the likelihood results as a sparse HEALPix map. | def write(self, outfile):
"""
Save the likelihood results as a sparse HEALPix map.
"""
data = odict()
data['PIXEL']=self.roi.pixels_target
# Full data output (too large for survey)
if self.config['scan']['full_pdf']:
data['LOG_LIKELIHOOD']=self.log_lik... |
Construct a synchronous Beanstalk Client from a URI.
The URI may be of the form beanstalk://host:port or beanstalkd://host:port
IPv6 literals must be wrapped in brackets as per RFC 2732. | def from_uri(cls, uri, socket_timeout=None, auto_decode=False):
"""Construct a synchronous Beanstalk Client from a URI.
The URI may be of the form beanstalk://host:port or beanstalkd://host:port
IPv6 literals must be wrapped in brackets as per RFC 2732.
"""
parts = six.moves.ur... |
Call after a close/re-connect.
Automatically re-establishes the USE and WATCH configs previously setup. | def _re_establish_use_watch(self):
"""Call after a close/re-connect.
Automatically re-establishes the USE and WATCH configs previously setup.
"""
if self.current_tube != self.desired_tube:
self.use(self.desired_tube)
if self._watchlist != self.desired_watchlist:
... |
Return a list of tubes that this beanstalk instance knows about
:rtype: list of tubes | def list_tubes(self):
"""Return a list of tubes that this beanstalk instance knows about
:rtype: list of tubes
"""
with self._sock_ctx() as sock:
self._send_message('list-tubes', sock)
body = self._receive_data_with_prefix(b'OK', sock)
tubes = yaml_lo... |
Return a dictionary with a bunch of instance-wide statistics
:rtype: dict | def stats(self):
"""Return a dictionary with a bunch of instance-wide statistics
:rtype: dict
"""
with self._sock_ctx() as socket:
self._send_message('stats', socket)
body = self._receive_data_with_prefix(b'OK', socket)
stats = yaml_load(body)
... |
Insert a new job into whatever queue is currently USEd
:param data: Job body
:type data: Text (either str which will be encoded as utf-8, or bytes which are already utf-8
:param pri: Priority for the job
:type pri: int
:param delay: Delay in seconds before the job should be plac... | def put_job(self, data, pri=65536, delay=0, ttr=120):
"""Insert a new job into whatever queue is currently USEd
:param data: Job body
:type data: Text (either str which will be encoded as utf-8, or bytes which are already utf-8
:param pri: Priority for the job
:type pri: int
... |
Insert a new job into a specific queue. Wrapper around :func:`put_job`.
:param tube_name: Tube name
:type tube_name: str
:param data: Job body
:type data: Text (either str which will be encoded as utf-8, or bytes which are already utf-8
:param pri: Priority for the job
:... | def put_job_into(self, tube_name, data, pri=65536, delay=0, ttr=120):
"""Insert a new job into a specific queue. Wrapper around :func:`put_job`.
:param tube_name: Tube name
:type tube_name: str
:param data: Job body
:type data: Text (either str which will be encoded as utf-8, or... |
Set the watchlist to the given tubes
:param tubes: A list of tubes to watch
Automatically un-watches any tubes that are not on the target list | def watchlist(self, tubes):
"""Set the watchlist to the given tubes
:param tubes: A list of tubes to watch
Automatically un-watches any tubes that are not on the target list
"""
tubes = set(tubes)
for tube in tubes - self._watchlist:
self.watch(tube)
... |
Add the given tube to the watchlist.
:param tube: Name of the tube to add to the watchlist
Note: Initially, all connections are watching a tube named "default". If
you manually call :func:`watch()`, we will un-watch the "default" tube.
To keep it in your list, first call :func:`watch()... | def watch(self, tube):
"""Add the given tube to the watchlist.
:param tube: Name of the tube to add to the watchlist
Note: Initially, all connections are watching a tube named "default". If
you manually call :func:`watch()`, we will un-watch the "default" tube.
To keep it in yo... |
Remove the given tube from the watchlist.
:param tube: Name of tube to remove from the watchlist
If all tubes are :func:`ignore()` d, beanstalk will auto-add "default" to the watchlist
to prevent the list from being empty. See :func:`watch()` for more unformation. | def ignore(self, tube):
"""Remove the given tube from the watchlist.
:param tube: Name of tube to remove from the watchlist
If all tubes are :func:`ignore()` d, beanstalk will auto-add "default" to the watchlist
to prevent the list from being empty. See :func:`watch()` for more unforma... |
Fetch statistics about a single job
:rtype: dict | def stats_job(self, job_id):
"""Fetch statistics about a single job
:rtype: dict
"""
with self._sock_ctx() as socket:
if hasattr(job_id, 'job_id'):
job_id = job_id.job_id
self._send_message('stats-job {0}'.format(job_id), socket)
body ... |
Fetch statistics about a single tube
:param tube_name: Tube to fetch stats about
:rtype: dict | def stats_tube(self, tube_name):
"""Fetch statistics about a single tube
:param tube_name: Tube to fetch stats about
:rtype: dict
"""
with self._sock_ctx() as socket:
self._send_message('stats-tube {0}'.format(tube_name), socket)
body = self._receive_data... |
Reserve a job for this connection. Blocks for TIMEOUT secionds and raises TIMED_OUT if no job was available
:param timeout: Time to wait for a job, in seconds.
:type timeout: int | def reserve_job(self, timeout=5):
"""Reserve a job for this connection. Blocks for TIMEOUT secionds and raises TIMED_OUT if no job was available
:param timeout: Time to wait for a job, in seconds.
:type timeout: int
"""
timeout = int(timeout)
if self.socket_timeout is no... |
Common implementation for the peek_* functions | def _peek_common(self, typ):
"""Common implementation for the peek_* functions"""
with self._sock_ctx() as socket:
self._send_message('peek-{0}'.format(typ), socket)
job_id, job_data = self._receive_id_and_data_with_prefix(b'FOUND', socket)
return Job(job_id, job_data... |
Delete the given job id. The job must have been previously reserved by this connection | def delete_job(self, job_id):
"""Delete the given job id. The job must have been previously reserved by this connection"""
if hasattr(job_id, 'job_id'):
job_id = job_id.job_id
with self._sock_ctx() as socket:
self._send_message('delete {0}'.format(job_id), socket)
... |
Mark the given job_id as buried. The job must have been previously reserved by this connection
:param job_id: Job to bury
:param pri: Priority for the newly-buried job. If not passed, will keep its current priority
:type pri: int | def bury_job(self, job_id, pri=65536):
"""Mark the given job_id as buried. The job must have been previously reserved by this connection
:param job_id: Job to bury
:param pri: Priority for the newly-buried job. If not passed, will keep its current priority
:type pri: int
"""
... |
Put a job back on the queue to be processed (indicating that you've aborted it)
You can only release a job which you have reserved using :func:`reserve_job()` or :func:`reserve_iter()`.
:param job_id: Job ID to return
:param pri: New priority (if not passed, will use old priority)
:typ... | def release_job(self, job_id, pri=65536, delay=0):
"""Put a job back on the queue to be processed (indicating that you've aborted it)
You can only release a job which you have reserved using :func:`reserve_job()` or :func:`reserve_iter()`.
:param job_id: Job ID to return
:param pri: Ne... |
Kick the given job id. The job must either be in the DELAYED or BURIED state and will be immediately moved to
the READY state. | def kick_job(self, job_id):
"""Kick the given job id. The job must either be in the DELAYED or BURIED state and will be immediately moved to
the READY state."""
if hasattr(job_id, 'job_id'):
job_id = job_id.job_id
with self._sock_ctx() as socket:
self._send_messag... |
Start producing jobs into the given tube.
:param tube: Name of the tube to USE
Subsequent calls to :func:`put_job` insert jobs into this tube. | def use(self, tube):
"""Start producing jobs into the given tube.
:param tube: Name of the tube to USE
Subsequent calls to :func:`put_job` insert jobs into this tube.
"""
with self._sock_ctx() as socket:
if self.current_tube != tube:
self.desired_tub... |
Context-manager to insert jobs into a specific tube
:param tube: Tube to insert to
Yields out an instance of :class:`BeanstalkInsertingProxy` to insert items into that tube
.. seealso::
:func:`use()`
Change the default tube
:func:`put_job()`
... | def using(self, tube):
"""Context-manager to insert jobs into a specific tube
:param tube: Tube to insert to
Yields out an instance of :class:`BeanstalkInsertingProxy` to insert items into that tube
.. seealso::
:func:`use()`
Change the default tube
... |
Kick some number of jobs from the buried queue onto the ready queue.
:param num_jobs: Number of jobs to kick
:type num_jobs: int
If not that many jobs are in the buried queue, it will kick as many as it can. | def kick_jobs(self, num_jobs):
"""Kick some number of jobs from the buried queue onto the ready queue.
:param num_jobs: Number of jobs to kick
:type num_jobs: int
If not that many jobs are in the buried queue, it will kick as many as it can."""
with self._sock_ctx() as socket:
... |
Pause a tube for some number of seconds, preventing it from issuing jobs.
:param delay: Time to pause for, in seconds
:type delay: int
There is no way to permanently pause a tube; passing 0 for delay actually un-pauses the tube.
.. seealso::
:func:`unpause_tube()` | def pause_tube(self, tube, delay=3600):
"""Pause a tube for some number of seconds, preventing it from issuing jobs.
:param delay: Time to pause for, in seconds
:type delay: int
There is no way to permanently pause a tube; passing 0 for delay actually un-pauses the tube.
.. se... |
Unpause a tube which was previously paused with :func:`pause_tube()`.
.. seealso::
:func:`pause_tube()` | def unpause_tube(self, tube):
"""Unpause a tube which was previously paused with :func:`pause_tube()`.
.. seealso::
:func:`pause_tube()`
"""
with self._sock_ctx() as socket:
self._send_message('pause-tube {0} 0'.format(tube), socket)
return self._rece... |
Pythonized interval for easy output to yaml | def interval(best,lo=np.nan,hi=np.nan):
"""
Pythonized interval for easy output to yaml
"""
return [float(best),[float(lo),float(hi)]] |
Interval assuming gaussian posterior. | def mean_interval(data, alpha=_alpha):
"""
Interval assuming gaussian posterior.
"""
mean =np.mean(data)
sigma = np.std(data)
scale = scipy.stats.norm.ppf(1-alpha/2.)
return interval(mean,mean-scale*sigma,mean+scale*sigma) |
Median including bayesian credible interval. | def median_interval(data, alpha=_alpha):
"""
Median including bayesian credible interval.
"""
q = [100*alpha/2., 50, 100*(1-alpha/2.)]
lo,med,hi = np.percentile(data,q)
return interval(med,lo,hi) |
Identify peak using Gaussian kernel density estimator.
Parameters:
-----------
data : The 1d data sample
npoints : The number of kde points to evaluate | def kde(data, npoints=_npoints):
"""
Identify peak using Gaussian kernel density estimator.
Parameters:
-----------
data : The 1d data sample
npoints : The number of kde points to evaluate
"""
# Clipping of severe outliers to concentrate more KDE samples in the parameter range of ... |
Identify interval using Gaussian kernel density estimator. | def peak_interval(data, alpha=_alpha, npoints=_npoints):
"""
Identify interval using Gaussian kernel density estimator.
"""
peak = kde_peak(data,npoints)
x = np.sort(data.flat); n = len(x)
# The number of entries in the interval
window = int(np.rint((1.0-alpha)*n))
# The start, stop, and... |
Outputs uniform points on sphere from:
[0 < lon < 360] & [-90 < lat < 90] | def sky(lon=None,lat=None,size=1):
"""
Outputs uniform points on sphere from:
[0 < lon < 360] & [-90 < lat < 90]
"""
if lon is None:
umin,umax = 0,1
else:
lon = np.asarray(lon)
lon = np.radians(lon + 360.*(lon<0))
if lon.size==1: umin=umax=lon/(2*np.pi)
... |
Add some supplemental columns | def supplement(self,coordsys='gal'):
""" Add some supplemental columns """
from ugali.utils.projector import gal2cel, gal2cel_angle
from ugali.utils.projector import cel2gal, cel2gal_angle
coordsys = coordsys.lower()
kwargs = dict(usemask=False, asrecarray=True)
out = co... |
Mean of the distribution. | def mean(self, name, **kwargs):
"""
Mean of the distribution.
"""
return np.mean(self.get(name,**kwargs)) |
Interval assuming gaussian posterior. | def mean_interval(self, name, alpha=_alpha, **kwargs):
"""
Interval assuming gaussian posterior.
"""
data = self.get(name,**kwargs)
#return ugali.utils.stats.mean_interval(data,alpha)
return mean_interval(data,alpha) |
Median of the distribution. | def median(self, name, **kwargs):
"""
Median of the distribution.
"""
data = self.get(name,**kwargs)
return np.percentile(data,[50]) |
Median including bayesian credible interval. | def median_interval(self, name, alpha=_alpha, **kwargs):
"""
Median including bayesian credible interval.
"""
data = self.get(name,**kwargs)
return median_interval(data,alpha) |
Calculate peak of kernel density estimator | def kde_peak(self, name, npoints=_npoints, **kwargs):
"""
Calculate peak of kernel density estimator
"""
data = self.get(name,**kwargs)
return kde_peak(data,npoints) |
Calculate kernel density estimator for parameter | def kde(self, name, npoints=_npoints, **kwargs):
"""
Calculate kernel density estimator for parameter
"""
data = self.get(name,**kwargs)
return kde(data,npoints) |
Calculate peak interval for parameter. | def peak_interval(self, name, alpha=_alpha, npoints=_npoints, **kwargs):
"""
Calculate peak interval for parameter.
"""
data = self.get(name, **kwargs)
return peak_interval(data,alpha,npoints) |
Calculate minimum interval for parameter. | def min_interval(self,name, alpha=_alpha, **kwargs):
"""
Calculate minimum interval for parameter.
"""
data = self.get(name, **kwargs)
return min_interval(data,alpha) |
Calculate the results for a set of parameters. | def results(self, names=None, alpha=_alpha, mode='peak', **kwargs):
"""
Calculate the results for a set of parameters.
"""
if names is None: names = self.names
ret = odict()
for n in names:
ret[n] = getattr(self,'%s_interval'%mode)(n, **kwargs)
return ... |
Increase the density of points along the parabolic curve. | def densify(self, factor=10):
"""
Increase the density of points along the parabolic curve.
"""
x = []
y = []
for ii in range(0, len(self.x) - 2):
p = Parabola(self.x[ii: ii + 3], self.y[ii: ii + 3])
x.append(np.linspace(self.x[ii], self.x[ii + 1],... |
Compute one-sided upperlimit via profile method. | def profileUpperLimit(self, delta = 2.71):
"""
Compute one-sided upperlimit via profile method.
"""
a = self.p_2
b = self.p_1
if self.vertex_x < 0:
c = self.p_0 + delta
else:
c = self.p_0 - self.vertex_y + delta
if b**2 - 4. * a * ... |
Compute one-sided upper limit using Bayesian Method of Helene.
Several methods of increasing numerical stability have been implemented. | def bayesianUpperLimit(self, alpha, steps=1.e5, plot=False):
"""
Compute one-sided upper limit using Bayesian Method of Helene.
Several methods of increasing numerical stability have been implemented.
"""
x_dense, y_dense = self.densify()
y_dense -= np.max(y_dense) # Nume... |
Compute one-sided upper limit using Bayesian Method of Helene. | def bayesianUpperLimit2(self, alpha, steps=1.e5, plot=False):
"""
Compute one-sided upper limit using Bayesian Method of Helene.
"""
cut = ((self.y / 2.) > -30.) # Numeric stability
try:
f = scipy.interpolate.interp1d(self.x[cut], self.y[cut], kind='cubic')
ex... |
Hammer-Aitoff projection (deg). | def aitoffSphereToImage(lon, lat):
"""
Hammer-Aitoff projection (deg).
"""
lon = lon - 360.*(lon>180)
lon = np.radians(lon)
lat = np.radians(lat)
half_lon = lon/2.
cos_lat = np.cos(lat)
gamma = (180. / np.pi) * np.sqrt(2. / (1. + (cos_lat * np.cos(half_lon))))
x = 2. * gam... |
Compute two-sided confidence interval by taking x-values corresponding to the largest PDF-values first. | def confidenceInterval(self, alpha=0.6827, steps=1.e5, plot=False):
"""
Compute two-sided confidence interval by taking x-values corresponding to the largest PDF-values first.
"""
x_dense, y_dense = self.densify()
y_dense -= np.max(y_dense) # Numeric stability
f = scipy.i... |
Inverse Hammer-Aitoff projection (deg). | def aitoffImageToSphere(x, y):
"""
Inverse Hammer-Aitoff projection (deg).
"""
x = x - 360.*(x>180)
x = np.asarray(np.radians(x))
y = np.asarray(np.radians(y))
z = np.sqrt(1. - (x / 4.)**2 - (y / 2.)**2) # rad
lon = 2. * np.arctan2((2. * z**2) - 1, (z / 2.) * x)
lat = np.arcsin( y * ... |
Gnomonic projection (deg). | def gnomonicSphereToImage(lon, lat):
"""
Gnomonic projection (deg).
"""
# Convert angle to [-180, 180] interval
lon = lon - 360.*(lon>180)
lon = np.radians(lon)
lat = np.radians(lat)
r_theta = (180. / np.pi) / np.tan(lat)
x = r_theta * np.cos(lon)
y = r_theta * np.sin(lon)
re... |
Inverse gnomonic projection (deg). | def gnomonicImageToSphere(x, y):
"""
Inverse gnomonic projection (deg).
"""
# Convert angle to [-180, 180] interval
x = x - 360.*(x>180)
x = np.asarray(x)
y = np.asarray(y)
lon = np.degrees(np.arctan2(y, x))
r_theta = np.sqrt(x**2 + y**2)
lat = np.degrees(np.arctan(180. / (np.pi ... |
Angular separation (deg) between two sky coordinates. | def angsep2(lon_1, lat_1, lon_2, lat_2):
"""
Angular separation (deg) between two sky coordinates.
"""
import healpy
v10, v11, v12 = healpy.ang2vec(np.radians(90. - lat_1), np.radians(lon_1)).transpose()
v20, v21, v22 = healpy.ang2vec(np.radians(90. - lat_2), np.radians(lon_2)).transpose()
... |
Converts Galactic (deg) to Celestial J2000 (deg) coordinates | def galToCel(ll, bb):
"""
Converts Galactic (deg) to Celestial J2000 (deg) coordinates
"""
bb = np.radians(bb)
sin_bb = np.sin(bb)
cos_bb = np.cos(bb)
ll = np.radians(ll)
ra_gp = np.radians(192.85948)
de_gp = np.radians(27.12825)
lcp = np.radians(122.932)
sin_lcp_ll = np.si... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.