repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 75 19.8k | code_tokens listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1
value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
OSSOS/MOP | src/ossos/core/ossos/astrom.py | AstromParser.parse | def parse(self, filename):
"""
Parses a file into an AstromData structure.
Args:
filename: str
The name of the file whose contents will be parsed.
Returns:
data: AstromData
The file contents extracted into a data structure for programmatic
access.
"""
filehandle = storage.open_vos_or_local(filename, "rb")
assert filehandle is not None, "Failed to open file {} ".format(filename)
filestr = filehandle.read()
filehandle.close()
assert filestr is not None, "File contents are None"
observations = self._parse_observation_list(filestr)
self._parse_observation_headers(filestr, observations)
sys_header = self._parse_system_header(filestr)
sources = self._parse_source_data(filestr, observations)
return AstromData(observations, sys_header, sources, discovery_only=self.discovery_only) | python | def parse(self, filename):
"""
Parses a file into an AstromData structure.
Args:
filename: str
The name of the file whose contents will be parsed.
Returns:
data: AstromData
The file contents extracted into a data structure for programmatic
access.
"""
filehandle = storage.open_vos_or_local(filename, "rb")
assert filehandle is not None, "Failed to open file {} ".format(filename)
filestr = filehandle.read()
filehandle.close()
assert filestr is not None, "File contents are None"
observations = self._parse_observation_list(filestr)
self._parse_observation_headers(filestr, observations)
sys_header = self._parse_system_header(filestr)
sources = self._parse_source_data(filestr, observations)
return AstromData(observations, sys_header, sources, discovery_only=self.discovery_only) | [
"def",
"parse",
"(",
"self",
",",
"filename",
")",
":",
"filehandle",
"=",
"storage",
".",
"open_vos_or_local",
"(",
"filename",
",",
"\"rb\"",
")",
"assert",
"filehandle",
"is",
"not",
"None",
",",
"\"Failed to open file {} \"",
".",
"format",
"(",
"filename"... | Parses a file into an AstromData structure.
Args:
filename: str
The name of the file whose contents will be parsed.
Returns:
data: AstromData
The file contents extracted into a data structure for programmatic
access. | [
"Parses",
"a",
"file",
"into",
"an",
"AstromData",
"structure",
"."
] | 94f91d32ad5ec081d5a1ebd67604a838003465af | https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/astrom.py#L209-L237 | train | 47,800 |
OSSOS/MOP | src/ossos/core/ossos/astrom.py | BaseAstromWriter.write_headers | def write_headers(self, observations, sys_header):
"""
Writes the header part of the astrom file so that only the source
data has to be filled in.
"""
if self._header_written:
raise AstromFormatError("Astrom file already has headers.")
self._write_observation_list(observations)
self._write_observation_headers(observations)
self._write_sys_header(sys_header)
self._write_source_header()
self._header_written = True | python | def write_headers(self, observations, sys_header):
"""
Writes the header part of the astrom file so that only the source
data has to be filled in.
"""
if self._header_written:
raise AstromFormatError("Astrom file already has headers.")
self._write_observation_list(observations)
self._write_observation_headers(observations)
self._write_sys_header(sys_header)
self._write_source_header()
self._header_written = True | [
"def",
"write_headers",
"(",
"self",
",",
"observations",
",",
"sys_header",
")",
":",
"if",
"self",
".",
"_header_written",
":",
"raise",
"AstromFormatError",
"(",
"\"Astrom file already has headers.\"",
")",
"self",
".",
"_write_observation_list",
"(",
"observations... | Writes the header part of the astrom file so that only the source
data has to be filled in. | [
"Writes",
"the",
"header",
"part",
"of",
"the",
"astrom",
"file",
"so",
"that",
"only",
"the",
"source",
"data",
"has",
"to",
"be",
"filled",
"in",
"."
] | 94f91d32ad5ec081d5a1ebd67604a838003465af | https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/astrom.py#L402-L415 | train | 47,801 |
OSSOS/MOP | src/ossos/core/ossos/astrom.py | BulkAstromWriter.write_astrom_data | def write_astrom_data(self, astrom_data):
"""
Writes a full AstromData structure at once.
"""
self.write_headers(astrom_data.observations, astrom_data.sys_header)
self._write_source_data(astrom_data.sources) | python | def write_astrom_data(self, astrom_data):
"""
Writes a full AstromData structure at once.
"""
self.write_headers(astrom_data.observations, astrom_data.sys_header)
self._write_source_data(astrom_data.sources) | [
"def",
"write_astrom_data",
"(",
"self",
",",
"astrom_data",
")",
":",
"self",
".",
"write_headers",
"(",
"astrom_data",
".",
"observations",
",",
"astrom_data",
".",
"sys_header",
")",
"self",
".",
"_write_source_data",
"(",
"astrom_data",
".",
"sources",
")"
] | Writes a full AstromData structure at once. | [
"Writes",
"a",
"full",
"AstromData",
"structure",
"at",
"once",
"."
] | 94f91d32ad5ec081d5a1ebd67604a838003465af | https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/astrom.py#L461-L466 | train | 47,802 |
OSSOS/MOP | src/ossos/core/ossos/astrom.py | SourceReading.reference_source_point | def reference_source_point(self):
"""
The location of the source in the reference image, in terms of the
current image coordinates.
"""
xref = isinstance(self.xref, Quantity) and self.xref.value or self.xref
yref = isinstance(self.yref, Quantity) and self.yref.value or self.yref
return xref + self.x_ref_offset, yref + self.y_ref_offset | python | def reference_source_point(self):
"""
The location of the source in the reference image, in terms of the
current image coordinates.
"""
xref = isinstance(self.xref, Quantity) and self.xref.value or self.xref
yref = isinstance(self.yref, Quantity) and self.yref.value or self.yref
return xref + self.x_ref_offset, yref + self.y_ref_offset | [
"def",
"reference_source_point",
"(",
"self",
")",
":",
"xref",
"=",
"isinstance",
"(",
"self",
".",
"xref",
",",
"Quantity",
")",
"and",
"self",
".",
"xref",
".",
"value",
"or",
"self",
".",
"xref",
"yref",
"=",
"isinstance",
"(",
"self",
".",
"yref",... | The location of the source in the reference image, in terms of the
current image coordinates. | [
"The",
"location",
"of",
"the",
"source",
"in",
"the",
"reference",
"image",
"in",
"terms",
"of",
"the",
"current",
"image",
"coordinates",
"."
] | 94f91d32ad5ec081d5a1ebd67604a838003465af | https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/astrom.py#L871-L879 | train | 47,803 |
OSSOS/MOP | src/ossos/core/ossos/astrom.py | SourceReading.get_coordinate_offset | def get_coordinate_offset(self, other_reading):
"""
Calculates the offsets between readings' coordinate systems.
Args:
other_reading: ossos.astrom.SourceReading
The reading to compare coordinate systems with.
Returns:
(offset_x, offset_y):
The x and y offsets between this reading and the other reading's
coordinate systems.
"""
my_x, my_y = self.reference_source_point
other_x, other_y = other_reading.reference_source_point
return my_x - other_x, my_y - other_y | python | def get_coordinate_offset(self, other_reading):
"""
Calculates the offsets between readings' coordinate systems.
Args:
other_reading: ossos.astrom.SourceReading
The reading to compare coordinate systems with.
Returns:
(offset_x, offset_y):
The x and y offsets between this reading and the other reading's
coordinate systems.
"""
my_x, my_y = self.reference_source_point
other_x, other_y = other_reading.reference_source_point
return my_x - other_x, my_y - other_y | [
"def",
"get_coordinate_offset",
"(",
"self",
",",
"other_reading",
")",
":",
"my_x",
",",
"my_y",
"=",
"self",
".",
"reference_source_point",
"other_x",
",",
"other_y",
"=",
"other_reading",
".",
"reference_source_point",
"return",
"my_x",
"-",
"other_x",
",",
"... | Calculates the offsets between readings' coordinate systems.
Args:
other_reading: ossos.astrom.SourceReading
The reading to compare coordinate systems with.
Returns:
(offset_x, offset_y):
The x and y offsets between this reading and the other reading's
coordinate systems. | [
"Calculates",
"the",
"offsets",
"between",
"readings",
"coordinate",
"systems",
"."
] | 94f91d32ad5ec081d5a1ebd67604a838003465af | https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/astrom.py#L894-L909 | train | 47,804 |
OSSOS/MOP | src/ossos/core/ossos/astrom.py | Observation.from_source_reference | def from_source_reference(expnum, ccd, x, y):
"""
Given the location of a source in the image, create an Observation.
"""
image_uri = storage.dbimages_uri(expnum=expnum,
ccd=None,
version='p',
ext='.fits',
subdir=None)
logger.debug('Trying to access {}'.format(image_uri))
if not storage.exists(image_uri, force=False):
logger.warning('Image not in dbimages? Trying subdir.')
image_uri = storage.dbimages_uri(expnum=expnum,
ccd=ccd,
version='p')
if not storage.exists(image_uri, force=False):
logger.warning("Image doesn't exist in ccd subdir. %s" % image_uri)
return None
if x == -9999 or y == -9999:
logger.warning("Skipping {} as x/y not resolved.".format(image_uri))
return None
mopheader_uri = storage.dbimages_uri(expnum=expnum,
ccd=ccd,
version='p',
ext='.mopheader')
if not storage.exists(mopheader_uri, force=False):
# ELEVATE! we need to know to go off and reprocess/include this image.
logger.critical('Image exists but processing incomplete. Mopheader missing. {}'.format(image_uri))
return None
# Build astrom.Observation
observation = Observation(expnum=str(expnum),
ftype='p',
ccdnum=str(ccd),
fk="")
# JJK commented this out, I think the following line is not true?
# observation.rawname = os.path.splitext(os.path.basename(image_uri))[0]+str(ccd).zfill(2)
return observation | python | def from_source_reference(expnum, ccd, x, y):
"""
Given the location of a source in the image, create an Observation.
"""
image_uri = storage.dbimages_uri(expnum=expnum,
ccd=None,
version='p',
ext='.fits',
subdir=None)
logger.debug('Trying to access {}'.format(image_uri))
if not storage.exists(image_uri, force=False):
logger.warning('Image not in dbimages? Trying subdir.')
image_uri = storage.dbimages_uri(expnum=expnum,
ccd=ccd,
version='p')
if not storage.exists(image_uri, force=False):
logger.warning("Image doesn't exist in ccd subdir. %s" % image_uri)
return None
if x == -9999 or y == -9999:
logger.warning("Skipping {} as x/y not resolved.".format(image_uri))
return None
mopheader_uri = storage.dbimages_uri(expnum=expnum,
ccd=ccd,
version='p',
ext='.mopheader')
if not storage.exists(mopheader_uri, force=False):
# ELEVATE! we need to know to go off and reprocess/include this image.
logger.critical('Image exists but processing incomplete. Mopheader missing. {}'.format(image_uri))
return None
# Build astrom.Observation
observation = Observation(expnum=str(expnum),
ftype='p',
ccdnum=str(ccd),
fk="")
# JJK commented this out, I think the following line is not true?
# observation.rawname = os.path.splitext(os.path.basename(image_uri))[0]+str(ccd).zfill(2)
return observation | [
"def",
"from_source_reference",
"(",
"expnum",
",",
"ccd",
",",
"x",
",",
"y",
")",
":",
"image_uri",
"=",
"storage",
".",
"dbimages_uri",
"(",
"expnum",
"=",
"expnum",
",",
"ccd",
"=",
"None",
",",
"version",
"=",
"'p'",
",",
"ext",
"=",
"'.fits'",
... | Given the location of a source in the image, create an Observation. | [
"Given",
"the",
"location",
"of",
"a",
"source",
"in",
"the",
"image",
"create",
"an",
"Observation",
"."
] | 94f91d32ad5ec081d5a1ebd67604a838003465af | https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/astrom.py#L990-L1034 | train | 47,805 |
JohnVinyard/zounds | zounds/learn/wgan.py | WassersteinGanTrainer._gradient_penalty | def _gradient_penalty(self, real_samples, fake_samples, kwargs):
"""
Compute the norm of the gradients for each sample in a batch, and
penalize anything on either side of unit norm
"""
import torch
from torch.autograd import Variable, grad
real_samples = real_samples.view(fake_samples.shape)
subset_size = real_samples.shape[0]
real_samples = real_samples[:subset_size]
fake_samples = fake_samples[:subset_size]
alpha = torch.rand(subset_size)
if self.use_cuda:
alpha = alpha.cuda()
alpha = alpha.view((-1,) + ((1,) * (real_samples.dim() - 1)))
interpolates = alpha * real_samples + ((1 - alpha) * fake_samples)
interpolates = Variable(interpolates, requires_grad=True)
if self.use_cuda:
interpolates = interpolates.cuda()
d_output = self.critic(interpolates, **kwargs)
grad_ouputs = torch.ones(d_output.size())
if self.use_cuda:
grad_ouputs = grad_ouputs.cuda()
gradients = grad(
outputs=d_output,
inputs=interpolates,
grad_outputs=grad_ouputs,
create_graph=True,
retain_graph=True,
only_inputs=True)[0]
return ((gradients.norm(2, dim=1) - 1) ** 2).mean() * 10 | python | def _gradient_penalty(self, real_samples, fake_samples, kwargs):
"""
Compute the norm of the gradients for each sample in a batch, and
penalize anything on either side of unit norm
"""
import torch
from torch.autograd import Variable, grad
real_samples = real_samples.view(fake_samples.shape)
subset_size = real_samples.shape[0]
real_samples = real_samples[:subset_size]
fake_samples = fake_samples[:subset_size]
alpha = torch.rand(subset_size)
if self.use_cuda:
alpha = alpha.cuda()
alpha = alpha.view((-1,) + ((1,) * (real_samples.dim() - 1)))
interpolates = alpha * real_samples + ((1 - alpha) * fake_samples)
interpolates = Variable(interpolates, requires_grad=True)
if self.use_cuda:
interpolates = interpolates.cuda()
d_output = self.critic(interpolates, **kwargs)
grad_ouputs = torch.ones(d_output.size())
if self.use_cuda:
grad_ouputs = grad_ouputs.cuda()
gradients = grad(
outputs=d_output,
inputs=interpolates,
grad_outputs=grad_ouputs,
create_graph=True,
retain_graph=True,
only_inputs=True)[0]
return ((gradients.norm(2, dim=1) - 1) ** 2).mean() * 10 | [
"def",
"_gradient_penalty",
"(",
"self",
",",
"real_samples",
",",
"fake_samples",
",",
"kwargs",
")",
":",
"import",
"torch",
"from",
"torch",
".",
"autograd",
"import",
"Variable",
",",
"grad",
"real_samples",
"=",
"real_samples",
".",
"view",
"(",
"fake_sam... | Compute the norm of the gradients for each sample in a batch, and
penalize anything on either side of unit norm | [
"Compute",
"the",
"norm",
"of",
"the",
"gradients",
"for",
"each",
"sample",
"in",
"a",
"batch",
"and",
"penalize",
"anything",
"on",
"either",
"side",
"of",
"unit",
"norm"
] | 337b3f98753d09eaab1c72dcd37bb852a3fa5ac6 | https://github.com/JohnVinyard/zounds/blob/337b3f98753d09eaab1c72dcd37bb852a3fa5ac6/zounds/learn/wgan.py#L61-L99 | train | 47,806 |
JohnVinyard/zounds | zounds/timeseries/audiosamples.py | AudioSamples.mono | def mono(self):
"""
Return this instance summed to mono. If the instance is already mono,
this is a no-op.
"""
if self.channels == 1:
return self
x = self.sum(axis=1) * 0.5
y = x * 0.5
return AudioSamples(y, self.samplerate) | python | def mono(self):
"""
Return this instance summed to mono. If the instance is already mono,
this is a no-op.
"""
if self.channels == 1:
return self
x = self.sum(axis=1) * 0.5
y = x * 0.5
return AudioSamples(y, self.samplerate) | [
"def",
"mono",
"(",
"self",
")",
":",
"if",
"self",
".",
"channels",
"==",
"1",
":",
"return",
"self",
"x",
"=",
"self",
".",
"sum",
"(",
"axis",
"=",
"1",
")",
"*",
"0.5",
"y",
"=",
"x",
"*",
"0.5",
"return",
"AudioSamples",
"(",
"y",
",",
"... | Return this instance summed to mono. If the instance is already mono,
this is a no-op. | [
"Return",
"this",
"instance",
"summed",
"to",
"mono",
".",
"If",
"the",
"instance",
"is",
"already",
"mono",
"this",
"is",
"a",
"no",
"-",
"op",
"."
] | 337b3f98753d09eaab1c72dcd37bb852a3fa5ac6 | https://github.com/JohnVinyard/zounds/blob/337b3f98753d09eaab1c72dcd37bb852a3fa5ac6/zounds/timeseries/audiosamples.py#L149-L158 | train | 47,807 |
JohnVinyard/zounds | zounds/timeseries/audiosamples.py | AudioSamples.encode | def encode(self, flo=None, fmt='WAV', subtype='PCM_16'):
"""
Return audio samples encoded as bytes given a particular audio format
Args:
flo (file-like): A file-like object to write the bytes to. If flo
is not supplied, a new :class:`io.BytesIO` instance will be
created and returned
fmt (str): A libsndfile-friendly identifier for an audio encoding
(detailed here: http://www.mega-nerd.com/libsndfile/api.html)
subtype (str): A libsndfile-friendly identifier for an audio
encoding subtype (detailed here:
http://www.mega-nerd.com/libsndfile/api.html)
Examples:
>>> from zounds import SR11025, AudioSamples
>>> import numpy as np
>>> silence = np.zeros(11025*10)
>>> samples = AudioSamples(silence, SR11025())
>>> bio = samples.encode()
>>> bio.read(10)
'RIFFx]\\x03\\x00WA'
"""
flo = flo or BytesIO()
with SoundFile(
flo,
mode='w',
channels=self.channels,
format=fmt,
subtype=subtype,
samplerate=self.samples_per_second) as f:
if fmt == 'OGG':
# KLUDGE: Trying to write too-large chunks to an ogg file seems
# to cause a segfault in libsndfile
# KLUDGE: This logic is very similar to logic in the OggVorbis
# processing node, and should probably be factored into a common
# location
factor = 20
chunksize = self.samples_per_second * factor
for i in range(0, len(self), chunksize):
chunk = self[i: i + chunksize]
f.write(chunk)
else:
# write everything in one chunk
f.write(self)
flo.seek(0)
return flo | python | def encode(self, flo=None, fmt='WAV', subtype='PCM_16'):
"""
Return audio samples encoded as bytes given a particular audio format
Args:
flo (file-like): A file-like object to write the bytes to. If flo
is not supplied, a new :class:`io.BytesIO` instance will be
created and returned
fmt (str): A libsndfile-friendly identifier for an audio encoding
(detailed here: http://www.mega-nerd.com/libsndfile/api.html)
subtype (str): A libsndfile-friendly identifier for an audio
encoding subtype (detailed here:
http://www.mega-nerd.com/libsndfile/api.html)
Examples:
>>> from zounds import SR11025, AudioSamples
>>> import numpy as np
>>> silence = np.zeros(11025*10)
>>> samples = AudioSamples(silence, SR11025())
>>> bio = samples.encode()
>>> bio.read(10)
'RIFFx]\\x03\\x00WA'
"""
flo = flo or BytesIO()
with SoundFile(
flo,
mode='w',
channels=self.channels,
format=fmt,
subtype=subtype,
samplerate=self.samples_per_second) as f:
if fmt == 'OGG':
# KLUDGE: Trying to write too-large chunks to an ogg file seems
# to cause a segfault in libsndfile
# KLUDGE: This logic is very similar to logic in the OggVorbis
# processing node, and should probably be factored into a common
# location
factor = 20
chunksize = self.samples_per_second * factor
for i in range(0, len(self), chunksize):
chunk = self[i: i + chunksize]
f.write(chunk)
else:
# write everything in one chunk
f.write(self)
flo.seek(0)
return flo | [
"def",
"encode",
"(",
"self",
",",
"flo",
"=",
"None",
",",
"fmt",
"=",
"'WAV'",
",",
"subtype",
"=",
"'PCM_16'",
")",
":",
"flo",
"=",
"flo",
"or",
"BytesIO",
"(",
")",
"with",
"SoundFile",
"(",
"flo",
",",
"mode",
"=",
"'w'",
",",
"channels",
"... | Return audio samples encoded as bytes given a particular audio format
Args:
flo (file-like): A file-like object to write the bytes to. If flo
is not supplied, a new :class:`io.BytesIO` instance will be
created and returned
fmt (str): A libsndfile-friendly identifier for an audio encoding
(detailed here: http://www.mega-nerd.com/libsndfile/api.html)
subtype (str): A libsndfile-friendly identifier for an audio
encoding subtype (detailed here:
http://www.mega-nerd.com/libsndfile/api.html)
Examples:
>>> from zounds import SR11025, AudioSamples
>>> import numpy as np
>>> silence = np.zeros(11025*10)
>>> samples = AudioSamples(silence, SR11025())
>>> bio = samples.encode()
>>> bio.read(10)
'RIFFx]\\x03\\x00WA' | [
"Return",
"audio",
"samples",
"encoded",
"as",
"bytes",
"given",
"a",
"particular",
"audio",
"format"
] | 337b3f98753d09eaab1c72dcd37bb852a3fa5ac6 | https://github.com/JohnVinyard/zounds/blob/337b3f98753d09eaab1c72dcd37bb852a3fa5ac6/zounds/timeseries/audiosamples.py#L181-L229 | train | 47,808 |
playpauseandstop/rororo | rororo/schemas/validators.py | extend_with_default | def extend_with_default(validator_class: Any) -> Any:
"""Append defaults from schema to instance need to be validated.
:param validator_class: Apply the change for given validator class.
"""
validate_properties = validator_class.VALIDATORS['properties']
def set_defaults(validator: Any,
properties: dict,
instance: dict,
schema: dict) -> Iterator[ValidationError]:
for prop, subschema in properties.items():
if 'default' in subschema:
instance.setdefault(prop, subschema['default'])
for error in validate_properties(
validator, properties, instance, schema,
):
yield error # pragma: no cover
return extend(validator_class, {'properties': set_defaults}) | python | def extend_with_default(validator_class: Any) -> Any:
"""Append defaults from schema to instance need to be validated.
:param validator_class: Apply the change for given validator class.
"""
validate_properties = validator_class.VALIDATORS['properties']
def set_defaults(validator: Any,
properties: dict,
instance: dict,
schema: dict) -> Iterator[ValidationError]:
for prop, subschema in properties.items():
if 'default' in subschema:
instance.setdefault(prop, subschema['default'])
for error in validate_properties(
validator, properties, instance, schema,
):
yield error # pragma: no cover
return extend(validator_class, {'properties': set_defaults}) | [
"def",
"extend_with_default",
"(",
"validator_class",
":",
"Any",
")",
"->",
"Any",
":",
"validate_properties",
"=",
"validator_class",
".",
"VALIDATORS",
"[",
"'properties'",
"]",
"def",
"set_defaults",
"(",
"validator",
":",
"Any",
",",
"properties",
":",
"dic... | Append defaults from schema to instance need to be validated.
:param validator_class: Apply the change for given validator class. | [
"Append",
"defaults",
"from",
"schema",
"to",
"instance",
"need",
"to",
"be",
"validated",
"."
] | 28a04e8028c29647941e727116335e9d6fd64c27 | https://github.com/playpauseandstop/rororo/blob/28a04e8028c29647941e727116335e9d6fd64c27/rororo/schemas/validators.py#L33-L53 | train | 47,809 |
OSSOS/MOP | src/ossos/core/ossos/downloads/core.py | Downloader.download_hdulist | def download_hdulist(self, uri, **kwargs):
"""
Downloads a FITS image as a HDUList.
Args:
uri: The URI of the FITS image to download.
kwargs: optional arguments to pass to the vos client.
For example, passing view="cutout" and cutout=[1] will result
in a cutout of extension 1 from the FITS image specified by the
URI.
Returns:
hdulist: astropy.io.fits.hdu.hdulist.HDUList
The requests FITS image as an Astropy HDUList object
(http://docs.astropy.org/en/latest/io/fits/api/hdulists.html).
"""
logger.debug(str(kwargs))
hdulist = None
try:
vobj = storage.vofile(uri, **kwargs)
try:
fobj = cStringIO.StringIO(vobj.read())
fobj.seek(0)
hdulist = fits.open(fobj)
except Exception as e:
sys.stderr.write("ERROR: {}\n".format(str(e)))
sys.stderr.write("While loading {} {}\n".format(uri, kwargs))
pass
finally:
vobj.close()
except Exception as e:
sys.stderr.write(str(e)+"\n")
sys.stderr.write("While opening connection to {}.\n".format(uri))
sys.stderr.write("Sending back FLAT instead, too keep display happy.")
hdulist = self.download_hdulist('vos:OSSOS/dbimages/calibrators/13AQ05_r_flat.fits', **kwargs)
return hdulist | python | def download_hdulist(self, uri, **kwargs):
"""
Downloads a FITS image as a HDUList.
Args:
uri: The URI of the FITS image to download.
kwargs: optional arguments to pass to the vos client.
For example, passing view="cutout" and cutout=[1] will result
in a cutout of extension 1 from the FITS image specified by the
URI.
Returns:
hdulist: astropy.io.fits.hdu.hdulist.HDUList
The requests FITS image as an Astropy HDUList object
(http://docs.astropy.org/en/latest/io/fits/api/hdulists.html).
"""
logger.debug(str(kwargs))
hdulist = None
try:
vobj = storage.vofile(uri, **kwargs)
try:
fobj = cStringIO.StringIO(vobj.read())
fobj.seek(0)
hdulist = fits.open(fobj)
except Exception as e:
sys.stderr.write("ERROR: {}\n".format(str(e)))
sys.stderr.write("While loading {} {}\n".format(uri, kwargs))
pass
finally:
vobj.close()
except Exception as e:
sys.stderr.write(str(e)+"\n")
sys.stderr.write("While opening connection to {}.\n".format(uri))
sys.stderr.write("Sending back FLAT instead, too keep display happy.")
hdulist = self.download_hdulist('vos:OSSOS/dbimages/calibrators/13AQ05_r_flat.fits', **kwargs)
return hdulist | [
"def",
"download_hdulist",
"(",
"self",
",",
"uri",
",",
"*",
"*",
"kwargs",
")",
":",
"logger",
".",
"debug",
"(",
"str",
"(",
"kwargs",
")",
")",
"hdulist",
"=",
"None",
"try",
":",
"vobj",
"=",
"storage",
".",
"vofile",
"(",
"uri",
",",
"*",
"... | Downloads a FITS image as a HDUList.
Args:
uri: The URI of the FITS image to download.
kwargs: optional arguments to pass to the vos client.
For example, passing view="cutout" and cutout=[1] will result
in a cutout of extension 1 from the FITS image specified by the
URI.
Returns:
hdulist: astropy.io.fits.hdu.hdulist.HDUList
The requests FITS image as an Astropy HDUList object
(http://docs.astropy.org/en/latest/io/fits/api/hdulists.html). | [
"Downloads",
"a",
"FITS",
"image",
"as",
"a",
"HDUList",
"."
] | 94f91d32ad5ec081d5a1ebd67604a838003465af | https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/downloads/core.py#L17-L53 | train | 47,810 |
OSSOS/MOP | src/ossos/core/ossos/downloads/core.py | Downloader.download_apcor | def download_apcor(self, uri):
"""
Downloads apcor data.
Args:
uri: The URI of the apcor data file.
Returns:
apcor: ossos.downloads.core.ApcorData
"""
local_file = os.path.basename(uri)
if os.access(local_file, os.F_OK):
fobj = open(local_file)
else:
fobj = storage.vofile(uri, view='data')
fobj.seek(0)
str = fobj.read()
fobj.close()
apcor_str = str
return ApcorData.from_string(apcor_str) | python | def download_apcor(self, uri):
"""
Downloads apcor data.
Args:
uri: The URI of the apcor data file.
Returns:
apcor: ossos.downloads.core.ApcorData
"""
local_file = os.path.basename(uri)
if os.access(local_file, os.F_OK):
fobj = open(local_file)
else:
fobj = storage.vofile(uri, view='data')
fobj.seek(0)
str = fobj.read()
fobj.close()
apcor_str = str
return ApcorData.from_string(apcor_str) | [
"def",
"download_apcor",
"(",
"self",
",",
"uri",
")",
":",
"local_file",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"uri",
")",
"if",
"os",
".",
"access",
"(",
"local_file",
",",
"os",
".",
"F_OK",
")",
":",
"fobj",
"=",
"open",
"(",
"local_fil... | Downloads apcor data.
Args:
uri: The URI of the apcor data file.
Returns:
apcor: ossos.downloads.core.ApcorData | [
"Downloads",
"apcor",
"data",
"."
] | 94f91d32ad5ec081d5a1ebd67604a838003465af | https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/downloads/core.py#L55-L75 | train | 47,811 |
OSSOS/MOP | src/ossos/core/ossos/downloads/core.py | ApcorData.from_string | def from_string(cls, rawstr):
"""
Creates an ApcorData record from the raw string format.
Expected string format:
ap_in ap_out ap_cor apcor_err
"""
try:
args = map(float, rawstr.split())
except Exception as ex:
import sys
logger.error("Failed to convert aperture correction: {}".format(ex))
raise ex
return cls(*args) | python | def from_string(cls, rawstr):
"""
Creates an ApcorData record from the raw string format.
Expected string format:
ap_in ap_out ap_cor apcor_err
"""
try:
args = map(float, rawstr.split())
except Exception as ex:
import sys
logger.error("Failed to convert aperture correction: {}".format(ex))
raise ex
return cls(*args) | [
"def",
"from_string",
"(",
"cls",
",",
"rawstr",
")",
":",
"try",
":",
"args",
"=",
"map",
"(",
"float",
",",
"rawstr",
".",
"split",
"(",
")",
")",
"except",
"Exception",
"as",
"ex",
":",
"import",
"sys",
"logger",
".",
"error",
"(",
"\"Failed to co... | Creates an ApcorData record from the raw string format.
Expected string format:
ap_in ap_out ap_cor apcor_err | [
"Creates",
"an",
"ApcorData",
"record",
"from",
"the",
"raw",
"string",
"format",
"."
] | 94f91d32ad5ec081d5a1ebd67604a838003465af | https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/downloads/core.py#L95-L108 | train | 47,812 |
OSSOS/MOP | src/jjk/preproc/ephemSearch.py | htmIndex | def htmIndex(ra,dec,htm_level=3):
"""Compute htm index of htm_level at position ra,dec"""
import re
if os.uname()[0] == "Linux": javabin = '/opt/java2/bin/java '
htm_level = htm_level
verc_htm_cmd = javabin+'-classpath /usr/cadc/misc/htm/htmIndex.jar edu.jhu.htm.app.lookup %s %s %s' % (htm_level, ra, dec)
for result in os.popen( verc_htm_cmd ).readlines():
result = result[:-1]
if re.search("ID/Name cc", result):
(void, coord ) = result.split("=")
(void, junk, htm_index) = coord.split(" ")
return htm_index | python | def htmIndex(ra,dec,htm_level=3):
"""Compute htm index of htm_level at position ra,dec"""
import re
if os.uname()[0] == "Linux": javabin = '/opt/java2/bin/java '
htm_level = htm_level
verc_htm_cmd = javabin+'-classpath /usr/cadc/misc/htm/htmIndex.jar edu.jhu.htm.app.lookup %s %s %s' % (htm_level, ra, dec)
for result in os.popen( verc_htm_cmd ).readlines():
result = result[:-1]
if re.search("ID/Name cc", result):
(void, coord ) = result.split("=")
(void, junk, htm_index) = coord.split(" ")
return htm_index | [
"def",
"htmIndex",
"(",
"ra",
",",
"dec",
",",
"htm_level",
"=",
"3",
")",
":",
"import",
"re",
"if",
"os",
".",
"uname",
"(",
")",
"[",
"0",
"]",
"==",
"\"Linux\"",
":",
"javabin",
"=",
"'/opt/java2/bin/java '",
"htm_level",
"=",
"htm_level",
"verc_ht... | Compute htm index of htm_level at position ra,dec | [
"Compute",
"htm",
"index",
"of",
"htm_level",
"at",
"position",
"ra",
"dec"
] | 94f91d32ad5ec081d5a1ebd67604a838003465af | https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/jjk/preproc/ephemSearch.py#L70-L82 | train | 47,813 |
OSSOS/MOP | src/jjk/preproc/ephemSearch.py | predict | def predict(abg,date,obs=568):
"""Run GB's predict using an ABG file as input."""
import orbfit
import RO.StringUtil
(ra,dec,a,b,ang) = orbfit.predict(abg,date,obs)
obj['RA']=ra
obj['DEC']=dec
obj['dRA']=a
obj['dDEC']=b
obj['dANG']=ang
return obj | python | def predict(abg,date,obs=568):
"""Run GB's predict using an ABG file as input."""
import orbfit
import RO.StringUtil
(ra,dec,a,b,ang) = orbfit.predict(abg,date,obs)
obj['RA']=ra
obj['DEC']=dec
obj['dRA']=a
obj['dDEC']=b
obj['dANG']=ang
return obj | [
"def",
"predict",
"(",
"abg",
",",
"date",
",",
"obs",
"=",
"568",
")",
":",
"import",
"orbfit",
"import",
"RO",
".",
"StringUtil",
"(",
"ra",
",",
"dec",
",",
"a",
",",
"b",
",",
"ang",
")",
"=",
"orbfit",
".",
"predict",
"(",
"abg",
",",
"dat... | Run GB's predict using an ABG file as input. | [
"Run",
"GB",
"s",
"predict",
"using",
"an",
"ABG",
"file",
"as",
"input",
"."
] | 94f91d32ad5ec081d5a1ebd67604a838003465af | https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/jjk/preproc/ephemSearch.py#L264-L274 | train | 47,814 |
OSSOS/MOP | src/ossos/core/ossos/util.py | config_logging | def config_logging(level):
"""
Configure the logging given the level desired
"""
logger = logging.getLogger('')
logger.setLevel(level)
if level < logging.DEBUG:
log_format = "%(asctime)s %(message)s"
else:
log_format = "%(asctime)s %(module)s : %(lineno)d %(message)s"
sh = logging.StreamHandler()
sh.formatter = logging.Formatter(fmt=log_format)
logger.handlers = []
logger.addHandler(sh) | python | def config_logging(level):
"""
Configure the logging given the level desired
"""
logger = logging.getLogger('')
logger.setLevel(level)
if level < logging.DEBUG:
log_format = "%(asctime)s %(message)s"
else:
log_format = "%(asctime)s %(module)s : %(lineno)d %(message)s"
sh = logging.StreamHandler()
sh.formatter = logging.Formatter(fmt=log_format)
logger.handlers = []
logger.addHandler(sh) | [
"def",
"config_logging",
"(",
"level",
")",
":",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
"''",
")",
"logger",
".",
"setLevel",
"(",
"level",
")",
"if",
"level",
"<",
"logging",
".",
"DEBUG",
":",
"log_format",
"=",
"\"%(asctime)s %(message)s\"",
"... | Configure the logging given the level desired | [
"Configure",
"the",
"logging",
"given",
"the",
"level",
"desired"
] | 94f91d32ad5ec081d5a1ebd67604a838003465af | https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/util.py#L27-L41 | train | 47,815 |
OSSOS/MOP | src/ossos/core/ossos/util.py | exec_prog | def exec_prog(args):
"""Run a subprocess, check for .OK and raise error if does not exist.
args: list of arguments, for value is the command to execute.
"""
program_name = args[0]
logging.info(" ".join(args))
output = subprocess.check_output(args, stderr=subprocess.STDOUT)
if not os.access(program_name+".OK", os.F_OK):
logging.error("No {}.OK file?".format(program_name))
raise subprocess.CalledProcessError(-1, ' '.join(args), output)
os.unlink(program_name+".OK")
if os.access(program_name+".FAILED", os.F_OK):
os.unlink(program_name+".FAILED")
return output | python | def exec_prog(args):
"""Run a subprocess, check for .OK and raise error if does not exist.
args: list of arguments, for value is the command to execute.
"""
program_name = args[0]
logging.info(" ".join(args))
output = subprocess.check_output(args, stderr=subprocess.STDOUT)
if not os.access(program_name+".OK", os.F_OK):
logging.error("No {}.OK file?".format(program_name))
raise subprocess.CalledProcessError(-1, ' '.join(args), output)
os.unlink(program_name+".OK")
if os.access(program_name+".FAILED", os.F_OK):
os.unlink(program_name+".FAILED")
return output | [
"def",
"exec_prog",
"(",
"args",
")",
":",
"program_name",
"=",
"args",
"[",
"0",
"]",
"logging",
".",
"info",
"(",
"\" \"",
".",
"join",
"(",
"args",
")",
")",
"output",
"=",
"subprocess",
".",
"check_output",
"(",
"args",
",",
"stderr",
"=",
"subpr... | Run a subprocess, check for .OK and raise error if does not exist.
args: list of arguments, for value is the command to execute. | [
"Run",
"a",
"subprocess",
"check",
"for",
".",
"OK",
"and",
"raise",
"error",
"if",
"does",
"not",
"exist",
"."
] | 94f91d32ad5ec081d5a1ebd67604a838003465af | https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/util.py#L58-L73 | train | 47,816 |
OSSOS/MOP | src/ossos/core/ossos/util.py | VOFileHandler.stream | def stream(self):
"""
the stream to write the log content too.
@return:
"""
if self._stream is None:
self._stream = tempfile.NamedTemporaryFile(delete=False)
try:
self._stream.write(self.client.open(self.filename, view='data').read())
except:
pass
return self._stream | python | def stream(self):
"""
the stream to write the log content too.
@return:
"""
if self._stream is None:
self._stream = tempfile.NamedTemporaryFile(delete=False)
try:
self._stream.write(self.client.open(self.filename, view='data').read())
except:
pass
return self._stream | [
"def",
"stream",
"(",
"self",
")",
":",
"if",
"self",
".",
"_stream",
"is",
"None",
":",
"self",
".",
"_stream",
"=",
"tempfile",
".",
"NamedTemporaryFile",
"(",
"delete",
"=",
"False",
")",
"try",
":",
"self",
".",
"_stream",
".",
"write",
"(",
"sel... | the stream to write the log content too.
@return: | [
"the",
"stream",
"to",
"write",
"the",
"log",
"content",
"too",
"."
] | 94f91d32ad5ec081d5a1ebd67604a838003465af | https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/util.py#L87-L98 | train | 47,817 |
OSSOS/MOP | src/ossos/core/ossos/util.py | VOFileHandler.client | def client(self):
"""
Send back the client we were sent, or construct a default one.
@rtype vospace.client
"""
if self._client is not None:
return self._client
self._client = vospace.client
return self._client | python | def client(self):
"""
Send back the client we were sent, or construct a default one.
@rtype vospace.client
"""
if self._client is not None:
return self._client
self._client = vospace.client
return self._client | [
"def",
"client",
"(",
"self",
")",
":",
"if",
"self",
".",
"_client",
"is",
"not",
"None",
":",
"return",
"self",
".",
"_client",
"self",
".",
"_client",
"=",
"vospace",
".",
"client",
"return",
"self",
".",
"_client"
] | Send back the client we were sent, or construct a default one.
@rtype vospace.client | [
"Send",
"back",
"the",
"client",
"we",
"were",
"sent",
"or",
"construct",
"a",
"default",
"one",
"."
] | 94f91d32ad5ec081d5a1ebd67604a838003465af | https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/util.py#L101-L110 | train | 47,818 |
OSSOS/MOP | src/ossos/core/ossos/util.py | TimeMPC.parse_string | def parse_string(self, timestr, subfmts):
"""Read time from a single string, using a set of possible formats."""
# Datetime components required for conversion to JD by ERFA, along
# with the default values.
components = ('year', 'mon', 'mday')
defaults = (None, 1, 1, 0)
# Assume that anything following "." on the right side is a
# floating fraction of a second.
try:
idot = timestr.rindex('.')
except:
fracday = 0.0
else:
timestr, fracday = timestr[:idot], timestr[idot:]
fracday = float(fracday)
for _, strptime_fmt_or_regex, _ in subfmts:
vals = []
#print strptime_fmt_or_regex
if isinstance(strptime_fmt_or_regex, six.string_types):
try:
#print timstr
#print strptime_fmt_or_regex
tm = time.strptime(timestr, strptime_fmt_or_regex)
tm.tm_hour += int(24 * fracday)
tm.tm_min += int(60 * (24 * fracday - tm.tm_hour))
tm.tm_sec += 60 * (60 * (24 * fracday - tm.tm_hour) - tm.tm_min)
except ValueError as ex:
print ex
continue
else:
vals = [getattr(tm, 'tm_' + component)
for component in components]
else:
tm = re.match(strptime_fmt_or_regex, timestr)
if tm is None:
continue
tm = tm.groupdict()
vals = [int(tm.get(component, default)) for component, default
in six.moves.zip(components, defaults)]
hrprt = int(24 * fracday)
vals.append(hrprt)
mnprt = int(60 * (24 * fracday - hrprt))
vals.append(mnprt)
scprt = 60 * (60 * (24 * fracday - hrprt) - mnprt)
vals.append(scprt)
return vals
else:
raise ValueError('Time {0} does not match {1} format'
.format(timestr, self.name)) | python | def parse_string(self, timestr, subfmts):
"""Read time from a single string, using a set of possible formats."""
# Datetime components required for conversion to JD by ERFA, along
# with the default values.
components = ('year', 'mon', 'mday')
defaults = (None, 1, 1, 0)
# Assume that anything following "." on the right side is a
# floating fraction of a second.
try:
idot = timestr.rindex('.')
except:
fracday = 0.0
else:
timestr, fracday = timestr[:idot], timestr[idot:]
fracday = float(fracday)
for _, strptime_fmt_or_regex, _ in subfmts:
vals = []
#print strptime_fmt_or_regex
if isinstance(strptime_fmt_or_regex, six.string_types):
try:
#print timstr
#print strptime_fmt_or_regex
tm = time.strptime(timestr, strptime_fmt_or_regex)
tm.tm_hour += int(24 * fracday)
tm.tm_min += int(60 * (24 * fracday - tm.tm_hour))
tm.tm_sec += 60 * (60 * (24 * fracday - tm.tm_hour) - tm.tm_min)
except ValueError as ex:
print ex
continue
else:
vals = [getattr(tm, 'tm_' + component)
for component in components]
else:
tm = re.match(strptime_fmt_or_regex, timestr)
if tm is None:
continue
tm = tm.groupdict()
vals = [int(tm.get(component, default)) for component, default
in six.moves.zip(components, defaults)]
hrprt = int(24 * fracday)
vals.append(hrprt)
mnprt = int(60 * (24 * fracday - hrprt))
vals.append(mnprt)
scprt = 60 * (60 * (24 * fracday - hrprt) - mnprt)
vals.append(scprt)
return vals
else:
raise ValueError('Time {0} does not match {1} format'
.format(timestr, self.name)) | [
"def",
"parse_string",
"(",
"self",
",",
"timestr",
",",
"subfmts",
")",
":",
"# Datetime components required for conversion to JD by ERFA, along",
"# with the default values.",
"components",
"=",
"(",
"'year'",
",",
"'mon'",
",",
"'mday'",
")",
"defaults",
"=",
"(",
... | Read time from a single string, using a set of possible formats. | [
"Read",
"time",
"from",
"a",
"single",
"string",
"using",
"a",
"set",
"of",
"possible",
"formats",
"."
] | 94f91d32ad5ec081d5a1ebd67604a838003465af | https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/util.py#L258-L309 | train | 47,819 |
OSSOS/MOP | src/jjk/webCat/MOPdbaccess.py | _get_db_options | def _get_db_options(args):
"""Parse through a command line of arguments to over-ride the values
in the users .dbrc file.
If no user name is given then the environment variable $USERNAME is
used. If $USERNAME is not defined then prompt for input.
"""
import optik, getpass,sys
from optik import OptionParser
parser=OptionParser()
parser.add_option("-d","--database",
action="store", type="string", dest="database",
default="cfht",
help="Name of the SYBASE database containing TABLE",
metavar="FILE")
parser.add_option("-u","--user",
action="store", type="string", dest="user",
default=getpass.getuser(),
help="User name to access db with",
metavar="USER")
(opt, unused_args) = parser.parse_args(args)
return opt.database,opt.user,unused_args | python | def _get_db_options(args):
"""Parse through a command line of arguments to over-ride the values
in the users .dbrc file.
If no user name is given then the environment variable $USERNAME is
used. If $USERNAME is not defined then prompt for input.
"""
import optik, getpass,sys
from optik import OptionParser
parser=OptionParser()
parser.add_option("-d","--database",
action="store", type="string", dest="database",
default="cfht",
help="Name of the SYBASE database containing TABLE",
metavar="FILE")
parser.add_option("-u","--user",
action="store", type="string", dest="user",
default=getpass.getuser(),
help="User name to access db with",
metavar="USER")
(opt, unused_args) = parser.parse_args(args)
return opt.database,opt.user,unused_args | [
"def",
"_get_db_options",
"(",
"args",
")",
":",
"import",
"optik",
",",
"getpass",
",",
"sys",
"from",
"optik",
"import",
"OptionParser",
"parser",
"=",
"OptionParser",
"(",
")",
"parser",
".",
"add_option",
"(",
"\"-d\"",
",",
"\"--database\"",
",",
"actio... | Parse through a command line of arguments to over-ride the values
in the users .dbrc file.
If no user name is given then the environment variable $USERNAME is
used. If $USERNAME is not defined then prompt for input. | [
"Parse",
"through",
"a",
"command",
"line",
"of",
"arguments",
"to",
"over",
"-",
"ride",
"the",
"values",
"in",
"the",
"users",
".",
"dbrc",
"file",
"."
] | 94f91d32ad5ec081d5a1ebd67604a838003465af | https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/jjk/webCat/MOPdbaccess.py#L33-L54 | train | 47,820 |
OSSOS/MOP | src/jjk/webCat/MOPdbaccess.py | _get_db_connect | def _get_db_connect(dbSystem,db,user,password):
"""Create a connection to the database specified on the command line
"""
if dbSystem=='SYBASE':
import Sybase
try:
dbh = Sybase.connect(dbSystem,
user,
password,
database=db )
except:
dbh=None
elif dbSystem=='MYSQL':
import MySQLdb
try:
dbh = MySQLdb.connect(user=user,
passwd=password,
db=db ,
host='gimli')
except:
dbh=None
return dbh | python | def _get_db_connect(dbSystem,db,user,password):
"""Create a connection to the database specified on the command line
"""
if dbSystem=='SYBASE':
import Sybase
try:
dbh = Sybase.connect(dbSystem,
user,
password,
database=db )
except:
dbh=None
elif dbSystem=='MYSQL':
import MySQLdb
try:
dbh = MySQLdb.connect(user=user,
passwd=password,
db=db ,
host='gimli')
except:
dbh=None
return dbh | [
"def",
"_get_db_connect",
"(",
"dbSystem",
",",
"db",
",",
"user",
",",
"password",
")",
":",
"if",
"dbSystem",
"==",
"'SYBASE'",
":",
"import",
"Sybase",
"try",
":",
"dbh",
"=",
"Sybase",
".",
"connect",
"(",
"dbSystem",
",",
"user",
",",
"password",
... | Create a connection to the database specified on the command line | [
"Create",
"a",
"connection",
"to",
"the",
"database",
"specified",
"on",
"the",
"command",
"line"
] | 94f91d32ad5ec081d5a1ebd67604a838003465af | https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/jjk/webCat/MOPdbaccess.py#L73-L95 | train | 47,821 |
OSSOS/MOP | src/ossos/core/ossos/downloads/cutouts/downloader.py | ImageCutoutDownloader.download_cutout | def download_cutout(self, reading, focus=None, needs_apcor=False):
"""
Downloads a cutout of the FITS image for a given source reading.
Args:
reading: ossos.astrom.SourceReading
The reading which will be the focus of the downloaded image.
focus: tuple(int, int)
The x, y coordinates that should be the focus of the downloaded
image. These coordinates should be in terms of the
source_reading parameter's coordinate system.
Default value is None, in which case the source reading's x, y
position is used as the focus.
needs_apcor: bool
If True, the apcor file with data needed for photometry
calculations is downloaded in addition to the image.
Defaults to False.
Returns:
cutout: ossos.downloads.data.SourceCutout
"""
logger.debug("Doing download_cutout with inputs: reading:{} focus:{} needs_apcor:{}".format(reading,
focus,
needs_apcor))
assert isinstance(reading, SourceReading)
min_radius = config.read('CUTOUTS.SINGLETS.RADIUS')
if not isinstance(min_radius, Quantity):
min_radius = min_radius * units.arcsec
radius = max(reading.uncertainty_ellipse.a,
reading.uncertainty_ellipse.b) * 2.5 + min_radius
logger.debug("got radius for cutout: {}".format(radius))
image_uri = reading.get_image_uri()
logger.debug("Getting cutout at {} for {}".format(reading.reference_sky_coord, image_uri))
hdulist = storage._cutout_expnum(reading.obs,
reading.reference_sky_coord, radius)
# hdulist = storage.ra_dec_cutout(image_uri, reading.reference_sky_coord, radius)
logger.debug("Getting the aperture correction.")
source = SourceCutout(reading, hdulist, radius=radius)
# Accessing the attribute here to trigger the download.
try:
apcor = source.apcor
zmag = source.zmag
source.reading.get_observation_header()
except Exception as ex:
if needs_apcor:
import sys, traceback
sys.stderr.write("Failed to retrieve apcor but apcor required. Raising error, see logs for more details")
sys.stderr.write(traceback.print_exc())
pass
logger.debug("Sending back the source reading.")
return source | python | def download_cutout(self, reading, focus=None, needs_apcor=False):
"""
Downloads a cutout of the FITS image for a given source reading.
Args:
reading: ossos.astrom.SourceReading
The reading which will be the focus of the downloaded image.
focus: tuple(int, int)
The x, y coordinates that should be the focus of the downloaded
image. These coordinates should be in terms of the
source_reading parameter's coordinate system.
Default value is None, in which case the source reading's x, y
position is used as the focus.
needs_apcor: bool
If True, the apcor file with data needed for photometry
calculations is downloaded in addition to the image.
Defaults to False.
Returns:
cutout: ossos.downloads.data.SourceCutout
"""
logger.debug("Doing download_cutout with inputs: reading:{} focus:{} needs_apcor:{}".format(reading,
focus,
needs_apcor))
assert isinstance(reading, SourceReading)
min_radius = config.read('CUTOUTS.SINGLETS.RADIUS')
if not isinstance(min_radius, Quantity):
min_radius = min_radius * units.arcsec
radius = max(reading.uncertainty_ellipse.a,
reading.uncertainty_ellipse.b) * 2.5 + min_radius
logger.debug("got radius for cutout: {}".format(radius))
image_uri = reading.get_image_uri()
logger.debug("Getting cutout at {} for {}".format(reading.reference_sky_coord, image_uri))
hdulist = storage._cutout_expnum(reading.obs,
reading.reference_sky_coord, radius)
# hdulist = storage.ra_dec_cutout(image_uri, reading.reference_sky_coord, radius)
logger.debug("Getting the aperture correction.")
source = SourceCutout(reading, hdulist, radius=radius)
# Accessing the attribute here to trigger the download.
try:
apcor = source.apcor
zmag = source.zmag
source.reading.get_observation_header()
except Exception as ex:
if needs_apcor:
import sys, traceback
sys.stderr.write("Failed to retrieve apcor but apcor required. Raising error, see logs for more details")
sys.stderr.write(traceback.print_exc())
pass
logger.debug("Sending back the source reading.")
return source | [
"def",
"download_cutout",
"(",
"self",
",",
"reading",
",",
"focus",
"=",
"None",
",",
"needs_apcor",
"=",
"False",
")",
":",
"logger",
".",
"debug",
"(",
"\"Doing download_cutout with inputs: reading:{} focus:{} needs_apcor:{}\"",
".",
"format",
"(",
"reading",
","... | Downloads a cutout of the FITS image for a given source reading.
Args:
reading: ossos.astrom.SourceReading
The reading which will be the focus of the downloaded image.
focus: tuple(int, int)
The x, y coordinates that should be the focus of the downloaded
image. These coordinates should be in terms of the
source_reading parameter's coordinate system.
Default value is None, in which case the source reading's x, y
position is used as the focus.
needs_apcor: bool
If True, the apcor file with data needed for photometry
calculations is downloaded in addition to the image.
Defaults to False.
Returns:
cutout: ossos.downloads.data.SourceCutout | [
"Downloads",
"a",
"cutout",
"of",
"the",
"FITS",
"image",
"for",
"a",
"given",
"source",
"reading",
"."
] | 94f91d32ad5ec081d5a1ebd67604a838003465af | https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/downloads/cutouts/downloader.py#L46-L99 | train | 47,822 |
OSSOS/MOP | src/ossos/core/ossos/planning/obs_planner.py | Plot.load_objects | def load_objects(self, directory_name=None):
"""Load the targets from a file.
"""
# for name in Neptune:
# self.kbos[name] = Neptune[name]
if directory_name is not None:
# defaults to looking at .ast files only
if directory_name == parameters.REAL_KBO_AST_DIR:
kbos = parsers.ossos_discoveries(all_objects=True, data_release=None)
else:
kbos = parsers.ossos_discoveries(directory_name, all_objects=False, data_release=None)
for kbo in kbos:
# if kbo.orbit.arc_length > 30.: # cull the short ones for now
self.kbos[kbo.name] = kbo.orbit
self.kbos[kbo.name].mag = kbo.mag
# else:
# print("Arc very short, large uncertainty. Skipping {} for now.\n".format(kbo.name))
self.doplot() | python | def load_objects(self, directory_name=None):
"""Load the targets from a file.
"""
# for name in Neptune:
# self.kbos[name] = Neptune[name]
if directory_name is not None:
# defaults to looking at .ast files only
if directory_name == parameters.REAL_KBO_AST_DIR:
kbos = parsers.ossos_discoveries(all_objects=True, data_release=None)
else:
kbos = parsers.ossos_discoveries(directory_name, all_objects=False, data_release=None)
for kbo in kbos:
# if kbo.orbit.arc_length > 30.: # cull the short ones for now
self.kbos[kbo.name] = kbo.orbit
self.kbos[kbo.name].mag = kbo.mag
# else:
# print("Arc very short, large uncertainty. Skipping {} for now.\n".format(kbo.name))
self.doplot() | [
"def",
"load_objects",
"(",
"self",
",",
"directory_name",
"=",
"None",
")",
":",
"# for name in Neptune:",
"# self.kbos[name] = Neptune[name]",
"if",
"directory_name",
"is",
"not",
"None",
":",
"# defaults to looking at .ast files only",
"if",
"directory_name",
"==",
... | Load the targets from a file. | [
"Load",
"the",
"targets",
"from",
"a",
"file",
"."
] | 94f91d32ad5ec081d5a1ebd67604a838003465af | https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/planning/obs_planner.py#L219-L240 | train | 47,823 |
OSSOS/MOP | src/ossos/core/ossos/planning/obs_planner.py | Plot.p2c | def p2c(self, p=None):
"""convert from plot to canvas coordinates.
See also c2p."""
if p is None:
p = [0, 0]
x = (p[0] - self.x1) * self.xscale + self.cx1
y = (p[1] - self.y1) * self.yscale + self.cy1
# logging.debug("p2c: ({},{}) -> ({},{})".format(p[0],p[1], x, y))
return (x, y) | python | def p2c(self, p=None):
"""convert from plot to canvas coordinates.
See also c2p."""
if p is None:
p = [0, 0]
x = (p[0] - self.x1) * self.xscale + self.cx1
y = (p[1] - self.y1) * self.yscale + self.cy1
# logging.debug("p2c: ({},{}) -> ({},{})".format(p[0],p[1], x, y))
return (x, y) | [
"def",
"p2c",
"(",
"self",
",",
"p",
"=",
"None",
")",
":",
"if",
"p",
"is",
"None",
":",
"p",
"=",
"[",
"0",
",",
"0",
"]",
"x",
"=",
"(",
"p",
"[",
"0",
"]",
"-",
"self",
".",
"x1",
")",
"*",
"self",
".",
"xscale",
"+",
"self",
".",
... | convert from plot to canvas coordinates.
See also c2p. | [
"convert",
"from",
"plot",
"to",
"canvas",
"coordinates",
"."
] | 94f91d32ad5ec081d5a1ebd67604a838003465af | https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/planning/obs_planner.py#L266-L276 | train | 47,824 |
OSSOS/MOP | src/ossos/core/ossos/planning/obs_planner.py | Plot.p2s | def p2s(self, p=None):
"""Convert from plot to screen coordinates"""
if not p: p = [0, 0]
s = self.p2c(p)
return self.c2s(s) | python | def p2s(self, p=None):
"""Convert from plot to screen coordinates"""
if not p: p = [0, 0]
s = self.p2c(p)
return self.c2s(s) | [
"def",
"p2s",
"(",
"self",
",",
"p",
"=",
"None",
")",
":",
"if",
"not",
"p",
":",
"p",
"=",
"[",
"0",
",",
"0",
"]",
"s",
"=",
"self",
".",
"p2c",
"(",
"p",
")",
"return",
"self",
".",
"c2s",
"(",
"s",
")"
] | Convert from plot to screen coordinates | [
"Convert",
"from",
"plot",
"to",
"screen",
"coordinates"
] | 94f91d32ad5ec081d5a1ebd67604a838003465af | https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/planning/obs_planner.py#L278-L283 | train | 47,825 |
OSSOS/MOP | src/ossos/core/ossos/planning/obs_planner.py | Plot.tickmark | def tickmark(self, x, y, size=10, orientation=90):
"""Draw a line of size and orientation at x,y"""
(x1, y1) = self.p2c([x, y])
x2 = x1 + size * math.cos(math.radians(orientation))
y2 = y1 - size * math.sin(math.radians(orientation))
self.create_line(x1, y1, x2, y2) | python | def tickmark(self, x, y, size=10, orientation=90):
"""Draw a line of size and orientation at x,y"""
(x1, y1) = self.p2c([x, y])
x2 = x1 + size * math.cos(math.radians(orientation))
y2 = y1 - size * math.sin(math.radians(orientation))
self.create_line(x1, y1, x2, y2) | [
"def",
"tickmark",
"(",
"self",
",",
"x",
",",
"y",
",",
"size",
"=",
"10",
",",
"orientation",
"=",
"90",
")",
":",
"(",
"x1",
",",
"y1",
")",
"=",
"self",
".",
"p2c",
"(",
"[",
"x",
",",
"y",
"]",
")",
"x2",
"=",
"x1",
"+",
"size",
"*",... | Draw a line of size and orientation at x,y | [
"Draw",
"a",
"line",
"of",
"size",
"and",
"orientation",
"at",
"x",
"y"
] | 94f91d32ad5ec081d5a1ebd67604a838003465af | https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/planning/obs_planner.py#L425-L431 | train | 47,826 |
OSSOS/MOP | src/ossos/core/ossos/planning/obs_planner.py | Plot.relocate | def relocate(self):
"""Move to the position of self.SearchVar"""
name = self.SearchVar.get()
if self.kbos.has_key(name):
kbo = self.kbos[name]
assert isinstance(kbo, orbfit.Orbfit)
this_time = Time(self.date.get(), scale='utc')
try:
kbo.predict(this_time)
self.recenter(kbo.coordinate.ra.radian, kbo.coordinate.dec.radian)
self.create_point(kbo.coordinate.ra.radian, kbo.coordinate.dec.radian, color='blue', size=4)
except:
logging.error("failed to compute KBO position") | python | def relocate(self):
"""Move to the position of self.SearchVar"""
name = self.SearchVar.get()
if self.kbos.has_key(name):
kbo = self.kbos[name]
assert isinstance(kbo, orbfit.Orbfit)
this_time = Time(self.date.get(), scale='utc')
try:
kbo.predict(this_time)
self.recenter(kbo.coordinate.ra.radian, kbo.coordinate.dec.radian)
self.create_point(kbo.coordinate.ra.radian, kbo.coordinate.dec.radian, color='blue', size=4)
except:
logging.error("failed to compute KBO position") | [
"def",
"relocate",
"(",
"self",
")",
":",
"name",
"=",
"self",
".",
"SearchVar",
".",
"get",
"(",
")",
"if",
"self",
".",
"kbos",
".",
"has_key",
"(",
"name",
")",
":",
"kbo",
"=",
"self",
".",
"kbos",
"[",
"name",
"]",
"assert",
"isinstance",
"(... | Move to the position of self.SearchVar | [
"Move",
"to",
"the",
"position",
"of",
"self",
".",
"SearchVar"
] | 94f91d32ad5ec081d5a1ebd67604a838003465af | https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/planning/obs_planner.py#L475-L488 | train | 47,827 |
OSSOS/MOP | src/ossos/core/ossos/planning/obs_planner.py | Plot.create_point | def create_point(self, xcen, ycen, size=10, color='red', fill=None):
"""Plot a circle of size at this x,y location"""
if fill is None:
fill = color
(x, y) = self.p2c((xcen, ycen))
x1 = x - size
x2 = x + size
y1 = y - size
y2 = y + size
self.create_rectangle(x1, y1, x2, y2, fill=fill, outline=color) | python | def create_point(self, xcen, ycen, size=10, color='red', fill=None):
"""Plot a circle of size at this x,y location"""
if fill is None:
fill = color
(x, y) = self.p2c((xcen, ycen))
x1 = x - size
x2 = x + size
y1 = y - size
y2 = y + size
self.create_rectangle(x1, y1, x2, y2, fill=fill, outline=color) | [
"def",
"create_point",
"(",
"self",
",",
"xcen",
",",
"ycen",
",",
"size",
"=",
"10",
",",
"color",
"=",
"'red'",
",",
"fill",
"=",
"None",
")",
":",
"if",
"fill",
"is",
"None",
":",
"fill",
"=",
"color",
"(",
"x",
",",
"y",
")",
"=",
"self",
... | Plot a circle of size at this x,y location | [
"Plot",
"a",
"circle",
"of",
"size",
"at",
"this",
"x",
"y",
"location"
] | 94f91d32ad5ec081d5a1ebd67604a838003465af | https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/planning/obs_planner.py#L559-L570 | train | 47,828 |
OSSOS/MOP | src/ossos/core/ossos/planning/obs_planner.py | Plot.current_pointing | def current_pointing(self, index):
"""set the color of the currently selected pointing to 'blue'"""
if self.current is not None:
for item in self.pointings[self.current]['items']:
self.itemconfigure(item, outline="black")
self.current = index
for item in self.pointings[self.current]['items']:
self.itemconfigure(item, outline="blue") | python | def current_pointing(self, index):
"""set the color of the currently selected pointing to 'blue'"""
if self.current is not None:
for item in self.pointings[self.current]['items']:
self.itemconfigure(item, outline="black")
self.current = index
for item in self.pointings[self.current]['items']:
self.itemconfigure(item, outline="blue") | [
"def",
"current_pointing",
"(",
"self",
",",
"index",
")",
":",
"if",
"self",
".",
"current",
"is",
"not",
"None",
":",
"for",
"item",
"in",
"self",
".",
"pointings",
"[",
"self",
".",
"current",
"]",
"[",
"'items'",
"]",
":",
"self",
".",
"itemconfi... | set the color of the currently selected pointing to 'blue | [
"set",
"the",
"color",
"of",
"the",
"currently",
"selected",
"pointing",
"to",
"blue"
] | 94f91d32ad5ec081d5a1ebd67604a838003465af | https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/planning/obs_planner.py#L572-L579 | train | 47,829 |
OSSOS/MOP | src/ossos/core/ossos/planning/obs_planner.py | Plot.delete_pointing | def delete_pointing(self, event):
"""Delete the currently active pointing"""
if self.current is None:
return
for item in self.pointings[self.current]['items']:
self.delete(item)
self.delete(self.pointings[self.current]['label']['id'])
del (self.pointings[self.current])
self.current = None | python | def delete_pointing(self, event):
"""Delete the currently active pointing"""
if self.current is None:
return
for item in self.pointings[self.current]['items']:
self.delete(item)
self.delete(self.pointings[self.current]['label']['id'])
del (self.pointings[self.current])
self.current = None | [
"def",
"delete_pointing",
"(",
"self",
",",
"event",
")",
":",
"if",
"self",
".",
"current",
"is",
"None",
":",
"return",
"for",
"item",
"in",
"self",
".",
"pointings",
"[",
"self",
".",
"current",
"]",
"[",
"'items'",
"]",
":",
"self",
".",
"delete"... | Delete the currently active pointing | [
"Delete",
"the",
"currently",
"active",
"pointing"
] | 94f91d32ad5ec081d5a1ebd67604a838003465af | https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/planning/obs_planner.py#L581-L591 | train | 47,830 |
OSSOS/MOP | src/ossos/core/ossos/planning/obs_planner.py | Plot.create_pointing | def create_pointing(self, event, label_text=None):
"""Plot the sky coverage of pointing at event.x,event.y on the canvas.
"""
x = self.canvasx(event.x)
y = self.canvasy(event.y)
(ra, dec) = self.c2p((x, y))
this_camera = Camera(ra=float(ra) * units.radian, dec=float(dec)*units.radian, camera=self.camera.get())
ccds = numpy.radians(numpy.array(this_camera.geometry))
items = []
for ccd in ccds:
if len(ccd) == 4:
(x1, y1) = self.p2c((ccd[0], ccd[1]))
(x2, y2) = self.p2c((ccd[2], ccd[3]))
item = self.create_rectangle(x1, y1, x2, y2, stipple='gray25', fill=None)
else:
(x1, y1) = self.p2c((ccd[0] - ccd[2], ccd[1] - ccd[2]))
(x2, y2) = self.p2c((ccd[0] + ccd[2], ccd[1] + ccd[2]))
item = self.create_oval(x1, y1, x2, y2)
items.append(item)
label = {}
if label_text is None:
label_text = self.plabel.get()
label['text'] = label_text
label['id'] = self.label(this_camera.ra.radian, this_camera.dec.radian, label['text'])
self.pointings.append({
"label": label,
"items": items,
"camera": this_camera})
self.current = len(self.pointings) - 1
self.current_pointing(len(self.pointings) - 1) | python | def create_pointing(self, event, label_text=None):
"""Plot the sky coverage of pointing at event.x,event.y on the canvas.
"""
x = self.canvasx(event.x)
y = self.canvasy(event.y)
(ra, dec) = self.c2p((x, y))
this_camera = Camera(ra=float(ra) * units.radian, dec=float(dec)*units.radian, camera=self.camera.get())
ccds = numpy.radians(numpy.array(this_camera.geometry))
items = []
for ccd in ccds:
if len(ccd) == 4:
(x1, y1) = self.p2c((ccd[0], ccd[1]))
(x2, y2) = self.p2c((ccd[2], ccd[3]))
item = self.create_rectangle(x1, y1, x2, y2, stipple='gray25', fill=None)
else:
(x1, y1) = self.p2c((ccd[0] - ccd[2], ccd[1] - ccd[2]))
(x2, y2) = self.p2c((ccd[0] + ccd[2], ccd[1] + ccd[2]))
item = self.create_oval(x1, y1, x2, y2)
items.append(item)
label = {}
if label_text is None:
label_text = self.plabel.get()
label['text'] = label_text
label['id'] = self.label(this_camera.ra.radian, this_camera.dec.radian, label['text'])
self.pointings.append({
"label": label,
"items": items,
"camera": this_camera})
self.current = len(self.pointings) - 1
self.current_pointing(len(self.pointings) - 1) | [
"def",
"create_pointing",
"(",
"self",
",",
"event",
",",
"label_text",
"=",
"None",
")",
":",
"x",
"=",
"self",
".",
"canvasx",
"(",
"event",
".",
"x",
")",
"y",
"=",
"self",
".",
"canvasy",
"(",
"event",
".",
"y",
")",
"(",
"ra",
",",
"dec",
... | Plot the sky coverage of pointing at event.x,event.y on the canvas. | [
"Plot",
"the",
"sky",
"coverage",
"of",
"pointing",
"at",
"event",
".",
"x",
"event",
".",
"y",
"on",
"the",
"canvas",
"."
] | 94f91d32ad5ec081d5a1ebd67604a838003465af | https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/planning/obs_planner.py#L715-L746 | train | 47,831 |
OSSOS/MOP | src/ossos/core/ossos/planning/obs_planner.py | Plot.move_pointing | def move_pointing(self, event):
"""Grab nearest pointing to event.x,event.y and with cursor"""
(ra, dec) = self.c2p((self.canvasx(event.x),
self.canvasy(event.y)))
closest = None
this_pointing = None
this_index = -1
index = -1
for pointing in self.pointings:
index = index + 1
# Find the camera we clicked closest too
ds = pointing["camera"].separation(ra, dec)
if this_pointing is None or ds < closest:
this_index = index
closest = ds
this_pointing = pointing
if this_pointing is None:
return
self.plabel.set(this_pointing['label']['text'])
this_pointing["camera"].set_coord((ra*units.radian, dec*units.radian))
ccds = numpy.radians(this_pointing["camera"].geometry)
items = this_pointing["items"]
label = this_pointing["label"]
(x1, y1) = self.p2c((this_pointing["camera"].ra.radian, this_pointing["camera"].dec.radian))
self.coords(label["id"], x1, y1)
for i in range(len(ccds)):
ccd = ccds[i]
item = items[i]
if len(ccd) == 4:
(x1, y1) = self.p2c((ccd[0], ccd[1]))
(x2, y2) = self.p2c((ccd[2], ccd[3]))
else:
(x1, y1) = self.p2c((ccd[0] - ccd[2]), ccd[1] - ccd[2])
(x2, y2) = self.p2c((ccd[0] + ccd[2]), ccd[1] + ccd[2])
self.coords(item, x1, y1, x2, y2)
self.current_pointing(this_index) | python | def move_pointing(self, event):
"""Grab nearest pointing to event.x,event.y and with cursor"""
(ra, dec) = self.c2p((self.canvasx(event.x),
self.canvasy(event.y)))
closest = None
this_pointing = None
this_index = -1
index = -1
for pointing in self.pointings:
index = index + 1
# Find the camera we clicked closest too
ds = pointing["camera"].separation(ra, dec)
if this_pointing is None or ds < closest:
this_index = index
closest = ds
this_pointing = pointing
if this_pointing is None:
return
self.plabel.set(this_pointing['label']['text'])
this_pointing["camera"].set_coord((ra*units.radian, dec*units.radian))
ccds = numpy.radians(this_pointing["camera"].geometry)
items = this_pointing["items"]
label = this_pointing["label"]
(x1, y1) = self.p2c((this_pointing["camera"].ra.radian, this_pointing["camera"].dec.radian))
self.coords(label["id"], x1, y1)
for i in range(len(ccds)):
ccd = ccds[i]
item = items[i]
if len(ccd) == 4:
(x1, y1) = self.p2c((ccd[0], ccd[1]))
(x2, y2) = self.p2c((ccd[2], ccd[3]))
else:
(x1, y1) = self.p2c((ccd[0] - ccd[2]), ccd[1] - ccd[2])
(x2, y2) = self.p2c((ccd[0] + ccd[2]), ccd[1] + ccd[2])
self.coords(item, x1, y1, x2, y2)
self.current_pointing(this_index) | [
"def",
"move_pointing",
"(",
"self",
",",
"event",
")",
":",
"(",
"ra",
",",
"dec",
")",
"=",
"self",
".",
"c2p",
"(",
"(",
"self",
".",
"canvasx",
"(",
"event",
".",
"x",
")",
",",
"self",
".",
"canvasy",
"(",
"event",
".",
"y",
")",
")",
")... | Grab nearest pointing to event.x,event.y and with cursor | [
"Grab",
"nearest",
"pointing",
"to",
"event",
".",
"x",
"event",
".",
"y",
"and",
"with",
"cursor"
] | 94f91d32ad5ec081d5a1ebd67604a838003465af | https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/planning/obs_planner.py#L787-L823 | train | 47,832 |
OSSOS/MOP | src/ossos/core/ossos/planning/obs_planner.py | Plot.ossos_pointings | def ossos_pointings(self):
"""
plot an OSSOS observation on the OSSOS plot.
"""
match = re.match('(\d+)\D(\d+)', self.expnum.get())
if match is not None:
expnum = int(match.group(1))
ccd = int(match.group(2))
x = 2112 / 2.0
y = 4644 / 2.0
else:
expnum = int(str(self.expnum.get()))
ccd = 22
x = 1000
y = 4644 - 15 / 0.185
header = None
try:
header = storage.get_astheader(expnum, ccd=ccd)
except:
if header is None:
print "Didn't get a header... "
return
ossos_wcs = wcs.WCS(header)
(ra, dec) = ossos_wcs.xy2sky(x, y)
class MyEvent(object):
def __init__(self, x, y):
self.x = x
self.y = y
(x, y) = self.p2s((math.radians(ra), math.radians(dec)))
event = MyEvent(x, y)
self.create_pointing(event, label_text=header['OBJECT'] + ' ccd{}'.format(ccd)) | python | def ossos_pointings(self):
"""
plot an OSSOS observation on the OSSOS plot.
"""
match = re.match('(\d+)\D(\d+)', self.expnum.get())
if match is not None:
expnum = int(match.group(1))
ccd = int(match.group(2))
x = 2112 / 2.0
y = 4644 / 2.0
else:
expnum = int(str(self.expnum.get()))
ccd = 22
x = 1000
y = 4644 - 15 / 0.185
header = None
try:
header = storage.get_astheader(expnum, ccd=ccd)
except:
if header is None:
print "Didn't get a header... "
return
ossos_wcs = wcs.WCS(header)
(ra, dec) = ossos_wcs.xy2sky(x, y)
class MyEvent(object):
def __init__(self, x, y):
self.x = x
self.y = y
(x, y) = self.p2s((math.radians(ra), math.radians(dec)))
event = MyEvent(x, y)
self.create_pointing(event, label_text=header['OBJECT'] + ' ccd{}'.format(ccd)) | [
"def",
"ossos_pointings",
"(",
"self",
")",
":",
"match",
"=",
"re",
".",
"match",
"(",
"'(\\d+)\\D(\\d+)'",
",",
"self",
".",
"expnum",
".",
"get",
"(",
")",
")",
"if",
"match",
"is",
"not",
"None",
":",
"expnum",
"=",
"int",
"(",
"match",
".",
"g... | plot an OSSOS observation on the OSSOS plot. | [
"plot",
"an",
"OSSOS",
"observation",
"on",
"the",
"OSSOS",
"plot",
"."
] | 94f91d32ad5ec081d5a1ebd67604a838003465af | https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/planning/obs_planner.py#L831-L864 | train | 47,833 |
OSSOS/MOP | src/ossos/core/ossos/planning/obs_planner.py | Plot.get_pointings | def get_pointings(self):
"""
Retrieve the MEGACAM pointings that overlap with the current FOV and plot.
@return: None
"""
self.camera.set("MEGACAM_40")
(ra1, dec1) = self.c2p((self.canvasx(1), self.canvasy(1)))
(ra2, dec2) = self.c2p((self.canvasx(480 * 2), self.canvasy(360 * 2)))
ra_cen = math.degrees((ra2 + ra1) / 2.0)
dec_cen = math.degrees((dec2 + dec1) / 2.0)
# width = math.degrees(math.fabs(ra1 - ra2))
width = 180
# height = math.degrees(math.fabs(dec2 - dec1))
height = 90
date = mpc.Time(self.date.get(), scale='utc').iso
table = cadc.cfht_megacam_tap_query(ra_cen, dec_cen, width, height, date=date)
for row in table:
ra = row['RAJ2000']
dec = row['DEJ2000']
(x, y) = self.p2s((math.radians(ra), math.radians(dec)))
event = MyEvent(x, y)
self.create_pointing(event, label_text="") | python | def get_pointings(self):
"""
Retrieve the MEGACAM pointings that overlap with the current FOV and plot.
@return: None
"""
self.camera.set("MEGACAM_40")
(ra1, dec1) = self.c2p((self.canvasx(1), self.canvasy(1)))
(ra2, dec2) = self.c2p((self.canvasx(480 * 2), self.canvasy(360 * 2)))
ra_cen = math.degrees((ra2 + ra1) / 2.0)
dec_cen = math.degrees((dec2 + dec1) / 2.0)
# width = math.degrees(math.fabs(ra1 - ra2))
width = 180
# height = math.degrees(math.fabs(dec2 - dec1))
height = 90
date = mpc.Time(self.date.get(), scale='utc').iso
table = cadc.cfht_megacam_tap_query(ra_cen, dec_cen, width, height, date=date)
for row in table:
ra = row['RAJ2000']
dec = row['DEJ2000']
(x, y) = self.p2s((math.radians(ra), math.radians(dec)))
event = MyEvent(x, y)
self.create_pointing(event, label_text="") | [
"def",
"get_pointings",
"(",
"self",
")",
":",
"self",
".",
"camera",
".",
"set",
"(",
"\"MEGACAM_40\"",
")",
"(",
"ra1",
",",
"dec1",
")",
"=",
"self",
".",
"c2p",
"(",
"(",
"self",
".",
"canvasx",
"(",
"1",
")",
",",
"self",
".",
"canvasy",
"("... | Retrieve the MEGACAM pointings that overlap with the current FOV and plot.
@return: None | [
"Retrieve",
"the",
"MEGACAM",
"pointings",
"that",
"overlap",
"with",
"the",
"current",
"FOV",
"and",
"plot",
"."
] | 94f91d32ad5ec081d5a1ebd67604a838003465af | https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/planning/obs_planner.py#L867-L891 | train | 47,834 |
OSSOS/MOP | src/ossos/core/ossos/planning/obs_planner.py | Plot.doplot | def doplot(self):
"""
Clear the plot and then redraw it.
"""
w = self
w.delete(ALL)
w.coord_grid()
w.objList.delete(0, END)
self._plot() | python | def doplot(self):
"""
Clear the plot and then redraw it.
"""
w = self
w.delete(ALL)
w.coord_grid()
w.objList.delete(0, END)
self._plot() | [
"def",
"doplot",
"(",
"self",
")",
":",
"w",
"=",
"self",
"w",
".",
"delete",
"(",
"ALL",
")",
"w",
".",
"coord_grid",
"(",
")",
"w",
".",
"objList",
".",
"delete",
"(",
"0",
",",
"END",
")",
"self",
".",
"_plot",
"(",
")"
] | Clear the plot and then redraw it. | [
"Clear",
"the",
"plot",
"and",
"then",
"redraw",
"it",
"."
] | 94f91d32ad5ec081d5a1ebd67604a838003465af | https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/planning/obs_planner.py#L1060-L1069 | train | 47,835 |
OSSOS/MOP | src/jjk/preproc/MOPcoord.py | coord.ec2eq | def ec2eq(self):
"""Convert ecliptic coordinates to equatorial coordinates"""
import math
#from numpy.matlib import sin, cos, arcsin, arctan2
from math import sin, cos
from math import asin as arcsin
from math import atan2 as arctan2
from math import acos as arccos
eb=self.eb
el=self.el
ob=math.radians(23.439281)
dec = arcsin(sin(eb)*cos(ob)+cos(eb)*sin(ob)*sin(el))
sra = (sin(dec)*cos(ob)-sin(eb))/(cos(dec)*sin(ob))
cra = cos(el)*cos(eb)/cos(dec)
if sra < 1 and sra > -1 :
sa= arcsin(sra)
else:
sa = 0
ca= arccos(cra)
tsa=sa
tca=ca
if tsa<0 :
ca=2.0*math.pi-ca
if tca>=math.pi/2.0:
sa=math.pi-sa
if ca >= math.pi*2.0:
ca=ca-math.pi*2.0
self.tsa=sra
self.tca=cra
self.ra=ca
self.dec=dec | python | def ec2eq(self):
"""Convert ecliptic coordinates to equatorial coordinates"""
import math
#from numpy.matlib import sin, cos, arcsin, arctan2
from math import sin, cos
from math import asin as arcsin
from math import atan2 as arctan2
from math import acos as arccos
eb=self.eb
el=self.el
ob=math.radians(23.439281)
dec = arcsin(sin(eb)*cos(ob)+cos(eb)*sin(ob)*sin(el))
sra = (sin(dec)*cos(ob)-sin(eb))/(cos(dec)*sin(ob))
cra = cos(el)*cos(eb)/cos(dec)
if sra < 1 and sra > -1 :
sa= arcsin(sra)
else:
sa = 0
ca= arccos(cra)
tsa=sa
tca=ca
if tsa<0 :
ca=2.0*math.pi-ca
if tca>=math.pi/2.0:
sa=math.pi-sa
if ca >= math.pi*2.0:
ca=ca-math.pi*2.0
self.tsa=sra
self.tca=cra
self.ra=ca
self.dec=dec | [
"def",
"ec2eq",
"(",
"self",
")",
":",
"import",
"math",
"#from numpy.matlib import sin, cos, arcsin, arctan2",
"from",
"math",
"import",
"sin",
",",
"cos",
"from",
"math",
"import",
"asin",
"as",
"arcsin",
"from",
"math",
"import",
"atan2",
"as",
"arctan2",
"fr... | Convert ecliptic coordinates to equatorial coordinates | [
"Convert",
"ecliptic",
"coordinates",
"to",
"equatorial",
"coordinates"
] | 94f91d32ad5ec081d5a1ebd67604a838003465af | https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/jjk/preproc/MOPcoord.py#L100-L134 | train | 47,836 |
OSSOS/MOP | src/ossos/core/ossos/planning/layout36.py | plot_line | def plot_line(axes, fname, ltype):
"""plot the ecliptic plane line on the given axes."""
x = np.genfromtxt(fname, unpack=True)
axes.plot(x[0], x[1], ltype) | python | def plot_line(axes, fname, ltype):
"""plot the ecliptic plane line on the given axes."""
x = np.genfromtxt(fname, unpack=True)
axes.plot(x[0], x[1], ltype) | [
"def",
"plot_line",
"(",
"axes",
",",
"fname",
",",
"ltype",
")",
":",
"x",
"=",
"np",
".",
"genfromtxt",
"(",
"fname",
",",
"unpack",
"=",
"True",
")",
"axes",
".",
"plot",
"(",
"x",
"[",
"0",
"]",
",",
"x",
"[",
"1",
"]",
",",
"ltype",
")"
... | plot the ecliptic plane line on the given axes. | [
"plot",
"the",
"ecliptic",
"plane",
"line",
"on",
"the",
"given",
"axes",
"."
] | 94f91d32ad5ec081d5a1ebd67604a838003465af | https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/planning/layout36.py#L28-L31 | train | 47,837 |
OSSOS/MOP | src/ossos/core/ossos/parameters.py | apmag_at_absmag | def apmag_at_absmag(H, d, phi=1):
"""
Calculate the apparent magnitude of a TNO given its absolute magnitude H, for a given distance.
:param H: TNO absolute magnitude (unitless)
:param d: barycentric distance (AU)
:param phi: phase angle (0-1, always v close to 1 for TNOs)
:return: apparent magnitude of TNO
"""
d_observer = 1. # 1 AU
# approximate object's distance d_heliocentric and d_geocentric as the same, d, because TNO
m_r = H + 2.5 * math.log10((d ** 4) / (phi * d_observer ** 4))
print("m_r = {:2.2f} for a H = {} TNO at {} AU at opposition.".format(
m_r, H, d))
return m_r | python | def apmag_at_absmag(H, d, phi=1):
"""
Calculate the apparent magnitude of a TNO given its absolute magnitude H, for a given distance.
:param H: TNO absolute magnitude (unitless)
:param d: barycentric distance (AU)
:param phi: phase angle (0-1, always v close to 1 for TNOs)
:return: apparent magnitude of TNO
"""
d_observer = 1. # 1 AU
# approximate object's distance d_heliocentric and d_geocentric as the same, d, because TNO
m_r = H + 2.5 * math.log10((d ** 4) / (phi * d_observer ** 4))
print("m_r = {:2.2f} for a H = {} TNO at {} AU at opposition.".format(
m_r, H, d))
return m_r | [
"def",
"apmag_at_absmag",
"(",
"H",
",",
"d",
",",
"phi",
"=",
"1",
")",
":",
"d_observer",
"=",
"1.",
"# 1 AU",
"# approximate object's distance d_heliocentric and d_geocentric as the same, d, because TNO",
"m_r",
"=",
"H",
"+",
"2.5",
"*",
"math",
".",
"log10",
... | Calculate the apparent magnitude of a TNO given its absolute magnitude H, for a given distance.
:param H: TNO absolute magnitude (unitless)
:param d: barycentric distance (AU)
:param phi: phase angle (0-1, always v close to 1 for TNOs)
:return: apparent magnitude of TNO | [
"Calculate",
"the",
"apparent",
"magnitude",
"of",
"a",
"TNO",
"given",
"its",
"absolute",
"magnitude",
"H",
"for",
"a",
"given",
"distance",
"."
] | 94f91d32ad5ec081d5a1ebd67604a838003465af | https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/parameters.py#L357-L371 | train | 47,838 |
openstack/python-scciclient | scciclient/irmc/scci.py | scci_cmd | def scci_cmd(host, userid, password, cmd, port=443, auth_method='basic',
client_timeout=60, do_async=True, **kwargs):
"""execute SCCI command
This function calls SCCI server modules
:param host: hostname or IP of iRMC
:param userid: userid for iRMC with administrator privileges
:param password: password for userid
:param cmd: SCCI command
:param port: port number of iRMC
:param auth_method: irmc_username
:param client_timeout: timeout for SCCI operations
:param do_async: async call if True, sync call otherwise
:returns: requests.Response from SCCI server
:raises: SCCIInvalidInputError if port and/or auth_method params
are invalid
:raises: SCCIClientError if SCCI failed
"""
auth_obj = None
try:
protocol = {80: 'http', 443: 'https'}[port]
auth_obj = {
'basic': requests.auth.HTTPBasicAuth(userid, password),
'digest': requests.auth.HTTPDigestAuth(userid, password)
}[auth_method.lower()]
except KeyError:
raise SCCIInvalidInputError(
("Invalid port %(port)d or " +
"auth_method for method %(auth_method)s") %
{'port': port, 'auth_method': auth_method})
try:
header = {'Content-type': 'application/x-www-form-urlencoded'}
if kwargs.get('upgrade_type') == 'irmc':
with open(cmd, 'rb') as file:
data = file.read()
config_type = '/irmcupdate?flashSelect=255'
elif kwargs.get('upgrade_type') == 'bios':
with open(cmd, 'rb') as file:
data = file.read()
config_type = '/biosupdate'
else:
data = cmd
config_type = '/config'
r = requests.post(protocol + '://' + host + config_type,
data=data,
headers=header,
verify=False,
timeout=client_timeout,
allow_redirects=False,
auth=auth_obj)
if not do_async:
time.sleep(5)
if DEBUG:
print(cmd)
print(r.text)
print("do_async = %s" % do_async)
if r.status_code not in (200, 201):
raise SCCIClientError(
('HTTP PROTOCOL ERROR, STATUS CODE = %s' %
str(r.status_code)))
result_xml = ET.fromstring(r.text)
status = result_xml.find("./Value")
# severity = result_xml.find("./Severity")
error = result_xml.find("./Error")
message = result_xml.find("./Message")
if not int(status.text) == 0:
raise SCCIClientError(
('SCCI PROTOCOL ERROR, STATUS CODE = %s, '
'ERROR = %s, MESSAGE = %s' %
(str(status.text), error.text, message.text)))
else:
return r
except IOError as input_error:
raise SCCIClientError(input_error)
except ET.ParseError as parse_error:
raise SCCIClientError(parse_error)
except requests.exceptions.RequestException as requests_exception:
raise SCCIClientError(requests_exception) | python | def scci_cmd(host, userid, password, cmd, port=443, auth_method='basic',
client_timeout=60, do_async=True, **kwargs):
"""execute SCCI command
This function calls SCCI server modules
:param host: hostname or IP of iRMC
:param userid: userid for iRMC with administrator privileges
:param password: password for userid
:param cmd: SCCI command
:param port: port number of iRMC
:param auth_method: irmc_username
:param client_timeout: timeout for SCCI operations
:param do_async: async call if True, sync call otherwise
:returns: requests.Response from SCCI server
:raises: SCCIInvalidInputError if port and/or auth_method params
are invalid
:raises: SCCIClientError if SCCI failed
"""
auth_obj = None
try:
protocol = {80: 'http', 443: 'https'}[port]
auth_obj = {
'basic': requests.auth.HTTPBasicAuth(userid, password),
'digest': requests.auth.HTTPDigestAuth(userid, password)
}[auth_method.lower()]
except KeyError:
raise SCCIInvalidInputError(
("Invalid port %(port)d or " +
"auth_method for method %(auth_method)s") %
{'port': port, 'auth_method': auth_method})
try:
header = {'Content-type': 'application/x-www-form-urlencoded'}
if kwargs.get('upgrade_type') == 'irmc':
with open(cmd, 'rb') as file:
data = file.read()
config_type = '/irmcupdate?flashSelect=255'
elif kwargs.get('upgrade_type') == 'bios':
with open(cmd, 'rb') as file:
data = file.read()
config_type = '/biosupdate'
else:
data = cmd
config_type = '/config'
r = requests.post(protocol + '://' + host + config_type,
data=data,
headers=header,
verify=False,
timeout=client_timeout,
allow_redirects=False,
auth=auth_obj)
if not do_async:
time.sleep(5)
if DEBUG:
print(cmd)
print(r.text)
print("do_async = %s" % do_async)
if r.status_code not in (200, 201):
raise SCCIClientError(
('HTTP PROTOCOL ERROR, STATUS CODE = %s' %
str(r.status_code)))
result_xml = ET.fromstring(r.text)
status = result_xml.find("./Value")
# severity = result_xml.find("./Severity")
error = result_xml.find("./Error")
message = result_xml.find("./Message")
if not int(status.text) == 0:
raise SCCIClientError(
('SCCI PROTOCOL ERROR, STATUS CODE = %s, '
'ERROR = %s, MESSAGE = %s' %
(str(status.text), error.text, message.text)))
else:
return r
except IOError as input_error:
raise SCCIClientError(input_error)
except ET.ParseError as parse_error:
raise SCCIClientError(parse_error)
except requests.exceptions.RequestException as requests_exception:
raise SCCIClientError(requests_exception) | [
"def",
"scci_cmd",
"(",
"host",
",",
"userid",
",",
"password",
",",
"cmd",
",",
"port",
"=",
"443",
",",
"auth_method",
"=",
"'basic'",
",",
"client_timeout",
"=",
"60",
",",
"do_async",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"auth_obj",
"=... | execute SCCI command
This function calls SCCI server modules
:param host: hostname or IP of iRMC
:param userid: userid for iRMC with administrator privileges
:param password: password for userid
:param cmd: SCCI command
:param port: port number of iRMC
:param auth_method: irmc_username
:param client_timeout: timeout for SCCI operations
:param do_async: async call if True, sync call otherwise
:returns: requests.Response from SCCI server
:raises: SCCIInvalidInputError if port and/or auth_method params
are invalid
:raises: SCCIClientError if SCCI failed | [
"execute",
"SCCI",
"command"
] | 4585ce2f76853b9773fb190ca0cfff0aa04a7cf8 | https://github.com/openstack/python-scciclient/blob/4585ce2f76853b9773fb190ca0cfff0aa04a7cf8/scciclient/irmc/scci.py#L249-L333 | train | 47,839 |
openstack/python-scciclient | scciclient/irmc/scci.py | get_client | def get_client(host, userid, password, port=443, auth_method='basic',
client_timeout=60, **kwargs):
"""get SCCI command partial function
This function returns SCCI command partial function
:param host: hostname or IP of iRMC
:param userid: userid for iRMC with administrator privileges
:param password: password for userid
:param port: port number of iRMC
:param auth_method: irmc_username
:param client_timeout: timeout for SCCI operations
:returns: scci_cmd partial function which takes a SCCI command param
"""
return functools.partial(scci_cmd, host, userid, password,
port=port, auth_method=auth_method,
client_timeout=client_timeout, **kwargs) | python | def get_client(host, userid, password, port=443, auth_method='basic',
client_timeout=60, **kwargs):
"""get SCCI command partial function
This function returns SCCI command partial function
:param host: hostname or IP of iRMC
:param userid: userid for iRMC with administrator privileges
:param password: password for userid
:param port: port number of iRMC
:param auth_method: irmc_username
:param client_timeout: timeout for SCCI operations
:returns: scci_cmd partial function which takes a SCCI command param
"""
return functools.partial(scci_cmd, host, userid, password,
port=port, auth_method=auth_method,
client_timeout=client_timeout, **kwargs) | [
"def",
"get_client",
"(",
"host",
",",
"userid",
",",
"password",
",",
"port",
"=",
"443",
",",
"auth_method",
"=",
"'basic'",
",",
"client_timeout",
"=",
"60",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"functools",
".",
"partial",
"(",
"scci_cmd",
... | get SCCI command partial function
This function returns SCCI command partial function
:param host: hostname or IP of iRMC
:param userid: userid for iRMC with administrator privileges
:param password: password for userid
:param port: port number of iRMC
:param auth_method: irmc_username
:param client_timeout: timeout for SCCI operations
:returns: scci_cmd partial function which takes a SCCI command param | [
"get",
"SCCI",
"command",
"partial",
"function"
] | 4585ce2f76853b9773fb190ca0cfff0aa04a7cf8 | https://github.com/openstack/python-scciclient/blob/4585ce2f76853b9773fb190ca0cfff0aa04a7cf8/scciclient/irmc/scci.py#L336-L352 | train | 47,840 |
openstack/python-scciclient | scciclient/irmc/scci.py | get_virtual_cd_set_params_cmd | def get_virtual_cd_set_params_cmd(remote_image_server,
remote_image_user_domain,
remote_image_share_type,
remote_image_share_name,
remote_image_deploy_iso,
remote_image_username,
remote_image_user_password):
"""get Virtual CD Media Set Parameters Command
This function returns Virtual CD Media Set Parameters Command
:param remote_image_server: remote image server name or IP
:param remote_image_user_domain: domain name of remote image server
:param remote_image_share_type: share type of ShareType
:param remote_image_share_name: share name
:param remote_image_deploy_iso: deploy ISO image file name
:param remote_image_username: username of remote image server
:param remote_image_user_password: password of the username
:returns: SCCI command
"""
cmd = _VIRTUAL_MEDIA_CD_SETTINGS % (
remote_image_server,
remote_image_user_domain,
remote_image_share_type,
remote_image_share_name,
remote_image_deploy_iso,
remote_image_username,
remote_image_user_password)
return cmd | python | def get_virtual_cd_set_params_cmd(remote_image_server,
remote_image_user_domain,
remote_image_share_type,
remote_image_share_name,
remote_image_deploy_iso,
remote_image_username,
remote_image_user_password):
"""get Virtual CD Media Set Parameters Command
This function returns Virtual CD Media Set Parameters Command
:param remote_image_server: remote image server name or IP
:param remote_image_user_domain: domain name of remote image server
:param remote_image_share_type: share type of ShareType
:param remote_image_share_name: share name
:param remote_image_deploy_iso: deploy ISO image file name
:param remote_image_username: username of remote image server
:param remote_image_user_password: password of the username
:returns: SCCI command
"""
cmd = _VIRTUAL_MEDIA_CD_SETTINGS % (
remote_image_server,
remote_image_user_domain,
remote_image_share_type,
remote_image_share_name,
remote_image_deploy_iso,
remote_image_username,
remote_image_user_password)
return cmd | [
"def",
"get_virtual_cd_set_params_cmd",
"(",
"remote_image_server",
",",
"remote_image_user_domain",
",",
"remote_image_share_type",
",",
"remote_image_share_name",
",",
"remote_image_deploy_iso",
",",
"remote_image_username",
",",
"remote_image_user_password",
")",
":",
"cmd",
... | get Virtual CD Media Set Parameters Command
This function returns Virtual CD Media Set Parameters Command
:param remote_image_server: remote image server name or IP
:param remote_image_user_domain: domain name of remote image server
:param remote_image_share_type: share type of ShareType
:param remote_image_share_name: share name
:param remote_image_deploy_iso: deploy ISO image file name
:param remote_image_username: username of remote image server
:param remote_image_user_password: password of the username
:returns: SCCI command | [
"get",
"Virtual",
"CD",
"Media",
"Set",
"Parameters",
"Command"
] | 4585ce2f76853b9773fb190ca0cfff0aa04a7cf8 | https://github.com/openstack/python-scciclient/blob/4585ce2f76853b9773fb190ca0cfff0aa04a7cf8/scciclient/irmc/scci.py#L355-L384 | train | 47,841 |
openstack/python-scciclient | scciclient/irmc/scci.py | get_virtual_fd_set_params_cmd | def get_virtual_fd_set_params_cmd(remote_image_server,
remote_image_user_domain,
remote_image_share_type,
remote_image_share_name,
remote_image_floppy_fat,
remote_image_username,
remote_image_user_password):
"""get Virtual FD Media Set Parameters Command
This function returns Virtual FD Media Set Parameters Command
:param remote_image_server: remote image server name or IP
:param remote_image_user_domain: domain name of remote image server
:param remote_image_share_type: share type of ShareType
:param remote_image_share_name: share name
:param remote_image_deploy_iso: deploy ISO image file name
:param remote_image_username: username of remote image server
:param remote_image_user_password: password of the username
:returns: SCCI command
"""
cmd = _VIRTUAL_MEDIA_FD_SETTINGS % (
remote_image_server,
remote_image_user_domain,
remote_image_share_type,
remote_image_share_name,
remote_image_floppy_fat,
remote_image_username,
remote_image_user_password)
return cmd | python | def get_virtual_fd_set_params_cmd(remote_image_server,
remote_image_user_domain,
remote_image_share_type,
remote_image_share_name,
remote_image_floppy_fat,
remote_image_username,
remote_image_user_password):
"""get Virtual FD Media Set Parameters Command
This function returns Virtual FD Media Set Parameters Command
:param remote_image_server: remote image server name or IP
:param remote_image_user_domain: domain name of remote image server
:param remote_image_share_type: share type of ShareType
:param remote_image_share_name: share name
:param remote_image_deploy_iso: deploy ISO image file name
:param remote_image_username: username of remote image server
:param remote_image_user_password: password of the username
:returns: SCCI command
"""
cmd = _VIRTUAL_MEDIA_FD_SETTINGS % (
remote_image_server,
remote_image_user_domain,
remote_image_share_type,
remote_image_share_name,
remote_image_floppy_fat,
remote_image_username,
remote_image_user_password)
return cmd | [
"def",
"get_virtual_fd_set_params_cmd",
"(",
"remote_image_server",
",",
"remote_image_user_domain",
",",
"remote_image_share_type",
",",
"remote_image_share_name",
",",
"remote_image_floppy_fat",
",",
"remote_image_username",
",",
"remote_image_user_password",
")",
":",
"cmd",
... | get Virtual FD Media Set Parameters Command
This function returns Virtual FD Media Set Parameters Command
:param remote_image_server: remote image server name or IP
:param remote_image_user_domain: domain name of remote image server
:param remote_image_share_type: share type of ShareType
:param remote_image_share_name: share name
:param remote_image_deploy_iso: deploy ISO image file name
:param remote_image_username: username of remote image server
:param remote_image_user_password: password of the username
:returns: SCCI command | [
"get",
"Virtual",
"FD",
"Media",
"Set",
"Parameters",
"Command"
] | 4585ce2f76853b9773fb190ca0cfff0aa04a7cf8 | https://github.com/openstack/python-scciclient/blob/4585ce2f76853b9773fb190ca0cfff0aa04a7cf8/scciclient/irmc/scci.py#L387-L415 | train | 47,842 |
openstack/python-scciclient | scciclient/irmc/scci.py | get_report | def get_report(host, userid, password,
port=443, auth_method='basic', client_timeout=60):
"""get iRMC report
This function returns iRMC report in XML format
:param host: hostname or IP of iRMC
:param userid: userid for iRMC with administrator privileges
:param password: password for userid
:param port: port number of iRMC
:param auth_method: irmc_username
:param client_timeout: timeout for SCCI operations
:returns: root element of SCCI report
:raises: ISCCIInvalidInputError if port and/or auth_method params
are invalid
:raises: SCCIClientError if SCCI failed
"""
auth_obj = None
try:
protocol = {80: 'http', 443: 'https'}[port]
auth_obj = {
'basic': requests.auth.HTTPBasicAuth(userid, password),
'digest': requests.auth.HTTPDigestAuth(userid, password)
}[auth_method.lower()]
except KeyError:
raise SCCIInvalidInputError(
("Invalid port %(port)d or " +
"auth_method for method %(auth_method)s") %
{'port': port, 'auth_method': auth_method})
try:
r = requests.get(protocol + '://' + host + '/report.xml',
verify=False,
timeout=(10, client_timeout),
allow_redirects=False,
auth=auth_obj)
if r.status_code not in (200, 201):
raise SCCIClientError(
('HTTP PROTOCOL ERROR, STATUS CODE = %s' %
str(r.status_code)))
root = ET.fromstring(r.text)
return root
except ET.ParseError as parse_error:
raise SCCIClientError(parse_error)
except requests.exceptions.RequestException as requests_exception:
raise SCCIClientError(requests_exception) | python | def get_report(host, userid, password,
port=443, auth_method='basic', client_timeout=60):
"""get iRMC report
This function returns iRMC report in XML format
:param host: hostname or IP of iRMC
:param userid: userid for iRMC with administrator privileges
:param password: password for userid
:param port: port number of iRMC
:param auth_method: irmc_username
:param client_timeout: timeout for SCCI operations
:returns: root element of SCCI report
:raises: ISCCIInvalidInputError if port and/or auth_method params
are invalid
:raises: SCCIClientError if SCCI failed
"""
auth_obj = None
try:
protocol = {80: 'http', 443: 'https'}[port]
auth_obj = {
'basic': requests.auth.HTTPBasicAuth(userid, password),
'digest': requests.auth.HTTPDigestAuth(userid, password)
}[auth_method.lower()]
except KeyError:
raise SCCIInvalidInputError(
("Invalid port %(port)d or " +
"auth_method for method %(auth_method)s") %
{'port': port, 'auth_method': auth_method})
try:
r = requests.get(protocol + '://' + host + '/report.xml',
verify=False,
timeout=(10, client_timeout),
allow_redirects=False,
auth=auth_obj)
if r.status_code not in (200, 201):
raise SCCIClientError(
('HTTP PROTOCOL ERROR, STATUS CODE = %s' %
str(r.status_code)))
root = ET.fromstring(r.text)
return root
except ET.ParseError as parse_error:
raise SCCIClientError(parse_error)
except requests.exceptions.RequestException as requests_exception:
raise SCCIClientError(requests_exception) | [
"def",
"get_report",
"(",
"host",
",",
"userid",
",",
"password",
",",
"port",
"=",
"443",
",",
"auth_method",
"=",
"'basic'",
",",
"client_timeout",
"=",
"60",
")",
":",
"auth_obj",
"=",
"None",
"try",
":",
"protocol",
"=",
"{",
"80",
":",
"'http'",
... | get iRMC report
This function returns iRMC report in XML format
:param host: hostname or IP of iRMC
:param userid: userid for iRMC with administrator privileges
:param password: password for userid
:param port: port number of iRMC
:param auth_method: irmc_username
:param client_timeout: timeout for SCCI operations
:returns: root element of SCCI report
:raises: ISCCIInvalidInputError if port and/or auth_method params
are invalid
:raises: SCCIClientError if SCCI failed | [
"get",
"iRMC",
"report"
] | 4585ce2f76853b9773fb190ca0cfff0aa04a7cf8 | https://github.com/openstack/python-scciclient/blob/4585ce2f76853b9773fb190ca0cfff0aa04a7cf8/scciclient/irmc/scci.py#L418-L468 | train | 47,843 |
openstack/python-scciclient | scciclient/irmc/scci.py | get_essential_properties | def get_essential_properties(report, prop_keys):
"""get essential properties
This function returns a dictionary which contains keys as in
prop_keys and its values from the report.
:param report: SCCI report element
:param prop_keys: a list of keys for essential properties
:returns: a dictionary which contains keys as in
prop_keys and its values.
"""
v = {}
v['memory_mb'] = int(report.find('./System/Memory/Installed').text)
v['local_gb'] = sum(
[int(int(size.text) / 1024)
for size in report.findall('.//PhysicalDrive/ConfigurableSize')])
v['cpus'] = sum([int(cpu.find('./CoreNumber').text)
for cpu in report.find('./System/Processor')
if cpu.find('./CoreNumber') is not None])
# v['cpus'] = sum([int(cpu.find('./LogicalCpuNumber').text)
# for cpu in report.find('./System/Processor')])
v['cpu_arch'] = 'x86_64'
return {k: v[k] for k in prop_keys} | python | def get_essential_properties(report, prop_keys):
"""get essential properties
This function returns a dictionary which contains keys as in
prop_keys and its values from the report.
:param report: SCCI report element
:param prop_keys: a list of keys for essential properties
:returns: a dictionary which contains keys as in
prop_keys and its values.
"""
v = {}
v['memory_mb'] = int(report.find('./System/Memory/Installed').text)
v['local_gb'] = sum(
[int(int(size.text) / 1024)
for size in report.findall('.//PhysicalDrive/ConfigurableSize')])
v['cpus'] = sum([int(cpu.find('./CoreNumber').text)
for cpu in report.find('./System/Processor')
if cpu.find('./CoreNumber') is not None])
# v['cpus'] = sum([int(cpu.find('./LogicalCpuNumber').text)
# for cpu in report.find('./System/Processor')])
v['cpu_arch'] = 'x86_64'
return {k: v[k] for k in prop_keys} | [
"def",
"get_essential_properties",
"(",
"report",
",",
"prop_keys",
")",
":",
"v",
"=",
"{",
"}",
"v",
"[",
"'memory_mb'",
"]",
"=",
"int",
"(",
"report",
".",
"find",
"(",
"'./System/Memory/Installed'",
")",
".",
"text",
")",
"v",
"[",
"'local_gb'",
"]"... | get essential properties
This function returns a dictionary which contains keys as in
prop_keys and its values from the report.
:param report: SCCI report element
:param prop_keys: a list of keys for essential properties
:returns: a dictionary which contains keys as in
prop_keys and its values. | [
"get",
"essential",
"properties"
] | 4585ce2f76853b9773fb190ca0cfff0aa04a7cf8 | https://github.com/openstack/python-scciclient/blob/4585ce2f76853b9773fb190ca0cfff0aa04a7cf8/scciclient/irmc/scci.py#L497-L520 | train | 47,844 |
openstack/python-scciclient | scciclient/irmc/scci.py | get_capabilities_properties | def get_capabilities_properties(d_info,
capa_keys,
gpu_ids,
fpga_ids=None,
**kwargs):
"""get capabilities properties
This function returns a dictionary which contains keys
and their values from the report.
:param d_info: the dictionary of ipmitool parameters for accessing a node.
:param capa_keys: a list of keys for additional capabilities properties.
:param gpu_ids: the list of string contains <vendorID>/<deviceID>
for GPU.
:param fpga_ids: the list of string contains <vendorID>/<deviceID>
for CPU FPGA.
:param kwargs: additional arguments passed to scciclient.
:returns: a dictionary which contains keys and their values.
"""
snmp_client = snmp.SNMPClient(d_info['irmc_address'],
d_info['irmc_snmp_port'],
d_info['irmc_snmp_version'],
d_info['irmc_snmp_community'],
d_info['irmc_snmp_security'])
try:
v = {}
if 'rom_firmware_version' in capa_keys:
v['rom_firmware_version'] = \
snmp.get_bios_firmware_version(snmp_client)
if 'irmc_firmware_version' in capa_keys:
v['irmc_firmware_version'] = \
snmp.get_irmc_firmware_version(snmp_client)
if 'server_model' in capa_keys:
v['server_model'] = snmp.get_server_model(snmp_client)
# Sometime the server started but PCI device list building is
# still in progress so system will response error. We have to wait
# for some more seconds.
if kwargs.get('sleep_flag', False) and \
any(k in capa_keys for k in ('pci_gpu_devices', 'cpu_fpga')):
time.sleep(5)
if 'pci_gpu_devices' in capa_keys:
v['pci_gpu_devices'] = ipmi.get_pci_device(d_info, gpu_ids)
if fpga_ids is not None and 'cpu_fpga' in capa_keys:
v['cpu_fpga'] = ipmi.get_pci_device(d_info, fpga_ids)
if 'trusted_boot' in capa_keys:
v['trusted_boot'] = ipmi.get_tpm_status(d_info)
return v
except (snmp.SNMPFailure, ipmi.IPMIFailure) as err:
raise SCCIClientError('Capabilities inspection failed: %s' % err) | python | def get_capabilities_properties(d_info,
capa_keys,
gpu_ids,
fpga_ids=None,
**kwargs):
"""get capabilities properties
This function returns a dictionary which contains keys
and their values from the report.
:param d_info: the dictionary of ipmitool parameters for accessing a node.
:param capa_keys: a list of keys for additional capabilities properties.
:param gpu_ids: the list of string contains <vendorID>/<deviceID>
for GPU.
:param fpga_ids: the list of string contains <vendorID>/<deviceID>
for CPU FPGA.
:param kwargs: additional arguments passed to scciclient.
:returns: a dictionary which contains keys and their values.
"""
snmp_client = snmp.SNMPClient(d_info['irmc_address'],
d_info['irmc_snmp_port'],
d_info['irmc_snmp_version'],
d_info['irmc_snmp_community'],
d_info['irmc_snmp_security'])
try:
v = {}
if 'rom_firmware_version' in capa_keys:
v['rom_firmware_version'] = \
snmp.get_bios_firmware_version(snmp_client)
if 'irmc_firmware_version' in capa_keys:
v['irmc_firmware_version'] = \
snmp.get_irmc_firmware_version(snmp_client)
if 'server_model' in capa_keys:
v['server_model'] = snmp.get_server_model(snmp_client)
# Sometime the server started but PCI device list building is
# still in progress so system will response error. We have to wait
# for some more seconds.
if kwargs.get('sleep_flag', False) and \
any(k in capa_keys for k in ('pci_gpu_devices', 'cpu_fpga')):
time.sleep(5)
if 'pci_gpu_devices' in capa_keys:
v['pci_gpu_devices'] = ipmi.get_pci_device(d_info, gpu_ids)
if fpga_ids is not None and 'cpu_fpga' in capa_keys:
v['cpu_fpga'] = ipmi.get_pci_device(d_info, fpga_ids)
if 'trusted_boot' in capa_keys:
v['trusted_boot'] = ipmi.get_tpm_status(d_info)
return v
except (snmp.SNMPFailure, ipmi.IPMIFailure) as err:
raise SCCIClientError('Capabilities inspection failed: %s' % err) | [
"def",
"get_capabilities_properties",
"(",
"d_info",
",",
"capa_keys",
",",
"gpu_ids",
",",
"fpga_ids",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"snmp_client",
"=",
"snmp",
".",
"SNMPClient",
"(",
"d_info",
"[",
"'irmc_address'",
"]",
",",
"d_info",
... | get capabilities properties
This function returns a dictionary which contains keys
and their values from the report.
:param d_info: the dictionary of ipmitool parameters for accessing a node.
:param capa_keys: a list of keys for additional capabilities properties.
:param gpu_ids: the list of string contains <vendorID>/<deviceID>
for GPU.
:param fpga_ids: the list of string contains <vendorID>/<deviceID>
for CPU FPGA.
:param kwargs: additional arguments passed to scciclient.
:returns: a dictionary which contains keys and their values. | [
"get",
"capabilities",
"properties"
] | 4585ce2f76853b9773fb190ca0cfff0aa04a7cf8 | https://github.com/openstack/python-scciclient/blob/4585ce2f76853b9773fb190ca0cfff0aa04a7cf8/scciclient/irmc/scci.py#L523-L580 | train | 47,845 |
openstack/python-scciclient | scciclient/irmc/scci.py | get_firmware_upgrade_status | def get_firmware_upgrade_status(irmc_info, upgrade_type):
"""get firmware upgrade status of bios or irmc
:param irmc_info: dict of iRMC params to access the server node
{
'irmc_address': host,
'irmc_username': user_id,
'irmc_password': password,
'irmc_port': 80 or 443, default is 443,
'irmc_auth_method': 'basic' or 'digest', default is 'digest',
'irmc_client_timeout': timeout, default is 60,
...
}
:param upgrade_type: flag to check upgrade with bios or irmc
:raises: ISCCIInvalidInputError if port and/or auth_method params
are invalid
:raises: SCCIClientError if SCCI failed
"""
host = irmc_info.get('irmc_address')
userid = irmc_info.get('irmc_username')
password = irmc_info.get('irmc_password')
port = irmc_info.get('irmc_port', 443)
auth_method = irmc_info.get('irmc_auth_method', 'digest')
client_timeout = irmc_info.get('irmc_client_timeout', 60)
auth_obj = None
try:
protocol = {80: 'http', 443: 'https'}[port]
auth_obj = {
'basic': requests.auth.HTTPBasicAuth(userid, password),
'digest': requests.auth.HTTPDigestAuth(userid, password)
}[auth_method.lower()]
except KeyError:
raise SCCIInvalidInputError(
("Invalid port %(port)d or " +
"auth_method for method %(auth_method)s") %
{'port': port, 'auth_method': auth_method})
try:
if upgrade_type == 'bios':
upgrade_type = '/biosprogress'
elif upgrade_type == 'irmc':
upgrade_type = '/irmcprogress'
r = requests.get(protocol + '://' + host + upgrade_type,
verify=False,
timeout=(10, client_timeout),
allow_redirects=False,
auth=auth_obj)
if r.status_code not in (200, 201):
raise SCCIClientError(
('HTTP PROTOCOL ERROR, STATUS CODE = %s' %
str(r.status_code)))
upgrade_status_xml = ET.fromstring(r.text)
return upgrade_status_xml
except ET.ParseError as parse_error:
raise SCCIClientError(parse_error) | python | def get_firmware_upgrade_status(irmc_info, upgrade_type):
"""get firmware upgrade status of bios or irmc
:param irmc_info: dict of iRMC params to access the server node
{
'irmc_address': host,
'irmc_username': user_id,
'irmc_password': password,
'irmc_port': 80 or 443, default is 443,
'irmc_auth_method': 'basic' or 'digest', default is 'digest',
'irmc_client_timeout': timeout, default is 60,
...
}
:param upgrade_type: flag to check upgrade with bios or irmc
:raises: ISCCIInvalidInputError if port and/or auth_method params
are invalid
:raises: SCCIClientError if SCCI failed
"""
host = irmc_info.get('irmc_address')
userid = irmc_info.get('irmc_username')
password = irmc_info.get('irmc_password')
port = irmc_info.get('irmc_port', 443)
auth_method = irmc_info.get('irmc_auth_method', 'digest')
client_timeout = irmc_info.get('irmc_client_timeout', 60)
auth_obj = None
try:
protocol = {80: 'http', 443: 'https'}[port]
auth_obj = {
'basic': requests.auth.HTTPBasicAuth(userid, password),
'digest': requests.auth.HTTPDigestAuth(userid, password)
}[auth_method.lower()]
except KeyError:
raise SCCIInvalidInputError(
("Invalid port %(port)d or " +
"auth_method for method %(auth_method)s") %
{'port': port, 'auth_method': auth_method})
try:
if upgrade_type == 'bios':
upgrade_type = '/biosprogress'
elif upgrade_type == 'irmc':
upgrade_type = '/irmcprogress'
r = requests.get(protocol + '://' + host + upgrade_type,
verify=False,
timeout=(10, client_timeout),
allow_redirects=False,
auth=auth_obj)
if r.status_code not in (200, 201):
raise SCCIClientError(
('HTTP PROTOCOL ERROR, STATUS CODE = %s' %
str(r.status_code)))
upgrade_status_xml = ET.fromstring(r.text)
return upgrade_status_xml
except ET.ParseError as parse_error:
raise SCCIClientError(parse_error) | [
"def",
"get_firmware_upgrade_status",
"(",
"irmc_info",
",",
"upgrade_type",
")",
":",
"host",
"=",
"irmc_info",
".",
"get",
"(",
"'irmc_address'",
")",
"userid",
"=",
"irmc_info",
".",
"get",
"(",
"'irmc_username'",
")",
"password",
"=",
"irmc_info",
".",
"ge... | get firmware upgrade status of bios or irmc
:param irmc_info: dict of iRMC params to access the server node
{
'irmc_address': host,
'irmc_username': user_id,
'irmc_password': password,
'irmc_port': 80 or 443, default is 443,
'irmc_auth_method': 'basic' or 'digest', default is 'digest',
'irmc_client_timeout': timeout, default is 60,
...
}
:param upgrade_type: flag to check upgrade with bios or irmc
:raises: ISCCIInvalidInputError if port and/or auth_method params
are invalid
:raises: SCCIClientError if SCCI failed | [
"get",
"firmware",
"upgrade",
"status",
"of",
"bios",
"or",
"irmc"
] | 4585ce2f76853b9773fb190ca0cfff0aa04a7cf8 | https://github.com/openstack/python-scciclient/blob/4585ce2f76853b9773fb190ca0cfff0aa04a7cf8/scciclient/irmc/scci.py#L663-L720 | train | 47,846 |
OSSOS/MOP | src/ossos/core/ossos/gui/controllers.py | AbstractController.on_toggle_autoplay_key | def on_toggle_autoplay_key(self):
"""
The user has pressed the keybind for toggling autoplay.
"""
if self.autoplay_manager.is_running():
self.autoplay_manager.stop_autoplay()
self.view.set_autoplay(False)
else:
self.autoplay_manager.start_autoplay()
self.view.set_autoplay(True) | python | def on_toggle_autoplay_key(self):
"""
The user has pressed the keybind for toggling autoplay.
"""
if self.autoplay_manager.is_running():
self.autoplay_manager.stop_autoplay()
self.view.set_autoplay(False)
else:
self.autoplay_manager.start_autoplay()
self.view.set_autoplay(True) | [
"def",
"on_toggle_autoplay_key",
"(",
"self",
")",
":",
"if",
"self",
".",
"autoplay_manager",
".",
"is_running",
"(",
")",
":",
"self",
".",
"autoplay_manager",
".",
"stop_autoplay",
"(",
")",
"self",
".",
"view",
".",
"set_autoplay",
"(",
"False",
")",
"... | The user has pressed the keybind for toggling autoplay. | [
"The",
"user",
"has",
"pressed",
"the",
"keybind",
"for",
"toggling",
"autoplay",
"."
] | 94f91d32ad5ec081d5a1ebd67604a838003465af | https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/gui/controllers.py#L161-L170 | train | 47,847 |
OSSOS/MOP | src/ossos/core/ossos/gui/controllers.py | ProcessRealsController.on_do_accept | def on_do_accept(self,
minor_planet_number,
provisional_name,
note1,
note2,
date_of_obs,
ra,
dec,
obs_mag,
obs_mag_err,
band,
observatory_code,
comment):
"""
After a source has been mark for acceptance create an MPC Observation record.
@param minor_planet_number: The MPC Number associated with the object
@param provisional_name: A provisional name associated with the object
@param note1: The observational quality note
@param note2: The observational circumstance note
@param date_of_obs: Date of the observation as a Time object.
@param ra: RA in degrees
@param dec: DE in degrees
@param obs_mag: observed magnitude.
@param obs_mag_err: Uncertainty in the observed magnitude.
@param band: filter/band of the observations
@param observatory_code: MPC Observatory Code of telescope.
@param comment: A free form comment (not part of MPC standard record)
"""
# Just extract the character code from the notes, not the
# full description
note1_code = note1.split(" ")[0]
note2_code = note2.split(" ")[0]
self.view.close_accept_source_dialog()
self.model.set_current_source_name(provisional_name)
source_cutout = self.model.get_current_cutout()
mpc_observation = mpc.Observation(
null_observation=False,
provisional_name=provisional_name,
note1=note1_code,
note2=note2_code,
date=date_of_obs,
ra=ra,
dec=dec,
mag=obs_mag,
mag_err=obs_mag_err,
band=band,
observatory_code=observatory_code,
discovery=self.is_discovery,
comment=comment,
xpos=source_cutout.reading.x,
ypos=source_cutout.reading.y,
frame=source_cutout.reading.obs.rawname,
astrometric_level=source_cutout.astrom_header.get('ASTLEVEL', None)
)
# Store the observation into the model.
data = self.model.get_current_workunit().data
key = mpc_observation.comment.frame.strip()
data.mpc_observations[key] = mpc_observation
# And write this observation out.
self.model.get_writer().write(mpc_observation)
# Mark the current item of the work unit as accepted.
self.model.accept_current_item()
# Detemine if the display should be reset.
reset_frame = False
if self.model.get_current_workunit().get_current_source_readings().is_on_last_item():
self.view.clear()
reset_frame = True
self.model.next_item()
if reset_frame:
self.view.frame(1) | python | def on_do_accept(self,
minor_planet_number,
provisional_name,
note1,
note2,
date_of_obs,
ra,
dec,
obs_mag,
obs_mag_err,
band,
observatory_code,
comment):
"""
After a source has been mark for acceptance create an MPC Observation record.
@param minor_planet_number: The MPC Number associated with the object
@param provisional_name: A provisional name associated with the object
@param note1: The observational quality note
@param note2: The observational circumstance note
@param date_of_obs: Date of the observation as a Time object.
@param ra: RA in degrees
@param dec: DE in degrees
@param obs_mag: observed magnitude.
@param obs_mag_err: Uncertainty in the observed magnitude.
@param band: filter/band of the observations
@param observatory_code: MPC Observatory Code of telescope.
@param comment: A free form comment (not part of MPC standard record)
"""
# Just extract the character code from the notes, not the
# full description
note1_code = note1.split(" ")[0]
note2_code = note2.split(" ")[0]
self.view.close_accept_source_dialog()
self.model.set_current_source_name(provisional_name)
source_cutout = self.model.get_current_cutout()
mpc_observation = mpc.Observation(
null_observation=False,
provisional_name=provisional_name,
note1=note1_code,
note2=note2_code,
date=date_of_obs,
ra=ra,
dec=dec,
mag=obs_mag,
mag_err=obs_mag_err,
band=band,
observatory_code=observatory_code,
discovery=self.is_discovery,
comment=comment,
xpos=source_cutout.reading.x,
ypos=source_cutout.reading.y,
frame=source_cutout.reading.obs.rawname,
astrometric_level=source_cutout.astrom_header.get('ASTLEVEL', None)
)
# Store the observation into the model.
data = self.model.get_current_workunit().data
key = mpc_observation.comment.frame.strip()
data.mpc_observations[key] = mpc_observation
# And write this observation out.
self.model.get_writer().write(mpc_observation)
# Mark the current item of the work unit as accepted.
self.model.accept_current_item()
# Detemine if the display should be reset.
reset_frame = False
if self.model.get_current_workunit().get_current_source_readings().is_on_last_item():
self.view.clear()
reset_frame = True
self.model.next_item()
if reset_frame:
self.view.frame(1) | [
"def",
"on_do_accept",
"(",
"self",
",",
"minor_planet_number",
",",
"provisional_name",
",",
"note1",
",",
"note2",
",",
"date_of_obs",
",",
"ra",
",",
"dec",
",",
"obs_mag",
",",
"obs_mag_err",
",",
"band",
",",
"observatory_code",
",",
"comment",
")",
":"... | After a source has been mark for acceptance create an MPC Observation record.
@param minor_planet_number: The MPC Number associated with the object
@param provisional_name: A provisional name associated with the object
@param note1: The observational quality note
@param note2: The observational circumstance note
@param date_of_obs: Date of the observation as a Time object.
@param ra: RA in degrees
@param dec: DE in degrees
@param obs_mag: observed magnitude.
@param obs_mag_err: Uncertainty in the observed magnitude.
@param band: filter/band of the observations
@param observatory_code: MPC Observatory Code of telescope.
@param comment: A free form comment (not part of MPC standard record) | [
"After",
"a",
"source",
"has",
"been",
"mark",
"for",
"acceptance",
"create",
"an",
"MPC",
"Observation",
"record",
"."
] | 94f91d32ad5ec081d5a1ebd67604a838003465af | https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/gui/controllers.py#L394-L471 | train | 47,848 |
OSSOS/MOP | src/ossos/core/ossos/gui/controllers.py | ProcessTracksController.on_load_comparison | def on_load_comparison(self, research=False):
"""
Display the comparison image
@param research: find a new comparison image even if one already known?
"""
cutout = self.model.get_current_cutout()
if research:
cutout.comparison_image_index = None
comparison_image = cutout.comparison_image
if comparison_image is None:
print "Failed to load comparison image: {}".format(cutout.comparison_image_list[cutout.comparison_image_index])
else:
self.view.display(cutout.comparison_image, self.use_pixel_coords)
self.view.align(self.model.get_current_cutout(),
self.model.get_current_reading(),
self.model.get_current_source())
self.model.get_current_workunit().previous_obs()
self.model.acknowledge_image_displayed() | python | def on_load_comparison(self, research=False):
"""
Display the comparison image
@param research: find a new comparison image even if one already known?
"""
cutout = self.model.get_current_cutout()
if research:
cutout.comparison_image_index = None
comparison_image = cutout.comparison_image
if comparison_image is None:
print "Failed to load comparison image: {}".format(cutout.comparison_image_list[cutout.comparison_image_index])
else:
self.view.display(cutout.comparison_image, self.use_pixel_coords)
self.view.align(self.model.get_current_cutout(),
self.model.get_current_reading(),
self.model.get_current_source())
self.model.get_current_workunit().previous_obs()
self.model.acknowledge_image_displayed() | [
"def",
"on_load_comparison",
"(",
"self",
",",
"research",
"=",
"False",
")",
":",
"cutout",
"=",
"self",
".",
"model",
".",
"get_current_cutout",
"(",
")",
"if",
"research",
":",
"cutout",
".",
"comparison_image_index",
"=",
"None",
"comparison_image",
"=",
... | Display the comparison image
@param research: find a new comparison image even if one already known? | [
"Display",
"the",
"comparison",
"image"
] | 94f91d32ad5ec081d5a1ebd67604a838003465af | https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/gui/controllers.py#L651-L669 | train | 47,849 |
openstack/python-scciclient | scciclient/irmc/viom/client.py | VIOMConfiguration.apply | def apply(self, reboot=False):
"""Apply the configuration to iRMC."""
self.root.use_virtual_addresses = True
self.root.manage.manage = True
self.root.mode = 'new'
self.root.init_boot = reboot
self.client.set_profile(self.root.get_json()) | python | def apply(self, reboot=False):
"""Apply the configuration to iRMC."""
self.root.use_virtual_addresses = True
self.root.manage.manage = True
self.root.mode = 'new'
self.root.init_boot = reboot
self.client.set_profile(self.root.get_json()) | [
"def",
"apply",
"(",
"self",
",",
"reboot",
"=",
"False",
")",
":",
"self",
".",
"root",
".",
"use_virtual_addresses",
"=",
"True",
"self",
".",
"root",
".",
"manage",
".",
"manage",
"=",
"True",
"self",
".",
"root",
".",
"mode",
"=",
"'new'",
"self"... | Apply the configuration to iRMC. | [
"Apply",
"the",
"configuration",
"to",
"iRMC",
"."
] | 4585ce2f76853b9773fb190ca0cfff0aa04a7cf8 | https://github.com/openstack/python-scciclient/blob/4585ce2f76853b9773fb190ca0cfff0aa04a7cf8/scciclient/irmc/viom/client.py#L268-L275 | train | 47,850 |
openstack/python-scciclient | scciclient/irmc/viom/client.py | VIOMConfiguration.terminate | def terminate(self, reboot=False):
"""Delete VIOM configuration from iRMC."""
self.root.manage.manage = False
self.root.mode = 'delete'
self.root.init_boot = reboot
self.client.set_profile(self.root.get_json()) | python | def terminate(self, reboot=False):
"""Delete VIOM configuration from iRMC."""
self.root.manage.manage = False
self.root.mode = 'delete'
self.root.init_boot = reboot
self.client.set_profile(self.root.get_json()) | [
"def",
"terminate",
"(",
"self",
",",
"reboot",
"=",
"False",
")",
":",
"self",
".",
"root",
".",
"manage",
".",
"manage",
"=",
"False",
"self",
".",
"root",
".",
"mode",
"=",
"'delete'",
"self",
".",
"root",
".",
"init_boot",
"=",
"reboot",
"self",
... | Delete VIOM configuration from iRMC. | [
"Delete",
"VIOM",
"configuration",
"from",
"iRMC",
"."
] | 4585ce2f76853b9773fb190ca0cfff0aa04a7cf8 | https://github.com/openstack/python-scciclient/blob/4585ce2f76853b9773fb190ca0cfff0aa04a7cf8/scciclient/irmc/viom/client.py#L277-L282 | train | 47,851 |
openstack/python-scciclient | scciclient/irmc/viom/client.py | VIOMConfiguration.set_lan_port | def set_lan_port(self, port_id, mac=None):
"""Set LAN port information to configuration.
:param port_id: Physical port ID.
:param mac: virtual MAC address if virtualization is necessary.
"""
port_handler = _parse_physical_port_id(port_id)
port = self._find_port(port_handler)
if port:
port_handler.set_lan_port(port, mac)
else:
self._add_port(port_handler, port_handler.create_lan_port(mac)) | python | def set_lan_port(self, port_id, mac=None):
"""Set LAN port information to configuration.
:param port_id: Physical port ID.
:param mac: virtual MAC address if virtualization is necessary.
"""
port_handler = _parse_physical_port_id(port_id)
port = self._find_port(port_handler)
if port:
port_handler.set_lan_port(port, mac)
else:
self._add_port(port_handler, port_handler.create_lan_port(mac)) | [
"def",
"set_lan_port",
"(",
"self",
",",
"port_id",
",",
"mac",
"=",
"None",
")",
":",
"port_handler",
"=",
"_parse_physical_port_id",
"(",
"port_id",
")",
"port",
"=",
"self",
".",
"_find_port",
"(",
"port_handler",
")",
"if",
"port",
":",
"port_handler",
... | Set LAN port information to configuration.
:param port_id: Physical port ID.
:param mac: virtual MAC address if virtualization is necessary. | [
"Set",
"LAN",
"port",
"information",
"to",
"configuration",
"."
] | 4585ce2f76853b9773fb190ca0cfff0aa04a7cf8 | https://github.com/openstack/python-scciclient/blob/4585ce2f76853b9773fb190ca0cfff0aa04a7cf8/scciclient/irmc/viom/client.py#L312-L323 | train | 47,852 |
openstack/python-scciclient | scciclient/irmc/viom/client.py | VIOMConfiguration.set_iscsi_volume | def set_iscsi_volume(self, port_id,
initiator_iqn, initiator_dhcp=False,
initiator_ip=None, initiator_netmask=None,
target_dhcp=False, target_iqn=None, target_ip=None,
target_port=3260, target_lun=0, boot_prio=1,
chap_user=None, chap_secret=None,
mutual_chap_secret=None):
"""Set iSCSI volume information to configuration.
:param port_id: Physical port ID.
:param initiator_iqn: IQN of initiator.
:param initiator_dhcp: True if DHCP is used in the iSCSI network.
:param initiator_ip: IP address of initiator. None if DHCP is used.
:param initiator_netmask: Netmask of initiator as integer. None if
DHCP is used.
:param target_dhcp: True if DHCP is used for iSCSI target.
:param target_iqn: IQN of target. None if DHCP is used.
:param target_ip: IP address of target. None if DHCP is used.
:param target_port: Port number of target. None if DHCP is used.
:param target_lun: LUN number of target. None if DHCP is used,
:param boot_prio: Boot priority of the volume. 1 indicates the highest
priority.
"""
initiator_netmask = (_convert_netmask(initiator_netmask)
if initiator_netmask else None)
port_handler = _parse_physical_port_id(port_id)
iscsi_boot = _create_iscsi_boot(
initiator_iqn,
initiator_dhcp=initiator_dhcp,
initiator_ip=initiator_ip,
initiator_netmask=initiator_netmask,
target_dhcp=target_dhcp,
target_iqn=target_iqn,
target_ip=target_ip,
target_port=target_port,
target_lun=target_lun,
boot_prio=boot_prio,
chap_user=chap_user,
chap_secret=chap_secret,
mutual_chap_secret=mutual_chap_secret)
port = self._find_port(port_handler)
if port:
port_handler.set_iscsi_port(port, iscsi_boot)
else:
port = port_handler.create_iscsi_port(iscsi_boot)
self._add_port(port_handler, port) | python | def set_iscsi_volume(self, port_id,
initiator_iqn, initiator_dhcp=False,
initiator_ip=None, initiator_netmask=None,
target_dhcp=False, target_iqn=None, target_ip=None,
target_port=3260, target_lun=0, boot_prio=1,
chap_user=None, chap_secret=None,
mutual_chap_secret=None):
"""Set iSCSI volume information to configuration.
:param port_id: Physical port ID.
:param initiator_iqn: IQN of initiator.
:param initiator_dhcp: True if DHCP is used in the iSCSI network.
:param initiator_ip: IP address of initiator. None if DHCP is used.
:param initiator_netmask: Netmask of initiator as integer. None if
DHCP is used.
:param target_dhcp: True if DHCP is used for iSCSI target.
:param target_iqn: IQN of target. None if DHCP is used.
:param target_ip: IP address of target. None if DHCP is used.
:param target_port: Port number of target. None if DHCP is used.
:param target_lun: LUN number of target. None if DHCP is used,
:param boot_prio: Boot priority of the volume. 1 indicates the highest
priority.
"""
initiator_netmask = (_convert_netmask(initiator_netmask)
if initiator_netmask else None)
port_handler = _parse_physical_port_id(port_id)
iscsi_boot = _create_iscsi_boot(
initiator_iqn,
initiator_dhcp=initiator_dhcp,
initiator_ip=initiator_ip,
initiator_netmask=initiator_netmask,
target_dhcp=target_dhcp,
target_iqn=target_iqn,
target_ip=target_ip,
target_port=target_port,
target_lun=target_lun,
boot_prio=boot_prio,
chap_user=chap_user,
chap_secret=chap_secret,
mutual_chap_secret=mutual_chap_secret)
port = self._find_port(port_handler)
if port:
port_handler.set_iscsi_port(port, iscsi_boot)
else:
port = port_handler.create_iscsi_port(iscsi_boot)
self._add_port(port_handler, port) | [
"def",
"set_iscsi_volume",
"(",
"self",
",",
"port_id",
",",
"initiator_iqn",
",",
"initiator_dhcp",
"=",
"False",
",",
"initiator_ip",
"=",
"None",
",",
"initiator_netmask",
"=",
"None",
",",
"target_dhcp",
"=",
"False",
",",
"target_iqn",
"=",
"None",
",",
... | Set iSCSI volume information to configuration.
:param port_id: Physical port ID.
:param initiator_iqn: IQN of initiator.
:param initiator_dhcp: True if DHCP is used in the iSCSI network.
:param initiator_ip: IP address of initiator. None if DHCP is used.
:param initiator_netmask: Netmask of initiator as integer. None if
DHCP is used.
:param target_dhcp: True if DHCP is used for iSCSI target.
:param target_iqn: IQN of target. None if DHCP is used.
:param target_ip: IP address of target. None if DHCP is used.
:param target_port: Port number of target. None if DHCP is used.
:param target_lun: LUN number of target. None if DHCP is used,
:param boot_prio: Boot priority of the volume. 1 indicates the highest
priority. | [
"Set",
"iSCSI",
"volume",
"information",
"to",
"configuration",
"."
] | 4585ce2f76853b9773fb190ca0cfff0aa04a7cf8 | https://github.com/openstack/python-scciclient/blob/4585ce2f76853b9773fb190ca0cfff0aa04a7cf8/scciclient/irmc/viom/client.py#L325-L373 | train | 47,853 |
openstack/python-scciclient | scciclient/irmc/viom/client.py | VIOMConfiguration.set_fc_volume | def set_fc_volume(self, port_id,
target_wwn, target_lun=0, boot_prio=1,
initiator_wwnn=None, initiator_wwpn=None):
"""Set FibreChannel volume information to configuration.
:param port_id: Physical port ID.
:param target_wwn: WWN of target.
:param target_lun: LUN number of target.
:param boot_prio: Boot priority of the volume. 1 indicates the highest
priority.
:param initiator_wwnn: Virtual WWNN for initiator if necessary.
:param initiator_wwpn: Virtual WWPN for initiator if necessary.
"""
port_handler = _parse_physical_port_id(port_id)
fc_target = elcm.FCTarget(target_wwn, target_lun)
fc_boot = elcm.FCBoot(boot_prio=boot_prio, boot_enable=True)
fc_boot.add_target(fc_target)
port = self._find_port(port_handler)
if port:
port_handler.set_fc_port(port, fc_boot,
wwnn=initiator_wwnn, wwpn=initiator_wwpn)
else:
port = port_handler.create_fc_port(fc_boot,
wwnn=initiator_wwnn,
wwpn=initiator_wwpn)
self._add_port(port_handler, port) | python | def set_fc_volume(self, port_id,
target_wwn, target_lun=0, boot_prio=1,
initiator_wwnn=None, initiator_wwpn=None):
"""Set FibreChannel volume information to configuration.
:param port_id: Physical port ID.
:param target_wwn: WWN of target.
:param target_lun: LUN number of target.
:param boot_prio: Boot priority of the volume. 1 indicates the highest
priority.
:param initiator_wwnn: Virtual WWNN for initiator if necessary.
:param initiator_wwpn: Virtual WWPN for initiator if necessary.
"""
port_handler = _parse_physical_port_id(port_id)
fc_target = elcm.FCTarget(target_wwn, target_lun)
fc_boot = elcm.FCBoot(boot_prio=boot_prio, boot_enable=True)
fc_boot.add_target(fc_target)
port = self._find_port(port_handler)
if port:
port_handler.set_fc_port(port, fc_boot,
wwnn=initiator_wwnn, wwpn=initiator_wwpn)
else:
port = port_handler.create_fc_port(fc_boot,
wwnn=initiator_wwnn,
wwpn=initiator_wwpn)
self._add_port(port_handler, port) | [
"def",
"set_fc_volume",
"(",
"self",
",",
"port_id",
",",
"target_wwn",
",",
"target_lun",
"=",
"0",
",",
"boot_prio",
"=",
"1",
",",
"initiator_wwnn",
"=",
"None",
",",
"initiator_wwpn",
"=",
"None",
")",
":",
"port_handler",
"=",
"_parse_physical_port_id",
... | Set FibreChannel volume information to configuration.
:param port_id: Physical port ID.
:param target_wwn: WWN of target.
:param target_lun: LUN number of target.
:param boot_prio: Boot priority of the volume. 1 indicates the highest
priority.
:param initiator_wwnn: Virtual WWNN for initiator if necessary.
:param initiator_wwpn: Virtual WWPN for initiator if necessary. | [
"Set",
"FibreChannel",
"volume",
"information",
"to",
"configuration",
"."
] | 4585ce2f76853b9773fb190ca0cfff0aa04a7cf8 | https://github.com/openstack/python-scciclient/blob/4585ce2f76853b9773fb190ca0cfff0aa04a7cf8/scciclient/irmc/viom/client.py#L375-L401 | train | 47,854 |
openstack/python-scciclient | scciclient/irmc/viom/client.py | VIOMConfiguration._pad_former_ports | def _pad_former_ports(self, port_handler):
"""Create ports with former port index.
:param port_handler: Port information to be registered.
Depending on slot type and card type, it is necessary to register
LAN ports with former index to VIOM table.
"""
if not port_handler.need_padding():
return
for port_idx in range(1, port_handler.port_idx):
pad_handler = port_handler.__class__(
port_handler.slot_type,
port_handler.card_type,
port_handler.slot_idx,
port_handler.card_idx,
port_idx)
if not self._find_port(pad_handler):
self._add_port(pad_handler,
pad_handler.create_lan_port()) | python | def _pad_former_ports(self, port_handler):
"""Create ports with former port index.
:param port_handler: Port information to be registered.
Depending on slot type and card type, it is necessary to register
LAN ports with former index to VIOM table.
"""
if not port_handler.need_padding():
return
for port_idx in range(1, port_handler.port_idx):
pad_handler = port_handler.__class__(
port_handler.slot_type,
port_handler.card_type,
port_handler.slot_idx,
port_handler.card_idx,
port_idx)
if not self._find_port(pad_handler):
self._add_port(pad_handler,
pad_handler.create_lan_port()) | [
"def",
"_pad_former_ports",
"(",
"self",
",",
"port_handler",
")",
":",
"if",
"not",
"port_handler",
".",
"need_padding",
"(",
")",
":",
"return",
"for",
"port_idx",
"in",
"range",
"(",
"1",
",",
"port_handler",
".",
"port_idx",
")",
":",
"pad_handler",
"=... | Create ports with former port index.
:param port_handler: Port information to be registered.
Depending on slot type and card type, it is necessary to register
LAN ports with former index to VIOM table. | [
"Create",
"ports",
"with",
"former",
"port",
"index",
"."
] | 4585ce2f76853b9773fb190ca0cfff0aa04a7cf8 | https://github.com/openstack/python-scciclient/blob/4585ce2f76853b9773fb190ca0cfff0aa04a7cf8/scciclient/irmc/viom/client.py#L411-L430 | train | 47,855 |
JohnVinyard/zounds | zounds/soundfile/byte_depth.py | chunk_size_samples | def chunk_size_samples(sf, buf):
"""
Black magic to account for the fact that libsndfile's behavior varies
depending on file format when using the virtual io api.
If you ask for more samples from an ogg or flac file than are available
at that moment, libsndfile will give you no more samples ever, even if
more bytes arrive in the buffer later.
"""
byte_depth = _lookup[sf.subtype]
channels = sf.channels
bytes_per_second = byte_depth * sf.samplerate * channels
secs = len(buf) / bytes_per_second
secs = max(1, secs - 6)
return int(secs * sf.samplerate) | python | def chunk_size_samples(sf, buf):
"""
Black magic to account for the fact that libsndfile's behavior varies
depending on file format when using the virtual io api.
If you ask for more samples from an ogg or flac file than are available
at that moment, libsndfile will give you no more samples ever, even if
more bytes arrive in the buffer later.
"""
byte_depth = _lookup[sf.subtype]
channels = sf.channels
bytes_per_second = byte_depth * sf.samplerate * channels
secs = len(buf) / bytes_per_second
secs = max(1, secs - 6)
return int(secs * sf.samplerate) | [
"def",
"chunk_size_samples",
"(",
"sf",
",",
"buf",
")",
":",
"byte_depth",
"=",
"_lookup",
"[",
"sf",
".",
"subtype",
"]",
"channels",
"=",
"sf",
".",
"channels",
"bytes_per_second",
"=",
"byte_depth",
"*",
"sf",
".",
"samplerate",
"*",
"channels",
"secs"... | Black magic to account for the fact that libsndfile's behavior varies
depending on file format when using the virtual io api.
If you ask for more samples from an ogg or flac file than are available
at that moment, libsndfile will give you no more samples ever, even if
more bytes arrive in the buffer later. | [
"Black",
"magic",
"to",
"account",
"for",
"the",
"fact",
"that",
"libsndfile",
"s",
"behavior",
"varies",
"depending",
"on",
"file",
"format",
"when",
"using",
"the",
"virtual",
"io",
"api",
"."
] | 337b3f98753d09eaab1c72dcd37bb852a3fa5ac6 | https://github.com/JohnVinyard/zounds/blob/337b3f98753d09eaab1c72dcd37bb852a3fa5ac6/zounds/soundfile/byte_depth.py#L19-L33 | train | 47,856 |
OSSOS/MOP | src/ossos/core/ossos/coding.py | encode | def encode(number, alphabet):
"""
Converts an integer to a base n string where n is the length of the
provided alphabet.
Modified from http://en.wikipedia.org/wiki/Base_36
"""
if not isinstance(number, (int, long)):
raise TypeError("Number must be an integer.")
base_n = ""
sign = ""
if number < 0:
sign = "-"
number = -number
if 0 <= number < len(alphabet):
return sign + alphabet[number]
while number != 0:
number, i = divmod(number, len(alphabet))
base_n = alphabet[i] + base_n
return sign + base_n | python | def encode(number, alphabet):
"""
Converts an integer to a base n string where n is the length of the
provided alphabet.
Modified from http://en.wikipedia.org/wiki/Base_36
"""
if not isinstance(number, (int, long)):
raise TypeError("Number must be an integer.")
base_n = ""
sign = ""
if number < 0:
sign = "-"
number = -number
if 0 <= number < len(alphabet):
return sign + alphabet[number]
while number != 0:
number, i = divmod(number, len(alphabet))
base_n = alphabet[i] + base_n
return sign + base_n | [
"def",
"encode",
"(",
"number",
",",
"alphabet",
")",
":",
"if",
"not",
"isinstance",
"(",
"number",
",",
"(",
"int",
",",
"long",
")",
")",
":",
"raise",
"TypeError",
"(",
"\"Number must be an integer.\"",
")",
"base_n",
"=",
"\"\"",
"sign",
"=",
"\"\""... | Converts an integer to a base n string where n is the length of the
provided alphabet.
Modified from http://en.wikipedia.org/wiki/Base_36 | [
"Converts",
"an",
"integer",
"to",
"a",
"base",
"n",
"string",
"where",
"n",
"is",
"the",
"length",
"of",
"the",
"provided",
"alphabet",
"."
] | 94f91d32ad5ec081d5a1ebd67604a838003465af | https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/coding.py#L17-L41 | train | 47,857 |
JohnVinyard/zounds | zounds/timeseries/functional.py | categorical | def categorical(x, mu=255, normalize=True):
"""
Mu-law compress a block of audio samples, and convert them into a
categorical distribution
"""
if normalize:
# normalize the signal
mx = x.max()
x = np.divide(x, mx, where=mx != 0)
# mu law compression
x = mu_law(x)
# translate and scale to [0, 1]
x = (x - x.min()) * 0.5
# convert to the range [0, 255]
x = (x * mu).astype(np.uint8)
# create the array to house the categorical representation
c = np.zeros((np.product(x.shape), mu + 1), dtype=np.uint8)
c[np.arange(len(c)), x.flatten()] = 1
return ArrayWithUnits(
c.reshape(x.shape + (mu + 1,)),
x.dimensions + (IdentityDimension(),)) | python | def categorical(x, mu=255, normalize=True):
"""
Mu-law compress a block of audio samples, and convert them into a
categorical distribution
"""
if normalize:
# normalize the signal
mx = x.max()
x = np.divide(x, mx, where=mx != 0)
# mu law compression
x = mu_law(x)
# translate and scale to [0, 1]
x = (x - x.min()) * 0.5
# convert to the range [0, 255]
x = (x * mu).astype(np.uint8)
# create the array to house the categorical representation
c = np.zeros((np.product(x.shape), mu + 1), dtype=np.uint8)
c[np.arange(len(c)), x.flatten()] = 1
return ArrayWithUnits(
c.reshape(x.shape + (mu + 1,)),
x.dimensions + (IdentityDimension(),)) | [
"def",
"categorical",
"(",
"x",
",",
"mu",
"=",
"255",
",",
"normalize",
"=",
"True",
")",
":",
"if",
"normalize",
":",
"# normalize the signal",
"mx",
"=",
"x",
".",
"max",
"(",
")",
"x",
"=",
"np",
".",
"divide",
"(",
"x",
",",
"mx",
",",
"wher... | Mu-law compress a block of audio samples, and convert them into a
categorical distribution | [
"Mu",
"-",
"law",
"compress",
"a",
"block",
"of",
"audio",
"samples",
"and",
"convert",
"them",
"into",
"a",
"categorical",
"distribution"
] | 337b3f98753d09eaab1c72dcd37bb852a3fa5ac6 | https://github.com/JohnVinyard/zounds/blob/337b3f98753d09eaab1c72dcd37bb852a3fa5ac6/zounds/timeseries/functional.py#L7-L33 | train | 47,858 |
JohnVinyard/zounds | zounds/timeseries/functional.py | inverse_categorical | def inverse_categorical(x, mu=255):
"""
Invert categorical samples
"""
flat = x.reshape((-1, x.shape[-1]))
indices = np.argmax(flat, axis=1).astype(np.float32)
indices = (indices / mu) - 0.5
inverted = inverse_mu_law(indices, mu=mu).reshape(x.shape[:-1])
return ArrayWithUnits(inverted, x.dimensions[:2]) | python | def inverse_categorical(x, mu=255):
"""
Invert categorical samples
"""
flat = x.reshape((-1, x.shape[-1]))
indices = np.argmax(flat, axis=1).astype(np.float32)
indices = (indices / mu) - 0.5
inverted = inverse_mu_law(indices, mu=mu).reshape(x.shape[:-1])
return ArrayWithUnits(inverted, x.dimensions[:2]) | [
"def",
"inverse_categorical",
"(",
"x",
",",
"mu",
"=",
"255",
")",
":",
"flat",
"=",
"x",
".",
"reshape",
"(",
"(",
"-",
"1",
",",
"x",
".",
"shape",
"[",
"-",
"1",
"]",
")",
")",
"indices",
"=",
"np",
".",
"argmax",
"(",
"flat",
",",
"axis"... | Invert categorical samples | [
"Invert",
"categorical",
"samples"
] | 337b3f98753d09eaab1c72dcd37bb852a3fa5ac6 | https://github.com/JohnVinyard/zounds/blob/337b3f98753d09eaab1c72dcd37bb852a3fa5ac6/zounds/timeseries/functional.py#L37-L45 | train | 47,859 |
JohnVinyard/zounds | zounds/synthesize/synthesize.py | SineSynthesizer.synthesize | def synthesize(self, duration, freqs_in_hz=[440.]):
"""
Synthesize one or more sine waves
Args:
duration (numpy.timdelta64): The duration of the sound to be
synthesized
freqs_in_hz (list of float): Numbers representing the frequencies
in hz that should be synthesized
"""
freqs = np.array(freqs_in_hz)
scaling = 1 / len(freqs)
sr = int(self.samplerate)
cps = freqs / sr
ts = (duration / Seconds(1)) * sr
ranges = np.array([np.arange(0, ts * c, c) for c in cps])
raw = (np.sin(ranges * (2 * np.pi)) * scaling).sum(axis=0)
return AudioSamples(raw, self.samplerate) | python | def synthesize(self, duration, freqs_in_hz=[440.]):
"""
Synthesize one or more sine waves
Args:
duration (numpy.timdelta64): The duration of the sound to be
synthesized
freqs_in_hz (list of float): Numbers representing the frequencies
in hz that should be synthesized
"""
freqs = np.array(freqs_in_hz)
scaling = 1 / len(freqs)
sr = int(self.samplerate)
cps = freqs / sr
ts = (duration / Seconds(1)) * sr
ranges = np.array([np.arange(0, ts * c, c) for c in cps])
raw = (np.sin(ranges * (2 * np.pi)) * scaling).sum(axis=0)
return AudioSamples(raw, self.samplerate) | [
"def",
"synthesize",
"(",
"self",
",",
"duration",
",",
"freqs_in_hz",
"=",
"[",
"440.",
"]",
")",
":",
"freqs",
"=",
"np",
".",
"array",
"(",
"freqs_in_hz",
")",
"scaling",
"=",
"1",
"/",
"len",
"(",
"freqs",
")",
"sr",
"=",
"int",
"(",
"self",
... | Synthesize one or more sine waves
Args:
duration (numpy.timdelta64): The duration of the sound to be
synthesized
freqs_in_hz (list of float): Numbers representing the frequencies
in hz that should be synthesized | [
"Synthesize",
"one",
"or",
"more",
"sine",
"waves"
] | 337b3f98753d09eaab1c72dcd37bb852a3fa5ac6 | https://github.com/JohnVinyard/zounds/blob/337b3f98753d09eaab1c72dcd37bb852a3fa5ac6/zounds/synthesize/synthesize.py#L546-L563 | train | 47,860 |
JohnVinyard/zounds | zounds/synthesize/synthesize.py | TickSynthesizer.synthesize | def synthesize(self, duration, tick_frequency):
"""
Synthesize periodic "ticks", generated from white noise and an envelope
Args:
duration (numpy.timedelta64): The total duration of the sound to be
synthesized
tick_frequency (numpy.timedelta64): The frequency of the ticking
sound
"""
sr = self.samplerate.samples_per_second
# create a short, tick sound
tick = np.random.uniform(low=-1., high=1., size=int(sr * .1))
tick *= np.linspace(1, 0, len(tick))
# create silence
samples = np.zeros(int(sr * (duration / Seconds(1))))
ticks_per_second = Seconds(1) / tick_frequency
# introduce periodic ticking sound
step = int(sr // ticks_per_second)
for i in range(0, len(samples), step):
size = len(samples[i:i + len(tick)])
samples[i:i + len(tick)] += tick[:size]
return AudioSamples(samples, self.samplerate) | python | def synthesize(self, duration, tick_frequency):
"""
Synthesize periodic "ticks", generated from white noise and an envelope
Args:
duration (numpy.timedelta64): The total duration of the sound to be
synthesized
tick_frequency (numpy.timedelta64): The frequency of the ticking
sound
"""
sr = self.samplerate.samples_per_second
# create a short, tick sound
tick = np.random.uniform(low=-1., high=1., size=int(sr * .1))
tick *= np.linspace(1, 0, len(tick))
# create silence
samples = np.zeros(int(sr * (duration / Seconds(1))))
ticks_per_second = Seconds(1) / tick_frequency
# introduce periodic ticking sound
step = int(sr // ticks_per_second)
for i in range(0, len(samples), step):
size = len(samples[i:i + len(tick)])
samples[i:i + len(tick)] += tick[:size]
return AudioSamples(samples, self.samplerate) | [
"def",
"synthesize",
"(",
"self",
",",
"duration",
",",
"tick_frequency",
")",
":",
"sr",
"=",
"self",
".",
"samplerate",
".",
"samples_per_second",
"# create a short, tick sound",
"tick",
"=",
"np",
".",
"random",
".",
"uniform",
"(",
"low",
"=",
"-",
"1.",... | Synthesize periodic "ticks", generated from white noise and an envelope
Args:
duration (numpy.timedelta64): The total duration of the sound to be
synthesized
tick_frequency (numpy.timedelta64): The frequency of the ticking
sound | [
"Synthesize",
"periodic",
"ticks",
"generated",
"from",
"white",
"noise",
"and",
"an",
"envelope"
] | 337b3f98753d09eaab1c72dcd37bb852a3fa5ac6 | https://github.com/JohnVinyard/zounds/blob/337b3f98753d09eaab1c72dcd37bb852a3fa5ac6/zounds/synthesize/synthesize.py#L593-L615 | train | 47,861 |
JohnVinyard/zounds | zounds/synthesize/synthesize.py | NoiseSynthesizer.synthesize | def synthesize(self, duration):
"""
Synthesize white noise
Args:
duration (numpy.timedelta64): The duration of the synthesized sound
"""
sr = self.samplerate.samples_per_second
seconds = duration / Seconds(1)
samples = np.random.uniform(low=-1., high=1., size=int(sr * seconds))
return AudioSamples(samples, self.samplerate) | python | def synthesize(self, duration):
"""
Synthesize white noise
Args:
duration (numpy.timedelta64): The duration of the synthesized sound
"""
sr = self.samplerate.samples_per_second
seconds = duration / Seconds(1)
samples = np.random.uniform(low=-1., high=1., size=int(sr * seconds))
return AudioSamples(samples, self.samplerate) | [
"def",
"synthesize",
"(",
"self",
",",
"duration",
")",
":",
"sr",
"=",
"self",
".",
"samplerate",
".",
"samples_per_second",
"seconds",
"=",
"duration",
"/",
"Seconds",
"(",
"1",
")",
"samples",
"=",
"np",
".",
"random",
".",
"uniform",
"(",
"low",
"=... | Synthesize white noise
Args:
duration (numpy.timedelta64): The duration of the synthesized sound | [
"Synthesize",
"white",
"noise"
] | 337b3f98753d09eaab1c72dcd37bb852a3fa5ac6 | https://github.com/JohnVinyard/zounds/blob/337b3f98753d09eaab1c72dcd37bb852a3fa5ac6/zounds/synthesize/synthesize.py#L644-L654 | train | 47,862 |
OSSOS/MOP | src/ossos/core/ossos/gui/models/workload.py | TracksWorkUnit.query_ssos | def query_ssos(self):
"""
Use the MPC file that has been built up in processing this work
unit to generate another workunit.
"""
self._ssos_queried = True
mpc_filename = self.save()
return self.builder.build_workunit(mpc_filename) | python | def query_ssos(self):
"""
Use the MPC file that has been built up in processing this work
unit to generate another workunit.
"""
self._ssos_queried = True
mpc_filename = self.save()
return self.builder.build_workunit(mpc_filename) | [
"def",
"query_ssos",
"(",
"self",
")",
":",
"self",
".",
"_ssos_queried",
"=",
"True",
"mpc_filename",
"=",
"self",
".",
"save",
"(",
")",
"return",
"self",
".",
"builder",
".",
"build_workunit",
"(",
"mpc_filename",
")"
] | Use the MPC file that has been built up in processing this work
unit to generate another workunit. | [
"Use",
"the",
"MPC",
"file",
"that",
"has",
"been",
"built",
"up",
"in",
"processing",
"this",
"work",
"unit",
"to",
"generate",
"another",
"workunit",
"."
] | 94f91d32ad5ec081d5a1ebd67604a838003465af | https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/gui/models/workload.py#L410-L417 | train | 47,863 |
OSSOS/MOP | src/ossos/core/ossos/gui/models/workload.py | TracksWorkUnit.save | def save(self):
"""
Update the SouceReading information for the currently recorded observations and then flush those to a file.
@return: mpc_filename of the resulting save.
"""
self.get_writer().flush()
mpc_filename = self.get_writer().get_filename()
self.get_writer().close()
self._writer = None
return mpc_filename | python | def save(self):
"""
Update the SouceReading information for the currently recorded observations and then flush those to a file.
@return: mpc_filename of the resulting save.
"""
self.get_writer().flush()
mpc_filename = self.get_writer().get_filename()
self.get_writer().close()
self._writer = None
return mpc_filename | [
"def",
"save",
"(",
"self",
")",
":",
"self",
".",
"get_writer",
"(",
")",
".",
"flush",
"(",
")",
"mpc_filename",
"=",
"self",
".",
"get_writer",
"(",
")",
".",
"get_filename",
"(",
")",
"self",
".",
"get_writer",
"(",
")",
".",
"close",
"(",
")",... | Update the SouceReading information for the currently recorded observations and then flush those to a file.
@return: mpc_filename of the resulting save. | [
"Update",
"the",
"SouceReading",
"information",
"for",
"the",
"currently",
"recorded",
"observations",
"and",
"then",
"flush",
"those",
"to",
"a",
"file",
"."
] | 94f91d32ad5ec081d5a1ebd67604a838003465af | https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/gui/models/workload.py#L419-L428 | train | 47,864 |
OSSOS/MOP | src/ossos/core/ossos/gui/models/workload.py | TracksWorkUnit.get_writer | def get_writer(self):
"""
Get a writer.
This method also makes the output filename be the same as the .track file but with .mpc.
(Currently only works on local filesystem)
:rtype MPCWriter
"""
if self._writer is None:
suffix = tasks.get_suffix(tasks.TRACK_TASK)
try:
base_name = re.search("(?P<base_name>.*?)\.\d*{}".format(suffix), self.filename).group('base_name')
except:
base_name = os.path.splitext(self.filename)[0]
mpc_filename_pattern = self.output_context.get_full_path(
"{}.?{}".format(base_name, suffix))
mpc_file_count = len(glob(mpc_filename_pattern))
mpc_filename = "{}.{}{}".format(base_name, mpc_file_count, suffix)
self._writer = self._create_writer(mpc_filename)
return self._writer | python | def get_writer(self):
"""
Get a writer.
This method also makes the output filename be the same as the .track file but with .mpc.
(Currently only works on local filesystem)
:rtype MPCWriter
"""
if self._writer is None:
suffix = tasks.get_suffix(tasks.TRACK_TASK)
try:
base_name = re.search("(?P<base_name>.*?)\.\d*{}".format(suffix), self.filename).group('base_name')
except:
base_name = os.path.splitext(self.filename)[0]
mpc_filename_pattern = self.output_context.get_full_path(
"{}.?{}".format(base_name, suffix))
mpc_file_count = len(glob(mpc_filename_pattern))
mpc_filename = "{}.{}{}".format(base_name, mpc_file_count, suffix)
self._writer = self._create_writer(mpc_filename)
return self._writer | [
"def",
"get_writer",
"(",
"self",
")",
":",
"if",
"self",
".",
"_writer",
"is",
"None",
":",
"suffix",
"=",
"tasks",
".",
"get_suffix",
"(",
"tasks",
".",
"TRACK_TASK",
")",
"try",
":",
"base_name",
"=",
"re",
".",
"search",
"(",
"\"(?P<base_name>.*?)\\.... | Get a writer.
This method also makes the output filename be the same as the .track file but with .mpc.
(Currently only works on local filesystem)
:rtype MPCWriter | [
"Get",
"a",
"writer",
"."
] | 94f91d32ad5ec081d5a1ebd67604a838003465af | https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/gui/models/workload.py#L466-L486 | train | 47,865 |
OSSOS/MOP | src/ossos/core/ossos/gui/models/workload.py | WorkUnitProvider._filter | def _filter(self, filename):
"""
return 'true' if filename doesn't match name_filter regex and should be filtered out of the list.
@param filename:
@return:
"""
return self.name_filter is not None and re.search(self.name_filter, filename) is None | python | def _filter(self, filename):
"""
return 'true' if filename doesn't match name_filter regex and should be filtered out of the list.
@param filename:
@return:
"""
return self.name_filter is not None and re.search(self.name_filter, filename) is None | [
"def",
"_filter",
"(",
"self",
",",
"filename",
")",
":",
"return",
"self",
".",
"name_filter",
"is",
"not",
"None",
"and",
"re",
".",
"search",
"(",
"self",
".",
"name_filter",
",",
"filename",
")",
"is",
"None"
] | return 'true' if filename doesn't match name_filter regex and should be filtered out of the list.
@param filename:
@return: | [
"return",
"true",
"if",
"filename",
"doesn",
"t",
"match",
"name_filter",
"regex",
"and",
"should",
"be",
"filtered",
"out",
"of",
"the",
"list",
"."
] | 94f91d32ad5ec081d5a1ebd67604a838003465af | https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/gui/models/workload.py#L571-L577 | train | 47,866 |
OSSOS/MOP | src/ossos/core/ossos/gui/models/workload.py | WorkUnitProvider.get_workunit | def get_workunit(self, ignore_list=None):
"""
Gets a new unit of work.
Args:
ignore_list: list(str)
A list of filenames which should be ignored. Defaults to None.
Returns:
new_workunit: WorkUnit
A new unit of work that has not yet been processed. A lock on
it has been acquired.
Raises:
NoAvailableWorkException
There is no more work available.
"""
if ignore_list is None:
ignore_list = []
potential_files = self.get_potential_files(ignore_list)
while len(potential_files) > 0:
potential_file = self.select_potential_file(potential_files)
potential_files.remove(potential_file)
if self._filter(potential_file):
continue
if self.directory_context.get_file_size(potential_file) == 0:
continue
if self.progress_manager.is_done(potential_file):
self._done.append(potential_file)
continue
else:
try:
self.progress_manager.lock(potential_file)
except FileLockedException:
continue
self._already_fetched.append(potential_file)
return self.builder.build_workunit(
self.directory_context.get_full_path(potential_file))
logger.info("No eligible workunits remain to be fetched.")
raise NoAvailableWorkException() | python | def get_workunit(self, ignore_list=None):
"""
Gets a new unit of work.
Args:
ignore_list: list(str)
A list of filenames which should be ignored. Defaults to None.
Returns:
new_workunit: WorkUnit
A new unit of work that has not yet been processed. A lock on
it has been acquired.
Raises:
NoAvailableWorkException
There is no more work available.
"""
if ignore_list is None:
ignore_list = []
potential_files = self.get_potential_files(ignore_list)
while len(potential_files) > 0:
potential_file = self.select_potential_file(potential_files)
potential_files.remove(potential_file)
if self._filter(potential_file):
continue
if self.directory_context.get_file_size(potential_file) == 0:
continue
if self.progress_manager.is_done(potential_file):
self._done.append(potential_file)
continue
else:
try:
self.progress_manager.lock(potential_file)
except FileLockedException:
continue
self._already_fetched.append(potential_file)
return self.builder.build_workunit(
self.directory_context.get_full_path(potential_file))
logger.info("No eligible workunits remain to be fetched.")
raise NoAvailableWorkException() | [
"def",
"get_workunit",
"(",
"self",
",",
"ignore_list",
"=",
"None",
")",
":",
"if",
"ignore_list",
"is",
"None",
":",
"ignore_list",
"=",
"[",
"]",
"potential_files",
"=",
"self",
".",
"get_potential_files",
"(",
"ignore_list",
")",
"while",
"len",
"(",
"... | Gets a new unit of work.
Args:
ignore_list: list(str)
A list of filenames which should be ignored. Defaults to None.
Returns:
new_workunit: WorkUnit
A new unit of work that has not yet been processed. A lock on
it has been acquired.
Raises:
NoAvailableWorkException
There is no more work available. | [
"Gets",
"a",
"new",
"unit",
"of",
"work",
"."
] | 94f91d32ad5ec081d5a1ebd67604a838003465af | https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/gui/models/workload.py#L579-L625 | train | 47,867 |
OSSOS/MOP | src/ossos/core/ossos/gui/models/workload.py | TracksWorkUnitBuilder.move_discovery_to_front | def move_discovery_to_front(self, data):
"""
Moves the discovery triplet to the front of the reading list.
Leaves everything else in the same order.
"""
readings = self.get_readings(data)
discovery_index = self.get_discovery_index(data)
reordered_readings = (readings[discovery_index:discovery_index + 3] +
readings[:discovery_index] +
readings[discovery_index + 3:])
self.set_readings(data, reordered_readings) | python | def move_discovery_to_front(self, data):
"""
Moves the discovery triplet to the front of the reading list.
Leaves everything else in the same order.
"""
readings = self.get_readings(data)
discovery_index = self.get_discovery_index(data)
reordered_readings = (readings[discovery_index:discovery_index + 3] +
readings[:discovery_index] +
readings[discovery_index + 3:])
self.set_readings(data, reordered_readings) | [
"def",
"move_discovery_to_front",
"(",
"self",
",",
"data",
")",
":",
"readings",
"=",
"self",
".",
"get_readings",
"(",
"data",
")",
"discovery_index",
"=",
"self",
".",
"get_discovery_index",
"(",
"data",
")",
"reordered_readings",
"=",
"(",
"readings",
"[",... | Moves the discovery triplet to the front of the reading list.
Leaves everything else in the same order. | [
"Moves",
"the",
"discovery",
"triplet",
"to",
"the",
"front",
"of",
"the",
"reading",
"list",
".",
"Leaves",
"everything",
"else",
"in",
"the",
"same",
"order",
"."
] | 94f91d32ad5ec081d5a1ebd67604a838003465af | https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/gui/models/workload.py#L832-L844 | train | 47,868 |
OSSOS/MOP | src/ossos/core/ossos/planning/megacam.py | TAPQuery | def TAPQuery(RAdeg=180.0, DECdeg=0.0, width=1, height=1):
"""Do a query of the CADC Megacam table. Get all observations insize the box. Returns a file-like object"""
QUERY =( """ SELECT """
""" COORD1(CENTROID(Plane.position_bounds)) AS "RAJ2000", COORD2(CENTROID(Plane.position_bounds)) AS "DEJ2000", Plane.time_bounds_lower as "MJDATE" """
""" FROM """
""" caom2.Observation as o JOIN caom2.Plane as Plane on o.obsID=Plane.obsID """
""" WHERE """
""" o.collection = 'CFHT' """
""" AND o.instrument_name = 'MegaPrime' """
""" AND INTERSECTS( BOX('ICRS', {}, {}, {}, {}), Plane.position_bounds ) = 1 """
""" AND ( o.proposal_id LIKE '%P05') """)
# """ AND ( o.proposal_id LIKE '%P05' OR o.proposal_id LIKE '%L03' or o.proposal_id LIKE '%L06' or o.proposal_id
# in ( '06AF33', '06BF98' ) ) """ )
QUERY = QUERY.format( RAdeg, DECdeg, width, height)
data={"QUERY": QUERY,
"REQUEST": "doQuery",
"LANG": "ADQL",
"FORMAT": "votable"}
url="http://www.cadc.hia.nrc.gc.ca/tap/sync"
print url, data
return urllib.urlopen(url,urllib.urlencode(data)) | python | def TAPQuery(RAdeg=180.0, DECdeg=0.0, width=1, height=1):
"""Do a query of the CADC Megacam table. Get all observations insize the box. Returns a file-like object"""
QUERY =( """ SELECT """
""" COORD1(CENTROID(Plane.position_bounds)) AS "RAJ2000", COORD2(CENTROID(Plane.position_bounds)) AS "DEJ2000", Plane.time_bounds_lower as "MJDATE" """
""" FROM """
""" caom2.Observation as o JOIN caom2.Plane as Plane on o.obsID=Plane.obsID """
""" WHERE """
""" o.collection = 'CFHT' """
""" AND o.instrument_name = 'MegaPrime' """
""" AND INTERSECTS( BOX('ICRS', {}, {}, {}, {}), Plane.position_bounds ) = 1 """
""" AND ( o.proposal_id LIKE '%P05') """)
# """ AND ( o.proposal_id LIKE '%P05' OR o.proposal_id LIKE '%L03' or o.proposal_id LIKE '%L06' or o.proposal_id
# in ( '06AF33', '06BF98' ) ) """ )
QUERY = QUERY.format( RAdeg, DECdeg, width, height)
data={"QUERY": QUERY,
"REQUEST": "doQuery",
"LANG": "ADQL",
"FORMAT": "votable"}
url="http://www.cadc.hia.nrc.gc.ca/tap/sync"
print url, data
return urllib.urlopen(url,urllib.urlencode(data)) | [
"def",
"TAPQuery",
"(",
"RAdeg",
"=",
"180.0",
",",
"DECdeg",
"=",
"0.0",
",",
"width",
"=",
"1",
",",
"height",
"=",
"1",
")",
":",
"QUERY",
"=",
"(",
"\"\"\" SELECT \"\"\"",
"\"\"\" COORD1(CENTROID(Plane.position_bounds)) AS \"RAJ2000\", COORD2(CENTROID(Plane.positi... | Do a query of the CADC Megacam table. Get all observations insize the box. Returns a file-like object | [
"Do",
"a",
"query",
"of",
"the",
"CADC",
"Megacam",
"table",
".",
"Get",
"all",
"observations",
"insize",
"the",
"box",
".",
"Returns",
"a",
"file",
"-",
"like",
"object"
] | 94f91d32ad5ec081d5a1ebd67604a838003465af | https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/planning/megacam.py#L5-L32 | train | 47,869 |
OSSOS/MOP | src/jjk/preproc/verifyDetection.py | get_flipped_ext | def get_flipped_ext(file_id,ccd):
"""Given a list of exposure numbers and CCD, get them from the DB"""
import MOPfits
import os, shutil
filename=MOPfits.adGet(file_id,extno=int(ccd))
if int(ccd)<18:
tfname=filename+"F"
shutil.move(filename, tfname)
os.system("imcopy %s[-*,-*] %s" % (tfname, filename))
os.unlink(tfname)
if not os.access(filename,os.R_OK):
return(None)
return(filename) | python | def get_flipped_ext(file_id,ccd):
"""Given a list of exposure numbers and CCD, get them from the DB"""
import MOPfits
import os, shutil
filename=MOPfits.adGet(file_id,extno=int(ccd))
if int(ccd)<18:
tfname=filename+"F"
shutil.move(filename, tfname)
os.system("imcopy %s[-*,-*] %s" % (tfname, filename))
os.unlink(tfname)
if not os.access(filename,os.R_OK):
return(None)
return(filename) | [
"def",
"get_flipped_ext",
"(",
"file_id",
",",
"ccd",
")",
":",
"import",
"MOPfits",
"import",
"os",
",",
"shutil",
"filename",
"=",
"MOPfits",
".",
"adGet",
"(",
"file_id",
",",
"extno",
"=",
"int",
"(",
"ccd",
")",
")",
"if",
"int",
"(",
"ccd",
")"... | Given a list of exposure numbers and CCD, get them from the DB | [
"Given",
"a",
"list",
"of",
"exposure",
"numbers",
"and",
"CCD",
"get",
"them",
"from",
"the",
"DB"
] | 94f91d32ad5ec081d5a1ebd67604a838003465af | https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/jjk/preproc/verifyDetection.py#L17-L31 | train | 47,870 |
OSSOS/MOP | src/jjk/preproc/verifyDetection.py | get_file_ids | def get_file_ids(object):
"""Get the exposure for a particular line in the meausre table"""
import MOPdbaccess
mysql = MOPdbaccess.connect('cfeps','cfhls',dbSystem='MYSQL')
cfeps=mysql.cursor()
sql="SELECT file_id FROM measure WHERE provisional LIKE %s"
cfeps.execute(sql,(object, ))
file_ids=cfeps.fetchall()
return (file_ids) | python | def get_file_ids(object):
"""Get the exposure for a particular line in the meausre table"""
import MOPdbaccess
mysql = MOPdbaccess.connect('cfeps','cfhls',dbSystem='MYSQL')
cfeps=mysql.cursor()
sql="SELECT file_id FROM measure WHERE provisional LIKE %s"
cfeps.execute(sql,(object, ))
file_ids=cfeps.fetchall()
return (file_ids) | [
"def",
"get_file_ids",
"(",
"object",
")",
":",
"import",
"MOPdbaccess",
"mysql",
"=",
"MOPdbaccess",
".",
"connect",
"(",
"'cfeps'",
",",
"'cfhls'",
",",
"dbSystem",
"=",
"'MYSQL'",
")",
"cfeps",
"=",
"mysql",
".",
"cursor",
"(",
")",
"sql",
"=",
"\"SEL... | Get the exposure for a particular line in the meausre table | [
"Get",
"the",
"exposure",
"for",
"a",
"particular",
"line",
"in",
"the",
"meausre",
"table"
] | 94f91d32ad5ec081d5a1ebd67604a838003465af | https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/jjk/preproc/verifyDetection.py#L34-L43 | train | 47,871 |
OSSOS/MOP | src/ossos/core/scripts/update_header.py | main | def main():
"""Do the script."""
parser = argparse.ArgumentParser(
description='replace image header')
parser.add_argument('--extname',
help='name of extension to in header')
parser.add_argument('expnum', type=str,
help='exposure to update')
parser.add_argument('-r', '--replace',
action='store_true',
help='store modified image back to VOSpace?')
parser.add_argument('-v', '--verbose', action='store_true')
parser.add_argument('--debug', action='store_true')
parser.add_argument('--force', action='store_true', help="Re-run even if previous success recorded")
parser.add_argument('--dbimages', help="VOSpace DATA storage area.", default="vos:OSSOS/dbimages")
args = parser.parse_args()
task = util.task()
dependency = 'preproc'
prefix = ""
storage.DBIMAGES = args.dbimages
level = logging.CRITICAL
message_format = "%(message)s"
if args.verbose:
level = logging.INFO
if args.debug:
level = logging.DEBUG
message_format = "%(module)s %(funcName)s %(lineno)s %(message)s"
logging.basicConfig(level=level, format=message_format)
storage.set_logger(task, prefix, args.expnum, None, None, False)
message = storage.SUCCESS
expnum = args.expnum
exit_status = 0
try:
# skip if already succeeded and not in force mode
if storage.get_status(task, prefix, expnum, "p", 36) and not args.force:
logging.info("Already updated, skipping")
sys.exit(0)
image_hdulist = storage.get_image(args.expnum, return_file=False)
ast_hdulist = storage.get_astheader(expnum, ccd=None)
run_update_header(image_hdulist, ast_hdulist)
image_filename = os.path.basename(storage.get_uri(expnum))
image_hdulist.writeto(image_filename)
if args.replace:
dest = storage.dbimages_uri(expnum)
storage.copy(image_filename, dest)
storage.set_status('update_header', "", expnum, 'p', 36, message)
except Exception as e:
message = str(e)
if args.replace:
storage.set_status(task, prefix, expnum, 'p', 36, message)
exit_status = message
logging.error(message)
return exit_status | python | def main():
"""Do the script."""
parser = argparse.ArgumentParser(
description='replace image header')
parser.add_argument('--extname',
help='name of extension to in header')
parser.add_argument('expnum', type=str,
help='exposure to update')
parser.add_argument('-r', '--replace',
action='store_true',
help='store modified image back to VOSpace?')
parser.add_argument('-v', '--verbose', action='store_true')
parser.add_argument('--debug', action='store_true')
parser.add_argument('--force', action='store_true', help="Re-run even if previous success recorded")
parser.add_argument('--dbimages', help="VOSpace DATA storage area.", default="vos:OSSOS/dbimages")
args = parser.parse_args()
task = util.task()
dependency = 'preproc'
prefix = ""
storage.DBIMAGES = args.dbimages
level = logging.CRITICAL
message_format = "%(message)s"
if args.verbose:
level = logging.INFO
if args.debug:
level = logging.DEBUG
message_format = "%(module)s %(funcName)s %(lineno)s %(message)s"
logging.basicConfig(level=level, format=message_format)
storage.set_logger(task, prefix, args.expnum, None, None, False)
message = storage.SUCCESS
expnum = args.expnum
exit_status = 0
try:
# skip if already succeeded and not in force mode
if storage.get_status(task, prefix, expnum, "p", 36) and not args.force:
logging.info("Already updated, skipping")
sys.exit(0)
image_hdulist = storage.get_image(args.expnum, return_file=False)
ast_hdulist = storage.get_astheader(expnum, ccd=None)
run_update_header(image_hdulist, ast_hdulist)
image_filename = os.path.basename(storage.get_uri(expnum))
image_hdulist.writeto(image_filename)
if args.replace:
dest = storage.dbimages_uri(expnum)
storage.copy(image_filename, dest)
storage.set_status('update_header', "", expnum, 'p', 36, message)
except Exception as e:
message = str(e)
if args.replace:
storage.set_status(task, prefix, expnum, 'p', 36, message)
exit_status = message
logging.error(message)
return exit_status | [
"def",
"main",
"(",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"'replace image header'",
")",
"parser",
".",
"add_argument",
"(",
"'--extname'",
",",
"help",
"=",
"'name of extension to in header'",
")",
"parser",
".",
"... | Do the script. | [
"Do",
"the",
"script",
"."
] | 94f91d32ad5ec081d5a1ebd67604a838003465af | https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/scripts/update_header.py#L48-L108 | train | 47,872 |
OSSOS/MOP | src/ossos/core/ossos/gui/errorhandling.py | DownloadErrorHandler.handle_error | def handle_error(self, error, download_request):
"""
Checks what error occured and looks for an appropriate solution.
Args:
error: Exception
The error that has occured.
download_request:
The request which resulted in the error.
"""
if hasattr(error, "errno") and error.errno == errno.EACCES:
self.handle_certificate_problem(str(error))
else:
self.handle_general_download_error(str(error), download_request) | python | def handle_error(self, error, download_request):
"""
Checks what error occured and looks for an appropriate solution.
Args:
error: Exception
The error that has occured.
download_request:
The request which resulted in the error.
"""
if hasattr(error, "errno") and error.errno == errno.EACCES:
self.handle_certificate_problem(str(error))
else:
self.handle_general_download_error(str(error), download_request) | [
"def",
"handle_error",
"(",
"self",
",",
"error",
",",
"download_request",
")",
":",
"if",
"hasattr",
"(",
"error",
",",
"\"errno\"",
")",
"and",
"error",
".",
"errno",
"==",
"errno",
".",
"EACCES",
":",
"self",
".",
"handle_certificate_problem",
"(",
"str... | Checks what error occured and looks for an appropriate solution.
Args:
error: Exception
The error that has occured.
download_request:
The request which resulted in the error. | [
"Checks",
"what",
"error",
"occured",
"and",
"looks",
"for",
"an",
"appropriate",
"solution",
"."
] | 94f91d32ad5ec081d5a1ebd67604a838003465af | https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/gui/errorhandling.py#L19-L32 | train | 47,873 |
OSSOS/MOP | src/ossos/core/ossos/gui/models/validation.py | ValidationModel.get_current_observation_date | def get_current_observation_date(self):
"""
Get the date of the current observation by looking in the header
of the observation for the DATE and EXPTIME keywords.
The 'DATE AT MIDDLE OF OBSERVATION' of the observation is returned
@return: Time
"""
# All HDU elements have the same date and time so just use
# last one, sometimes the first one is missing the header, in MEF
header = self.get_current_cutout().hdulist[-1].header
mjd_obs = float(header.get('MJD-OBS'))
exptime = float(header.get('EXPTIME'))
mpc_date = Time(mjd_obs,
format='mjd',
scale='utc',
precision=config.read('MPC.DATE_PRECISION'))
mpc_date += TimeDelta(exptime * units.second) / 2.0
mpc_date = mpc_date.mpc
return mpc_date | python | def get_current_observation_date(self):
"""
Get the date of the current observation by looking in the header
of the observation for the DATE and EXPTIME keywords.
The 'DATE AT MIDDLE OF OBSERVATION' of the observation is returned
@return: Time
"""
# All HDU elements have the same date and time so just use
# last one, sometimes the first one is missing the header, in MEF
header = self.get_current_cutout().hdulist[-1].header
mjd_obs = float(header.get('MJD-OBS'))
exptime = float(header.get('EXPTIME'))
mpc_date = Time(mjd_obs,
format='mjd',
scale='utc',
precision=config.read('MPC.DATE_PRECISION'))
mpc_date += TimeDelta(exptime * units.second) / 2.0
mpc_date = mpc_date.mpc
return mpc_date | [
"def",
"get_current_observation_date",
"(",
"self",
")",
":",
"# All HDU elements have the same date and time so just use",
"# last one, sometimes the first one is missing the header, in MEF",
"header",
"=",
"self",
".",
"get_current_cutout",
"(",
")",
".",
"hdulist",
"[",
"-",
... | Get the date of the current observation by looking in the header
of the observation for the DATE and EXPTIME keywords.
The 'DATE AT MIDDLE OF OBSERVATION' of the observation is returned
@return: Time | [
"Get",
"the",
"date",
"of",
"the",
"current",
"observation",
"by",
"looking",
"in",
"the",
"header",
"of",
"the",
"observation",
"for",
"the",
"DATE",
"and",
"EXPTIME",
"keywords",
"."
] | 94f91d32ad5ec081d5a1ebd67604a838003465af | https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/gui/models/validation.py#L222-L241 | train | 47,874 |
OSSOS/MOP | src/ossos/utils/effunction.py | parse_eff | def parse_eff(filename):
"""
Parse through Jean-Marcs OSSSO .eff files.
The efficiency files comes in 'chunks' meant to be used at different 'rates' of motion.
"""
blocks = []
block = {}
with open(filename) as efile:
for line in efile.readlines():
if line.lstrip().startswith("#"):
continue
keyword = line.lstrip().split("=")[0]
funcs = {'square_param': parse_square_param,
'rates': rates}
block[keyword] = funcs.get(keyword, dummy)(line)
if keyword == 'mag_lim':
blocks.append(block)
block = {}
return blocks | python | def parse_eff(filename):
"""
Parse through Jean-Marcs OSSSO .eff files.
The efficiency files comes in 'chunks' meant to be used at different 'rates' of motion.
"""
blocks = []
block = {}
with open(filename) as efile:
for line in efile.readlines():
if line.lstrip().startswith("#"):
continue
keyword = line.lstrip().split("=")[0]
funcs = {'square_param': parse_square_param,
'rates': rates}
block[keyword] = funcs.get(keyword, dummy)(line)
if keyword == 'mag_lim':
blocks.append(block)
block = {}
return blocks | [
"def",
"parse_eff",
"(",
"filename",
")",
":",
"blocks",
"=",
"[",
"]",
"block",
"=",
"{",
"}",
"with",
"open",
"(",
"filename",
")",
"as",
"efile",
":",
"for",
"line",
"in",
"efile",
".",
"readlines",
"(",
")",
":",
"if",
"line",
".",
"lstrip",
... | Parse through Jean-Marcs OSSSO .eff files.
The efficiency files comes in 'chunks' meant to be used at different 'rates' of motion. | [
"Parse",
"through",
"Jean",
"-",
"Marcs",
"OSSSO",
".",
"eff",
"files",
".",
"The",
"efficiency",
"files",
"comes",
"in",
"chunks",
"meant",
"to",
"be",
"used",
"at",
"different",
"rates",
"of",
"motion",
"."
] | 94f91d32ad5ec081d5a1ebd67604a838003465af | https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/utils/effunction.py#L57-L79 | train | 47,875 |
OSSOS/MOP | src/ossos/core/ossos/gui/config.py | read | def read(keypath, configfile=None):
"""
Reads a value from the configuration file.
Args:
keypath: str
Specifies the key for which the value is desired. It can be a
hierarchical path. Example: "section1.subsection.key1"
configfile: str
Path to the config file to read. Defaults to None, in which case
the application's default config file is used.
Returns:
value from configuration file
"""
if configfile in _configs:
appconfig = _configs[configfile]
else:
appconfig = AppConfig(configfile=configfile)
_configs[configfile] = appconfig
return appconfig.read(keypath) | python | def read(keypath, configfile=None):
"""
Reads a value from the configuration file.
Args:
keypath: str
Specifies the key for which the value is desired. It can be a
hierarchical path. Example: "section1.subsection.key1"
configfile: str
Path to the config file to read. Defaults to None, in which case
the application's default config file is used.
Returns:
value from configuration file
"""
if configfile in _configs:
appconfig = _configs[configfile]
else:
appconfig = AppConfig(configfile=configfile)
_configs[configfile] = appconfig
return appconfig.read(keypath) | [
"def",
"read",
"(",
"keypath",
",",
"configfile",
"=",
"None",
")",
":",
"if",
"configfile",
"in",
"_configs",
":",
"appconfig",
"=",
"_configs",
"[",
"configfile",
"]",
"else",
":",
"appconfig",
"=",
"AppConfig",
"(",
"configfile",
"=",
"configfile",
")",... | Reads a value from the configuration file.
Args:
keypath: str
Specifies the key for which the value is desired. It can be a
hierarchical path. Example: "section1.subsection.key1"
configfile: str
Path to the config file to read. Defaults to None, in which case
the application's default config file is used.
Returns:
value from configuration file | [
"Reads",
"a",
"value",
"from",
"the",
"configuration",
"file",
"."
] | 94f91d32ad5ec081d5a1ebd67604a838003465af | https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/gui/config.py#L10-L31 | train | 47,876 |
OSSOS/MOP | src/ossos/core/ossos/ephem_target.py | EphemTarget._cdata_header | def _cdata_header(self, colsep="|"):
"""
Create a header for the CDATA section, as a visual guide.
"""
fields = self.fields
header_lines = []
line = ""
for fieldName in self.field_names:
width = int(fields[fieldName]['attr']['width'])
line += self._entry(fieldName, width, colsep)
header_lines.append(line)
line = ""
for fieldName in self.field_names:
width = int(fields[fieldName]['attr']['width'])
line += self._entry(fields[fieldName]['attr']['format'], width=width, colsep=colsep)
header_lines.append(line)
line = ""
for fieldName in self.field_names:
width = int(fields[fieldName]['attr']['width'])
(l, m) = divmod(width, 10)
guide = ""
for i in range(l):
guide += "".join(map(str, range(10)))
guide += "".join(map(str, range(m)))
line += self._entry(guide, width=width, colsep=colsep)
header_lines.append(line)
line = ""
for fieldName in self.field_names:
width = int(fields[fieldName]['attr']['width'])
guide = "-" * width
line += self._entry(guide, width=width, colsep=colsep)
header_lines.append(line)
return header_lines | python | def _cdata_header(self, colsep="|"):
"""
Create a header for the CDATA section, as a visual guide.
"""
fields = self.fields
header_lines = []
line = ""
for fieldName in self.field_names:
width = int(fields[fieldName]['attr']['width'])
line += self._entry(fieldName, width, colsep)
header_lines.append(line)
line = ""
for fieldName in self.field_names:
width = int(fields[fieldName]['attr']['width'])
line += self._entry(fields[fieldName]['attr']['format'], width=width, colsep=colsep)
header_lines.append(line)
line = ""
for fieldName in self.field_names:
width = int(fields[fieldName]['attr']['width'])
(l, m) = divmod(width, 10)
guide = ""
for i in range(l):
guide += "".join(map(str, range(10)))
guide += "".join(map(str, range(m)))
line += self._entry(guide, width=width, colsep=colsep)
header_lines.append(line)
line = ""
for fieldName in self.field_names:
width = int(fields[fieldName]['attr']['width'])
guide = "-" * width
line += self._entry(guide, width=width, colsep=colsep)
header_lines.append(line)
return header_lines | [
"def",
"_cdata_header",
"(",
"self",
",",
"colsep",
"=",
"\"|\"",
")",
":",
"fields",
"=",
"self",
".",
"fields",
"header_lines",
"=",
"[",
"]",
"line",
"=",
"\"\"",
"for",
"fieldName",
"in",
"self",
".",
"field_names",
":",
"width",
"=",
"int",
"(",
... | Create a header for the CDATA section, as a visual guide. | [
"Create",
"a",
"header",
"for",
"the",
"CDATA",
"section",
"as",
"a",
"visual",
"guide",
"."
] | 94f91d32ad5ec081d5a1ebd67604a838003465af | https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/ephem_target.py#L103-L139 | train | 47,877 |
OSSOS/MOP | src/ossos/core/ossos/ephem_target.py | EphemTarget._append_cdata | def _append_cdata(self, coordinate):
"""
Append an target location to the ephemeris listing.
"""
fields = self.fields
sra = coordinate.ra.to_string(units.hour, sep=':', precision=2, pad=True)
sdec = coordinate.dec.to_string(units.degree, sep=':', precision=1, alwayssign=True)
coord = SkyCoord(sra + " " + sdec, unit=(units.hour, units.degree))
sra = coord.ra.to_string(units.hour, sep=":", precision=2, pad=True)
sdec = coord.dec.to_string(units.degree, sep=":", precision=1, pad=True, alwayssign=True)
sdate = str(coordinate.obstime.replicate(format('iso')))
self.cdata.appendData(self._entry(sdate, fields["DATE_UTC"]['attr']['width'], colsep=self.column_separator))
self.cdata.appendData(self._entry(sra, fields["RA_J2000"]['attr']['width'], colsep=self.column_separator))
self.cdata.appendData(self._entry(sdec, fields["DEC_J2000"]["attr"]["width"], colsep=self.column_separator))
self.cdata.appendData("\n") | python | def _append_cdata(self, coordinate):
"""
Append an target location to the ephemeris listing.
"""
fields = self.fields
sra = coordinate.ra.to_string(units.hour, sep=':', precision=2, pad=True)
sdec = coordinate.dec.to_string(units.degree, sep=':', precision=1, alwayssign=True)
coord = SkyCoord(sra + " " + sdec, unit=(units.hour, units.degree))
sra = coord.ra.to_string(units.hour, sep=":", precision=2, pad=True)
sdec = coord.dec.to_string(units.degree, sep=":", precision=1, pad=True, alwayssign=True)
sdate = str(coordinate.obstime.replicate(format('iso')))
self.cdata.appendData(self._entry(sdate, fields["DATE_UTC"]['attr']['width'], colsep=self.column_separator))
self.cdata.appendData(self._entry(sra, fields["RA_J2000"]['attr']['width'], colsep=self.column_separator))
self.cdata.appendData(self._entry(sdec, fields["DEC_J2000"]["attr"]["width"], colsep=self.column_separator))
self.cdata.appendData("\n") | [
"def",
"_append_cdata",
"(",
"self",
",",
"coordinate",
")",
":",
"fields",
"=",
"self",
".",
"fields",
"sra",
"=",
"coordinate",
".",
"ra",
".",
"to_string",
"(",
"units",
".",
"hour",
",",
"sep",
"=",
"':'",
",",
"precision",
"=",
"2",
",",
"pad",
... | Append an target location to the ephemeris listing. | [
"Append",
"an",
"target",
"location",
"to",
"the",
"ephemeris",
"listing",
"."
] | 94f91d32ad5ec081d5a1ebd67604a838003465af | https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/ephem_target.py#L144-L158 | train | 47,878 |
OSSOS/MOP | src/ossos/core/ossos/ephem_target.py | EphemTarget.gemini_writer | def gemini_writer(self, f_handle):
"""
Write out a GEMINI formated OT ephemeris. This is just a hack of SSD Horizons output.
"""
f_handle.write(GEMINI_HEADER)
# Date__(UT)__HR:MN Date_________JDUT R.A.___(ICRF/J2000.0)___DEC dRA*cosD d(DEC)/dt
# 1 2 3 4 5 6 7 8 9
# 123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890
# ' 2019-Jan-30 00:00 01 46 56.46 +10 28 54.9 01 47 56.17 +10 34 27.6 3.520
for coordinate in self.coordinates:
date = coordinate.obstime.datetime.strftime('%Y-%b-%d %H:%M')[:17]
f_handle.write(" {:16} {:17.9f} {:27} {:+8.5f} {:+8.5f}\n".format(date,
coordinate.obstime.jd,
coordinate.to_string('hmsdms',
sep=' ',
precision=4,
pad=True)[:27],
float(coordinate.dra),
float(coordinate.ddec)),
)
f_handle.write(GEMINI_FOOTER)
return | python | def gemini_writer(self, f_handle):
"""
Write out a GEMINI formated OT ephemeris. This is just a hack of SSD Horizons output.
"""
f_handle.write(GEMINI_HEADER)
# Date__(UT)__HR:MN Date_________JDUT R.A.___(ICRF/J2000.0)___DEC dRA*cosD d(DEC)/dt
# 1 2 3 4 5 6 7 8 9
# 123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890
# ' 2019-Jan-30 00:00 01 46 56.46 +10 28 54.9 01 47 56.17 +10 34 27.6 3.520
for coordinate in self.coordinates:
date = coordinate.obstime.datetime.strftime('%Y-%b-%d %H:%M')[:17]
f_handle.write(" {:16} {:17.9f} {:27} {:+8.5f} {:+8.5f}\n".format(date,
coordinate.obstime.jd,
coordinate.to_string('hmsdms',
sep=' ',
precision=4,
pad=True)[:27],
float(coordinate.dra),
float(coordinate.ddec)),
)
f_handle.write(GEMINI_FOOTER)
return | [
"def",
"gemini_writer",
"(",
"self",
",",
"f_handle",
")",
":",
"f_handle",
".",
"write",
"(",
"GEMINI_HEADER",
")",
"# Date__(UT)__HR:MN Date_________JDUT R.A.___(ICRF/J2000.0)___DEC dRA*cosD d(DEC)/dt",
"# 1 2 3 4 5 6 7 ... | Write out a GEMINI formated OT ephemeris. This is just a hack of SSD Horizons output. | [
"Write",
"out",
"a",
"GEMINI",
"formated",
"OT",
"ephemeris",
".",
"This",
"is",
"just",
"a",
"hack",
"of",
"SSD",
"Horizons",
"output",
"."
] | 94f91d32ad5ec081d5a1ebd67604a838003465af | https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/ephem_target.py#L175-L197 | train | 47,879 |
JohnVinyard/zounds | zounds/spectral/frequencyscale.py | FrequencyBand.intersect | def intersect(self, other):
"""
Return the intersection between this frequency band and another.
Args:
other (FrequencyBand): the instance to intersect with
Examples::
>>> import zounds
>>> b1 = zounds.FrequencyBand(500, 1000)
>>> b2 = zounds.FrequencyBand(900, 2000)
>>> intersection = b1.intersect(b2)
>>> intersection.start_hz, intersection.stop_hz
(900, 1000)
"""
lowest_stop = min(self.stop_hz, other.stop_hz)
highest_start = max(self.start_hz, other.start_hz)
return FrequencyBand(highest_start, lowest_stop) | python | def intersect(self, other):
"""
Return the intersection between this frequency band and another.
Args:
other (FrequencyBand): the instance to intersect with
Examples::
>>> import zounds
>>> b1 = zounds.FrequencyBand(500, 1000)
>>> b2 = zounds.FrequencyBand(900, 2000)
>>> intersection = b1.intersect(b2)
>>> intersection.start_hz, intersection.stop_hz
(900, 1000)
"""
lowest_stop = min(self.stop_hz, other.stop_hz)
highest_start = max(self.start_hz, other.start_hz)
return FrequencyBand(highest_start, lowest_stop) | [
"def",
"intersect",
"(",
"self",
",",
"other",
")",
":",
"lowest_stop",
"=",
"min",
"(",
"self",
".",
"stop_hz",
",",
"other",
".",
"stop_hz",
")",
"highest_start",
"=",
"max",
"(",
"self",
".",
"start_hz",
",",
"other",
".",
"start_hz",
")",
"return",... | Return the intersection between this frequency band and another.
Args:
other (FrequencyBand): the instance to intersect with
Examples::
>>> import zounds
>>> b1 = zounds.FrequencyBand(500, 1000)
>>> b2 = zounds.FrequencyBand(900, 2000)
>>> intersection = b1.intersect(b2)
>>> intersection.start_hz, intersection.stop_hz
(900, 1000) | [
"Return",
"the",
"intersection",
"between",
"this",
"frequency",
"band",
"and",
"another",
"."
] | 337b3f98753d09eaab1c72dcd37bb852a3fa5ac6 | https://github.com/JohnVinyard/zounds/blob/337b3f98753d09eaab1c72dcd37bb852a3fa5ac6/zounds/spectral/frequencyscale.py#L66-L83 | train | 47,880 |
JohnVinyard/zounds | zounds/spectral/frequencyscale.py | FrequencyScale.bands | def bands(self):
"""
An iterable of all bands in this scale
"""
if self._bands is None:
self._bands = self._compute_bands()
return self._bands | python | def bands(self):
"""
An iterable of all bands in this scale
"""
if self._bands is None:
self._bands = self._compute_bands()
return self._bands | [
"def",
"bands",
"(",
"self",
")",
":",
"if",
"self",
".",
"_bands",
"is",
"None",
":",
"self",
".",
"_bands",
"=",
"self",
".",
"_compute_bands",
"(",
")",
"return",
"self",
".",
"_bands"
] | An iterable of all bands in this scale | [
"An",
"iterable",
"of",
"all",
"bands",
"in",
"this",
"scale"
] | 337b3f98753d09eaab1c72dcd37bb852a3fa5ac6 | https://github.com/JohnVinyard/zounds/blob/337b3f98753d09eaab1c72dcd37bb852a3fa5ac6/zounds/spectral/frequencyscale.py#L167-L173 | train | 47,881 |
JohnVinyard/zounds | zounds/spectral/frequencyscale.py | FrequencyScale.Q | def Q(self):
"""
The quality factor of the scale, or, the ratio of center frequencies
to bandwidths
"""
return np.array(list(self.center_frequencies)) \
/ np.array(list(self.bandwidths)) | python | def Q(self):
"""
The quality factor of the scale, or, the ratio of center frequencies
to bandwidths
"""
return np.array(list(self.center_frequencies)) \
/ np.array(list(self.bandwidths)) | [
"def",
"Q",
"(",
"self",
")",
":",
"return",
"np",
".",
"array",
"(",
"list",
"(",
"self",
".",
"center_frequencies",
")",
")",
"/",
"np",
".",
"array",
"(",
"list",
"(",
"self",
".",
"bandwidths",
")",
")"
] | The quality factor of the scale, or, the ratio of center frequencies
to bandwidths | [
"The",
"quality",
"factor",
"of",
"the",
"scale",
"or",
"the",
"ratio",
"of",
"center",
"frequencies",
"to",
"bandwidths"
] | 337b3f98753d09eaab1c72dcd37bb852a3fa5ac6 | https://github.com/JohnVinyard/zounds/blob/337b3f98753d09eaab1c72dcd37bb852a3fa5ac6/zounds/spectral/frequencyscale.py#L241-L247 | train | 47,882 |
JohnVinyard/zounds | zounds/spectral/frequencyscale.py | FrequencyScale.get_slice | def get_slice(self, frequency_band):
"""
Given a frequency band, and a frequency dimension comprised of
n_samples, return a slice using integer indices that may be used to
extract only the frequency samples that intersect with the frequency
band
"""
index = frequency_band
if isinstance(index, slice):
types = {
index.start.__class__,
index.stop.__class__,
index.step.__class__
}
if Hertz not in types:
return index
try:
start = Hertz(0) if index.start is None else index.start
if start < Hertz(0):
start = self.stop_hz + start
stop = self.stop_hz if index.stop is None else index.stop
if stop < Hertz(0):
stop = self.stop_hz + stop
frequency_band = FrequencyBand(start, stop)
except (ValueError, TypeError):
pass
start_index = bisect.bisect_left(
self.band_stops, frequency_band.start_hz)
stop_index = bisect.bisect_left(
self.band_starts, frequency_band.stop_hz)
if self.always_even and (stop_index - start_index) % 2:
# KLUDGE: This is simple, but it may make sense to choose move the
# upper *or* lower bound, based on which one introduces a lower
# error
stop_index += 1
return slice(start_index, stop_index) | python | def get_slice(self, frequency_band):
"""
Given a frequency band, and a frequency dimension comprised of
n_samples, return a slice using integer indices that may be used to
extract only the frequency samples that intersect with the frequency
band
"""
index = frequency_band
if isinstance(index, slice):
types = {
index.start.__class__,
index.stop.__class__,
index.step.__class__
}
if Hertz not in types:
return index
try:
start = Hertz(0) if index.start is None else index.start
if start < Hertz(0):
start = self.stop_hz + start
stop = self.stop_hz if index.stop is None else index.stop
if stop < Hertz(0):
stop = self.stop_hz + stop
frequency_band = FrequencyBand(start, stop)
except (ValueError, TypeError):
pass
start_index = bisect.bisect_left(
self.band_stops, frequency_band.start_hz)
stop_index = bisect.bisect_left(
self.band_starts, frequency_band.stop_hz)
if self.always_even and (stop_index - start_index) % 2:
# KLUDGE: This is simple, but it may make sense to choose move the
# upper *or* lower bound, based on which one introduces a lower
# error
stop_index += 1
return slice(start_index, stop_index) | [
"def",
"get_slice",
"(",
"self",
",",
"frequency_band",
")",
":",
"index",
"=",
"frequency_band",
"if",
"isinstance",
"(",
"index",
",",
"slice",
")",
":",
"types",
"=",
"{",
"index",
".",
"start",
".",
"__class__",
",",
"index",
".",
"stop",
".",
"__c... | Given a frequency band, and a frequency dimension comprised of
n_samples, return a slice using integer indices that may be used to
extract only the frequency samples that intersect with the frequency
band | [
"Given",
"a",
"frequency",
"band",
"and",
"a",
"frequency",
"dimension",
"comprised",
"of",
"n_samples",
"return",
"a",
"slice",
"using",
"integer",
"indices",
"that",
"may",
"be",
"used",
"to",
"extract",
"only",
"the",
"frequency",
"samples",
"that",
"inters... | 337b3f98753d09eaab1c72dcd37bb852a3fa5ac6 | https://github.com/JohnVinyard/zounds/blob/337b3f98753d09eaab1c72dcd37bb852a3fa5ac6/zounds/spectral/frequencyscale.py#L289-L329 | train | 47,883 |
JohnVinyard/zounds | zounds/spectral/frequencyscale.py | ChromaScale._hz_to_semitones | def _hz_to_semitones(self, hz):
"""
Convert hertz into a number of semitones above or below some reference
value, in this case, A440
"""
return np.log(hz / self._a440) / np.log(self._a) | python | def _hz_to_semitones(self, hz):
"""
Convert hertz into a number of semitones above or below some reference
value, in this case, A440
"""
return np.log(hz / self._a440) / np.log(self._a) | [
"def",
"_hz_to_semitones",
"(",
"self",
",",
"hz",
")",
":",
"return",
"np",
".",
"log",
"(",
"hz",
"/",
"self",
".",
"_a440",
")",
"/",
"np",
".",
"log",
"(",
"self",
".",
"_a",
")"
] | Convert hertz into a number of semitones above or below some reference
value, in this case, A440 | [
"Convert",
"hertz",
"into",
"a",
"number",
"of",
"semitones",
"above",
"or",
"below",
"some",
"reference",
"value",
"in",
"this",
"case",
"A440"
] | 337b3f98753d09eaab1c72dcd37bb852a3fa5ac6 | https://github.com/JohnVinyard/zounds/blob/337b3f98753d09eaab1c72dcd37bb852a3fa5ac6/zounds/spectral/frequencyscale.py#L592-L597 | train | 47,884 |
OSSOS/MOP | src/jjk/preproc/cfhtCutout.py | resolve | def resolve(object):
"""Look up the name of a source using a resolver"""
import re
sesame_cmd = 'curl -s http://cdsweb.u-strasbg.fr/viz-bin/nph-sesame/-oI?'+string.replace(object,' ','')
f = os.popen(sesame_cmd)
lines = f.readlines()
f.close()
for line in lines:
if re.search('%J ', line):
result2 = line.split()
ra_deg = float(result2[1])
dec_deg = float(result2[2])
return (ra_deg, dec_deg)
return (0,0) | python | def resolve(object):
"""Look up the name of a source using a resolver"""
import re
sesame_cmd = 'curl -s http://cdsweb.u-strasbg.fr/viz-bin/nph-sesame/-oI?'+string.replace(object,' ','')
f = os.popen(sesame_cmd)
lines = f.readlines()
f.close()
for line in lines:
if re.search('%J ', line):
result2 = line.split()
ra_deg = float(result2[1])
dec_deg = float(result2[2])
return (ra_deg, dec_deg)
return (0,0) | [
"def",
"resolve",
"(",
"object",
")",
":",
"import",
"re",
"sesame_cmd",
"=",
"'curl -s http://cdsweb.u-strasbg.fr/viz-bin/nph-sesame/-oI?'",
"+",
"string",
".",
"replace",
"(",
"object",
",",
"' '",
",",
"''",
")",
"f",
"=",
"os",
".",
"popen",
"(",
"sesame_c... | Look up the name of a source using a resolver | [
"Look",
"up",
"the",
"name",
"of",
"a",
"source",
"using",
"a",
"resolver"
] | 94f91d32ad5ec081d5a1ebd67604a838003465af | https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/jjk/preproc/cfhtCutout.py#L74-L90 | train | 47,885 |
OSSOS/MOP | src/jjk/preproc/demo.py | handle_exit_code | def handle_exit_code(d, code):
"""Sample function showing how to interpret the dialog exit codes.
This function is not used after every call to dialog in this demo
for two reasons:
1. For some boxes, unfortunately, dialog returns the code for
ERROR when the user presses ESC (instead of the one chosen
for ESC). As these boxes only have an OK button, and an
exception is raised and correctly handled here in case of
real dialog errors, there is no point in testing the dialog
exit status (it can't be CANCEL as there is no CANCEL
button; it can't be ESC as unfortunately, the dialog makes
it appear as an error; it can't be ERROR as this is handled
in dialog.py to raise an exception; therefore, it *is* OK).
2. To not clutter simple code with things that are
demonstrated elsewhere.
"""
# d is supposed to be a Dialog instance
if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
if code == d.DIALOG_CANCEL:
msg = "You chose cancel in the last dialog box. Do you want to " \
"exit this demo?"
else:
msg = "You pressed ESC in the last dialog box. Do you want to " \
"exit this demo?"
# "No" or "ESC" will bring the user back to the demo.
# DIALOG_ERROR is propagated as an exception and caught in main().
# So we only need to handle OK here.
if d.yesno(msg) == d.DIALOG_OK:
sys.exit(0)
return 0
else:
return 1 | python | def handle_exit_code(d, code):
"""Sample function showing how to interpret the dialog exit codes.
This function is not used after every call to dialog in this demo
for two reasons:
1. For some boxes, unfortunately, dialog returns the code for
ERROR when the user presses ESC (instead of the one chosen
for ESC). As these boxes only have an OK button, and an
exception is raised and correctly handled here in case of
real dialog errors, there is no point in testing the dialog
exit status (it can't be CANCEL as there is no CANCEL
button; it can't be ESC as unfortunately, the dialog makes
it appear as an error; it can't be ERROR as this is handled
in dialog.py to raise an exception; therefore, it *is* OK).
2. To not clutter simple code with things that are
demonstrated elsewhere.
"""
# d is supposed to be a Dialog instance
if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
if code == d.DIALOG_CANCEL:
msg = "You chose cancel in the last dialog box. Do you want to " \
"exit this demo?"
else:
msg = "You pressed ESC in the last dialog box. Do you want to " \
"exit this demo?"
# "No" or "ESC" will bring the user back to the demo.
# DIALOG_ERROR is propagated as an exception and caught in main().
# So we only need to handle OK here.
if d.yesno(msg) == d.DIALOG_OK:
sys.exit(0)
return 0
else:
return 1 | [
"def",
"handle_exit_code",
"(",
"d",
",",
"code",
")",
":",
"# d is supposed to be a Dialog instance",
"if",
"code",
"in",
"(",
"d",
".",
"DIALOG_CANCEL",
",",
"d",
".",
"DIALOG_ESC",
")",
":",
"if",
"code",
"==",
"d",
".",
"DIALOG_CANCEL",
":",
"msg",
"="... | Sample function showing how to interpret the dialog exit codes.
This function is not used after every call to dialog in this demo
for two reasons:
1. For some boxes, unfortunately, dialog returns the code for
ERROR when the user presses ESC (instead of the one chosen
for ESC). As these boxes only have an OK button, and an
exception is raised and correctly handled here in case of
real dialog errors, there is no point in testing the dialog
exit status (it can't be CANCEL as there is no CANCEL
button; it can't be ESC as unfortunately, the dialog makes
it appear as an error; it can't be ERROR as this is handled
in dialog.py to raise an exception; therefore, it *is* OK).
2. To not clutter simple code with things that are
demonstrated elsewhere. | [
"Sample",
"function",
"showing",
"how",
"to",
"interpret",
"the",
"dialog",
"exit",
"codes",
"."
] | 94f91d32ad5ec081d5a1ebd67604a838003465af | https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/jjk/preproc/demo.py#L28-L63 | train | 47,886 |
OSSOS/MOP | src/jjk/preproc/demo.py | main | def main():
"""This demo shows the main features of the pythondialog Dialog class.
"""
try:
demo()
except dialog.error, exc_instance:
sys.stderr.write("Error:\n\n%s\n" % exc_instance.complete_message())
sys.exit(1)
sys.exit(0) | python | def main():
"""This demo shows the main features of the pythondialog Dialog class.
"""
try:
demo()
except dialog.error, exc_instance:
sys.stderr.write("Error:\n\n%s\n" % exc_instance.complete_message())
sys.exit(1)
sys.exit(0) | [
"def",
"main",
"(",
")",
":",
"try",
":",
"demo",
"(",
")",
"except",
"dialog",
".",
"error",
",",
"exc_instance",
":",
"sys",
".",
"stderr",
".",
"write",
"(",
"\"Error:\\n\\n%s\\n\"",
"%",
"exc_instance",
".",
"complete_message",
"(",
")",
")",
"sys",
... | This demo shows the main features of the pythondialog Dialog class. | [
"This",
"demo",
"shows",
"the",
"main",
"features",
"of",
"the",
"pythondialog",
"Dialog",
"class",
"."
] | 94f91d32ad5ec081d5a1ebd67604a838003465af | https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/jjk/preproc/demo.py#L307-L317 | train | 47,887 |
OSSOS/MOP | src/ossos/core/ossos/planning/optimize_pointings.py | is_up | def is_up(coordinate, current_time):
"""
Given the position and time determin if the given target is up.
@param coordinate: the J2000 location of the source
@param current_time: The time of the observations
@return: True/False
"""
cfht.date = current_time.iso.replace('-', '/')
cfht.horizon = math.radians(-7)
sun.compute(cfht)
sun_rise = Time(str(sun.rise_time).replace('/', '-'))
sun_set = Time(str(sun.set_time).replace('/', '-'))
if current_time < sun_set or current_time > sun_rise:
return False
fb._ra = coordinate.ra.radian
fb._dec = coordinate.dec.radian
cfht.horizon = math.radians(40)
fb.compute(cfht)
fb_rise_time = Time(str(fb.rise_time).replace('/', '-'))
fb_set_time = Time(str(fb.set_time).replace('/', '-'))
if (current_time > fb_set_time > fb_set_time or
fb_rise_time > current_time > fb_set_time):
return False
return True | python | def is_up(coordinate, current_time):
"""
Given the position and time determin if the given target is up.
@param coordinate: the J2000 location of the source
@param current_time: The time of the observations
@return: True/False
"""
cfht.date = current_time.iso.replace('-', '/')
cfht.horizon = math.radians(-7)
sun.compute(cfht)
sun_rise = Time(str(sun.rise_time).replace('/', '-'))
sun_set = Time(str(sun.set_time).replace('/', '-'))
if current_time < sun_set or current_time > sun_rise:
return False
fb._ra = coordinate.ra.radian
fb._dec = coordinate.dec.radian
cfht.horizon = math.radians(40)
fb.compute(cfht)
fb_rise_time = Time(str(fb.rise_time).replace('/', '-'))
fb_set_time = Time(str(fb.set_time).replace('/', '-'))
if (current_time > fb_set_time > fb_set_time or
fb_rise_time > current_time > fb_set_time):
return False
return True | [
"def",
"is_up",
"(",
"coordinate",
",",
"current_time",
")",
":",
"cfht",
".",
"date",
"=",
"current_time",
".",
"iso",
".",
"replace",
"(",
"'-'",
",",
"'/'",
")",
"cfht",
".",
"horizon",
"=",
"math",
".",
"radians",
"(",
"-",
"7",
")",
"sun",
"."... | Given the position and time determin if the given target is up.
@param coordinate: the J2000 location of the source
@param current_time: The time of the observations
@return: True/False | [
"Given",
"the",
"position",
"and",
"time",
"determin",
"if",
"the",
"given",
"target",
"is",
"up",
"."
] | 94f91d32ad5ec081d5a1ebd67604a838003465af | https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/planning/optimize_pointings.py#L27-L54 | train | 47,888 |
openstack/python-scciclient | scciclient/irmc/viom/elcm.py | VIOMTable.get_json | def get_json(self):
"""Create JSON data for AdapterConfig.
:returns: JSON data as follows:
{
"VIOMManage":{
},
"InitBoot":{
},
"UseVirtualAddresses":{
},
"BootMenuEnable":{
},
"SmuxSetting":{
},
"Slots":{
}
}
"""
viom_table = self.get_basic_json()
if self.slots:
viom_table['Slots'] = {
'Slot': [s.get_json() for s in self.slots.values()]
}
if self.manage:
viom_table['VIOMManage'] = self.manage.get_json()
return viom_table | python | def get_json(self):
"""Create JSON data for AdapterConfig.
:returns: JSON data as follows:
{
"VIOMManage":{
},
"InitBoot":{
},
"UseVirtualAddresses":{
},
"BootMenuEnable":{
},
"SmuxSetting":{
},
"Slots":{
}
}
"""
viom_table = self.get_basic_json()
if self.slots:
viom_table['Slots'] = {
'Slot': [s.get_json() for s in self.slots.values()]
}
if self.manage:
viom_table['VIOMManage'] = self.manage.get_json()
return viom_table | [
"def",
"get_json",
"(",
"self",
")",
":",
"viom_table",
"=",
"self",
".",
"get_basic_json",
"(",
")",
"if",
"self",
".",
"slots",
":",
"viom_table",
"[",
"'Slots'",
"]",
"=",
"{",
"'Slot'",
":",
"[",
"s",
".",
"get_json",
"(",
")",
"for",
"s",
"in"... | Create JSON data for AdapterConfig.
:returns: JSON data as follows:
{
"VIOMManage":{
},
"InitBoot":{
},
"UseVirtualAddresses":{
},
"BootMenuEnable":{
},
"SmuxSetting":{
},
"Slots":{
}
} | [
"Create",
"JSON",
"data",
"for",
"AdapterConfig",
"."
] | 4585ce2f76853b9773fb190ca0cfff0aa04a7cf8 | https://github.com/openstack/python-scciclient/blob/4585ce2f76853b9773fb190ca0cfff0aa04a7cf8/scciclient/irmc/viom/elcm.py#L171-L198 | train | 47,889 |
openstack/python-scciclient | scciclient/irmc/viom/elcm.py | Slot.get_json | def get_json(self):
"""Create JSON data for slot.
:returns: JSON data for slot as follows:
{
"@SlotIdx":0,
"OnboardControllers":{
"OnboardController": [
]
},
"AddOnCards":{
"AddOnCard": [
]
}
}
"""
json = self.get_basic_json()
if self.onboard_cards:
json['OnboardControllers'] = {
'OnboardController':
[c.get_json() for c in self.onboard_cards.values()]
}
if self.addon_cards:
json['AddOnCards'] = {
'AddOnCard': [c.get_json() for c in self.addon_cards.values()]
}
return json | python | def get_json(self):
"""Create JSON data for slot.
:returns: JSON data for slot as follows:
{
"@SlotIdx":0,
"OnboardControllers":{
"OnboardController": [
]
},
"AddOnCards":{
"AddOnCard": [
]
}
}
"""
json = self.get_basic_json()
if self.onboard_cards:
json['OnboardControllers'] = {
'OnboardController':
[c.get_json() for c in self.onboard_cards.values()]
}
if self.addon_cards:
json['AddOnCards'] = {
'AddOnCard': [c.get_json() for c in self.addon_cards.values()]
}
return json | [
"def",
"get_json",
"(",
"self",
")",
":",
"json",
"=",
"self",
".",
"get_basic_json",
"(",
")",
"if",
"self",
".",
"onboard_cards",
":",
"json",
"[",
"'OnboardControllers'",
"]",
"=",
"{",
"'OnboardController'",
":",
"[",
"c",
".",
"get_json",
"(",
")",
... | Create JSON data for slot.
:returns: JSON data for slot as follows:
{
"@SlotIdx":0,
"OnboardControllers":{
"OnboardController": [
]
},
"AddOnCards":{
"AddOnCard": [
]
}
} | [
"Create",
"JSON",
"data",
"for",
"slot",
"."
] | 4585ce2f76853b9773fb190ca0cfff0aa04a7cf8 | https://github.com/openstack/python-scciclient/blob/4585ce2f76853b9773fb190ca0cfff0aa04a7cf8/scciclient/irmc/viom/elcm.py#L260-L287 | train | 47,890 |
openstack/python-scciclient | scciclient/irmc/viom/elcm.py | LANPort.get_json | def get_json(self):
"""Create JSON data for LANPort.
:returns: JSON data as follows:
{
"@PortIdx":1,
"PortEnable":{
},
"UseVirtualAddresses":{
},
"BootProtocol":{
},
"VirtualAddress":{
"MAC":{
}
},
"BootPriority":{
},
"ISCSIBootEnvironment":{
}
}
"""
port = self.get_basic_json()
port.update({
'BootProtocol': self.boot.BOOT_PROTOCOL,
'BootPriority': self.boot.boot_prio,
})
boot_env = self.boot.get_json()
if boot_env:
port.update(boot_env)
if self.use_virtual_addresses and self.mac:
port['VirtualAddress'] = {'MAC': self.mac}
return port | python | def get_json(self):
"""Create JSON data for LANPort.
:returns: JSON data as follows:
{
"@PortIdx":1,
"PortEnable":{
},
"UseVirtualAddresses":{
},
"BootProtocol":{
},
"VirtualAddress":{
"MAC":{
}
},
"BootPriority":{
},
"ISCSIBootEnvironment":{
}
}
"""
port = self.get_basic_json()
port.update({
'BootProtocol': self.boot.BOOT_PROTOCOL,
'BootPriority': self.boot.boot_prio,
})
boot_env = self.boot.get_json()
if boot_env:
port.update(boot_env)
if self.use_virtual_addresses and self.mac:
port['VirtualAddress'] = {'MAC': self.mac}
return port | [
"def",
"get_json",
"(",
"self",
")",
":",
"port",
"=",
"self",
".",
"get_basic_json",
"(",
")",
"port",
".",
"update",
"(",
"{",
"'BootProtocol'",
":",
"self",
".",
"boot",
".",
"BOOT_PROTOCOL",
",",
"'BootPriority'",
":",
"self",
".",
"boot",
".",
"bo... | Create JSON data for LANPort.
:returns: JSON data as follows:
{
"@PortIdx":1,
"PortEnable":{
},
"UseVirtualAddresses":{
},
"BootProtocol":{
},
"VirtualAddress":{
"MAC":{
}
},
"BootPriority":{
},
"ISCSIBootEnvironment":{
}
} | [
"Create",
"JSON",
"data",
"for",
"LANPort",
"."
] | 4585ce2f76853b9773fb190ca0cfff0aa04a7cf8 | https://github.com/openstack/python-scciclient/blob/4585ce2f76853b9773fb190ca0cfff0aa04a7cf8/scciclient/irmc/viom/elcm.py#L422-L456 | train | 47,891 |
openstack/python-scciclient | scciclient/irmc/viom/elcm.py | FCPort.get_json | def get_json(self):
"""Create FC port.
:returns: JSON for FC port as follows:
{
"@PortIdx":1,
"PortEnable":{
},
"UseVirtualAddresses":{
},
"VirtualAddress":{
"WWNN":{
},
"WWPN":{
},
"MAC":{
}
},
"BootProtocol":{
},
"BootPriority":{
},
"FCBootEnvironment":{
}
}
"""
port = self.get_basic_json()
port.update({
'BootProtocol': self.boot.BOOT_PROTOCOL,
'BootPriority': self.boot.boot_prio,
})
boot_env = self.boot.get_json()
if boot_env:
port.update(boot_env)
if self.use_virtual_addresses:
addresses = {}
if self.wwnn:
addresses['WWNN'] = self.wwnn
if self.wwpn:
addresses['WWPN'] = self.wwpn
if addresses:
port['VirtualAddress'] = addresses
return port | python | def get_json(self):
"""Create FC port.
:returns: JSON for FC port as follows:
{
"@PortIdx":1,
"PortEnable":{
},
"UseVirtualAddresses":{
},
"VirtualAddress":{
"WWNN":{
},
"WWPN":{
},
"MAC":{
}
},
"BootProtocol":{
},
"BootPriority":{
},
"FCBootEnvironment":{
}
}
"""
port = self.get_basic_json()
port.update({
'BootProtocol': self.boot.BOOT_PROTOCOL,
'BootPriority': self.boot.boot_prio,
})
boot_env = self.boot.get_json()
if boot_env:
port.update(boot_env)
if self.use_virtual_addresses:
addresses = {}
if self.wwnn:
addresses['WWNN'] = self.wwnn
if self.wwpn:
addresses['WWPN'] = self.wwpn
if addresses:
port['VirtualAddress'] = addresses
return port | [
"def",
"get_json",
"(",
"self",
")",
":",
"port",
"=",
"self",
".",
"get_basic_json",
"(",
")",
"port",
".",
"update",
"(",
"{",
"'BootProtocol'",
":",
"self",
".",
"boot",
".",
"BOOT_PROTOCOL",
",",
"'BootPriority'",
":",
"self",
".",
"boot",
".",
"bo... | Create FC port.
:returns: JSON for FC port as follows:
{
"@PortIdx":1,
"PortEnable":{
},
"UseVirtualAddresses":{
},
"VirtualAddress":{
"WWNN":{
},
"WWPN":{
},
"MAC":{
}
},
"BootProtocol":{
},
"BootPriority":{
},
"FCBootEnvironment":{
}
} | [
"Create",
"FC",
"port",
"."
] | 4585ce2f76853b9773fb190ca0cfff0aa04a7cf8 | https://github.com/openstack/python-scciclient/blob/4585ce2f76853b9773fb190ca0cfff0aa04a7cf8/scciclient/irmc/viom/elcm.py#L476-L519 | train | 47,892 |
openstack/python-scciclient | scciclient/irmc/viom/elcm.py | CNAPort.get_json | def get_json(self):
"""Create JSON for CNA port.
:returns: JSON for CNA port as follows:
{
"@PortIdx":1,
"PortEnable":{
},
"Functions":{
}
}
"""
port = self.get_basic_json()
port['Functions'] = {
'Function': [f.get_json() for f in self.functions.values()]
}
return port | python | def get_json(self):
"""Create JSON for CNA port.
:returns: JSON for CNA port as follows:
{
"@PortIdx":1,
"PortEnable":{
},
"Functions":{
}
}
"""
port = self.get_basic_json()
port['Functions'] = {
'Function': [f.get_json() for f in self.functions.values()]
}
return port | [
"def",
"get_json",
"(",
"self",
")",
":",
"port",
"=",
"self",
".",
"get_basic_json",
"(",
")",
"port",
"[",
"'Functions'",
"]",
"=",
"{",
"'Function'",
":",
"[",
"f",
".",
"get_json",
"(",
")",
"for",
"f",
"in",
"self",
".",
"functions",
".",
"val... | Create JSON for CNA port.
:returns: JSON for CNA port as follows:
{
"@PortIdx":1,
"PortEnable":{
},
"Functions":{
}
} | [
"Create",
"JSON",
"for",
"CNA",
"port",
"."
] | 4585ce2f76853b9773fb190ca0cfff0aa04a7cf8 | https://github.com/openstack/python-scciclient/blob/4585ce2f76853b9773fb190ca0cfff0aa04a7cf8/scciclient/irmc/viom/elcm.py#L539-L555 | train | 47,893 |
openstack/python-scciclient | scciclient/irmc/viom/elcm.py | FCBoot.get_json | def get_json(self):
"""Create JSON for FCBootEnvironment.
:returns: JSON for FCBootEnvironment as follows:
{
"FCBootEnvironment":{
"FCTargets":{
"FCTarget":[
]
},
"FCLinkSpeed":{
},
"SANBootEnable":{
},
"FCTopology":{
}
}
}
"""
json = self.get_basic_json()
for i in range(len(self.targets)):
# @FCTargetIdx starts from 1.
self.targets[i].set_index(i + 1)
json['FCTargets'] = {
'FCTarget': [t.get_json() for t in self.targets]
}
return {'FCBootEnvironment': json} | python | def get_json(self):
"""Create JSON for FCBootEnvironment.
:returns: JSON for FCBootEnvironment as follows:
{
"FCBootEnvironment":{
"FCTargets":{
"FCTarget":[
]
},
"FCLinkSpeed":{
},
"SANBootEnable":{
},
"FCTopology":{
}
}
}
"""
json = self.get_basic_json()
for i in range(len(self.targets)):
# @FCTargetIdx starts from 1.
self.targets[i].set_index(i + 1)
json['FCTargets'] = {
'FCTarget': [t.get_json() for t in self.targets]
}
return {'FCBootEnvironment': json} | [
"def",
"get_json",
"(",
"self",
")",
":",
"json",
"=",
"self",
".",
"get_basic_json",
"(",
")",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"self",
".",
"targets",
")",
")",
":",
"# @FCTargetIdx starts from 1.",
"self",
".",
"targets",
"[",
"i",
"]",
... | Create JSON for FCBootEnvironment.
:returns: JSON for FCBootEnvironment as follows:
{
"FCBootEnvironment":{
"FCTargets":{
"FCTarget":[
]
},
"FCLinkSpeed":{
},
"SANBootEnable":{
},
"FCTopology":{
}
}
} | [
"Create",
"JSON",
"for",
"FCBootEnvironment",
"."
] | 4585ce2f76853b9773fb190ca0cfff0aa04a7cf8 | https://github.com/openstack/python-scciclient/blob/4585ce2f76853b9773fb190ca0cfff0aa04a7cf8/scciclient/irmc/viom/elcm.py#L772-L799 | train | 47,894 |
openstack/python-scciclient | scciclient/irmc/viom/elcm.py | ISCSIInitiator.get_json | def get_json(self):
"""Create JSON data for iSCSI initiator.
:returns: JSON data for iSCSI initiator as follows:
{
"DHCPUsage":{
},
"Name":{
},
"IPv4Address":{
},
"SubnetMask":{
},
"GatewayIPv4Address":{
},
"VLANId":{
}
}
"""
if self.dhcp_usage:
return {'DHCPUsage': self.dhcp_usage,
'Name': self.iqn}
else:
return self.get_basic_json() | python | def get_json(self):
"""Create JSON data for iSCSI initiator.
:returns: JSON data for iSCSI initiator as follows:
{
"DHCPUsage":{
},
"Name":{
},
"IPv4Address":{
},
"SubnetMask":{
},
"GatewayIPv4Address":{
},
"VLANId":{
}
}
"""
if self.dhcp_usage:
return {'DHCPUsage': self.dhcp_usage,
'Name': self.iqn}
else:
return self.get_basic_json() | [
"def",
"get_json",
"(",
"self",
")",
":",
"if",
"self",
".",
"dhcp_usage",
":",
"return",
"{",
"'DHCPUsage'",
":",
"self",
".",
"dhcp_usage",
",",
"'Name'",
":",
"self",
".",
"iqn",
"}",
"else",
":",
"return",
"self",
".",
"get_basic_json",
"(",
")"
] | Create JSON data for iSCSI initiator.
:returns: JSON data for iSCSI initiator as follows:
{
"DHCPUsage":{
},
"Name":{
},
"IPv4Address":{
},
"SubnetMask":{
},
"GatewayIPv4Address":{
},
"VLANId":{
}
} | [
"Create",
"JSON",
"data",
"for",
"iSCSI",
"initiator",
"."
] | 4585ce2f76853b9773fb190ca0cfff0aa04a7cf8 | https://github.com/openstack/python-scciclient/blob/4585ce2f76853b9773fb190ca0cfff0aa04a7cf8/scciclient/irmc/viom/elcm.py#L875-L899 | train | 47,895 |
openstack/python-scciclient | scciclient/irmc/viom/elcm.py | ISCSITarget.get_json | def get_json(self):
"""Create JSON data for iSCSI target.
:returns: JSON data for iSCSI target as follows:
{
"DHCPUsage":{
},
"Name":{
},
"IPv4Address":{
},
"PortNumber":{
},
"BootLUN":{
},
"AuthenticationMethod":{
},
"ChapUserName":{
},
"ChapSecret":{
},
"MutualChapSecret":{
}
}
"""
json = {
'DHCPUsage': self.dhcp_usage,
'AuthenticationMethod': self.auth_method,
}
if not self.dhcp_usage:
json['Name'] = self.iqn
json['IPv4Address'] = self.ip
json['PortNumber'] = self.port
json['BootLUN'] = self.lun
if self.chap_user:
json['ChapUserName'] = self.chap_user
if self.chap_secret:
json['ChapSecret'] = self.chap_secret
if self.mutual_chap_secret:
json['MutualChapSecret'] = self.mutual_chap_secret
return json | python | def get_json(self):
"""Create JSON data for iSCSI target.
:returns: JSON data for iSCSI target as follows:
{
"DHCPUsage":{
},
"Name":{
},
"IPv4Address":{
},
"PortNumber":{
},
"BootLUN":{
},
"AuthenticationMethod":{
},
"ChapUserName":{
},
"ChapSecret":{
},
"MutualChapSecret":{
}
}
"""
json = {
'DHCPUsage': self.dhcp_usage,
'AuthenticationMethod': self.auth_method,
}
if not self.dhcp_usage:
json['Name'] = self.iqn
json['IPv4Address'] = self.ip
json['PortNumber'] = self.port
json['BootLUN'] = self.lun
if self.chap_user:
json['ChapUserName'] = self.chap_user
if self.chap_secret:
json['ChapSecret'] = self.chap_secret
if self.mutual_chap_secret:
json['MutualChapSecret'] = self.mutual_chap_secret
return json | [
"def",
"get_json",
"(",
"self",
")",
":",
"json",
"=",
"{",
"'DHCPUsage'",
":",
"self",
".",
"dhcp_usage",
",",
"'AuthenticationMethod'",
":",
"self",
".",
"auth_method",
",",
"}",
"if",
"not",
"self",
".",
"dhcp_usage",
":",
"json",
"[",
"'Name'",
"]",
... | Create JSON data for iSCSI target.
:returns: JSON data for iSCSI target as follows:
{
"DHCPUsage":{
},
"Name":{
},
"IPv4Address":{
},
"PortNumber":{
},
"BootLUN":{
},
"AuthenticationMethod":{
},
"ChapUserName":{
},
"ChapSecret":{
},
"MutualChapSecret":{
}
} | [
"Create",
"JSON",
"data",
"for",
"iSCSI",
"target",
"."
] | 4585ce2f76853b9773fb190ca0cfff0aa04a7cf8 | https://github.com/openstack/python-scciclient/blob/4585ce2f76853b9773fb190ca0cfff0aa04a7cf8/scciclient/irmc/viom/elcm.py#L919-L960 | train | 47,896 |
OSSOS/MOP | src/jjk/preproc/plot.py | zscale | def zscale(data,contrast,min=100,max=60000):
"""Scale the data cube into the range 0-255"""
## pic 100 random elements along each dimension
## use zscale (see the IRAF display man page or
## http://iraf.net/article.php/20051205162333315
import random
x=[]
for i in random.sample(xrange(data.shape[0]),50):
for j in random.sample(xrange(data.shape[1]),50):
x.append(data[i,j])
yl=numarray.sort(numarray.clip(x,min,max))
n=len(yl)
ym=sum(yl)/float(n)
xl=numarray.array(range(n))
xm=sum(xl)/float(n)
ss_xx=sum((xl-xm)*(xl-xm))
ss_yy=sum((yl-ym)*(yl-ym))
ss_xy=sum((xl-xm)*(yl-ym))
b=ss_xy/ss_xx
a=ym-b*xm
z1=yl[n/2] + (b/contrast)*(1-n/2)
z2=yl[n/2] + (b/contrast)*(n-n/2)
## Now put the data inbetween Z1 and Z2
high=data-z1
z2=z2-z1
high=numarray.clip(high,0,z2)
## and change that to 0-255
high= 256-256*high/z2
### send back the scalled data
return high | python | def zscale(data,contrast,min=100,max=60000):
"""Scale the data cube into the range 0-255"""
## pic 100 random elements along each dimension
## use zscale (see the IRAF display man page or
## http://iraf.net/article.php/20051205162333315
import random
x=[]
for i in random.sample(xrange(data.shape[0]),50):
for j in random.sample(xrange(data.shape[1]),50):
x.append(data[i,j])
yl=numarray.sort(numarray.clip(x,min,max))
n=len(yl)
ym=sum(yl)/float(n)
xl=numarray.array(range(n))
xm=sum(xl)/float(n)
ss_xx=sum((xl-xm)*(xl-xm))
ss_yy=sum((yl-ym)*(yl-ym))
ss_xy=sum((xl-xm)*(yl-ym))
b=ss_xy/ss_xx
a=ym-b*xm
z1=yl[n/2] + (b/contrast)*(1-n/2)
z2=yl[n/2] + (b/contrast)*(n-n/2)
## Now put the data inbetween Z1 and Z2
high=data-z1
z2=z2-z1
high=numarray.clip(high,0,z2)
## and change that to 0-255
high= 256-256*high/z2
### send back the scalled data
return high | [
"def",
"zscale",
"(",
"data",
",",
"contrast",
",",
"min",
"=",
"100",
",",
"max",
"=",
"60000",
")",
":",
"## pic 100 random elements along each dimension",
"## use zscale (see the IRAF display man page or",
"## http://iraf.net/article.php/20051205162333315",
"import",
"rand... | Scale the data cube into the range 0-255 | [
"Scale",
"the",
"data",
"cube",
"into",
"the",
"range",
"0",
"-",
"255"
] | 94f91d32ad5ec081d5a1ebd67604a838003465af | https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/jjk/preproc/plot.py#L12-L52 | train | 47,897 |
OSSOS/MOP | src/ossos/core/ossos/downloads/cutouts/calculator.py | CoordinateConverter.convert | def convert(self, point):
"""
Convert a point from one coordinate system to another.
Args:
point: tuple(int x, int y)
The point in the original coordinate system.
Returns:
converted_point: tuple(int x, int y)
The point in the new coordinate system.
Example: convert coordinate from original image into a pixel location
within a cutout image.
@rtype: list(float,float)
"""
x, y = point
(x1, y1) = x - self.x_offset, y - self.y_offset
logger.debug("converted {} {} ==> {} {}".format(x, y, x1, y1))
return x1, y1 | python | def convert(self, point):
"""
Convert a point from one coordinate system to another.
Args:
point: tuple(int x, int y)
The point in the original coordinate system.
Returns:
converted_point: tuple(int x, int y)
The point in the new coordinate system.
Example: convert coordinate from original image into a pixel location
within a cutout image.
@rtype: list(float,float)
"""
x, y = point
(x1, y1) = x - self.x_offset, y - self.y_offset
logger.debug("converted {} {} ==> {} {}".format(x, y, x1, y1))
return x1, y1 | [
"def",
"convert",
"(",
"self",
",",
"point",
")",
":",
"x",
",",
"y",
"=",
"point",
"(",
"x1",
",",
"y1",
")",
"=",
"x",
"-",
"self",
".",
"x_offset",
",",
"y",
"-",
"self",
".",
"y_offset",
"logger",
".",
"debug",
"(",
"\"converted {} {} ==> {} {}... | Convert a point from one coordinate system to another.
Args:
point: tuple(int x, int y)
The point in the original coordinate system.
Returns:
converted_point: tuple(int x, int y)
The point in the new coordinate system.
Example: convert coordinate from original image into a pixel location
within a cutout image.
@rtype: list(float,float) | [
"Convert",
"a",
"point",
"from",
"one",
"coordinate",
"system",
"to",
"another",
"."
] | 94f91d32ad5ec081d5a1ebd67604a838003465af | https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/downloads/cutouts/calculator.py#L36-L56 | train | 47,898 |
JohnVinyard/zounds | zounds/learn/util.py | apply_network | def apply_network(network, x, chunksize=None):
"""
Apply a pytorch network, potentially in chunks
"""
network_is_cuda = next(network.parameters()).is_cuda
x = torch.from_numpy(x)
with torch.no_grad():
if network_is_cuda:
x = x.cuda()
if chunksize is None:
return from_var(network(x))
return np.concatenate(
[from_var(network(x[i: i + chunksize]))
for i in range(0, len(x), chunksize)]) | python | def apply_network(network, x, chunksize=None):
"""
Apply a pytorch network, potentially in chunks
"""
network_is_cuda = next(network.parameters()).is_cuda
x = torch.from_numpy(x)
with torch.no_grad():
if network_is_cuda:
x = x.cuda()
if chunksize is None:
return from_var(network(x))
return np.concatenate(
[from_var(network(x[i: i + chunksize]))
for i in range(0, len(x), chunksize)]) | [
"def",
"apply_network",
"(",
"network",
",",
"x",
",",
"chunksize",
"=",
"None",
")",
":",
"network_is_cuda",
"=",
"next",
"(",
"network",
".",
"parameters",
"(",
")",
")",
".",
"is_cuda",
"x",
"=",
"torch",
".",
"from_numpy",
"(",
"x",
")",
"with",
... | Apply a pytorch network, potentially in chunks | [
"Apply",
"a",
"pytorch",
"network",
"potentially",
"in",
"chunks"
] | 337b3f98753d09eaab1c72dcd37bb852a3fa5ac6 | https://github.com/JohnVinyard/zounds/blob/337b3f98753d09eaab1c72dcd37bb852a3fa5ac6/zounds/learn/util.py#L92-L109 | train | 47,899 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.