code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
def read_and_expand(match):
filename = match.group('filename')
filename = join(path, filename)
text = read(filename)
return expand_includes(
text, path=join(path, dirname(filename)))
return re.sub(r'^\.\. include:: (?P<filename>.*)$',
read_and_... | def expand_includes(text, path='.') | Recursively expands includes in given text. | 3.024447 | 2.940188 | 1.028658 |
ra1_rad = np.radians(ra1)
dec1_rad = np.radians(dec1)
ra2_rad = np.radians(ra2)
dec2_rad = np.radians(dec2)
sin_dec1, cos_dec1 = np.sin(dec1_rad), np.cos(dec1_rad)
sin_dec2, cos_dec2 = np.sin(dec2_rad), np.cos(dec2_rad)
delta_ra = ra2_rad - ra1_rad
cos_delta_ra, sin_delta_ra = np.c... | def angSepVincenty(ra1, dec1, ra2, dec2) | Vincenty formula for distances on a sphere | 1.482813 | 1.486738 | 0.99736 |
try:
a, b, mag = np.atleast_2d(
np.genfromtxt(
infile,
usecols=[0, 1, 2],
delimiter=','
)
).T
... | def parse_file(infile, exit_on_error=True) | Parse a comma-separated file with columns "ra,dec,magnitude". | 3.827989 | 3.434984 | 1.114413 |
dist = angSepVincenty(FovObj.ra0_deg, FovObj.dec0_deg, ra_deg, dec_deg)
if dist >= 90.:
return False
# padding_pix=3 means that objects less than 3 pixels off the edge of
# a channel are counted inside, to account for inaccuracies in K2fov.
return FovObj.isOnSilicon(ra_deg, dec_deg, pad... | def onSiliconCheck(ra_deg, dec_deg, FovObj, padding_pix=DEFAULT_PADDING) | Check a single position. | 6.153287 | 6.474002 | 0.950461 |
dist = angSepVincenty(FovObj.ra0_deg, FovObj.dec0_deg, ra_deg, dec_deg)
mask = (dist < 90.)
out = np.zeros(len(dist), dtype=bool)
out[mask] = FovObj.isOnSiliconList(ra_deg[mask], dec_deg[mask], padding_pix=padding_pix)
return out | def onSiliconCheckList(ra_deg, dec_deg, FovObj, padding_pix=DEFAULT_PADDING) | Check a list of positions. | 2.990099 | 3.071803 | 0.973402 |
ra_sources_deg, dec_sources_deg, mag = parse_file(infile)
n_sources = np.shape(ra_sources_deg)[0]
if n_sources > 500:
logger.warning("Warning: there are {0} sources in your target list, "
"this could take some time".format(n_sources))
k = fields.getKeplerFov(fieldnum... | def K2onSilicon(infile, fieldnum, do_nearSiliconCheck=False) | Checks whether targets are on silicon during a given campaign.
This function will write a csv table called targets_siliconFlag.csv,
which details the silicon status for each target listed in `infile`
(0 = not on silicon, 2 = on silion).
Parameters
----------
infile : str
Path to a csv ... | 2.951969 | 2.866742 | 1.02973 |
import argparse
parser = argparse.ArgumentParser(
description="Run K2onSilicon to find which targets in a "
"list call on active silicon for a given K2 campaign.")
parser.add_argument('csv_file', type=str,
help="Name of input csv file with targets, co... | def K2onSilicon_main(args=None) | Function called when `K2onSilicon` is executed on the command line. | 5.721479 | 5.722826 | 0.999765 |
if template_name not in self.chached_templates:
self.chached_templates[template_name] = self.env.get_template(template_name)
return self.chached_templates[template_name] | def _get_template(self, template_name) | Retrieve the cached version of the template | 2.313631 | 2.072019 | 1.116607 |
blocks = {}
template = self._get_template(template_name)
for block in template.blocks:
blocks[block] = self._render_context(template,
template.blocks[block],
**context)
re... | def render_blocks(self, template_name, **context) | To render all the blocks
:param template_name: The template file name
:param context: **kwargs context to render
:retuns dict: of all the blocks with block_name as key | 2.853631 | 3.410613 | 0.836692 |
template = self._get_template(template_name)
return self._render_context(template,
template.blocks[block],
**context) | def render(self, template_name, block, **context) | TO render a block in the template
:param template_name: the template file name
:param block: the name of the block within {% block $block_name %}
:param context: **kwargs context to render
:returns string: of rendered content | 4.022539 | 5.510888 | 0.729926 |
return u''.join(block(template.new_context(context))) | def _render_context(self, template, block, **context) | Render a block to a string with its context | 12.192492 | 10.850933 | 1.123635 |
self.__init__(aws_access_key_id=app.config.get("SES_AWS_ACCESS_KEY"),
aws_secret_access_key=app.config.get("SES_AWS_SECRET_KEY"),
region=app.config.get("SES_REGION", "us-east-1"),
sender=app.config.get("SES_SENDER", None),
... | def init_app(self, app) | For Flask using the app config | 1.946568 | 1.969062 | 0.988576 |
if not self.sender:
raise AttributeError("Sender email 'sender' or 'source' is not provided")
kwargs["to_addresses"] = to
kwargs["subject"] = subject
kwargs["body"] = body
kwargs["source"] = self._get_sender(self.sender)[0]
kwargs["reply_addresses"] ... | def send(self, to, subject, body, reply_to=None, **kwargs) | Send email via AWS SES.
:returns string: message id
***
Composes an email message based on input data, and then immediately
queues the message for sending.
:type to: list of strings or string
:param to: The To: field(s) of the message.
:type subject: string
... | 3.984972 | 4.541526 | 0.877452 |
mail_data = self.parse_template(template, **context)
subject = mail_data["subject"]
body = mail_data["body"]
del(mail_data["subject"])
del(mail_data["body"])
return self.send(to=to,
subject=subject,
body=body,
... | def send_template(self, template, to, reply_to=None, **context) | Send email from template | 2.244154 | 2.24191 | 1.001001 |
required_blocks = ["subject", "body"]
optional_blocks = ["text_body", "html_body", "return_path", "format"]
if self.template_context:
context = dict(self.template_context.items() + context.items())
blocks = self.template.render_blocks(template, **context)
f... | def parse_template(self, template, **context) | To parse a template and return all the blocks | 3.047432 | 2.905524 | 1.048841 |
if isinstance(sender, tuple):
return "%s <%s>" % sender, sender[0], sender[1]
else:
return sender, sender, sender | def _get_sender(self, sender) | Return a tuple of 3 elements
0: the email signature "Me <email@me.com>"
1: the name "Me"
2: the email address "email@me.com"
if sender is an email string, all 3 elements will be the email address | 4.286282 | 3.546823 | 1.208485 |
if isinstance(x, collections.Sequence):
return list(map(_to_instance, x))
elif isinstance(x, collections.Iterable):
return x
return None if x is None else [_to_instance(x)] | def _typelist(x) | Helper function converting all items of x to instances. | 4.031956 | 3.245331 | 1.242387 |
if not self._write:
raise AttributeError('Command is not writeable')
if self.protocol:
protocol = self.protocol
if self._write.data_type:
data = _dump(self._write.data_type, data)
else:
# TODO We silently ignore possible data
... | def write(self, transport, protocol, *data) | Generates and sends a command message unit.
:param transport: An object implementing the `.Transport` interface.
It is used by the protocol to send the message.
:param protocol: An object implementing the `.Protocol` interface.
:param data: The program data.
:raises Attribu... | 6.44029 | 5.797668 | 1.110842 |
if not self._query:
raise AttributeError('Command is not queryable')
if self.protocol:
protocol = self.protocol
if self._query.data_type:
data = _dump(self._query.data_type, data)
else:
# TODO We silently ignore possible data
... | def query(self, transport, protocol, *data) | Generates and sends a query message unit.
:param transport: An object implementing the `.Transport` interface.
It is used by the protocol to send the message and receive the
response.
:param protocol: An object implementing the `.Protocol` interface.
:param data: The pro... | 4.995116 | 4.683244 | 1.066593 |
cmd = Command(write=cmd)
cmd.write(self._transport, self._protocol, *datas) | def _write(self, cmd, *datas) | Helper function to simplify writing. | 9.712699 | 8.563744 | 1.134165 |
cmd = Command(query=cmd)
return cmd.query(self._transport, self._protocol, *datas) | def _query(self, cmd, *datas) | Helper function to allow method queries. | 10.196567 | 7.693382 | 1.325369 |
def createDAM(dam_name, config):
''' create DAM '''
if 'yahoo' == dam_name:
from analyzerdam.yahooDAM import YahooDAM
dam=YahooDAM()
elif 'google' == dam_name:
from analyzerdam.google import GoogleDAM
dam=GoogleDAM()
elif 'excel' ==... | create DAM | null | null | null | |
def getAll(self, symbol):
values = self.__request(symbol, 'l1c1va2xj1b4j4dyekjm3m4rr5p5p6s7').split(',')
data = {}
data['price'] = values[0]
data['change'] = values[1]
data['volume'] = values[2]
data['avg_daily_volume'] = values[3]
data['stock_exc... | Get all available quote data for the given ticker symbol.
Returns a dictionary. | null | null | null | |
def getQuotes(self, symbol, start, end):
try:
start = str(start).replace('-', '')
end = str(end).replace('-', '')
url = 'http://ichart.yahoo.com/table.csv?s=%s&' % symbol + \
'd=%s&' % str(int(end[4:6]) - 1) + \
'e=%s&' % str(... | Get historical prices for the given ticker symbol.
Date format is 'YYYY-MM-DD'
Returns a nested list. | null | null | null | |
def install():
i = Installation(store=userstore)
i.types = self.types
i.install()
userstore.transact(install) | def installProductOn(self, userstore) | Creates an Installation in this user store for our collection
of powerups, and then install those powerups on the user's
store. | 11.026824 | 8.369246 | 1.317541 |
def uninstall():
#this is probably highly insufficient, but i don't know the
#requirements
i = userstore.findFirst(Installation,
Installation.types == self.types)
i.uninstall()
i.deleteFromStore()
us... | def removeProductFrom(self, userstore) | Uninstall all the powerups this product references and remove
the Installation item from the user's store. Doesn't remove
the actual powerups currently, but /should/ reactivate them if
this product is reinstalled. | 15.981118 | 10.16936 | 1.571497 |
for i in userstore.query(Installation, Installation.types == self.types):
if i.suspended:
unsuspendTabProviders(i)
return
else:
raise RuntimeError("installOrResume called for an"
" installation th... | def installOrResume(self, userstore) | Install this product on a user store. If this product has been
installed on the user store already and the installation is suspended,
it will be resumed. If it exists and is not suspended, an error will be
raised. | 10.879017 | 8.886781 | 1.22418 |
for id in self._items:
yield self.store.getItemByID(int(id)) | def items(self) | Loads the items this Installation refers to. | 12.064756 | 8.132575 | 1.48351 |
items = []
for typeName in self.types:
it = self.store.findOrCreate(namedAny(typeName))
installOn(it, self.store)
items.append(str(it.storeID).decode('ascii'))
self._items = items | def install(self) | Called when installed on the user store. Installs my powerups. | 9.094774 | 8.164028 | 1.114006 |
for item in self.items:
uninstallFrom(item, self.store)
self._items = [] | def uninstall(self) | Called when uninstalled from the user store. Uninstalls all my
powerups. | 11.129291 | 11.422097 | 0.974365 |
types = [qual(powerup).decode('ascii')
for powerup in powerups]
for p in self.store.parent.query(Product):
for t in types:
if t in p.types:
raise ValueError("%s is already included in a Product" % (t,))
return Produc... | def createProduct(self, powerups) | Create a new L{Product} instance which confers the given
powerups.
@type powerups: C{list} of powerup item types
@rtype: L{Product}
@return: The new product instance. | 7.221841 | 7.408527 | 0.974801 |
self.original.createProduct(filter(None, kw.values()))
return u'Created.' | def coerceProduct(self, **kw) | Create a product and return a status string which should be part of a
template.
@param **kw: Fully qualified Python names for powerup types to
associate with the created product. | 22.148235 | 23.431988 | 0.945214 |
api = self.doapi_manager
return api._action(api.request(self.url)["action"]) | def fetch(self) | Fetch & return a new `Action` object representing the action's current
state
:rtype: Action
:raises DOAPIError: if the API endpoint replies with an error | 43.111324 | 32.355106 | 1.332443 |
try:
if self.resource_type == "droplet":
return self.doapi_manager.fetch_droplet(self.resource_id)
elif self.resource_type == "image":
return self.doapi_manager.fetch_image(self.resource_id)
elif self.resource_type == "floating_ip":
... | def fetch_resource(self) | Fetch & return the resource that the action operated on, or `None` if
the resource no longer exists (specifically, if the API returns a 404)
:rtype: `Droplet`, `Image`, `FloatingIP`, or `None`
:raises ValueError: if the action has an unknown ``resource_type``
(This indicates a defic... | 2.308095 | 1.843039 | 1.252331 |
return next(self.doapi_manager.wait_actions([self], wait_interval,
wait_time)) | def wait(self, wait_interval=None, wait_time=None) | Poll the server periodically until the action has either completed or
errored out and return its final state.
If ``wait_time`` is exceeded, a `WaitTimeoutError` (containing the
action's most recently fetched state) is raised.
If a `KeyboardInterrupt` is caught, the action's most recent... | 20.325865 | 15.824804 | 1.284431 |
self.filePath.restat()
mtime = self.filePath.getmtime()
if mtime >= self.lastModified:
return True
else:
return False | def wasModified(self) | Check to see if this module has been modified on disk since the last
time it was cached.
@return: True if it has been modified, False if not. | 5.537463 | 5.625854 | 0.984288 |
if self.wasModified():
self.lastModified = self.filePath.getmtime()
self.fileContents = self.filePath.getContent()
self.hashValue = hashlib.sha1(self.fileContents).hexdigest() | def maybeUpdate(self) | Check this cache entry and update it if any filesystem information has
changed. | 5.55686 | 4.380656 | 1.2685 |
if moduleName not in self.moduleCache:
modulePath = FilePath(
athena.jsDeps.getModuleForName(moduleName)._cache.path)
cachedModule = self.moduleCache[moduleName] = CachedJSModule(
moduleName, modulePath)
else:
cachedModule = se... | def getModule(self, moduleName) | Retrieve a JavaScript module cache from the file path cache.
@returns: Module cache for the named module.
@rtype: L{CachedJSModule} | 6.08821 | 5.087469 | 1.196707 |
if len(segments) != 2:
return NotFound
hashCode, moduleName = segments
cachedModule = self.getModule(moduleName)
return static.Data(
cachedModule.fileContents,
'text/javascript', expires=(60 * 60 * 24 * 365 * 5)), [] | def locateChild(self, ctx, segments) | Retrieve an L{inevow.IResource} to render the contents of the given
module. | 8.724431 | 7.464386 | 1.168808 |
# jsonresolver will evaluate current_app on import if outside of function.
from flask import current_app
pid_value = '10.13039/{0}'.format(doi_grant_code)
try:
_, record = Resolver(pid_type='grant', object_type='rec',
getter=Record.get_record).resolve(pid_value)... | def resolve_grant_endpoint(doi_grant_code) | Resolve the OpenAIRE grant. | 6.199046 | 6.052253 | 1.024254 |
from flask import current_app
url_map.add(Rule(
'/grants/10.13039/<path:doi_grant_code>',
endpoint=resolve_grant_endpoint,
host=current_app.config['OPENAIRE_JSONRESOLVER_GRANTS_HOST'])) | def jsonresolver_loader(url_map) | Resolve the OpenAIRE grant. | 6.848533 | 4.814481 | 1.422486 |
if not isinstance(data, dict):
return False
if key:
if key in data:
return True
return False
if 'resultCode' in data.keys():
# OpenBus
return True if data.get('resultCode', -1) == 0 else False
elif 'code' in data.keys():
# Parking
... | def check_result(data, key='') | Check the result of an API response.
Ideally, this should be done by checking that the value of the ``resultCode``
attribute is 0, but there are endpoints that simply do not follow this rule.
Args:
data (dict): Response obtained from the API endpoint.
key (string): Key to check for existen... | 3.072897 | 3.310483 | 0.928232 |
# Overflow
if hour < 0 or hour > 23: hour = 0
if minute < 0 or minute > 60: minute = 0
return '%d-%02d-%02dT%02d:%02d:00' % (year, month, day, hour, minute) | def datetime_string(day, month, year, hour, minute) | Build a date string using the provided day, month, year numbers.
Automatically adds a leading zero to ``day`` and ``month`` if they only have
one digit.
Args:
day (int): Day number.
month(int): Month number.
year(int): Year number.
hour (int): Hour of the day in 24h format.... | 2.329686 | 2.725453 | 0.854789 |
if not isinstance(ints, list):
return six.u(str(ints))
return '|'.join(six.u(str(l)) for l in ints) | def ints_to_string(ints) | Convert a list of integers to a *|* separated string.
Args:
ints (list[int]|int): List of integer items to convert or single
integer to convert.
Returns:
str: Formatted string | 4.489361 | 5.505376 | 0.81545 |
if key not in data:
return None
if isinstance(data[key], list):
return data[key]
else:
return [data[key],] | def response_list(data, key) | Obtain the relevant response data in a list.
If the response does not already contain the result in a list, a new one
will be created to ease iteration in the parser methods.
Args:
data (dict): API response.
key (str): Attribute of the response that contains the result values.
Returns... | 2.892631 | 3.416125 | 0.846758 |
if self._base_uri is None:
if self._resolver is not None:
self._base_uri = self.resolver.resolution_scope
else:
self._base_uri = 'http://pudo.github.io/jsongraph'
return URIRef(self._base_uri) | def base_uri(self) | Resolution base for JSON schema. Also used as the default
graph ID for RDF. | 4.798384 | 4.177767 | 1.148552 |
if self._resolver is None:
self._resolver = RefResolver(self.base_uri, {})
# if self.base_uri not in self._resolver.store:
# self._resolver.store[self.base_uri] = self.config
return self._resolver | def resolver(self) | Resolver for JSON Schema references. This can be based around a
file or HTTP-based resolution base URI. | 3.619501 | 3.087494 | 1.17231 |
if self._store is None:
config = self.config.get('store', {})
if 'query' in config and 'update' in config:
self._store = sparql_store(config.get('query'),
config.get('update'))
else:
self._sto... | def store(self) | Backend storage for RDF data. Either an in-memory store, or an
external triple store controlled via SPARQL. | 4.782766 | 3.666291 | 1.304524 |
if not hasattr(self, '_graph') or self._graph is None:
self._graph = ConjunctiveGraph(store=self.store,
identifier=self.base_uri)
return self._graph | def graph(self) | A conjunctive graph of all statements in the current instance. | 3.850487 | 2.810196 | 1.370184 |
if 'buffered' not in self.config:
return not isinstance(self.store, (Memory, IOMemory))
return self.config.get('buffered') | def buffered(self) | Whether write operations should be buffered, i.e. run against a
local graph before being stored to the main data store. | 8.457171 | 7.705589 | 1.097537 |
return Context(self, identifier=identifier, meta=meta) | def context(self, identifier=None, meta=None) | Get or create a context, with the given identifier and/or
provenance meta data. A context can be used to add, update or delete
objects in the store. | 5.519969 | 5.979293 | 0.923181 |
# TODO: do we want to constrain the valid alias names.
if isinstance(uri, dict):
id = uri.get('id', alias)
self.resolver.store[id] = uri
uri = id
self.aliases[alias] = uri | def register(self, alias, uri) | Register a new schema URI under a given name. | 6.805606 | 6.586067 | 1.033334 |
if alias in self.aliases.keys():
return self.aliases[alias]
if alias in self.aliases.values():
return alias
raise GraphException('No such schema: %r' % alias) | def get_uri(self, alias) | Get the URI for a given alias. A registered URI will return itself,
otherwise ``None`` is returned. | 4.163215 | 4.786624 | 0.86976 |
if isinstance(alias, dict):
return alias
uri = self.get_uri(alias)
if uri is None:
raise GraphException('No such schema: %r' % alias)
uri, schema = self.resolver.resolve(uri)
return schema | def get_schema(self, alias) | Actually resolve the schema for the given alias/URI. | 4.270342 | 3.53688 | 1.207375 |
context = URIRef(context).n3() if context is not None else '?g'
query = % (context, context)
self.parent.graph.update(query) | def clear(self, context=None) | Delete all data from the graph. | 13.994222 | 11.361096 | 1.231767 |
if text is None:
return False
text = text.lower()
return text.startswith('http://') or text.startswith('https://') or \
text.startswith('urn:') or text.startswith('file://') | def is_url(text) | Check if the given text looks like a URL. | 2.720811 | 2.579235 | 1.054891 |
url_ = url.parse(text).sanitize().deuserinfo().canonical()
return URIRef(url_.punycode().unicode()) | def safe_uriref(text) | Escape a URL properly. | 31.33666 | 30.703693 | 1.020615 |
stats_dict = {}
with os.popen('qstat -xf ' + str(job_id)) as f:
try:
line = f.readline().strip()
while line:
if line.startswith('Job Id:'):
stats_dict['job_id'] = line.split(':')[1].split('.')[0].strip()
elif line.startswit... | def job_stats_enhanced(job_id) | Get full job and step stats for job_id | 1.974821 | 1.981665 | 0.996546 |
out = self.origin.copy()
if cartesian is False:
out = self.getRaDecs(out)
return out | def getOrigin(self, cartesian=False) | Return the ra/decs of the channel corners if the S/C
is pointed at the origin (ra,dec = 0,0)
Inputs:
cartesian (bool) If True, return each channel corner
as a unit vector
Returns:
A 2d numpy array. Each row represents a channel corner
The columns a... | 7.934204 | 8.550024 | 0.927974 |
# Roll FOV
Rrotate = r.rotateInXMat(roll_deg) # Roll
# Slew from ra/dec of zero
Ra = r.rightAscensionRotationMatrix(ra_deg)
Rd = r.declinationRotationMatrix(dec_deg)
Rslew = np.dot(Ra, Rd)
R = np.dot(Rslew, Rrotate)
slew = self.origin*1
... | def computePointing(self, ra_deg, dec_deg, roll_deg, cartesian=False) | Compute a pointing model without changing the internal object pointing | 5.754889 | 5.805597 | 0.991266 |
raDecOut = np.empty( (len(mods), 5))
raDecOut[:,0:3] = mods[:,0:3]
for i, row in enumerate(mods):
raDecOut[i, 3:5] = r.raDecFromVec(row[3:6])
return raDecOut | def getRaDecs(self, mods) | Internal function converting cartesian coords to
ra dec | 4.037507 | 3.934717 | 1.026124 |
ch, col, row = self.getChannelColRowList(ra_deg, dec_deg)
out = np.zeros(len(ch), dtype=bool)
for channel in set(ch):
mask = (ch == channel)
if channel in self.brokenChannels:
continue
if channel > 84:
continue
... | def isOnSiliconList(self, ra_deg, dec_deg, padding_pix=DEFAULT_PADDING) | similar to isOnSilicon() but takes lists as input | 4.629706 | 4.453213 | 1.039633 |
try:
ch = self.pickAChannelList(ra, dec)
except ValueError:
logger.warning("WARN: %.7f %.7f not on any channel" % (ra, dec))
return (0, 0, 0)
col = np.zeros(len(ch))
row = np.zeros(len(ch))
for channel in set(ch):
mask = (... | def getChannelColRowList(self, ra, dec, wantZeroOffset=False,
allowIllegalReturnValues=True) | similar to getChannelColRow() but takes lists as input | 3.390338 | 3.34881 | 1.012401 |
try:
from astropy.coordinates import SkyCoord
from astropy import units as u
except ImportError:
raise ImportError("AstroPy needs to be installed to use this feature.")
cRa = self.currentRaDec[:, 3] # Ra of each channel corner
cDec = self.cur... | def pickAChannelList(self, ra_deg, dec_deg) | Similar to pickAChannel() but takes lists as input.
This will require AstroPy to be installed. | 3.213917 | 2.956483 | 1.087075 |
out = np.ones(len(col), dtype=bool)
col_arr = np.array(col)
row_arr = np.array(row)
mask = np.bitwise_or(col_arr < 12. - padding, col_arr > 1111 + padding)
out[mask] = False
mask = np.bitwise_or(row_arr < 20. - padding, row_arr > 1043 + padding)
out[mask]... | def colRowIsOnSciencePixelList(self, col, row, padding=DEFAULT_PADDING) | similar to colRowIsOnSciencePixelList() but takes lists as input | 2.716195 | 2.581704 | 1.052094 |
ch, col, row = self.getChannelColRow(ra_deg, dec_deg)
# Modules 3 and 7 are no longer operational
if ch in self.brokenChannels:
return False
# K2fov encodes the Fine Guidance Sensors (FGS) as
# "channel" numbers 85-88; they are not science CCDs.
if ch... | def isOnSilicon(self, ra_deg, dec_deg, padding_pix=DEFAULT_PADDING) | Returns True if the given location is observable with a science CCD.
Parameters
----------
ra_deg : float
Right Ascension (J2000) in decimal degrees.
dec_deg : float
Declination (J2000) in decimal degrees.
padding : float
Objects <= this ma... | 12.531158 | 10.925667 | 1.146947 |
try:
ch = self.pickAChannel(ra, dec)
except ValueError:
logger.warning("WARN: %.7f %.7f not on any channel" % (ra, dec))
return (0, 0, 0)
col, row = self.getColRowWithinChannel(ra, dec, ch, wantZeroOffset,
... | def getChannelColRow(self, ra, dec, wantZeroOffset=False,
allowIllegalReturnValues=True) | Returns (channel, column, row) given an (ra, dec) coordinate.
Returns (0, 0, 0) or a ValueError if the coordinate is not on silicon. | 3.499987 | 3.211354 | 1.089879 |
# Could improve speed by doing this in the projection plane
# instead of sky coords
cRa = self.currentRaDec[:, 3] # Ra of each channel corner
cDec = self.currentRaDec[:, 4] # dec of each channel corner
dist = cRa * 0
for i in range(len(dist)):
dist... | def pickAChannel(self, ra_deg, dec_deg) | Returns the channel number closest to a given (ra, dec) coordinate. | 5.944446 | 5.901142 | 1.007338 |
# How close is a given ra/dec to the origin of a KeplerModule?
x, y = self.defaultMap.skyToPix(ra, dec)
kepModule = self.getChannelAsPolygon(ch)
r = np.array([x[0],y[0]]) - kepModule.polygon[0, :]
v1 = kepModule.polygon[1, :] - kepModule.polygon[0, :]
v3 = kepMo... | def getColRowWithinChannel(self, ra, dec, ch, wantZeroOffset=False,
allowIllegalReturnValues=True) | Returns (col, row) given a (ra, dec) coordinate and channel number. | 5.318948 | 5.323401 | 0.999164 |
if col < 12. - padding or col > 1111 + padding:
return False
if row < 20 - padding or row > 1043 + padding:
return False
return True | def colRowIsOnSciencePixel(self, col, row, padding=DEFAULT_PADDING) | Is col row on a science pixel?
Ranges taken from Fig 25 or Instrument Handbook (p50)
Padding allows for the fact that distortion means the
results from getColRowWithinChannel can be off by a bit.
Setting padding > 0 means that objects that are computed
to lie a small amount off... | 5.514155 | 6.143978 | 0.897489 |
if col < 12. - padding or col > 547 + padding:
return False
if row < 0 - padding or row > 527 + padding :
return False
return True | def colRowIsOnFgsPixel(self, col, row, padding=-50) | Is col row on a science pixel?
#See Kepler Flight Segment User's Manual (SP0039-702) \S 5.4 (p88)
Inputs:
col, row (floats or ints)
padding If padding <0, pixel must be on silicon and this many
pixels away from the edge of the CCD to return True
Returns:
... | 6.402087 | 7.094092 | 0.902453 |
polyList = []
for ch in self.origin[:, 2]:
poly = self.getChannelAsPolygon(ch, maptype)
polyList.append(poly)
return polyList | def getAllChannelsAsPolygons(self, maptype=None) | Return slew the telescope and return the corners of the modules
as Polygon objects.
If a projection is supplied, the ras and
decs are mapped onto x, y using that projection | 4.648093 | 5.724677 | 0.81194 |
if maptype is None:
maptype=self.defaultMap
radec = self.currentRaDec
for ch in radec[:,2][::4]:
idx = np.where(radec[:,2].astype(np.int) == ch)[0]
idx = np.append(idx, idx[0]) #% points to draw a box
c = colour
if ch in s... | def plotPointing(self, maptype=None, colour='b', mod3='r', showOuts=True, **kwargs) | Plot the FOV | 4.685972 | 4.785037 | 0.979297 |
if maptype is None:
maptype=self.defaultMap
xarr = []
yarr = []
radec = self.currentRaDec
for ch in [20,4,11,28,32, 71,68, 84, 75, 60, 56, 15 ]:
idx = np.where(radec[:,2].astype(np.int) == ch)[0]
idx = idx[0] #Take on the first on... | def plotOutline(self, maptype=None, colour='#AAAAAA', **kwargs) | Plot an outline of the FOV. | 3.888005 | 3.846395 | 1.010818 |
if maptype is None:
maptype=self.defaultMap
#Plot direction of spacecraft +y axis. The subtraction of
#90 degrees accounts for the different defintions of where
#zero roll is.
yAngle_deg = getSpacecraftRollAngleFromFovAngle(self.roll0_deg)
yAngle_deg... | def plotSpacecraftYAxis(self, maptype=None) | Plot a line pointing in the direction of the spacecraft
y-axis (i.e normal to the solar panel | 6.148968 | 6.119825 | 1.004762 |
if maptype is None:
maptype = self.defaultMap
polyList = self.getAllChannelsAsPolygons(maptype)
for p in polyList:
p.identifyModule(modout=modout) | def plotChIds(self, maptype=None, modout=False) | Print the channel numbers on the plotting display
Note:
---------
This method will behave poorly if you are plotting in
mixed projections. Because the channel vertex polygons
are already projected using self.defaultMap, applying
this function when plotting in a different... | 7.408593 | 6.325103 | 1.1713 |
point = np.array([xp, yp]).transpose()
polygon = self.polygon
numVert, numDim = polygon.shape
#Subtract each point from the previous one.
polyVec = np.roll(polygon, -1, 0) - polygon
#Get the vector from each vertex to the given point
pointVec = point - ... | def isPointInside(self, xp, yp) | Is the given point inside the polygon?
Input:
------------
xp, yp
(floats) Coordinates of point in same units that
array vertices are specified when object created.
Returns:
-----------
**True** / **False** | 4.167058 | 4.176059 | 0.997845 |
ax = mp.gca()
shape = matplotlib.patches.Polygon(self.polygon, **kwargs)
ax.add_artist(shape) | def draw(self, **kwargs) | Draw the polygon
Optional Inputs:
------------
All optional inputs are passed to ``matplotlib.patches.Polygon``
Notes:
---------
Does not accept maptype as an argument. | 6.077447 | 5.591001 | 1.087005 |
x,y = np.mean(self.polygon, 0)
if modout:
modout = modOutFromChannel(self.channel)
mp.text(x, y, "%i-%i" %(modout[0], modout[1]), fontsize=8, \
ha="center", clip_on=True)
else:
mp.text(x,y, "%i" %(self.channel), fontsize=8, \
... | def identifyModule(self, modout=False) | Write the name of a channel/modout on a plot
Optional Inputs:
-----------
modout
(boolean). If True, write module and output. Otherwise
write channel number
Returns:
------------
**None**
Output:
-----------
Channel numbe... | 4.344625 | 4.040656 | 1.075227 |
response = response.decode(self.encoding)
if header:
header = "".join((self.resp_prefix, header, self.resp_header_sep))
if not response.startswith(header):
raise IEC60488.ParsingError('Response header mismatch')
response = response[len(header)... | def parse_response(self, response, header=None) | Parses the response message.
The following graph shows the structure of response messages.
::
+----------+
+--+ data sep +<-+
| +---------... | 4.945512 | 4.389605 | 1.126642 |
logger.debug('IEC60488 trigger')
with transport:
try:
transport.trigger()
except AttributeError:
trigger_msg = self.create_message('*TRG')
transport.write(trigger_msg) | def trigger(self, transport) | Triggers the transport. | 9.520576 | 9.863577 | 0.965226 |
logger.debug('IEC60488 clear')
with transport:
try:
transport.clear()
except AttributeError:
clear_msg = self.create_message('*CLS')
transport.write(clear_msg) | def clear(self, transport) | Issues a device clear command. | 9.604292 | 8.892337 | 1.080064 |
message = self.create_message(header, *data)
logger.debug('SignalRecovery query bytes: %r', message)
with transport:
transport.write(message)
response = transport.read_exactly(num_bytes)
logger.debug('SignalRecovery response: %r', response)
... | def query_bytes(self, transport, num_bytes, header, *data) | Queries for binary data
:param transport: A transport object.
:param num_bytes: The exact number of data bytes expected.
:param header: The message header.
:param data: Optional data.
:returns: The raw unparsed data bytearray. | 5.59286 | 5.696097 | 0.981876 |
#Ensure v is a normal vector
v /= np.linalg.norm(v)
ra_deg=0 #otherwise not in namespace0
dec_rad = np.arcsin(v[2])
s = np.hypot(v[0], v[1])
if s ==0:
ra_rad = 0
else:
ra_rad = np.arcsin(v[1]/s)
ra_deg = np.degrees(ra_rad)
if v[0] >= 0:
i... | def raDecFromVec(v) | Taken from
http://www.math.montana.edu/frankw/ccp/multiworld/multipleIVP/spherical/learn.htm
Search for "convert from Cartestion to spherical coordinates"
Adapted because I'm dealing with declination which is defined
with 90degrees at zenith | 2.93893 | 2.841435 | 1.034312 |
ct = np.cos(np.radians(theta_deg))
st = np.sin(np.radians(theta_deg))
term1 = v1*ct
term2 = np.cross(w, v1) * st
term3 = np.dot(w, v1)
term3 = w * term3 * (1-ct)
return term1 + term2 + term3 | def rotateAroundVector(v1, w, theta_deg) | Rotate vector v1 by an angle theta around w
Taken from https://en.wikipedia.org/wiki/Axis%E2%80%93angle_representation
(see Section "Rotating a vector")
Notes:
Rotating the x axis 90 degrees about the y axis gives -z
Rotating the x axis 90 degrees about the z axis gives +y | 2.72061 | 2.847513 | 0.955434 |
axis = np.array([0,-1,0])
return rotateAroundVector(v1, axis, theta_deg) | def rotateInDeclination(v1, theta_deg) | Rotation is chosen so a rotation of 90 degrees from zenith
ends up at ra=0, dec=0 | 3.970711 | 4.20863 | 0.943469 |
ct = np.cos(np.radians(theta_deg))
st = np.sin(np.radians(theta_deg))
mat = np.zeros((3,3))
mat[0,0] = ct
mat[0,2] = -st
mat[1,1] = 1
mat[2,0] = st
mat[2,2] = ct
return mat | def declinationRotationMatrix(theta_deg) | Construct the rotation matrix for a rotation of the declination
coords (i.e around the axis of ra=90, dec=0)
Taken from Section 3.3 of Arfken and Weber (Eqn 3.91)
Modfied the signs of the sines so that a rotation of the zenith
vector by 90 degrees ends up at ra, dec = 0,0 | 1.658904 | 1.710161 | 0.970028 |
sweep_modes = ['UP', 'DOWN', 'PAUSE', 'ZERO', 'LIMIT']
sweep_speed = ['SLOW', 'FAST', None]
if not mode in sweep_modes:
raise ValueError('Invalid sweep mode.')
if not speed in sweep_speed:
raise ValueError('Invalid sweep speed.')
if speed is None:... | def sweep(self, mode, speed=None) | Starts the output current sweep.
:param mode: The sweep mode. Valid entries are `'UP'`, `'DOWN'`,
`'PAUSE'`or `'ZERO'`. If in shim mode, `'LIMIT'` is valid as well.
:param speed: The sweeping speed. Valid entries are `'FAST'`, `'SLOW'`
or `None`. | 2.63669 | 2.155388 | 1.223302 |
if not args:
args = ()
if not kwargs:
kwargs = {}
self.microservice.get_io_loop().add_callback(func, *args, **kwargs) | def run_on_main_thread(self, func, args=None, kwargs=None) | Runs the ``func`` callable on the main thread, by using the provided microservice
instance's IOLoop.
:param func: callable to run on the main thread
:param args: tuple or list with the positional arguments.
:param kwargs: dict with the keyword arguments.
:return: | 3.516211 | 2.813763 | 1.249647 |
ct = np.cos(np.radians(theta_deg))
st = np.sin(np.radians(theta_deg))
# Ensure vector has normal length
vec /= np.linalg.norm(vec)
assert( np.all( np.isfinite(vec)))
# compute the three terms
term1 = ct * np.eye(3)
ucross = np.zeros( (3,3))
ucross[0] = [0, -vec[2], vec[1]]
... | def rotateAboutVectorMatrix(vec, theta_deg) | Construct the matrix that rotates vector a about
vector vec by an angle of theta_deg degrees
Taken from
http://en.wikipedia.org/wiki/Rotation_matrix#Rotation_matrix_from_axis_and_angle
Input:
theta_deg (float) Angle through which vectors should be
rotated in degrees
Returns:... | 2.395213 | 2.558228 | 0.936278 |
ct = np.cos( np.radians(theta_deg))
st = np.sin( np.radians(theta_deg))
rMat = np.array([ [ ct, -st, 0],
[ st, ct, 0],
[ 0, 0, 1],
])
return rMat | def rotateInZMat(theta_deg) | Rotate a vector theta degrees around the z-axis
Equivalent to yaw left
Rotates the vector in the sense that the x-axis is rotated
towards the y-axis. If looking along the z-axis (which is
not the way you usually look at it), the vector rotates
clockwise.
If sitting on the vector [1,0,0], the ... | 2.474365 | 2.745506 | 0.901242 |
if tweet['retweeted']:
text = 'RT {user}: {text}'.format(
user=TWITTER_USERNAME_URL.format(screen_name=tweet['user']['screen_name']),
text=tweet['text'])
else:
text = tweet['text']
for hashtag in tweet['entities']['hashtags']:
text = text.replace(
... | def urlize_tweet(tweet) | Turn #hashtag and @username in a text to Twitter hyperlinks,
similar to the ``urlize()`` function in Django.
Replace shortened URLs with long URLs in the twitter status,
and add the "RT" flag. Should be used before urlize_tweet | 1.612596 | 1.610124 | 1.001536 |
def getReadSession(self):
''' return scopted session '''
if self.ReadSession is None:
self.ReadSession=scoped_session(sessionmaker(bind=self.engine))
return self.ReadSession | return scopted session | null | null | null | |
def getWriteSession(self):
''' return unscope session, TODO, make it clear '''
if self.WriteSession is None:
self.WriteSession=sessionmaker(bind=self.engine)
self.writeSession=self.WriteSession()
return self.writeSession | return unscope session, TODO, make it clear | null | null | null | |
def readTupleQuotes(self, symbol, start, end):
''' read quotes as tuple '''
if end is None:
end=sys.maxint
session=self.getReadSession()()
try:
rows=session.query(Quote).filter(and_(Quote.symbol == symbol,
... | read quotes as tuple | null | null | null | |
def readBatchTupleQuotes(self, symbols, start, end):
'''
read batch quotes as tuple to save memory
'''
if end is None:
end=sys.maxint
ret={}
session=self.getReadSession()()
try:
symbolChunks=splitListEqually(symbols, 100)
... | read batch quotes as tuple to save memory | null | null | null | |
def read_tuple_ticks(self, symbol, start, end):
''' read ticks as tuple '''
if end is None:
end=sys.maxint
session=self.getReadSession()()
try:
rows=session.query(Tick).filter(and_(Tick.symbol == symbol,
... | read ticks as tuple | null | null | null | |
def write_quotes(self, quotes):
''' write quotes '''
if self.first:
Base.metadata.create_all(self.engine, checkfirst=True)
self.first=False
session=self.getWriteSession()
session.add_all([self.__quoteToSql(quote) for quote in quotes]) | write quotes | null | null | null | |
def write_ticks(self, ticks):
''' write ticks '''
if self.first:
Base.metadata.create_all(self.engine, checkfirst=True)
self.first=False
session=self.getWriteSession()
session.add_all([self.__tickToSql(tick) for tick in ticks]) | write ticks | null | null | null | |
def write_fundamental(self, keyTimeValueDict):
''' write fundamental '''
if self.first:
Base.metadata.create_all(self.__getEngine(), checkfirst=True)
self.first=False
sqls=self._fundamentalToSqls(keyTimeValueDict)
session=self.Session()
try:
... | write fundamental | null | null | null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.