repo stringlengths 7 55 | path stringlengths 4 223 | func_name stringlengths 1 134 | original_string stringlengths 75 104k | language stringclasses 1 value | code stringlengths 75 104k | code_tokens listlengths 19 28.4k | docstring stringlengths 1 46.9k | docstring_tokens listlengths 1 1.97k | sha stringlengths 40 40 | url stringlengths 87 315 | partition stringclasses 1 value |
|---|---|---|---|---|---|---|---|---|---|---|---|
Britefury/batchup | batchup/data_source.py | RandomAccessDataSource.samples_by_indices | def samples_by_indices(self, indices):
"""
Gather a batch of samples by indices, applying the mapping
described by the (optional) `indices` array passed to the
constructor.
Parameters
----------
indices: 1D-array of ints or slice
The samples to retrieve
Returns
-------
list of arrays
A mini-batch in the form of a list of NumPy arrays
"""
indices = self.sampler.map_indices(indices)
return self.samples_by_indices_nomapping(indices) | python | def samples_by_indices(self, indices):
"""
Gather a batch of samples by indices, applying the mapping
described by the (optional) `indices` array passed to the
constructor.
Parameters
----------
indices: 1D-array of ints or slice
The samples to retrieve
Returns
-------
list of arrays
A mini-batch in the form of a list of NumPy arrays
"""
indices = self.sampler.map_indices(indices)
return self.samples_by_indices_nomapping(indices) | [
"def",
"samples_by_indices",
"(",
"self",
",",
"indices",
")",
":",
"indices",
"=",
"self",
".",
"sampler",
".",
"map_indices",
"(",
"indices",
")",
"return",
"self",
".",
"samples_by_indices_nomapping",
"(",
"indices",
")"
] | Gather a batch of samples by indices, applying the mapping
described by the (optional) `indices` array passed to the
constructor.
Parameters
----------
indices: 1D-array of ints or slice
The samples to retrieve
Returns
-------
list of arrays
A mini-batch in the form of a list of NumPy arrays | [
"Gather",
"a",
"batch",
"of",
"samples",
"by",
"indices",
"applying",
"the",
"mapping",
"described",
"by",
"the",
"(",
"optional",
")",
"indices",
"array",
"passed",
"to",
"the",
"constructor",
"."
] | 3fc2304e629f813c05f9e7a85a18acef3581a536 | https://github.com/Britefury/batchup/blob/3fc2304e629f813c05f9e7a85a18acef3581a536/batchup/data_source.py#L419-L436 | train |
Britefury/batchup | batchup/data_source.py | RandomAccessDataSource.batch_indices_iterator | def batch_indices_iterator(self, batch_size, shuffle=None, **kwargs):
"""
Create an iterator that generates mini-batch sample indices.
The batches will have `batch_size` elements, with the exception
of the final batch which will have less if there are insufficient
elements left to make a complete batch.
If `shuffle` is `None` or `False` elements will be extracted in
order. If it is a `numpy.random.RandomState`, it will be used to
randomise the order in which elements are extracted from the data.
If it is `True`, NumPy's default random number generator will be
use to shuffle elements.
If an array of indices was provided to the constructor, the subset of
samples identified in that array is used, rather than the complete
set of samples.
The generated mini-batches indices take the form of 1D NumPy integer
arrays.
Parameters
----------
batch_size: int
Mini-batch size
shuffle: `numpy.random.RandomState` or `True` or `None`
Used to randomise element order. If `None`, elements will be
extracted in order. If it is a `RandomState` instance, that
RNG will be used to shuffle elements. If it is `True`, NumPy's
default RNG will be used.
Returns
-------
iterator
An iterator that generates mini-batches in the form of 1D NumPy
integer arrays.
"""
shuffle_rng = self._get_shuffle_rng(shuffle)
if shuffle_rng is not None:
return self.sampler.shuffled_indices_batch_iterator(
batch_size, shuffle_rng)
else:
return self.sampler.in_order_indices_batch_iterator(batch_size) | python | def batch_indices_iterator(self, batch_size, shuffle=None, **kwargs):
"""
Create an iterator that generates mini-batch sample indices.
The batches will have `batch_size` elements, with the exception
of the final batch which will have less if there are insufficient
elements left to make a complete batch.
If `shuffle` is `None` or `False` elements will be extracted in
order. If it is a `numpy.random.RandomState`, it will be used to
randomise the order in which elements are extracted from the data.
If it is `True`, NumPy's default random number generator will be
use to shuffle elements.
If an array of indices was provided to the constructor, the subset of
samples identified in that array is used, rather than the complete
set of samples.
The generated mini-batches indices take the form of 1D NumPy integer
arrays.
Parameters
----------
batch_size: int
Mini-batch size
shuffle: `numpy.random.RandomState` or `True` or `None`
Used to randomise element order. If `None`, elements will be
extracted in order. If it is a `RandomState` instance, that
RNG will be used to shuffle elements. If it is `True`, NumPy's
default RNG will be used.
Returns
-------
iterator
An iterator that generates mini-batches in the form of 1D NumPy
integer arrays.
"""
shuffle_rng = self._get_shuffle_rng(shuffle)
if shuffle_rng is not None:
return self.sampler.shuffled_indices_batch_iterator(
batch_size, shuffle_rng)
else:
return self.sampler.in_order_indices_batch_iterator(batch_size) | [
"def",
"batch_indices_iterator",
"(",
"self",
",",
"batch_size",
",",
"shuffle",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"shuffle_rng",
"=",
"self",
".",
"_get_shuffle_rng",
"(",
"shuffle",
")",
"if",
"shuffle_rng",
"is",
"not",
"None",
":",
"return",
"self",
".",
"sampler",
".",
"shuffled_indices_batch_iterator",
"(",
"batch_size",
",",
"shuffle_rng",
")",
"else",
":",
"return",
"self",
".",
"sampler",
".",
"in_order_indices_batch_iterator",
"(",
"batch_size",
")"
] | Create an iterator that generates mini-batch sample indices.
The batches will have `batch_size` elements, with the exception
of the final batch which will have less if there are insufficient
elements left to make a complete batch.
If `shuffle` is `None` or `False` elements will be extracted in
order. If it is a `numpy.random.RandomState`, it will be used to
randomise the order in which elements are extracted from the data.
If it is `True`, NumPy's default random number generator will be
use to shuffle elements.
If an array of indices was provided to the constructor, the subset of
samples identified in that array is used, rather than the complete
set of samples.
The generated mini-batches indices take the form of 1D NumPy integer
arrays.
Parameters
----------
batch_size: int
Mini-batch size
shuffle: `numpy.random.RandomState` or `True` or `None`
Used to randomise element order. If `None`, elements will be
extracted in order. If it is a `RandomState` instance, that
RNG will be used to shuffle elements. If it is `True`, NumPy's
default RNG will be used.
Returns
-------
iterator
An iterator that generates mini-batches in the form of 1D NumPy
integer arrays. | [
"Create",
"an",
"iterator",
"that",
"generates",
"mini",
"-",
"batch",
"sample",
"indices",
".",
"The",
"batches",
"will",
"have",
"batch_size",
"elements",
"with",
"the",
"exception",
"of",
"the",
"final",
"batch",
"which",
"will",
"have",
"less",
"if",
"there",
"are",
"insufficient",
"elements",
"left",
"to",
"make",
"a",
"complete",
"batch",
"."
] | 3fc2304e629f813c05f9e7a85a18acef3581a536 | https://github.com/Britefury/batchup/blob/3fc2304e629f813c05f9e7a85a18acef3581a536/batchup/data_source.py#L438-L479 | train |
Britefury/batchup | batchup/data_source.py | RandomAccessDataSource.batch_iterator | def batch_iterator(self, batch_size, shuffle=None, **kwargs):
"""
Create an iterator that generates mini-batches extracted from
this data source. The batches will have `batch_size` elements, with
the exception of the final batch which will have less if there are
insufficient elements left to make a complete batch.
If `shuffle` is `None` or `False` elements will be extracted in
order. If it is a `numpy.random.RandomState`, it will be used to
randomise the order in which elements are extracted from the data.
If it is `True`, NumPy's default random number generator will be
use to shuffle elements.
If an array of indices was provided to the constructor, the subset of
samples identified in that array is used, rather than the complete
set of samples.
The generated mini-batches take the form `[batch_x, batch_y, ...]`.
Parameters
----------
batch_size: int
Mini-batch size
shuffle: `numpy.random.RandomState` or `True` or `None`
Used to randomise element order. If `None`, elements will be
extracted in order. If it is a `RandomState` instance, that
RNG will be used to shuffle elements. If it is `True`, NumPy's
default RNG will be used.
Returns
-------
iterator
An iterator that generates items of type `[batch_x, batch_y, ...]`
where `batch_x`, `batch_y`, etc are themselves arrays.
"""
for batch_ndx in self.batch_indices_iterator(
batch_size, shuffle=shuffle, **kwargs):
yield self.samples_by_indices_nomapping(batch_ndx) | python | def batch_iterator(self, batch_size, shuffle=None, **kwargs):
"""
Create an iterator that generates mini-batches extracted from
this data source. The batches will have `batch_size` elements, with
the exception of the final batch which will have less if there are
insufficient elements left to make a complete batch.
If `shuffle` is `None` or `False` elements will be extracted in
order. If it is a `numpy.random.RandomState`, it will be used to
randomise the order in which elements are extracted from the data.
If it is `True`, NumPy's default random number generator will be
use to shuffle elements.
If an array of indices was provided to the constructor, the subset of
samples identified in that array is used, rather than the complete
set of samples.
The generated mini-batches take the form `[batch_x, batch_y, ...]`.
Parameters
----------
batch_size: int
Mini-batch size
shuffle: `numpy.random.RandomState` or `True` or `None`
Used to randomise element order. If `None`, elements will be
extracted in order. If it is a `RandomState` instance, that
RNG will be used to shuffle elements. If it is `True`, NumPy's
default RNG will be used.
Returns
-------
iterator
An iterator that generates items of type `[batch_x, batch_y, ...]`
where `batch_x`, `batch_y`, etc are themselves arrays.
"""
for batch_ndx in self.batch_indices_iterator(
batch_size, shuffle=shuffle, **kwargs):
yield self.samples_by_indices_nomapping(batch_ndx) | [
"def",
"batch_iterator",
"(",
"self",
",",
"batch_size",
",",
"shuffle",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"for",
"batch_ndx",
"in",
"self",
".",
"batch_indices_iterator",
"(",
"batch_size",
",",
"shuffle",
"=",
"shuffle",
",",
"*",
"*",
"kwargs",
")",
":",
"yield",
"self",
".",
"samples_by_indices_nomapping",
"(",
"batch_ndx",
")"
] | Create an iterator that generates mini-batches extracted from
this data source. The batches will have `batch_size` elements, with
the exception of the final batch which will have less if there are
insufficient elements left to make a complete batch.
If `shuffle` is `None` or `False` elements will be extracted in
order. If it is a `numpy.random.RandomState`, it will be used to
randomise the order in which elements are extracted from the data.
If it is `True`, NumPy's default random number generator will be
use to shuffle elements.
If an array of indices was provided to the constructor, the subset of
samples identified in that array is used, rather than the complete
set of samples.
The generated mini-batches take the form `[batch_x, batch_y, ...]`.
Parameters
----------
batch_size: int
Mini-batch size
shuffle: `numpy.random.RandomState` or `True` or `None`
Used to randomise element order. If `None`, elements will be
extracted in order. If it is a `RandomState` instance, that
RNG will be used to shuffle elements. If it is `True`, NumPy's
default RNG will be used.
Returns
-------
iterator
An iterator that generates items of type `[batch_x, batch_y, ...]`
where `batch_x`, `batch_y`, etc are themselves arrays. | [
"Create",
"an",
"iterator",
"that",
"generates",
"mini",
"-",
"batches",
"extracted",
"from",
"this",
"data",
"source",
".",
"The",
"batches",
"will",
"have",
"batch_size",
"elements",
"with",
"the",
"exception",
"of",
"the",
"final",
"batch",
"which",
"will",
"have",
"less",
"if",
"there",
"are",
"insufficient",
"elements",
"left",
"to",
"make",
"a",
"complete",
"batch",
"."
] | 3fc2304e629f813c05f9e7a85a18acef3581a536 | https://github.com/Britefury/batchup/blob/3fc2304e629f813c05f9e7a85a18acef3581a536/batchup/data_source.py#L481-L518 | train |
Britefury/batchup | batchup/data_source.py | ArrayDataSource.samples_by_indices_nomapping | def samples_by_indices_nomapping(self, indices):
"""
Gather a batch of samples by indices *without* applying any index
mapping resulting from the (optional) use of the `indices` array
passed to the constructor.
Parameters
----------
indices: 1D-array of ints or slice
The samples to retrieve
Returns
-------
list of arrays
A mini-batch in the form of a list of NumPy arrays
"""
batch = tuple([d[indices] for d in self.data])
if self.include_indices:
if isinstance(indices, slice):
indices = np.arange(indices.start, indices.stop,
indices.step)
return (indices,) + batch
else:
return batch | python | def samples_by_indices_nomapping(self, indices):
"""
Gather a batch of samples by indices *without* applying any index
mapping resulting from the (optional) use of the `indices` array
passed to the constructor.
Parameters
----------
indices: 1D-array of ints or slice
The samples to retrieve
Returns
-------
list of arrays
A mini-batch in the form of a list of NumPy arrays
"""
batch = tuple([d[indices] for d in self.data])
if self.include_indices:
if isinstance(indices, slice):
indices = np.arange(indices.start, indices.stop,
indices.step)
return (indices,) + batch
else:
return batch | [
"def",
"samples_by_indices_nomapping",
"(",
"self",
",",
"indices",
")",
":",
"batch",
"=",
"tuple",
"(",
"[",
"d",
"[",
"indices",
"]",
"for",
"d",
"in",
"self",
".",
"data",
"]",
")",
"if",
"self",
".",
"include_indices",
":",
"if",
"isinstance",
"(",
"indices",
",",
"slice",
")",
":",
"indices",
"=",
"np",
".",
"arange",
"(",
"indices",
".",
"start",
",",
"indices",
".",
"stop",
",",
"indices",
".",
"step",
")",
"return",
"(",
"indices",
",",
")",
"+",
"batch",
"else",
":",
"return",
"batch"
] | Gather a batch of samples by indices *without* applying any index
mapping resulting from the (optional) use of the `indices` array
passed to the constructor.
Parameters
----------
indices: 1D-array of ints or slice
The samples to retrieve
Returns
-------
list of arrays
A mini-batch in the form of a list of NumPy arrays | [
"Gather",
"a",
"batch",
"of",
"samples",
"by",
"indices",
"*",
"without",
"*",
"applying",
"any",
"index",
"mapping",
"resulting",
"from",
"the",
"(",
"optional",
")",
"use",
"of",
"the",
"indices",
"array",
"passed",
"to",
"the",
"constructor",
"."
] | 3fc2304e629f813c05f9e7a85a18acef3581a536 | https://github.com/Britefury/batchup/blob/3fc2304e629f813c05f9e7a85a18acef3581a536/batchup/data_source.py#L666-L689 | train |
Britefury/batchup | batchup/data_source.py | CallableDataSource.num_samples | def num_samples(self, **kwargs):
"""
Get the number of samples in this data source.
Returns
-------
int, `np.inf` or `None`.
An int if the number of samples is known, `np.inf` if it is
infinite or `None` if the number of samples is unknown.
"""
if self.num_samples_fn is None:
return None
elif callable(self.num_samples_fn):
return self.num_samples_fn(**kwargs)
else:
return self.num_samples_fn | python | def num_samples(self, **kwargs):
"""
Get the number of samples in this data source.
Returns
-------
int, `np.inf` or `None`.
An int if the number of samples is known, `np.inf` if it is
infinite or `None` if the number of samples is unknown.
"""
if self.num_samples_fn is None:
return None
elif callable(self.num_samples_fn):
return self.num_samples_fn(**kwargs)
else:
return self.num_samples_fn | [
"def",
"num_samples",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"self",
".",
"num_samples_fn",
"is",
"None",
":",
"return",
"None",
"elif",
"callable",
"(",
"self",
".",
"num_samples_fn",
")",
":",
"return",
"self",
".",
"num_samples_fn",
"(",
"*",
"*",
"kwargs",
")",
"else",
":",
"return",
"self",
".",
"num_samples_fn"
] | Get the number of samples in this data source.
Returns
-------
int, `np.inf` or `None`.
An int if the number of samples is known, `np.inf` if it is
infinite or `None` if the number of samples is unknown. | [
"Get",
"the",
"number",
"of",
"samples",
"in",
"this",
"data",
"source",
"."
] | 3fc2304e629f813c05f9e7a85a18acef3581a536 | https://github.com/Britefury/batchup/blob/3fc2304e629f813c05f9e7a85a18acef3581a536/batchup/data_source.py#L752-L767 | train |
Britefury/batchup | batchup/data_source.py | CompositeDataSource.samples_by_indices_nomapping | def samples_by_indices_nomapping(self, indices):
"""
Gather a batch of samples by indices *without* applying any index
mapping.
Parameters
----------
indices: list of either 1D-array of ints or slice
A list of index arrays or slices; one for each data source
that identify the samples to access
Returns
-------
nested list of arrays
A mini-batch
"""
if not self._random_access:
raise TypeError('samples_by_indices_nomapping method not '
'supported as one or more of the underlying '
'data sources does not support random access')
if len(indices) != len(self.datasets):
raise ValueError(
'length mis-match: indices has {} items, self has {} data '
'sources, should be equal'.format(len(indices),
len(self.datasets)))
batch = tuple([ds.samples_by_indices_nomapping(ndx)
for ds, ndx in zip(self.datasets, indices)])
return self._prepare_batch(batch) | python | def samples_by_indices_nomapping(self, indices):
"""
Gather a batch of samples by indices *without* applying any index
mapping.
Parameters
----------
indices: list of either 1D-array of ints or slice
A list of index arrays or slices; one for each data source
that identify the samples to access
Returns
-------
nested list of arrays
A mini-batch
"""
if not self._random_access:
raise TypeError('samples_by_indices_nomapping method not '
'supported as one or more of the underlying '
'data sources does not support random access')
if len(indices) != len(self.datasets):
raise ValueError(
'length mis-match: indices has {} items, self has {} data '
'sources, should be equal'.format(len(indices),
len(self.datasets)))
batch = tuple([ds.samples_by_indices_nomapping(ndx)
for ds, ndx in zip(self.datasets, indices)])
return self._prepare_batch(batch) | [
"def",
"samples_by_indices_nomapping",
"(",
"self",
",",
"indices",
")",
":",
"if",
"not",
"self",
".",
"_random_access",
":",
"raise",
"TypeError",
"(",
"'samples_by_indices_nomapping method not '",
"'supported as one or more of the underlying '",
"'data sources does not support random access'",
")",
"if",
"len",
"(",
"indices",
")",
"!=",
"len",
"(",
"self",
".",
"datasets",
")",
":",
"raise",
"ValueError",
"(",
"'length mis-match: indices has {} items, self has {} data '",
"'sources, should be equal'",
".",
"format",
"(",
"len",
"(",
"indices",
")",
",",
"len",
"(",
"self",
".",
"datasets",
")",
")",
")",
"batch",
"=",
"tuple",
"(",
"[",
"ds",
".",
"samples_by_indices_nomapping",
"(",
"ndx",
")",
"for",
"ds",
",",
"ndx",
"in",
"zip",
"(",
"self",
".",
"datasets",
",",
"indices",
")",
"]",
")",
"return",
"self",
".",
"_prepare_batch",
"(",
"batch",
")"
] | Gather a batch of samples by indices *without* applying any index
mapping.
Parameters
----------
indices: list of either 1D-array of ints or slice
A list of index arrays or slices; one for each data source
that identify the samples to access
Returns
-------
nested list of arrays
A mini-batch | [
"Gather",
"a",
"batch",
"of",
"samples",
"by",
"indices",
"*",
"without",
"*",
"applying",
"any",
"index",
"mapping",
"."
] | 3fc2304e629f813c05f9e7a85a18acef3581a536 | https://github.com/Britefury/batchup/blob/3fc2304e629f813c05f9e7a85a18acef3581a536/batchup/data_source.py#L982-L1009 | train |
Britefury/batchup | batchup/data_source.py | CompositeDataSource.batch_indices_iterator | def batch_indices_iterator(self, batch_size, **kwargs):
"""
Create an iterator that generates mini-batch sample indices
The generated mini-batches indices take the form of nested lists of
either:
- 1D NumPy integer arrays
- slices
The list nesting structure with match that of the tree of data sources
rooted at `self`
Parameters
----------
batch_size: int
Mini-batch size
Returns
-------
iterator
An iterator that generates items that are nested lists of slices
or 1D NumPy integer arrays.
"""
if not self._random_access:
raise TypeError('batch_indices_iterator method not supported as '
'one or more of the underlying data sources '
'does not support random access')
iterators = [d.batch_indices_iterator(batch_size, **kwargs)
for d in self.datasets]
for batch in six.moves.zip(*iterators):
yield self._prepare_index_batch(batch) | python | def batch_indices_iterator(self, batch_size, **kwargs):
"""
Create an iterator that generates mini-batch sample indices
The generated mini-batches indices take the form of nested lists of
either:
- 1D NumPy integer arrays
- slices
The list nesting structure with match that of the tree of data sources
rooted at `self`
Parameters
----------
batch_size: int
Mini-batch size
Returns
-------
iterator
An iterator that generates items that are nested lists of slices
or 1D NumPy integer arrays.
"""
if not self._random_access:
raise TypeError('batch_indices_iterator method not supported as '
'one or more of the underlying data sources '
'does not support random access')
iterators = [d.batch_indices_iterator(batch_size, **kwargs)
for d in self.datasets]
for batch in six.moves.zip(*iterators):
yield self._prepare_index_batch(batch) | [
"def",
"batch_indices_iterator",
"(",
"self",
",",
"batch_size",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"self",
".",
"_random_access",
":",
"raise",
"TypeError",
"(",
"'batch_indices_iterator method not supported as '",
"'one or more of the underlying data sources '",
"'does not support random access'",
")",
"iterators",
"=",
"[",
"d",
".",
"batch_indices_iterator",
"(",
"batch_size",
",",
"*",
"*",
"kwargs",
")",
"for",
"d",
"in",
"self",
".",
"datasets",
"]",
"for",
"batch",
"in",
"six",
".",
"moves",
".",
"zip",
"(",
"*",
"iterators",
")",
":",
"yield",
"self",
".",
"_prepare_index_batch",
"(",
"batch",
")"
] | Create an iterator that generates mini-batch sample indices
The generated mini-batches indices take the form of nested lists of
either:
- 1D NumPy integer arrays
- slices
The list nesting structure with match that of the tree of data sources
rooted at `self`
Parameters
----------
batch_size: int
Mini-batch size
Returns
-------
iterator
An iterator that generates items that are nested lists of slices
or 1D NumPy integer arrays. | [
"Create",
"an",
"iterator",
"that",
"generates",
"mini",
"-",
"batch",
"sample",
"indices"
] | 3fc2304e629f813c05f9e7a85a18acef3581a536 | https://github.com/Britefury/batchup/blob/3fc2304e629f813c05f9e7a85a18acef3581a536/batchup/data_source.py#L1040-L1071 | train |
Britefury/batchup | batchup/data_source.py | ChoiceDataSource.samples_by_indices_nomapping | def samples_by_indices_nomapping(self, indices):
"""
Gather a batch of samples by indices *without* applying any index
mapping.
Parameters
----------
indices: a tuple of the form `(dataset_index, sample_indices)`
The `dataset_index` identifies the dataset from which to draw
samples while `sample_indices` identifies the samples to draw
from it.
Returns
-------
nested list of arrays
A mini-batch
"""
if not self._random_access:
raise TypeError('samples_by_indices_nomapping method not '
'supported as one or more of the underlying '
'data sources does not support random access')
if not isinstance(indices, tuple):
raise TypeError('indices should be a tuple, not a {}'.format(
type(indices)
))
dataset_index, sample_indices = indices
ds = self.datasets[dataset_index]
return ds.samples_by_indices_nomapping(sample_indices) | python | def samples_by_indices_nomapping(self, indices):
"""
Gather a batch of samples by indices *without* applying any index
mapping.
Parameters
----------
indices: a tuple of the form `(dataset_index, sample_indices)`
The `dataset_index` identifies the dataset from which to draw
samples while `sample_indices` identifies the samples to draw
from it.
Returns
-------
nested list of arrays
A mini-batch
"""
if not self._random_access:
raise TypeError('samples_by_indices_nomapping method not '
'supported as one or more of the underlying '
'data sources does not support random access')
if not isinstance(indices, tuple):
raise TypeError('indices should be a tuple, not a {}'.format(
type(indices)
))
dataset_index, sample_indices = indices
ds = self.datasets[dataset_index]
return ds.samples_by_indices_nomapping(sample_indices) | [
"def",
"samples_by_indices_nomapping",
"(",
"self",
",",
"indices",
")",
":",
"if",
"not",
"self",
".",
"_random_access",
":",
"raise",
"TypeError",
"(",
"'samples_by_indices_nomapping method not '",
"'supported as one or more of the underlying '",
"'data sources does not support random access'",
")",
"if",
"not",
"isinstance",
"(",
"indices",
",",
"tuple",
")",
":",
"raise",
"TypeError",
"(",
"'indices should be a tuple, not a {}'",
".",
"format",
"(",
"type",
"(",
"indices",
")",
")",
")",
"dataset_index",
",",
"sample_indices",
"=",
"indices",
"ds",
"=",
"self",
".",
"datasets",
"[",
"dataset_index",
"]",
"return",
"ds",
".",
"samples_by_indices_nomapping",
"(",
"sample_indices",
")"
] | Gather a batch of samples by indices *without* applying any index
mapping.
Parameters
----------
indices: a tuple of the form `(dataset_index, sample_indices)`
The `dataset_index` identifies the dataset from which to draw
samples while `sample_indices` identifies the samples to draw
from it.
Returns
-------
nested list of arrays
A mini-batch | [
"Gather",
"a",
"batch",
"of",
"samples",
"by",
"indices",
"*",
"without",
"*",
"applying",
"any",
"index",
"mapping",
"."
] | 3fc2304e629f813c05f9e7a85a18acef3581a536 | https://github.com/Britefury/batchup/blob/3fc2304e629f813c05f9e7a85a18acef3581a536/batchup/data_source.py#L1147-L1174 | train |
Britefury/batchup | batchup/data_source.py | ChoiceDataSource.batch_indices_iterator | def batch_indices_iterator(self, batch_size, shuffle=None, **kwargs):
"""
Create an iterator that generates mini-batch sample indices
The generated mini-batches indices take the form of nested lists of
either:
- 1D NumPy integer arrays
- slices
The list nesting structure with match that of the tree of data sources
rooted at `self`
Parameters
----------
batch_size: int
Mini-batch size
shuffle: `numpy.random.RandomState` or `True` or `None`
Used to randomise element order. If `None`, elements will be
extracted in order. If it is a `RandomState` instance, that
RNG will be used to shuffle elements. If it is `True`, NumPy's
default RNG will be used.
Returns
-------
iterator
An iterator that generates items that are nested lists of slices
or 1D NumPy integer arrays.
"""
if not self._random_access:
raise TypeError('batch_indices_iterator method not supported as '
'one or more of the underlying data sources '
'does not support random access')
shuffle_rng = self._get_shuffle_rng(shuffle)
iterators = [d.batch_indices_iterator(batch_size,
shuffle=shuffle_rng, **kwargs)
for d in self.datasets]
return self._ds_iterator(batch_size, iterators, shuffle_rng, **kwargs) | python | def batch_indices_iterator(self, batch_size, shuffle=None, **kwargs):
"""
Create an iterator that generates mini-batch sample indices
The generated mini-batches indices take the form of nested lists of
either:
- 1D NumPy integer arrays
- slices
The list nesting structure with match that of the tree of data sources
rooted at `self`
Parameters
----------
batch_size: int
Mini-batch size
shuffle: `numpy.random.RandomState` or `True` or `None`
Used to randomise element order. If `None`, elements will be
extracted in order. If it is a `RandomState` instance, that
RNG will be used to shuffle elements. If it is `True`, NumPy's
default RNG will be used.
Returns
-------
iterator
An iterator that generates items that are nested lists of slices
or 1D NumPy integer arrays.
"""
if not self._random_access:
raise TypeError('batch_indices_iterator method not supported as '
'one or more of the underlying data sources '
'does not support random access')
shuffle_rng = self._get_shuffle_rng(shuffle)
iterators = [d.batch_indices_iterator(batch_size,
shuffle=shuffle_rng, **kwargs)
for d in self.datasets]
return self._ds_iterator(batch_size, iterators, shuffle_rng, **kwargs) | [
"def",
"batch_indices_iterator",
"(",
"self",
",",
"batch_size",
",",
"shuffle",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"self",
".",
"_random_access",
":",
"raise",
"TypeError",
"(",
"'batch_indices_iterator method not supported as '",
"'one or more of the underlying data sources '",
"'does not support random access'",
")",
"shuffle_rng",
"=",
"self",
".",
"_get_shuffle_rng",
"(",
"shuffle",
")",
"iterators",
"=",
"[",
"d",
".",
"batch_indices_iterator",
"(",
"batch_size",
",",
"shuffle",
"=",
"shuffle_rng",
",",
"*",
"*",
"kwargs",
")",
"for",
"d",
"in",
"self",
".",
"datasets",
"]",
"return",
"self",
".",
"_ds_iterator",
"(",
"batch_size",
",",
"iterators",
",",
"shuffle_rng",
",",
"*",
"*",
"kwargs",
")"
] | Create an iterator that generates mini-batch sample indices
The generated mini-batches indices take the form of nested lists of
either:
- 1D NumPy integer arrays
- slices
The list nesting structure with match that of the tree of data sources
rooted at `self`
Parameters
----------
batch_size: int
Mini-batch size
shuffle: `numpy.random.RandomState` or `True` or `None`
Used to randomise element order. If `None`, elements will be
extracted in order. If it is a `RandomState` instance, that
RNG will be used to shuffle elements. If it is `True`, NumPy's
default RNG will be used.
Returns
-------
iterator
An iterator that generates items that are nested lists of slices
or 1D NumPy integer arrays. | [
"Create",
"an",
"iterator",
"that",
"generates",
"mini",
"-",
"batch",
"sample",
"indices"
] | 3fc2304e629f813c05f9e7a85a18acef3581a536 | https://github.com/Britefury/batchup/blob/3fc2304e629f813c05f9e7a85a18acef3581a536/batchup/data_source.py#L1205-L1241 | train |
Britefury/batchup | batchup/data_source.py | MapDataSource.samples_by_indices_nomapping | def samples_by_indices_nomapping(self, indices):
"""
Gather a batch of samples by indices *without* applying any index
mapping.
Parameters
----------
indices: 1D-array of ints or slice
An index array or a slice that selects the samples to retrieve
Returns
-------
nested list of arrays
A mini-batch
"""
if not self._random_access:
raise TypeError('samples_by_indices_nomapping method not '
'supported as one or more of the underlying '
'data sources does not support random access')
batch = self.source.samples_by_indices_nomapping(indices)
return self.fn(*batch) | python | def samples_by_indices_nomapping(self, indices):
"""
Gather a batch of samples by indices *without* applying any index
mapping.
Parameters
----------
indices: 1D-array of ints or slice
An index array or a slice that selects the samples to retrieve
Returns
-------
nested list of arrays
A mini-batch
"""
if not self._random_access:
raise TypeError('samples_by_indices_nomapping method not '
'supported as one or more of the underlying '
'data sources does not support random access')
batch = self.source.samples_by_indices_nomapping(indices)
return self.fn(*batch) | [
"def",
"samples_by_indices_nomapping",
"(",
"self",
",",
"indices",
")",
":",
"if",
"not",
"self",
".",
"_random_access",
":",
"raise",
"TypeError",
"(",
"'samples_by_indices_nomapping method not '",
"'supported as one or more of the underlying '",
"'data sources does not support random access'",
")",
"batch",
"=",
"self",
".",
"source",
".",
"samples_by_indices_nomapping",
"(",
"indices",
")",
"return",
"self",
".",
"fn",
"(",
"*",
"batch",
")"
] | Gather a batch of samples by indices *without* applying any index
mapping.
Parameters
----------
indices: 1D-array of ints or slice
An index array or a slice that selects the samples to retrieve
Returns
-------
nested list of arrays
A mini-batch | [
"Gather",
"a",
"batch",
"of",
"samples",
"by",
"indices",
"*",
"without",
"*",
"applying",
"any",
"index",
"mapping",
"."
] | 3fc2304e629f813c05f9e7a85a18acef3581a536 | https://github.com/Britefury/batchup/blob/3fc2304e629f813c05f9e7a85a18acef3581a536/batchup/data_source.py#L1404-L1424 | train |
Britefury/batchup | batchup/data_source.py | MapDataSource.samples_by_indices | def samples_by_indices(self, indices):
"""
Gather a batch of samples by indices, applying any index
mapping defined by the underlying data sources.
Parameters
----------
indices: 1D-array of ints or slice
An index array or a slice that selects the samples to retrieve
Returns
-------
nested list of arrays
A mini-batch
"""
if not self._random_access:
raise TypeError('samples_by_indices method not supported as one '
'or more of the underlying data sources does '
'not support random access')
batch = self.source.samples_by_indices(indices)
return self.fn(*batch) | python | def samples_by_indices(self, indices):
"""
Gather a batch of samples by indices, applying any index
mapping defined by the underlying data sources.
Parameters
----------
indices: 1D-array of ints or slice
An index array or a slice that selects the samples to retrieve
Returns
-------
nested list of arrays
A mini-batch
"""
if not self._random_access:
raise TypeError('samples_by_indices method not supported as one '
'or more of the underlying data sources does '
'not support random access')
batch = self.source.samples_by_indices(indices)
return self.fn(*batch) | [
"def",
"samples_by_indices",
"(",
"self",
",",
"indices",
")",
":",
"if",
"not",
"self",
".",
"_random_access",
":",
"raise",
"TypeError",
"(",
"'samples_by_indices method not supported as one '",
"'or more of the underlying data sources does '",
"'not support random access'",
")",
"batch",
"=",
"self",
".",
"source",
".",
"samples_by_indices",
"(",
"indices",
")",
"return",
"self",
".",
"fn",
"(",
"*",
"batch",
")"
] | Gather a batch of samples by indices, applying any index
mapping defined by the underlying data sources.
Parameters
----------
indices: 1D-array of ints or slice
An index array or a slice that selects the samples to retrieve
Returns
-------
nested list of arrays
A mini-batch | [
"Gather",
"a",
"batch",
"of",
"samples",
"by",
"indices",
"applying",
"any",
"index",
"mapping",
"defined",
"by",
"the",
"underlying",
"data",
"sources",
"."
] | 3fc2304e629f813c05f9e7a85a18acef3581a536 | https://github.com/Britefury/batchup/blob/3fc2304e629f813c05f9e7a85a18acef3581a536/batchup/data_source.py#L1426-L1446 | train |
Britefury/batchup | batchup/data_source.py | MapDataSource.batch_indices_iterator | def batch_indices_iterator(self, batch_size, **kwargs):
"""
Create an iterator that generates mini-batch sample indices
The generated mini-batches indices take the form of nested lists of
either:
- 1D NumPy integer arrays
- slices
The list nesting structure with match that of the tree of data sources
rooted at `self`
Parameters
----------
batch_size: int
Mini-batch size
Returns
-------
iterator
An iterator that generates items that are nested lists of slices
or 1D NumPy integer arrays.
"""
if not self._random_access:
raise TypeError('batch_indices_iterator method not supported as '
'one or more of the underlying data sources '
'does not support random access')
return self.source.batch_indices_iterator(batch_size, **kwargs) | python | def batch_indices_iterator(self, batch_size, **kwargs):
"""
Create an iterator that generates mini-batch sample indices
The generated mini-batches indices take the form of nested lists of
either:
- 1D NumPy integer arrays
- slices
The list nesting structure with match that of the tree of data sources
rooted at `self`
Parameters
----------
batch_size: int
Mini-batch size
Returns
-------
iterator
An iterator that generates items that are nested lists of slices
or 1D NumPy integer arrays.
"""
if not self._random_access:
raise TypeError('batch_indices_iterator method not supported as '
'one or more of the underlying data sources '
'does not support random access')
return self.source.batch_indices_iterator(batch_size, **kwargs) | [
"def",
"batch_indices_iterator",
"(",
"self",
",",
"batch_size",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"self",
".",
"_random_access",
":",
"raise",
"TypeError",
"(",
"'batch_indices_iterator method not supported as '",
"'one or more of the underlying data sources '",
"'does not support random access'",
")",
"return",
"self",
".",
"source",
".",
"batch_indices_iterator",
"(",
"batch_size",
",",
"*",
"*",
"kwargs",
")"
] | Create an iterator that generates mini-batch sample indices
The generated mini-batches indices take the form of nested lists of
either:
- 1D NumPy integer arrays
- slices
The list nesting structure with match that of the tree of data sources
rooted at `self`
Parameters
----------
batch_size: int
Mini-batch size
Returns
-------
iterator
An iterator that generates items that are nested lists of slices
or 1D NumPy integer arrays. | [
"Create",
"an",
"iterator",
"that",
"generates",
"mini",
"-",
"batch",
"sample",
"indices"
] | 3fc2304e629f813c05f9e7a85a18acef3581a536 | https://github.com/Britefury/batchup/blob/3fc2304e629f813c05f9e7a85a18acef3581a536/batchup/data_source.py#L1448-L1475 | train |
datacats/datacats | datacats/cli/purge.py | purge | def purge(opts):
"""Purge environment database and uploaded files
Usage:
datacats purge [-s NAME | --delete-environment] [-y] [ENVIRONMENT]
Options:
--delete-environment Delete environment directory as well as its data, as
well as the data for **all** sites.
-s --site=NAME Specify a site to be purge [default: primary]
-y --yes Respond yes to all prompts (i.e. force)
ENVIRONMENT may be an environment name or a path to an environment directory.
Default: '.'
"""
old = False
try:
environment = Environment.load(opts['ENVIRONMENT'], opts['--site'])
except DatacatsError:
environment = Environment.load(opts['ENVIRONMENT'], opts['--site'], data_only=True)
if get_format_version(environment.datadir) == 1:
old = True
environment = Environment.load(opts['ENVIRONMENT'], opts['--site'], allow_old=True)
# We need a valid site if they don't want to blow away everything.
if not opts['--delete-environment'] and not old:
environment.require_valid_site()
sites = [opts['--site']] if not opts['--delete-environment'] else environment.sites
if not opts['--yes']:
y_or_n_prompt('datacats purge will delete all stored data')
environment.stop_ckan()
environment.stop_supporting_containers()
environment.purge_data(sites)
if opts['--delete-environment']:
if environment.target:
rmtree(environment.target)
else:
DatacatsError(("Unable to find the environment source"
" directory so that it can be deleted.\n"
"Chances are it's because it already does not exist")) | python | def purge(opts):
"""Purge environment database and uploaded files
Usage:
datacats purge [-s NAME | --delete-environment] [-y] [ENVIRONMENT]
Options:
--delete-environment Delete environment directory as well as its data, as
well as the data for **all** sites.
-s --site=NAME Specify a site to be purge [default: primary]
-y --yes Respond yes to all prompts (i.e. force)
ENVIRONMENT may be an environment name or a path to an environment directory.
Default: '.'
"""
old = False
try:
environment = Environment.load(opts['ENVIRONMENT'], opts['--site'])
except DatacatsError:
environment = Environment.load(opts['ENVIRONMENT'], opts['--site'], data_only=True)
if get_format_version(environment.datadir) == 1:
old = True
environment = Environment.load(opts['ENVIRONMENT'], opts['--site'], allow_old=True)
# We need a valid site if they don't want to blow away everything.
if not opts['--delete-environment'] and not old:
environment.require_valid_site()
sites = [opts['--site']] if not opts['--delete-environment'] else environment.sites
if not opts['--yes']:
y_or_n_prompt('datacats purge will delete all stored data')
environment.stop_ckan()
environment.stop_supporting_containers()
environment.purge_data(sites)
if opts['--delete-environment']:
if environment.target:
rmtree(environment.target)
else:
DatacatsError(("Unable to find the environment source"
" directory so that it can be deleted.\n"
"Chances are it's because it already does not exist")) | [
"def",
"purge",
"(",
"opts",
")",
":",
"old",
"=",
"False",
"try",
":",
"environment",
"=",
"Environment",
".",
"load",
"(",
"opts",
"[",
"'ENVIRONMENT'",
"]",
",",
"opts",
"[",
"'--site'",
"]",
")",
"except",
"DatacatsError",
":",
"environment",
"=",
"Environment",
".",
"load",
"(",
"opts",
"[",
"'ENVIRONMENT'",
"]",
",",
"opts",
"[",
"'--site'",
"]",
",",
"data_only",
"=",
"True",
")",
"if",
"get_format_version",
"(",
"environment",
".",
"datadir",
")",
"==",
"1",
":",
"old",
"=",
"True",
"environment",
"=",
"Environment",
".",
"load",
"(",
"opts",
"[",
"'ENVIRONMENT'",
"]",
",",
"opts",
"[",
"'--site'",
"]",
",",
"allow_old",
"=",
"True",
")",
"# We need a valid site if they don't want to blow away everything.",
"if",
"not",
"opts",
"[",
"'--delete-environment'",
"]",
"and",
"not",
"old",
":",
"environment",
".",
"require_valid_site",
"(",
")",
"sites",
"=",
"[",
"opts",
"[",
"'--site'",
"]",
"]",
"if",
"not",
"opts",
"[",
"'--delete-environment'",
"]",
"else",
"environment",
".",
"sites",
"if",
"not",
"opts",
"[",
"'--yes'",
"]",
":",
"y_or_n_prompt",
"(",
"'datacats purge will delete all stored data'",
")",
"environment",
".",
"stop_ckan",
"(",
")",
"environment",
".",
"stop_supporting_containers",
"(",
")",
"environment",
".",
"purge_data",
"(",
"sites",
")",
"if",
"opts",
"[",
"'--delete-environment'",
"]",
":",
"if",
"environment",
".",
"target",
":",
"rmtree",
"(",
"environment",
".",
"target",
")",
"else",
":",
"DatacatsError",
"(",
"(",
"\"Unable to find the environment source\"",
"\" directory so that it can be deleted.\\n\"",
"\"Chances are it's because it already does not exist\"",
")",
")"
] | Purge environment database and uploaded files
Usage:
datacats purge [-s NAME | --delete-environment] [-y] [ENVIRONMENT]
Options:
--delete-environment Delete environment directory as well as its data, as
well as the data for **all** sites.
-s --site=NAME Specify a site to be purge [default: primary]
-y --yes Respond yes to all prompts (i.e. force)
ENVIRONMENT may be an environment name or a path to an environment directory.
Default: '.' | [
"Purge",
"environment",
"database",
"and",
"uploaded",
"files"
] | e4bae503efa997660fb3f34fe166699569653157 | https://github.com/datacats/datacats/blob/e4bae503efa997660fb3f34fe166699569653157/datacats/cli/purge.py#L15-L59 | train |
datacats/datacats | datacats/error.py | DatacatsError.pretty_print | def pretty_print(self):
"""
Print the error message to stdout with colors and borders
"""
print colored.blue("-" * 40)
print colored.red("datacats: problem was encountered:")
print self.message
print colored.blue("-" * 40) | python | def pretty_print(self):
"""
Print the error message to stdout with colors and borders
"""
print colored.blue("-" * 40)
print colored.red("datacats: problem was encountered:")
print self.message
print colored.blue("-" * 40) | [
"def",
"pretty_print",
"(",
"self",
")",
":",
"print",
"colored",
".",
"blue",
"(",
"\"-\"",
"*",
"40",
")",
"print",
"colored",
".",
"red",
"(",
"\"datacats: problem was encountered:\"",
")",
"print",
"self",
".",
"message",
"print",
"colored",
".",
"blue",
"(",
"\"-\"",
"*",
"40",
")"
] | Print the error message to stdout with colors and borders | [
"Print",
"the",
"error",
"message",
"to",
"stdout",
"with",
"colors",
"and",
"borders"
] | e4bae503efa997660fb3f34fe166699569653157 | https://github.com/datacats/datacats/blob/e4bae503efa997660fb3f34fe166699569653157/datacats/error.py#L25-L32 | train |
datacats/datacats | datacats/password.py | generate_password | def generate_password():
"""
Return a 16-character alphanumeric random string generated by the
operating system's secure pseudo random number generator
"""
chars = uppercase + lowercase + digits
return ''.join(SystemRandom().choice(chars) for x in xrange(16)) | python | def generate_password():
"""
Return a 16-character alphanumeric random string generated by the
operating system's secure pseudo random number generator
"""
chars = uppercase + lowercase + digits
return ''.join(SystemRandom().choice(chars) for x in xrange(16)) | [
"def",
"generate_password",
"(",
")",
":",
"chars",
"=",
"uppercase",
"+",
"lowercase",
"+",
"digits",
"return",
"''",
".",
"join",
"(",
"SystemRandom",
"(",
")",
".",
"choice",
"(",
"chars",
")",
"for",
"x",
"in",
"xrange",
"(",
"16",
")",
")"
] | Return a 16-character alphanumeric random string generated by the
operating system's secure pseudo random number generator | [
"Return",
"a",
"16",
"-",
"character",
"alphanumeric",
"random",
"string",
"generated",
"by",
"the",
"operating",
"system",
"s",
"secure",
"pseudo",
"random",
"number",
"generator"
] | e4bae503efa997660fb3f34fe166699569653157 | https://github.com/datacats/datacats/blob/e4bae503efa997660fb3f34fe166699569653157/datacats/password.py#L10-L16 | train |
datacats/datacats | datacats/docker.py | _machine_check_connectivity | def _machine_check_connectivity():
"""
This method calls to docker-machine on the command line and
makes sure that it is up and ready.
Potential improvements to be made:
- Support multiple machine names (run a `docker-machine ls` and then
see which machines are active. Use a priority list)
"""
with open(devnull, 'w') as devnull_f:
try:
status = subprocess.check_output(
['docker-machine', 'status', 'dev'],
stderr=devnull_f).strip()
if status == 'Stopped':
raise DatacatsError('Please start your docker-machine '
'VM with "docker-machine start dev"')
# XXX HACK: This exists because of
# http://github.com/datacats/datacats/issues/63,
# as a temporary fix.
if 'tls' in _docker_kwargs:
# It will print out messages to the user otherwise.
_docker_kwargs['tls'].assert_hostname = False
except subprocess.CalledProcessError:
raise DatacatsError('Please create a docker-machine with '
'"docker-machine start dev"') | python | def _machine_check_connectivity():
"""
This method calls to docker-machine on the command line and
makes sure that it is up and ready.
Potential improvements to be made:
- Support multiple machine names (run a `docker-machine ls` and then
see which machines are active. Use a priority list)
"""
with open(devnull, 'w') as devnull_f:
try:
status = subprocess.check_output(
['docker-machine', 'status', 'dev'],
stderr=devnull_f).strip()
if status == 'Stopped':
raise DatacatsError('Please start your docker-machine '
'VM with "docker-machine start dev"')
# XXX HACK: This exists because of
# http://github.com/datacats/datacats/issues/63,
# as a temporary fix.
if 'tls' in _docker_kwargs:
# It will print out messages to the user otherwise.
_docker_kwargs['tls'].assert_hostname = False
except subprocess.CalledProcessError:
raise DatacatsError('Please create a docker-machine with '
'"docker-machine start dev"') | [
"def",
"_machine_check_connectivity",
"(",
")",
":",
"with",
"open",
"(",
"devnull",
",",
"'w'",
")",
"as",
"devnull_f",
":",
"try",
":",
"status",
"=",
"subprocess",
".",
"check_output",
"(",
"[",
"'docker-machine'",
",",
"'status'",
",",
"'dev'",
"]",
",",
"stderr",
"=",
"devnull_f",
")",
".",
"strip",
"(",
")",
"if",
"status",
"==",
"'Stopped'",
":",
"raise",
"DatacatsError",
"(",
"'Please start your docker-machine '",
"'VM with \"docker-machine start dev\"'",
")",
"# XXX HACK: This exists because of",
"# http://github.com/datacats/datacats/issues/63,",
"# as a temporary fix.",
"if",
"'tls'",
"in",
"_docker_kwargs",
":",
"# It will print out messages to the user otherwise.",
"_docker_kwargs",
"[",
"'tls'",
"]",
".",
"assert_hostname",
"=",
"False",
"except",
"subprocess",
".",
"CalledProcessError",
":",
"raise",
"DatacatsError",
"(",
"'Please create a docker-machine with '",
"'\"docker-machine start dev\"'",
")"
] | This method calls to docker-machine on the command line and
makes sure that it is up and ready.
Potential improvements to be made:
- Support multiple machine names (run a `docker-machine ls` and then
see which machines are active. Use a priority list) | [
"This",
"method",
"calls",
"to",
"docker",
"-",
"machine",
"on",
"the",
"command",
"line",
"and",
"makes",
"sure",
"that",
"it",
"is",
"up",
"and",
"ready",
"."
] | e4bae503efa997660fb3f34fe166699569653157 | https://github.com/datacats/datacats/blob/e4bae503efa997660fb3f34fe166699569653157/datacats/docker.py#L66-L92 | train |
datacats/datacats | datacats/docker.py | ro_rw_to_binds | def ro_rw_to_binds(ro, rw):
"""
ro and rw {localdir: binddir} dicts to docker-py's
{localdir: {'bind': binddir, 'ro': T/F}} binds dicts
"""
out = {}
if ro:
for localdir, binddir in ro.iteritems():
out[localdir] = {'bind': binddir, 'ro': True}
if rw:
for localdir, binddir in rw.iteritems():
out[localdir] = {'bind': binddir, 'ro': False}
return out | python | def ro_rw_to_binds(ro, rw):
"""
ro and rw {localdir: binddir} dicts to docker-py's
{localdir: {'bind': binddir, 'ro': T/F}} binds dicts
"""
out = {}
if ro:
for localdir, binddir in ro.iteritems():
out[localdir] = {'bind': binddir, 'ro': True}
if rw:
for localdir, binddir in rw.iteritems():
out[localdir] = {'bind': binddir, 'ro': False}
return out | [
"def",
"ro_rw_to_binds",
"(",
"ro",
",",
"rw",
")",
":",
"out",
"=",
"{",
"}",
"if",
"ro",
":",
"for",
"localdir",
",",
"binddir",
"in",
"ro",
".",
"iteritems",
"(",
")",
":",
"out",
"[",
"localdir",
"]",
"=",
"{",
"'bind'",
":",
"binddir",
",",
"'ro'",
":",
"True",
"}",
"if",
"rw",
":",
"for",
"localdir",
",",
"binddir",
"in",
"rw",
".",
"iteritems",
"(",
")",
":",
"out",
"[",
"localdir",
"]",
"=",
"{",
"'bind'",
":",
"binddir",
",",
"'ro'",
":",
"False",
"}",
"return",
"out"
] | ro and rw {localdir: binddir} dicts to docker-py's
{localdir: {'bind': binddir, 'ro': T/F}} binds dicts | [
"ro",
"and",
"rw",
"{",
"localdir",
":",
"binddir",
"}",
"dicts",
"to",
"docker",
"-",
"py",
"s",
"{",
"localdir",
":",
"{",
"bind",
":",
"binddir",
"ro",
":",
"T",
"/",
"F",
"}}",
"binds",
"dicts"
] | e4bae503efa997660fb3f34fe166699569653157 | https://github.com/datacats/datacats/blob/e4bae503efa997660fb3f34fe166699569653157/datacats/docker.py#L140-L152 | train |
datacats/datacats | datacats/docker.py | web_command | def web_command(command, ro=None, rw=None, links=None,
image='datacats/web', volumes_from=None, commit=False,
clean_up=False, stream_output=None, entrypoint=None):
"""
Run a single command in a web image optionally preloaded with the ckan
source and virtual envrionment.
:param command: command to execute
:param ro: {localdir: binddir} dict for read-only volumes
:param rw: {localdir: binddir} dict for read-write volumes
:param links: links passed to start
:param image: docker image name to use
:param volumes_from:
:param commit: True to create a new image based on result
:param clean_up: True to remove container even on error
:param stream_output: file to write stderr+stdout from command
:param entrypoint: override entrypoint (script that runs command)
:returns: image id if commit=True
"""
binds = ro_rw_to_binds(ro, rw)
c = _get_docker().create_container(
image=image,
command=command,
volumes=binds_to_volumes(binds),
detach=False,
host_config=_get_docker().create_host_config(binds=binds, volumes_from=volumes_from, links=links),
entrypoint=entrypoint)
_get_docker().start(
container=c['Id'],
)
if stream_output:
for output in _get_docker().attach(
c['Id'], stdout=True, stderr=True, stream=True):
stream_output.write(output)
if _get_docker().wait(c['Id']):
# Before the (potential) cleanup, grab the logs!
logs = _get_docker().logs(c['Id'])
if clean_up:
remove_container(c['Id'])
raise WebCommandError(command, c['Id'][:12], logs)
if commit:
rval = _get_docker().commit(c['Id'])
if not remove_container(c['Id']):
# circle ci doesn't let us remove containers, quiet the warnings
if not environ.get('CIRCLECI', False):
warn('failed to remove container: {0}'.format(c['Id']))
if commit:
return rval['Id'] | python | def web_command(command, ro=None, rw=None, links=None,
image='datacats/web', volumes_from=None, commit=False,
clean_up=False, stream_output=None, entrypoint=None):
"""
Run a single command in a web image optionally preloaded with the ckan
source and virtual envrionment.
:param command: command to execute
:param ro: {localdir: binddir} dict for read-only volumes
:param rw: {localdir: binddir} dict for read-write volumes
:param links: links passed to start
:param image: docker image name to use
:param volumes_from:
:param commit: True to create a new image based on result
:param clean_up: True to remove container even on error
:param stream_output: file to write stderr+stdout from command
:param entrypoint: override entrypoint (script that runs command)
:returns: image id if commit=True
"""
binds = ro_rw_to_binds(ro, rw)
c = _get_docker().create_container(
image=image,
command=command,
volumes=binds_to_volumes(binds),
detach=False,
host_config=_get_docker().create_host_config(binds=binds, volumes_from=volumes_from, links=links),
entrypoint=entrypoint)
_get_docker().start(
container=c['Id'],
)
if stream_output:
for output in _get_docker().attach(
c['Id'], stdout=True, stderr=True, stream=True):
stream_output.write(output)
if _get_docker().wait(c['Id']):
# Before the (potential) cleanup, grab the logs!
logs = _get_docker().logs(c['Id'])
if clean_up:
remove_container(c['Id'])
raise WebCommandError(command, c['Id'][:12], logs)
if commit:
rval = _get_docker().commit(c['Id'])
if not remove_container(c['Id']):
# circle ci doesn't let us remove containers, quiet the warnings
if not environ.get('CIRCLECI', False):
warn('failed to remove container: {0}'.format(c['Id']))
if commit:
return rval['Id'] | [
"def",
"web_command",
"(",
"command",
",",
"ro",
"=",
"None",
",",
"rw",
"=",
"None",
",",
"links",
"=",
"None",
",",
"image",
"=",
"'datacats/web'",
",",
"volumes_from",
"=",
"None",
",",
"commit",
"=",
"False",
",",
"clean_up",
"=",
"False",
",",
"stream_output",
"=",
"None",
",",
"entrypoint",
"=",
"None",
")",
":",
"binds",
"=",
"ro_rw_to_binds",
"(",
"ro",
",",
"rw",
")",
"c",
"=",
"_get_docker",
"(",
")",
".",
"create_container",
"(",
"image",
"=",
"image",
",",
"command",
"=",
"command",
",",
"volumes",
"=",
"binds_to_volumes",
"(",
"binds",
")",
",",
"detach",
"=",
"False",
",",
"host_config",
"=",
"_get_docker",
"(",
")",
".",
"create_host_config",
"(",
"binds",
"=",
"binds",
",",
"volumes_from",
"=",
"volumes_from",
",",
"links",
"=",
"links",
")",
",",
"entrypoint",
"=",
"entrypoint",
")",
"_get_docker",
"(",
")",
".",
"start",
"(",
"container",
"=",
"c",
"[",
"'Id'",
"]",
",",
")",
"if",
"stream_output",
":",
"for",
"output",
"in",
"_get_docker",
"(",
")",
".",
"attach",
"(",
"c",
"[",
"'Id'",
"]",
",",
"stdout",
"=",
"True",
",",
"stderr",
"=",
"True",
",",
"stream",
"=",
"True",
")",
":",
"stream_output",
".",
"write",
"(",
"output",
")",
"if",
"_get_docker",
"(",
")",
".",
"wait",
"(",
"c",
"[",
"'Id'",
"]",
")",
":",
"# Before the (potential) cleanup, grab the logs!",
"logs",
"=",
"_get_docker",
"(",
")",
".",
"logs",
"(",
"c",
"[",
"'Id'",
"]",
")",
"if",
"clean_up",
":",
"remove_container",
"(",
"c",
"[",
"'Id'",
"]",
")",
"raise",
"WebCommandError",
"(",
"command",
",",
"c",
"[",
"'Id'",
"]",
"[",
":",
"12",
"]",
",",
"logs",
")",
"if",
"commit",
":",
"rval",
"=",
"_get_docker",
"(",
")",
".",
"commit",
"(",
"c",
"[",
"'Id'",
"]",
")",
"if",
"not",
"remove_container",
"(",
"c",
"[",
"'Id'",
"]",
")",
":",
"# circle ci doesn't let us remove containers, quiet the warnings",
"if",
"not",
"environ",
".",
"get",
"(",
"'CIRCLECI'",
",",
"False",
")",
":",
"warn",
"(",
"'failed to remove container: {0}'",
".",
"format",
"(",
"c",
"[",
"'Id'",
"]",
")",
")",
"if",
"commit",
":",
"return",
"rval",
"[",
"'Id'",
"]"
] | Run a single command in a web image optionally preloaded with the ckan
source and virtual envrionment.
:param command: command to execute
:param ro: {localdir: binddir} dict for read-only volumes
:param rw: {localdir: binddir} dict for read-write volumes
:param links: links passed to start
:param image: docker image name to use
:param volumes_from:
:param commit: True to create a new image based on result
:param clean_up: True to remove container even on error
:param stream_output: file to write stderr+stdout from command
:param entrypoint: override entrypoint (script that runs command)
:returns: image id if commit=True | [
"Run",
"a",
"single",
"command",
"in",
"a",
"web",
"image",
"optionally",
"preloaded",
"with",
"the",
"ckan",
"source",
"and",
"virtual",
"envrionment",
"."
] | e4bae503efa997660fb3f34fe166699569653157 | https://github.com/datacats/datacats/blob/e4bae503efa997660fb3f34fe166699569653157/datacats/docker.py#L163-L212 | train |
datacats/datacats | datacats/docker.py | remote_server_command | def remote_server_command(command, environment, user_profile, **kwargs):
"""
Wraps web_command function with docker bindings needed to connect to
a remote server (such as datacats.com) and run commands there
(for example, when you want to copy your catalog to that server).
The files binded to the docker image include the user's ssh credentials:
ssh_config file,
rsa and rsa.pub user keys
known_hosts whith public keys of the remote server (if known)
The **kwargs (keyword arguments) are passed on to the web_command call
intact, see the web_command's doc string for details
"""
if environment.remote_server_key:
temp = tempfile.NamedTemporaryFile(mode="wb")
temp.write(environment.remote_server_key)
temp.seek(0)
known_hosts = temp.name
else:
known_hosts = get_script_path('known_hosts')
binds = {
user_profile.profiledir + '/id_rsa': '/root/.ssh/id_rsa',
known_hosts: '/root/.ssh/known_hosts',
get_script_path('ssh_config'): '/etc/ssh/ssh_config'
}
if kwargs.get("include_project_dir", None):
binds[environment.target] = '/project'
del kwargs["include_project_dir"]
kwargs["ro"] = binds
try:
web_command(command, **kwargs)
except WebCommandError as e:
e.user_description = 'Sending a command to remote server failed'
raise e | python | def remote_server_command(command, environment, user_profile, **kwargs):
"""
Wraps web_command function with docker bindings needed to connect to
a remote server (such as datacats.com) and run commands there
(for example, when you want to copy your catalog to that server).
The files binded to the docker image include the user's ssh credentials:
ssh_config file,
rsa and rsa.pub user keys
known_hosts whith public keys of the remote server (if known)
The **kwargs (keyword arguments) are passed on to the web_command call
intact, see the web_command's doc string for details
"""
if environment.remote_server_key:
temp = tempfile.NamedTemporaryFile(mode="wb")
temp.write(environment.remote_server_key)
temp.seek(0)
known_hosts = temp.name
else:
known_hosts = get_script_path('known_hosts')
binds = {
user_profile.profiledir + '/id_rsa': '/root/.ssh/id_rsa',
known_hosts: '/root/.ssh/known_hosts',
get_script_path('ssh_config'): '/etc/ssh/ssh_config'
}
if kwargs.get("include_project_dir", None):
binds[environment.target] = '/project'
del kwargs["include_project_dir"]
kwargs["ro"] = binds
try:
web_command(command, **kwargs)
except WebCommandError as e:
e.user_description = 'Sending a command to remote server failed'
raise e | [
"def",
"remote_server_command",
"(",
"command",
",",
"environment",
",",
"user_profile",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"environment",
".",
"remote_server_key",
":",
"temp",
"=",
"tempfile",
".",
"NamedTemporaryFile",
"(",
"mode",
"=",
"\"wb\"",
")",
"temp",
".",
"write",
"(",
"environment",
".",
"remote_server_key",
")",
"temp",
".",
"seek",
"(",
"0",
")",
"known_hosts",
"=",
"temp",
".",
"name",
"else",
":",
"known_hosts",
"=",
"get_script_path",
"(",
"'known_hosts'",
")",
"binds",
"=",
"{",
"user_profile",
".",
"profiledir",
"+",
"'/id_rsa'",
":",
"'/root/.ssh/id_rsa'",
",",
"known_hosts",
":",
"'/root/.ssh/known_hosts'",
",",
"get_script_path",
"(",
"'ssh_config'",
")",
":",
"'/etc/ssh/ssh_config'",
"}",
"if",
"kwargs",
".",
"get",
"(",
"\"include_project_dir\"",
",",
"None",
")",
":",
"binds",
"[",
"environment",
".",
"target",
"]",
"=",
"'/project'",
"del",
"kwargs",
"[",
"\"include_project_dir\"",
"]",
"kwargs",
"[",
"\"ro\"",
"]",
"=",
"binds",
"try",
":",
"web_command",
"(",
"command",
",",
"*",
"*",
"kwargs",
")",
"except",
"WebCommandError",
"as",
"e",
":",
"e",
".",
"user_description",
"=",
"'Sending a command to remote server failed'",
"raise",
"e"
] | Wraps web_command function with docker bindings needed to connect to
a remote server (such as datacats.com) and run commands there
(for example, when you want to copy your catalog to that server).
The files binded to the docker image include the user's ssh credentials:
ssh_config file,
rsa and rsa.pub user keys
known_hosts whith public keys of the remote server (if known)
The **kwargs (keyword arguments) are passed on to the web_command call
intact, see the web_command's doc string for details | [
"Wraps",
"web_command",
"function",
"with",
"docker",
"bindings",
"needed",
"to",
"connect",
"to",
"a",
"remote",
"server",
"(",
"such",
"as",
"datacats",
".",
"com",
")",
"and",
"run",
"commands",
"there",
"(",
"for",
"example",
"when",
"you",
"want",
"to",
"copy",
"your",
"catalog",
"to",
"that",
"server",
")",
"."
] | e4bae503efa997660fb3f34fe166699569653157 | https://github.com/datacats/datacats/blob/e4bae503efa997660fb3f34fe166699569653157/datacats/docker.py#L215-L253 | train |
datacats/datacats | datacats/docker.py | run_container | def run_container(name, image, command=None, environment=None,
ro=None, rw=None, links=None, detach=True, volumes_from=None,
port_bindings=None, log_syslog=False):
"""
Wrapper for docker create_container, start calls
:param log_syslog: bool flag to redirect container's logs to host's syslog
:returns: container info dict or None if container couldn't be created
Raises PortAllocatedError if container couldn't start on the
requested port.
"""
binds = ro_rw_to_binds(ro, rw)
log_config = LogConfig(type=LogConfig.types.JSON)
if log_syslog:
log_config = LogConfig(
type=LogConfig.types.SYSLOG,
config={'syslog-tag': name})
host_config = _get_docker().create_host_config(binds=binds, log_config=log_config, links=links, volumes_from=volumes_from, port_bindings=port_bindings)
c = _get_docker().create_container(
name=name,
image=image,
command=command,
environment=environment,
volumes=binds_to_volumes(binds),
detach=detach,
stdin_open=False,
tty=False,
ports=list(port_bindings) if port_bindings else None,
host_config=host_config)
try:
_get_docker().start(
container=c['Id'],
)
except APIError as e:
if 'address already in use' in e.explanation:
try:
_get_docker().remove_container(name, force=True)
except APIError:
pass
raise PortAllocatedError()
raise
return c | python | def run_container(name, image, command=None, environment=None,
ro=None, rw=None, links=None, detach=True, volumes_from=None,
port_bindings=None, log_syslog=False):
"""
Wrapper for docker create_container, start calls
:param log_syslog: bool flag to redirect container's logs to host's syslog
:returns: container info dict or None if container couldn't be created
Raises PortAllocatedError if container couldn't start on the
requested port.
"""
binds = ro_rw_to_binds(ro, rw)
log_config = LogConfig(type=LogConfig.types.JSON)
if log_syslog:
log_config = LogConfig(
type=LogConfig.types.SYSLOG,
config={'syslog-tag': name})
host_config = _get_docker().create_host_config(binds=binds, log_config=log_config, links=links, volumes_from=volumes_from, port_bindings=port_bindings)
c = _get_docker().create_container(
name=name,
image=image,
command=command,
environment=environment,
volumes=binds_to_volumes(binds),
detach=detach,
stdin_open=False,
tty=False,
ports=list(port_bindings) if port_bindings else None,
host_config=host_config)
try:
_get_docker().start(
container=c['Id'],
)
except APIError as e:
if 'address already in use' in e.explanation:
try:
_get_docker().remove_container(name, force=True)
except APIError:
pass
raise PortAllocatedError()
raise
return c | [
"def",
"run_container",
"(",
"name",
",",
"image",
",",
"command",
"=",
"None",
",",
"environment",
"=",
"None",
",",
"ro",
"=",
"None",
",",
"rw",
"=",
"None",
",",
"links",
"=",
"None",
",",
"detach",
"=",
"True",
",",
"volumes_from",
"=",
"None",
",",
"port_bindings",
"=",
"None",
",",
"log_syslog",
"=",
"False",
")",
":",
"binds",
"=",
"ro_rw_to_binds",
"(",
"ro",
",",
"rw",
")",
"log_config",
"=",
"LogConfig",
"(",
"type",
"=",
"LogConfig",
".",
"types",
".",
"JSON",
")",
"if",
"log_syslog",
":",
"log_config",
"=",
"LogConfig",
"(",
"type",
"=",
"LogConfig",
".",
"types",
".",
"SYSLOG",
",",
"config",
"=",
"{",
"'syslog-tag'",
":",
"name",
"}",
")",
"host_config",
"=",
"_get_docker",
"(",
")",
".",
"create_host_config",
"(",
"binds",
"=",
"binds",
",",
"log_config",
"=",
"log_config",
",",
"links",
"=",
"links",
",",
"volumes_from",
"=",
"volumes_from",
",",
"port_bindings",
"=",
"port_bindings",
")",
"c",
"=",
"_get_docker",
"(",
")",
".",
"create_container",
"(",
"name",
"=",
"name",
",",
"image",
"=",
"image",
",",
"command",
"=",
"command",
",",
"environment",
"=",
"environment",
",",
"volumes",
"=",
"binds_to_volumes",
"(",
"binds",
")",
",",
"detach",
"=",
"detach",
",",
"stdin_open",
"=",
"False",
",",
"tty",
"=",
"False",
",",
"ports",
"=",
"list",
"(",
"port_bindings",
")",
"if",
"port_bindings",
"else",
"None",
",",
"host_config",
"=",
"host_config",
")",
"try",
":",
"_get_docker",
"(",
")",
".",
"start",
"(",
"container",
"=",
"c",
"[",
"'Id'",
"]",
",",
")",
"except",
"APIError",
"as",
"e",
":",
"if",
"'address already in use'",
"in",
"e",
".",
"explanation",
":",
"try",
":",
"_get_docker",
"(",
")",
".",
"remove_container",
"(",
"name",
",",
"force",
"=",
"True",
")",
"except",
"APIError",
":",
"pass",
"raise",
"PortAllocatedError",
"(",
")",
"raise",
"return",
"c"
] | Wrapper for docker create_container, start calls
:param log_syslog: bool flag to redirect container's logs to host's syslog
:returns: container info dict or None if container couldn't be created
Raises PortAllocatedError if container couldn't start on the
requested port. | [
"Wrapper",
"for",
"docker",
"create_container",
"start",
"calls"
] | e4bae503efa997660fb3f34fe166699569653157 | https://github.com/datacats/datacats/blob/e4bae503efa997660fb3f34fe166699569653157/datacats/docker.py#L256-L300 | train |
datacats/datacats | datacats/docker.py | remove_container | def remove_container(name, force=False):
"""
Wrapper for docker remove_container
:returns: True if container was found and removed
"""
try:
if not force:
_get_docker().stop(name)
except APIError:
pass
try:
_get_docker().remove_container(name, force=True)
return True
except APIError:
return False | python | def remove_container(name, force=False):
"""
Wrapper for docker remove_container
:returns: True if container was found and removed
"""
try:
if not force:
_get_docker().stop(name)
except APIError:
pass
try:
_get_docker().remove_container(name, force=True)
return True
except APIError:
return False | [
"def",
"remove_container",
"(",
"name",
",",
"force",
"=",
"False",
")",
":",
"try",
":",
"if",
"not",
"force",
":",
"_get_docker",
"(",
")",
".",
"stop",
"(",
"name",
")",
"except",
"APIError",
":",
"pass",
"try",
":",
"_get_docker",
"(",
")",
".",
"remove_container",
"(",
"name",
",",
"force",
"=",
"True",
")",
"return",
"True",
"except",
"APIError",
":",
"return",
"False"
] | Wrapper for docker remove_container
:returns: True if container was found and removed | [
"Wrapper",
"for",
"docker",
"remove_container"
] | e4bae503efa997660fb3f34fe166699569653157 | https://github.com/datacats/datacats/blob/e4bae503efa997660fb3f34fe166699569653157/datacats/docker.py#L318-L334 | train |
datacats/datacats | datacats/docker.py | container_logs | def container_logs(name, tail, follow, timestamps):
"""
Wrapper for docker logs, attach commands.
"""
if follow:
return _get_docker().attach(
name,
stdout=True,
stderr=True,
stream=True
)
return _docker.logs(
name,
stdout=True,
stderr=True,
tail=tail,
timestamps=timestamps,
) | python | def container_logs(name, tail, follow, timestamps):
"""
Wrapper for docker logs, attach commands.
"""
if follow:
return _get_docker().attach(
name,
stdout=True,
stderr=True,
stream=True
)
return _docker.logs(
name,
stdout=True,
stderr=True,
tail=tail,
timestamps=timestamps,
) | [
"def",
"container_logs",
"(",
"name",
",",
"tail",
",",
"follow",
",",
"timestamps",
")",
":",
"if",
"follow",
":",
"return",
"_get_docker",
"(",
")",
".",
"attach",
"(",
"name",
",",
"stdout",
"=",
"True",
",",
"stderr",
"=",
"True",
",",
"stream",
"=",
"True",
")",
"return",
"_docker",
".",
"logs",
"(",
"name",
",",
"stdout",
"=",
"True",
",",
"stderr",
"=",
"True",
",",
"tail",
"=",
"tail",
",",
"timestamps",
"=",
"timestamps",
",",
")"
] | Wrapper for docker logs, attach commands. | [
"Wrapper",
"for",
"docker",
"logs",
"attach",
"commands",
"."
] | e4bae503efa997660fb3f34fe166699569653157 | https://github.com/datacats/datacats/blob/e4bae503efa997660fb3f34fe166699569653157/datacats/docker.py#L349-L367 | train |
datacats/datacats | datacats/docker.py | collect_logs | def collect_logs(name):
"""
Returns a string representation of the logs from a container.
This is similar to container_logs but uses the `follow` option
and flattens the logs into a string instead of a generator.
:param name: The container name to grab logs for
:return: A string representation of the logs
"""
logs = container_logs(name, "all", True, None)
string = ""
for s in logs:
string += s
return string | python | def collect_logs(name):
"""
Returns a string representation of the logs from a container.
This is similar to container_logs but uses the `follow` option
and flattens the logs into a string instead of a generator.
:param name: The container name to grab logs for
:return: A string representation of the logs
"""
logs = container_logs(name, "all", True, None)
string = ""
for s in logs:
string += s
return string | [
"def",
"collect_logs",
"(",
"name",
")",
":",
"logs",
"=",
"container_logs",
"(",
"name",
",",
"\"all\"",
",",
"True",
",",
"None",
")",
"string",
"=",
"\"\"",
"for",
"s",
"in",
"logs",
":",
"string",
"+=",
"s",
"return",
"string"
] | Returns a string representation of the logs from a container.
This is similar to container_logs but uses the `follow` option
and flattens the logs into a string instead of a generator.
:param name: The container name to grab logs for
:return: A string representation of the logs | [
"Returns",
"a",
"string",
"representation",
"of",
"the",
"logs",
"from",
"a",
"container",
".",
"This",
"is",
"similar",
"to",
"container_logs",
"but",
"uses",
"the",
"follow",
"option",
"and",
"flattens",
"the",
"logs",
"into",
"a",
"string",
"instead",
"of",
"a",
"generator",
"."
] | e4bae503efa997660fb3f34fe166699569653157 | https://github.com/datacats/datacats/blob/e4bae503efa997660fb3f34fe166699569653157/datacats/docker.py#L370-L383 | train |
datacats/datacats | datacats/docker.py | pull_stream | def pull_stream(image):
"""
Return generator of pull status objects
"""
return (json.loads(s) for s in _get_docker().pull(image, stream=True)) | python | def pull_stream(image):
"""
Return generator of pull status objects
"""
return (json.loads(s) for s in _get_docker().pull(image, stream=True)) | [
"def",
"pull_stream",
"(",
"image",
")",
":",
"return",
"(",
"json",
".",
"loads",
"(",
"s",
")",
"for",
"s",
"in",
"_get_docker",
"(",
")",
".",
"pull",
"(",
"image",
",",
"stream",
"=",
"True",
")",
")"
] | Return generator of pull status objects | [
"Return",
"generator",
"of",
"pull",
"status",
"objects"
] | e4bae503efa997660fb3f34fe166699569653157 | https://github.com/datacats/datacats/blob/e4bae503efa997660fb3f34fe166699569653157/datacats/docker.py#L394-L398 | train |
datacats/datacats | datacats/docker.py | data_only_container | def data_only_container(name, volumes):
"""
create "data-only container" if it doesn't already exist.
We'd like to avoid these, but postgres + boot2docker make
it difficult, see issue #5
"""
info = inspect_container(name)
if info:
return
c = _get_docker().create_container(
name=name,
image='datacats/postgres', # any image will do
command='true',
volumes=volumes,
detach=True)
return c | python | def data_only_container(name, volumes):
"""
create "data-only container" if it doesn't already exist.
We'd like to avoid these, but postgres + boot2docker make
it difficult, see issue #5
"""
info = inspect_container(name)
if info:
return
c = _get_docker().create_container(
name=name,
image='datacats/postgres', # any image will do
command='true',
volumes=volumes,
detach=True)
return c | [
"def",
"data_only_container",
"(",
"name",
",",
"volumes",
")",
":",
"info",
"=",
"inspect_container",
"(",
"name",
")",
"if",
"info",
":",
"return",
"c",
"=",
"_get_docker",
"(",
")",
".",
"create_container",
"(",
"name",
"=",
"name",
",",
"image",
"=",
"'datacats/postgres'",
",",
"# any image will do",
"command",
"=",
"'true'",
",",
"volumes",
"=",
"volumes",
",",
"detach",
"=",
"True",
")",
"return",
"c"
] | create "data-only container" if it doesn't already exist.
We'd like to avoid these, but postgres + boot2docker make
it difficult, see issue #5 | [
"create",
"data",
"-",
"only",
"container",
"if",
"it",
"doesn",
"t",
"already",
"exist",
"."
] | e4bae503efa997660fb3f34fe166699569653157 | https://github.com/datacats/datacats/blob/e4bae503efa997660fb3f34fe166699569653157/datacats/docker.py#L401-L417 | train |
datacats/datacats | datacats/cli/main.py | main | def main():
"""
The main entry point for datacats cli tool
(as defined in setup.py's entry_points)
It parses the cli arguments for corresponding options
and runs the corresponding command
"""
# pylint: disable=bare-except
try:
command_fn, opts = _parse_arguments(sys.argv[1:])
# purge handles loading differently
# 1 - Bail and just call the command if it doesn't have ENVIRONMENT.
if command_fn == purge.purge or 'ENVIRONMENT' not in opts:
return command_fn(opts)
environment = Environment.load(
opts['ENVIRONMENT'] or '.',
opts['--site'] if '--site' in opts else 'primary')
if command_fn not in COMMANDS_THAT_USE_SSH:
return command_fn(environment, opts)
# for commands that communicate with a remote server
# we load UserProfile and test our communication
user_profile = UserProfile()
user_profile.test_ssh_key(environment)
return command_fn(environment, opts, user_profile)
except DatacatsError as e:
_error_exit(e)
except SystemExit:
raise
except:
exc_info = "\n".join([line.rstrip()
for line in traceback.format_exception(*sys.exc_info())])
user_message = ("Something that should not"
" have happened happened when attempting"
" to run this command:\n"
" datacats {args}\n\n"
"It is seems to be a bug.\n"
"Please report this issue to us by"
" creating an issue ticket at\n\n"
" https://github.com/datacats/datacats/issues\n\n"
"so that we would be able to look into that "
"and fix the issue."
).format(args=" ".join(sys.argv[1:]))
_error_exit(DatacatsError(user_message,
parent_exception=UndocumentedError(exc_info))) | python | def main():
"""
The main entry point for datacats cli tool
(as defined in setup.py's entry_points)
It parses the cli arguments for corresponding options
and runs the corresponding command
"""
# pylint: disable=bare-except
try:
command_fn, opts = _parse_arguments(sys.argv[1:])
# purge handles loading differently
# 1 - Bail and just call the command if it doesn't have ENVIRONMENT.
if command_fn == purge.purge or 'ENVIRONMENT' not in opts:
return command_fn(opts)
environment = Environment.load(
opts['ENVIRONMENT'] or '.',
opts['--site'] if '--site' in opts else 'primary')
if command_fn not in COMMANDS_THAT_USE_SSH:
return command_fn(environment, opts)
# for commands that communicate with a remote server
# we load UserProfile and test our communication
user_profile = UserProfile()
user_profile.test_ssh_key(environment)
return command_fn(environment, opts, user_profile)
except DatacatsError as e:
_error_exit(e)
except SystemExit:
raise
except:
exc_info = "\n".join([line.rstrip()
for line in traceback.format_exception(*sys.exc_info())])
user_message = ("Something that should not"
" have happened happened when attempting"
" to run this command:\n"
" datacats {args}\n\n"
"It is seems to be a bug.\n"
"Please report this issue to us by"
" creating an issue ticket at\n\n"
" https://github.com/datacats/datacats/issues\n\n"
"so that we would be able to look into that "
"and fix the issue."
).format(args=" ".join(sys.argv[1:]))
_error_exit(DatacatsError(user_message,
parent_exception=UndocumentedError(exc_info))) | [
"def",
"main",
"(",
")",
":",
"# pylint: disable=bare-except",
"try",
":",
"command_fn",
",",
"opts",
"=",
"_parse_arguments",
"(",
"sys",
".",
"argv",
"[",
"1",
":",
"]",
")",
"# purge handles loading differently",
"# 1 - Bail and just call the command if it doesn't have ENVIRONMENT.",
"if",
"command_fn",
"==",
"purge",
".",
"purge",
"or",
"'ENVIRONMENT'",
"not",
"in",
"opts",
":",
"return",
"command_fn",
"(",
"opts",
")",
"environment",
"=",
"Environment",
".",
"load",
"(",
"opts",
"[",
"'ENVIRONMENT'",
"]",
"or",
"'.'",
",",
"opts",
"[",
"'--site'",
"]",
"if",
"'--site'",
"in",
"opts",
"else",
"'primary'",
")",
"if",
"command_fn",
"not",
"in",
"COMMANDS_THAT_USE_SSH",
":",
"return",
"command_fn",
"(",
"environment",
",",
"opts",
")",
"# for commands that communicate with a remote server",
"# we load UserProfile and test our communication",
"user_profile",
"=",
"UserProfile",
"(",
")",
"user_profile",
".",
"test_ssh_key",
"(",
"environment",
")",
"return",
"command_fn",
"(",
"environment",
",",
"opts",
",",
"user_profile",
")",
"except",
"DatacatsError",
"as",
"e",
":",
"_error_exit",
"(",
"e",
")",
"except",
"SystemExit",
":",
"raise",
"except",
":",
"exc_info",
"=",
"\"\\n\"",
".",
"join",
"(",
"[",
"line",
".",
"rstrip",
"(",
")",
"for",
"line",
"in",
"traceback",
".",
"format_exception",
"(",
"*",
"sys",
".",
"exc_info",
"(",
")",
")",
"]",
")",
"user_message",
"=",
"(",
"\"Something that should not\"",
"\" have happened happened when attempting\"",
"\" to run this command:\\n\"",
"\" datacats {args}\\n\\n\"",
"\"It is seems to be a bug.\\n\"",
"\"Please report this issue to us by\"",
"\" creating an issue ticket at\\n\\n\"",
"\" https://github.com/datacats/datacats/issues\\n\\n\"",
"\"so that we would be able to look into that \"",
"\"and fix the issue.\"",
")",
".",
"format",
"(",
"args",
"=",
"\" \"",
".",
"join",
"(",
"sys",
".",
"argv",
"[",
"1",
":",
"]",
")",
")",
"_error_exit",
"(",
"DatacatsError",
"(",
"user_message",
",",
"parent_exception",
"=",
"UndocumentedError",
"(",
"exc_info",
")",
")",
")"
] | The main entry point for datacats cli tool
(as defined in setup.py's entry_points)
It parses the cli arguments for corresponding options
and runs the corresponding command | [
"The",
"main",
"entry",
"point",
"for",
"datacats",
"cli",
"tool"
] | e4bae503efa997660fb3f34fe166699569653157 | https://github.com/datacats/datacats/blob/e4bae503efa997660fb3f34fe166699569653157/datacats/cli/main.py#L78-L128 | train |
datacats/datacats | datacats/cli/main.py | _subcommand_arguments | def _subcommand_arguments(args):
"""
Return (subcommand, (possibly adjusted) arguments for that subcommand)
Returns (None, args) when no subcommand is found
Parsing our arguments is hard. Each subcommand has its own docopt
validation, and some subcommands (paster and shell) have positional
options (some options passed to datacats and others passed to
commands run inside the container)
"""
skip_site = False
# Find subcommand without docopt so that subcommand options may appear
# anywhere
for i, a in enumerate(args):
if skip_site:
skip_site = False
continue
if a.startswith('-'):
if a == '-s' or a == '--site':
skip_site = True
continue
if a == 'help':
return _subcommand_arguments(args[:i] + ['--help'] + args[i + 1:])
if a not in COMMANDS:
raise DatacatsError("\'{0}\' command is not recognized. \n"
"See \'datacats help\' for the list of available commands".format(a))
command = a
break
else:
return None, args
if command != 'shell' and command != 'paster':
return command, args
# shell requires the environment name, paster does not
remaining_positional = 2 if command == 'shell' else 1
# i is where the subcommand starts.
# shell, paster are special: options might belong to the command being
# find where the the inner command starts and insert a '--' before
# so that we can separate inner options from ones we need to parse
while i < len(args):
a = args[i]
if a.startswith('-'):
if a == '-s' or a == '--site':
# site name is coming
i += 2
continue
i += 1
continue
if remaining_positional:
remaining_positional -= 1
i += 1
continue
return command, args[:i] + ['--'] + args[i:]
return command, args | python | def _subcommand_arguments(args):
"""
Return (subcommand, (possibly adjusted) arguments for that subcommand)
Returns (None, args) when no subcommand is found
Parsing our arguments is hard. Each subcommand has its own docopt
validation, and some subcommands (paster and shell) have positional
options (some options passed to datacats and others passed to
commands run inside the container)
"""
skip_site = False
# Find subcommand without docopt so that subcommand options may appear
# anywhere
for i, a in enumerate(args):
if skip_site:
skip_site = False
continue
if a.startswith('-'):
if a == '-s' or a == '--site':
skip_site = True
continue
if a == 'help':
return _subcommand_arguments(args[:i] + ['--help'] + args[i + 1:])
if a not in COMMANDS:
raise DatacatsError("\'{0}\' command is not recognized. \n"
"See \'datacats help\' for the list of available commands".format(a))
command = a
break
else:
return None, args
if command != 'shell' and command != 'paster':
return command, args
# shell requires the environment name, paster does not
remaining_positional = 2 if command == 'shell' else 1
# i is where the subcommand starts.
# shell, paster are special: options might belong to the command being
# find where the the inner command starts and insert a '--' before
# so that we can separate inner options from ones we need to parse
while i < len(args):
a = args[i]
if a.startswith('-'):
if a == '-s' or a == '--site':
# site name is coming
i += 2
continue
i += 1
continue
if remaining_positional:
remaining_positional -= 1
i += 1
continue
return command, args[:i] + ['--'] + args[i:]
return command, args | [
"def",
"_subcommand_arguments",
"(",
"args",
")",
":",
"skip_site",
"=",
"False",
"# Find subcommand without docopt so that subcommand options may appear",
"# anywhere",
"for",
"i",
",",
"a",
"in",
"enumerate",
"(",
"args",
")",
":",
"if",
"skip_site",
":",
"skip_site",
"=",
"False",
"continue",
"if",
"a",
".",
"startswith",
"(",
"'-'",
")",
":",
"if",
"a",
"==",
"'-s'",
"or",
"a",
"==",
"'--site'",
":",
"skip_site",
"=",
"True",
"continue",
"if",
"a",
"==",
"'help'",
":",
"return",
"_subcommand_arguments",
"(",
"args",
"[",
":",
"i",
"]",
"+",
"[",
"'--help'",
"]",
"+",
"args",
"[",
"i",
"+",
"1",
":",
"]",
")",
"if",
"a",
"not",
"in",
"COMMANDS",
":",
"raise",
"DatacatsError",
"(",
"\"\\'{0}\\' command is not recognized. \\n\"",
"\"See \\'datacats help\\' for the list of available commands\"",
".",
"format",
"(",
"a",
")",
")",
"command",
"=",
"a",
"break",
"else",
":",
"return",
"None",
",",
"args",
"if",
"command",
"!=",
"'shell'",
"and",
"command",
"!=",
"'paster'",
":",
"return",
"command",
",",
"args",
"# shell requires the environment name, paster does not",
"remaining_positional",
"=",
"2",
"if",
"command",
"==",
"'shell'",
"else",
"1",
"# i is where the subcommand starts.",
"# shell, paster are special: options might belong to the command being",
"# find where the the inner command starts and insert a '--' before",
"# so that we can separate inner options from ones we need to parse",
"while",
"i",
"<",
"len",
"(",
"args",
")",
":",
"a",
"=",
"args",
"[",
"i",
"]",
"if",
"a",
".",
"startswith",
"(",
"'-'",
")",
":",
"if",
"a",
"==",
"'-s'",
"or",
"a",
"==",
"'--site'",
":",
"# site name is coming",
"i",
"+=",
"2",
"continue",
"i",
"+=",
"1",
"continue",
"if",
"remaining_positional",
":",
"remaining_positional",
"-=",
"1",
"i",
"+=",
"1",
"continue",
"return",
"command",
",",
"args",
"[",
":",
"i",
"]",
"+",
"[",
"'--'",
"]",
"+",
"args",
"[",
"i",
":",
"]",
"return",
"command",
",",
"args"
] | Return (subcommand, (possibly adjusted) arguments for that subcommand)
Returns (None, args) when no subcommand is found
Parsing our arguments is hard. Each subcommand has its own docopt
validation, and some subcommands (paster and shell) have positional
options (some options passed to datacats and others passed to
commands run inside the container) | [
"Return",
"(",
"subcommand",
"(",
"possibly",
"adjusted",
")",
"arguments",
"for",
"that",
"subcommand",
")"
] | e4bae503efa997660fb3f34fe166699569653157 | https://github.com/datacats/datacats/blob/e4bae503efa997660fb3f34fe166699569653157/datacats/cli/main.py#L156-L213 | train |
datacats/datacats | datacats/cli/manage.py | start | def start(environment, opts):
"""Create containers and start serving environment
Usage:
datacats start [-b] [--site-url SITE_URL] [-p|--no-watch] [-s NAME]
[-i] [--syslog] [--address=IP] [ENVIRONMENT [PORT]]
datacats start -r [-b] [--site-url SITE_URL] [-s NAME] [--syslog]
[-i] [--address=IP] [ENVIRONMENT]
Options:
--address=IP Address to listen on (Linux-only)
-b --background Don't wait for response from web server
--no-watch Do not automatically reload templates and .py files on change
-i --interactive Calls out to docker via the command line, allowing
for interactivity with the web image.
-p --production Start with apache and debug=false
-s --site=NAME Specify a site to start [default: primary]
--syslog Log to the syslog
--site-url SITE_URL The site_url to use in API responses. Defaults to old setting or
will attempt to determine it. (e.g. http://example.org:{port}/)
ENVIRONMENT may be an environment name or a path to an environment directory.
Default: '.'
"""
environment.require_data()
if environment.fully_running():
print 'Already running at {0}'.format(environment.web_address())
return
reload_(environment, opts) | python | def start(environment, opts):
"""Create containers and start serving environment
Usage:
datacats start [-b] [--site-url SITE_URL] [-p|--no-watch] [-s NAME]
[-i] [--syslog] [--address=IP] [ENVIRONMENT [PORT]]
datacats start -r [-b] [--site-url SITE_URL] [-s NAME] [--syslog]
[-i] [--address=IP] [ENVIRONMENT]
Options:
--address=IP Address to listen on (Linux-only)
-b --background Don't wait for response from web server
--no-watch Do not automatically reload templates and .py files on change
-i --interactive Calls out to docker via the command line, allowing
for interactivity with the web image.
-p --production Start with apache and debug=false
-s --site=NAME Specify a site to start [default: primary]
--syslog Log to the syslog
--site-url SITE_URL The site_url to use in API responses. Defaults to old setting or
will attempt to determine it. (e.g. http://example.org:{port}/)
ENVIRONMENT may be an environment name or a path to an environment directory.
Default: '.'
"""
environment.require_data()
if environment.fully_running():
print 'Already running at {0}'.format(environment.web_address())
return
reload_(environment, opts) | [
"def",
"start",
"(",
"environment",
",",
"opts",
")",
":",
"environment",
".",
"require_data",
"(",
")",
"if",
"environment",
".",
"fully_running",
"(",
")",
":",
"print",
"'Already running at {0}'",
".",
"format",
"(",
"environment",
".",
"web_address",
"(",
")",
")",
"return",
"reload_",
"(",
"environment",
",",
"opts",
")"
] | Create containers and start serving environment
Usage:
datacats start [-b] [--site-url SITE_URL] [-p|--no-watch] [-s NAME]
[-i] [--syslog] [--address=IP] [ENVIRONMENT [PORT]]
datacats start -r [-b] [--site-url SITE_URL] [-s NAME] [--syslog]
[-i] [--address=IP] [ENVIRONMENT]
Options:
--address=IP Address to listen on (Linux-only)
-b --background Don't wait for response from web server
--no-watch Do not automatically reload templates and .py files on change
-i --interactive Calls out to docker via the command line, allowing
for interactivity with the web image.
-p --production Start with apache and debug=false
-s --site=NAME Specify a site to start [default: primary]
--syslog Log to the syslog
--site-url SITE_URL The site_url to use in API responses. Defaults to old setting or
will attempt to determine it. (e.g. http://example.org:{port}/)
ENVIRONMENT may be an environment name or a path to an environment directory.
Default: '.' | [
"Create",
"containers",
"and",
"start",
"serving",
"environment"
] | e4bae503efa997660fb3f34fe166699569653157 | https://github.com/datacats/datacats/blob/e4bae503efa997660fb3f34fe166699569653157/datacats/cli/manage.py#L41-L71 | train |
datacats/datacats | datacats/cli/manage.py | reload_ | def reload_(environment, opts):
"""Reload environment source and configuration
Usage:
datacats reload [-b] [-p|--no-watch] [--syslog] [-s NAME] [--site-url=SITE_URL]
[-i] [--address=IP] [ENVIRONMENT [PORT]]
datacats reload -r [-b] [--syslog] [-s NAME] [--address=IP] [--site-url=SITE_URL]
[-i] [ENVIRONMENT]
Options:
--address=IP Address to listen on (Linux-only)
-i --interactive Calls out to docker via the command line, allowing
for interactivity with the web image.
--site-url=SITE_URL The site_url to use in API responses. Can use Python template syntax
to insert the port and address (e.g. http://example.org:{port}/)
-b --background Don't wait for response from web server
--no-watch Do not automatically reload templates and .py files on change
-p --production Reload with apache and debug=false
-s --site=NAME Specify a site to reload [default: primary]
--syslog Log to the syslog
ENVIRONMENT may be an environment name or a path to an environment directory.
Default: '.'
"""
if opts['--interactive']:
# We can't wait for the server if we're tty'd
opts['--background'] = True
if opts['--address'] and is_boot2docker():
raise DatacatsError('Cannot specify address on boot2docker.')
environment.require_data()
environment.stop_ckan()
if opts['PORT'] or opts['--address'] or opts['--site-url']:
if opts['PORT']:
environment.port = int(opts['PORT'])
if opts['--address']:
environment.address = opts['--address']
if opts['--site-url']:
site_url = opts['--site-url']
# TODO: Check it against a regex or use urlparse
try:
site_url = site_url.format(address=environment.address, port=environment.port)
environment.site_url = site_url
environment.save_site(False)
except (KeyError, IndexError, ValueError) as e:
raise DatacatsError('Could not parse site_url: {}'.format(e))
environment.save()
for container in environment.extra_containers:
require_extra_image(EXTRA_IMAGE_MAPPING[container])
environment.stop_supporting_containers()
environment.start_supporting_containers()
environment.start_ckan(
production=opts['--production'],
paster_reload=not opts['--no-watch'],
log_syslog=opts['--syslog'],
interactive=opts['--interactive'])
write('Starting web server at {0} ...'.format(environment.web_address()))
if opts['--background']:
write('\n')
return
try:
environment.wait_for_web_available()
finally:
write('\n') | python | def reload_(environment, opts):
"""Reload environment source and configuration
Usage:
datacats reload [-b] [-p|--no-watch] [--syslog] [-s NAME] [--site-url=SITE_URL]
[-i] [--address=IP] [ENVIRONMENT [PORT]]
datacats reload -r [-b] [--syslog] [-s NAME] [--address=IP] [--site-url=SITE_URL]
[-i] [ENVIRONMENT]
Options:
--address=IP Address to listen on (Linux-only)
-i --interactive Calls out to docker via the command line, allowing
for interactivity with the web image.
--site-url=SITE_URL The site_url to use in API responses. Can use Python template syntax
to insert the port and address (e.g. http://example.org:{port}/)
-b --background Don't wait for response from web server
--no-watch Do not automatically reload templates and .py files on change
-p --production Reload with apache and debug=false
-s --site=NAME Specify a site to reload [default: primary]
--syslog Log to the syslog
ENVIRONMENT may be an environment name or a path to an environment directory.
Default: '.'
"""
if opts['--interactive']:
# We can't wait for the server if we're tty'd
opts['--background'] = True
if opts['--address'] and is_boot2docker():
raise DatacatsError('Cannot specify address on boot2docker.')
environment.require_data()
environment.stop_ckan()
if opts['PORT'] or opts['--address'] or opts['--site-url']:
if opts['PORT']:
environment.port = int(opts['PORT'])
if opts['--address']:
environment.address = opts['--address']
if opts['--site-url']:
site_url = opts['--site-url']
# TODO: Check it against a regex or use urlparse
try:
site_url = site_url.format(address=environment.address, port=environment.port)
environment.site_url = site_url
environment.save_site(False)
except (KeyError, IndexError, ValueError) as e:
raise DatacatsError('Could not parse site_url: {}'.format(e))
environment.save()
for container in environment.extra_containers:
require_extra_image(EXTRA_IMAGE_MAPPING[container])
environment.stop_supporting_containers()
environment.start_supporting_containers()
environment.start_ckan(
production=opts['--production'],
paster_reload=not opts['--no-watch'],
log_syslog=opts['--syslog'],
interactive=opts['--interactive'])
write('Starting web server at {0} ...'.format(environment.web_address()))
if opts['--background']:
write('\n')
return
try:
environment.wait_for_web_available()
finally:
write('\n') | [
"def",
"reload_",
"(",
"environment",
",",
"opts",
")",
":",
"if",
"opts",
"[",
"'--interactive'",
"]",
":",
"# We can't wait for the server if we're tty'd",
"opts",
"[",
"'--background'",
"]",
"=",
"True",
"if",
"opts",
"[",
"'--address'",
"]",
"and",
"is_boot2docker",
"(",
")",
":",
"raise",
"DatacatsError",
"(",
"'Cannot specify address on boot2docker.'",
")",
"environment",
".",
"require_data",
"(",
")",
"environment",
".",
"stop_ckan",
"(",
")",
"if",
"opts",
"[",
"'PORT'",
"]",
"or",
"opts",
"[",
"'--address'",
"]",
"or",
"opts",
"[",
"'--site-url'",
"]",
":",
"if",
"opts",
"[",
"'PORT'",
"]",
":",
"environment",
".",
"port",
"=",
"int",
"(",
"opts",
"[",
"'PORT'",
"]",
")",
"if",
"opts",
"[",
"'--address'",
"]",
":",
"environment",
".",
"address",
"=",
"opts",
"[",
"'--address'",
"]",
"if",
"opts",
"[",
"'--site-url'",
"]",
":",
"site_url",
"=",
"opts",
"[",
"'--site-url'",
"]",
"# TODO: Check it against a regex or use urlparse",
"try",
":",
"site_url",
"=",
"site_url",
".",
"format",
"(",
"address",
"=",
"environment",
".",
"address",
",",
"port",
"=",
"environment",
".",
"port",
")",
"environment",
".",
"site_url",
"=",
"site_url",
"environment",
".",
"save_site",
"(",
"False",
")",
"except",
"(",
"KeyError",
",",
"IndexError",
",",
"ValueError",
")",
"as",
"e",
":",
"raise",
"DatacatsError",
"(",
"'Could not parse site_url: {}'",
".",
"format",
"(",
"e",
")",
")",
"environment",
".",
"save",
"(",
")",
"for",
"container",
"in",
"environment",
".",
"extra_containers",
":",
"require_extra_image",
"(",
"EXTRA_IMAGE_MAPPING",
"[",
"container",
"]",
")",
"environment",
".",
"stop_supporting_containers",
"(",
")",
"environment",
".",
"start_supporting_containers",
"(",
")",
"environment",
".",
"start_ckan",
"(",
"production",
"=",
"opts",
"[",
"'--production'",
"]",
",",
"paster_reload",
"=",
"not",
"opts",
"[",
"'--no-watch'",
"]",
",",
"log_syslog",
"=",
"opts",
"[",
"'--syslog'",
"]",
",",
"interactive",
"=",
"opts",
"[",
"'--interactive'",
"]",
")",
"write",
"(",
"'Starting web server at {0} ...'",
".",
"format",
"(",
"environment",
".",
"web_address",
"(",
")",
")",
")",
"if",
"opts",
"[",
"'--background'",
"]",
":",
"write",
"(",
"'\\n'",
")",
"return",
"try",
":",
"environment",
".",
"wait_for_web_available",
"(",
")",
"finally",
":",
"write",
"(",
"'\\n'",
")"
] | Reload environment source and configuration
Usage:
datacats reload [-b] [-p|--no-watch] [--syslog] [-s NAME] [--site-url=SITE_URL]
[-i] [--address=IP] [ENVIRONMENT [PORT]]
datacats reload -r [-b] [--syslog] [-s NAME] [--address=IP] [--site-url=SITE_URL]
[-i] [ENVIRONMENT]
Options:
--address=IP Address to listen on (Linux-only)
-i --interactive Calls out to docker via the command line, allowing
for interactivity with the web image.
--site-url=SITE_URL The site_url to use in API responses. Can use Python template syntax
to insert the port and address (e.g. http://example.org:{port}/)
-b --background Don't wait for response from web server
--no-watch Do not automatically reload templates and .py files on change
-p --production Reload with apache and debug=false
-s --site=NAME Specify a site to reload [default: primary]
--syslog Log to the syslog
ENVIRONMENT may be an environment name or a path to an environment directory.
Default: '.' | [
"Reload",
"environment",
"source",
"and",
"configuration"
] | e4bae503efa997660fb3f34fe166699569653157 | https://github.com/datacats/datacats/blob/e4bae503efa997660fb3f34fe166699569653157/datacats/cli/manage.py#L74-L140 | train |
datacats/datacats | datacats/cli/manage.py | info | def info(environment, opts):
"""Display information about environment and running containers
Usage:
datacats info [-qr] [ENVIRONMENT]
Options:
-q --quiet Echo only the web URL or nothing if not running
ENVIRONMENT may be an environment name or a path to an environment directory.
Default: '.'
"""
damaged = False
sites = environment.sites
if not environment.sites:
sites = []
damaged = True
if opts['--quiet']:
if damaged:
raise DatacatsError('Damaged datadir: cannot get address.')
for site in sites:
environment.site_name = site
print '{}: {}'.format(site, environment.web_address())
return
datadir = environment.datadir
if not environment.data_exists():
datadir = ''
elif damaged:
datadir += ' (damaged)'
print 'Environment name: ' + environment.name
print ' Environment dir: ' + environment.target
print ' Data dir: ' + datadir
print ' Sites: ' + ' '.join(environment.sites)
for site in environment.sites:
print
environment.site_name = site
print ' Site: ' + site
print ' Containers: ' + ' '.join(environment.containers_running())
sitedir = environment.sitedir + (' (damaged)' if not environment.data_complete() else '')
print ' Site dir: ' + sitedir
addr = environment.web_address()
if addr:
print ' Available at: ' + addr | python | def info(environment, opts):
"""Display information about environment and running containers
Usage:
datacats info [-qr] [ENVIRONMENT]
Options:
-q --quiet Echo only the web URL or nothing if not running
ENVIRONMENT may be an environment name or a path to an environment directory.
Default: '.'
"""
damaged = False
sites = environment.sites
if not environment.sites:
sites = []
damaged = True
if opts['--quiet']:
if damaged:
raise DatacatsError('Damaged datadir: cannot get address.')
for site in sites:
environment.site_name = site
print '{}: {}'.format(site, environment.web_address())
return
datadir = environment.datadir
if not environment.data_exists():
datadir = ''
elif damaged:
datadir += ' (damaged)'
print 'Environment name: ' + environment.name
print ' Environment dir: ' + environment.target
print ' Data dir: ' + datadir
print ' Sites: ' + ' '.join(environment.sites)
for site in environment.sites:
print
environment.site_name = site
print ' Site: ' + site
print ' Containers: ' + ' '.join(environment.containers_running())
sitedir = environment.sitedir + (' (damaged)' if not environment.data_complete() else '')
print ' Site dir: ' + sitedir
addr = environment.web_address()
if addr:
print ' Available at: ' + addr | [
"def",
"info",
"(",
"environment",
",",
"opts",
")",
":",
"damaged",
"=",
"False",
"sites",
"=",
"environment",
".",
"sites",
"if",
"not",
"environment",
".",
"sites",
":",
"sites",
"=",
"[",
"]",
"damaged",
"=",
"True",
"if",
"opts",
"[",
"'--quiet'",
"]",
":",
"if",
"damaged",
":",
"raise",
"DatacatsError",
"(",
"'Damaged datadir: cannot get address.'",
")",
"for",
"site",
"in",
"sites",
":",
"environment",
".",
"site_name",
"=",
"site",
"print",
"'{}: {}'",
".",
"format",
"(",
"site",
",",
"environment",
".",
"web_address",
"(",
")",
")",
"return",
"datadir",
"=",
"environment",
".",
"datadir",
"if",
"not",
"environment",
".",
"data_exists",
"(",
")",
":",
"datadir",
"=",
"''",
"elif",
"damaged",
":",
"datadir",
"+=",
"' (damaged)'",
"print",
"'Environment name: '",
"+",
"environment",
".",
"name",
"print",
"' Environment dir: '",
"+",
"environment",
".",
"target",
"print",
"' Data dir: '",
"+",
"datadir",
"print",
"' Sites: '",
"+",
"' '",
".",
"join",
"(",
"environment",
".",
"sites",
")",
"for",
"site",
"in",
"environment",
".",
"sites",
":",
"print",
"environment",
".",
"site_name",
"=",
"site",
"print",
"' Site: '",
"+",
"site",
"print",
"' Containers: '",
"+",
"' '",
".",
"join",
"(",
"environment",
".",
"containers_running",
"(",
")",
")",
"sitedir",
"=",
"environment",
".",
"sitedir",
"+",
"(",
"' (damaged)'",
"if",
"not",
"environment",
".",
"data_complete",
"(",
")",
"else",
"''",
")",
"print",
"' Site dir: '",
"+",
"sitedir",
"addr",
"=",
"environment",
".",
"web_address",
"(",
")",
"if",
"addr",
":",
"print",
"' Available at: '",
"+",
"addr"
] | Display information about environment and running containers
Usage:
datacats info [-qr] [ENVIRONMENT]
Options:
-q --quiet Echo only the web URL or nothing if not running
ENVIRONMENT may be an environment name or a path to an environment directory.
Default: '.' | [
"Display",
"information",
"about",
"environment",
"and",
"running",
"containers"
] | e4bae503efa997660fb3f34fe166699569653157 | https://github.com/datacats/datacats/blob/e4bae503efa997660fb3f34fe166699569653157/datacats/cli/manage.py#L143-L190 | train |
datacats/datacats | datacats/cli/manage.py | logs | def logs(environment, opts):
"""Display or follow container logs
Usage:
datacats logs [--postgres | --solr | --datapusher] [-s NAME] [-tr] [--tail=LINES] [ENVIRONMENT]
datacats logs -f [--postgres | --solr | --datapusher] [-s NAME] [-r] [ENVIRONMENT]
Options:
--datapusher Show logs for datapusher instead of web logs
--postgres Show postgres database logs instead of web logs
-f --follow Follow logs instead of exiting immediately
--solr Show solr search logs instead of web logs
-t --timestamps Add timestamps to log lines
-s --site=NAME Specify a site for logs if needed [default: primary]
--tail=LINES Number of lines to show [default: all]
ENVIRONMENT may be an environment name or a path to an environment directory.
Default: '.'
"""
container = 'web'
if opts['--solr']:
container = 'solr'
if opts['--postgres']:
container = 'postgres'
if opts['--datapusher']:
container = 'datapusher'
tail = opts['--tail']
if tail != 'all':
tail = int(tail)
l = environment.logs(container, tail, opts['--follow'],
opts['--timestamps'])
if not opts['--follow']:
print l
return
try:
for message in l:
write(message)
except KeyboardInterrupt:
print | python | def logs(environment, opts):
"""Display or follow container logs
Usage:
datacats logs [--postgres | --solr | --datapusher] [-s NAME] [-tr] [--tail=LINES] [ENVIRONMENT]
datacats logs -f [--postgres | --solr | --datapusher] [-s NAME] [-r] [ENVIRONMENT]
Options:
--datapusher Show logs for datapusher instead of web logs
--postgres Show postgres database logs instead of web logs
-f --follow Follow logs instead of exiting immediately
--solr Show solr search logs instead of web logs
-t --timestamps Add timestamps to log lines
-s --site=NAME Specify a site for logs if needed [default: primary]
--tail=LINES Number of lines to show [default: all]
ENVIRONMENT may be an environment name or a path to an environment directory.
Default: '.'
"""
container = 'web'
if opts['--solr']:
container = 'solr'
if opts['--postgres']:
container = 'postgres'
if opts['--datapusher']:
container = 'datapusher'
tail = opts['--tail']
if tail != 'all':
tail = int(tail)
l = environment.logs(container, tail, opts['--follow'],
opts['--timestamps'])
if not opts['--follow']:
print l
return
try:
for message in l:
write(message)
except KeyboardInterrupt:
print | [
"def",
"logs",
"(",
"environment",
",",
"opts",
")",
":",
"container",
"=",
"'web'",
"if",
"opts",
"[",
"'--solr'",
"]",
":",
"container",
"=",
"'solr'",
"if",
"opts",
"[",
"'--postgres'",
"]",
":",
"container",
"=",
"'postgres'",
"if",
"opts",
"[",
"'--datapusher'",
"]",
":",
"container",
"=",
"'datapusher'",
"tail",
"=",
"opts",
"[",
"'--tail'",
"]",
"if",
"tail",
"!=",
"'all'",
":",
"tail",
"=",
"int",
"(",
"tail",
")",
"l",
"=",
"environment",
".",
"logs",
"(",
"container",
",",
"tail",
",",
"opts",
"[",
"'--follow'",
"]",
",",
"opts",
"[",
"'--timestamps'",
"]",
")",
"if",
"not",
"opts",
"[",
"'--follow'",
"]",
":",
"print",
"l",
"return",
"try",
":",
"for",
"message",
"in",
"l",
":",
"write",
"(",
"message",
")",
"except",
"KeyboardInterrupt",
":",
"print"
] | Display or follow container logs
Usage:
datacats logs [--postgres | --solr | --datapusher] [-s NAME] [-tr] [--tail=LINES] [ENVIRONMENT]
datacats logs -f [--postgres | --solr | --datapusher] [-s NAME] [-r] [ENVIRONMENT]
Options:
--datapusher Show logs for datapusher instead of web logs
--postgres Show postgres database logs instead of web logs
-f --follow Follow logs instead of exiting immediately
--solr Show solr search logs instead of web logs
-t --timestamps Add timestamps to log lines
-s --site=NAME Specify a site for logs if needed [default: primary]
--tail=LINES Number of lines to show [default: all]
ENVIRONMENT may be an environment name or a path to an environment directory.
Default: '.' | [
"Display",
"or",
"follow",
"container",
"logs"
] | e4bae503efa997660fb3f34fe166699569653157 | https://github.com/datacats/datacats/blob/e4bae503efa997660fb3f34fe166699569653157/datacats/cli/manage.py#L206-L244 | train |
datacats/datacats | datacats/cli/manage.py | open_ | def open_(environment, opts):
# pylint: disable=unused-argument
"""Open web browser window to this environment
Usage:
datacats open [-r] [-s NAME] [ENVIRONMENT]
Options:
-s --site=NAME Choose a site to open [default: primary]
ENVIRONMENT may be an environment name or a path to an environment directory.
Default: '.'
"""
environment.require_data()
addr = environment.web_address()
if not addr:
print "Site not currently running"
else:
webbrowser.open(addr) | python | def open_(environment, opts):
# pylint: disable=unused-argument
"""Open web browser window to this environment
Usage:
datacats open [-r] [-s NAME] [ENVIRONMENT]
Options:
-s --site=NAME Choose a site to open [default: primary]
ENVIRONMENT may be an environment name or a path to an environment directory.
Default: '.'
"""
environment.require_data()
addr = environment.web_address()
if not addr:
print "Site not currently running"
else:
webbrowser.open(addr) | [
"def",
"open_",
"(",
"environment",
",",
"opts",
")",
":",
"# pylint: disable=unused-argument",
"environment",
".",
"require_data",
"(",
")",
"addr",
"=",
"environment",
".",
"web_address",
"(",
")",
"if",
"not",
"addr",
":",
"print",
"\"Site not currently running\"",
"else",
":",
"webbrowser",
".",
"open",
"(",
"addr",
")"
] | Open web browser window to this environment
Usage:
datacats open [-r] [-s NAME] [ENVIRONMENT]
Options:
-s --site=NAME Choose a site to open [default: primary]
ENVIRONMENT may be an environment name or a path to an environment directory.
Default: '.' | [
"Open",
"web",
"browser",
"window",
"to",
"this",
"environment"
] | e4bae503efa997660fb3f34fe166699569653157 | https://github.com/datacats/datacats/blob/e4bae503efa997660fb3f34fe166699569653157/datacats/cli/manage.py#L247-L266 | train |
datacats/datacats | datacats/cli/manage.py | tweak | def tweak(environment, opts):
"""Commands operating on environment data
Usage:
datacats tweak --install-postgis [ENVIRONMENT]
datacats tweak --add-redis [ENVIRONMENT]
datacats tweak --admin-password [ENVIRONMENT]
Options:
--install-postgis Install postgis in ckan database
--add-redis Adds redis next time this environment reloads
-s --site=NAME Choose a site to tweak [default: primary]
-p --admin-password Prompt to change the admin password
ENVIRONMENT may be an environment name or a path to an environment directory.
Default: '.'
"""
environment.require_data()
if opts['--install-postgis']:
print "Installing postgis"
environment.install_postgis_sql()
if opts['--add-redis']:
# Let the user know if they are trying to add it and it is already there
print ('Adding redis extra container... Please note that you will have '
'to reload your environment for these changes to take effect ("datacats reload {}")'
.format(environment.name))
environment.add_extra_container('redis', error_on_exists=True)
if opts['--admin-password']:
environment.create_admin_set_password(confirm_password()) | python | def tweak(environment, opts):
"""Commands operating on environment data
Usage:
datacats tweak --install-postgis [ENVIRONMENT]
datacats tweak --add-redis [ENVIRONMENT]
datacats tweak --admin-password [ENVIRONMENT]
Options:
--install-postgis Install postgis in ckan database
--add-redis Adds redis next time this environment reloads
-s --site=NAME Choose a site to tweak [default: primary]
-p --admin-password Prompt to change the admin password
ENVIRONMENT may be an environment name or a path to an environment directory.
Default: '.'
"""
environment.require_data()
if opts['--install-postgis']:
print "Installing postgis"
environment.install_postgis_sql()
if opts['--add-redis']:
# Let the user know if they are trying to add it and it is already there
print ('Adding redis extra container... Please note that you will have '
'to reload your environment for these changes to take effect ("datacats reload {}")'
.format(environment.name))
environment.add_extra_container('redis', error_on_exists=True)
if opts['--admin-password']:
environment.create_admin_set_password(confirm_password()) | [
"def",
"tweak",
"(",
"environment",
",",
"opts",
")",
":",
"environment",
".",
"require_data",
"(",
")",
"if",
"opts",
"[",
"'--install-postgis'",
"]",
":",
"print",
"\"Installing postgis\"",
"environment",
".",
"install_postgis_sql",
"(",
")",
"if",
"opts",
"[",
"'--add-redis'",
"]",
":",
"# Let the user know if they are trying to add it and it is already there",
"print",
"(",
"'Adding redis extra container... Please note that you will have '",
"'to reload your environment for these changes to take effect (\"datacats reload {}\")'",
".",
"format",
"(",
"environment",
".",
"name",
")",
")",
"environment",
".",
"add_extra_container",
"(",
"'redis'",
",",
"error_on_exists",
"=",
"True",
")",
"if",
"opts",
"[",
"'--admin-password'",
"]",
":",
"environment",
".",
"create_admin_set_password",
"(",
"confirm_password",
"(",
")",
")"
] | Commands operating on environment data
Usage:
datacats tweak --install-postgis [ENVIRONMENT]
datacats tweak --add-redis [ENVIRONMENT]
datacats tweak --admin-password [ENVIRONMENT]
Options:
--install-postgis Install postgis in ckan database
--add-redis Adds redis next time this environment reloads
-s --site=NAME Choose a site to tweak [default: primary]
-p --admin-password Prompt to change the admin password
ENVIRONMENT may be an environment name or a path to an environment directory.
Default: '.' | [
"Commands",
"operating",
"on",
"environment",
"data"
] | e4bae503efa997660fb3f34fe166699569653157 | https://github.com/datacats/datacats/blob/e4bae503efa997660fb3f34fe166699569653157/datacats/cli/manage.py#L269-L299 | train |
datacats/datacats | datacats/migrate.py | _split_path | def _split_path(path):
"""
A wrapper around the normal split function that ignores any trailing /.
:return: A tuple of the form (dirname, last) where last is the last element
in the path.
"""
# Get around a quirk in path_split where a / at the end will make the
# dirname (split[0]) the entire path
path = path[:-1] if path[-1] == '/' else path
split = path_split(path)
return split | python | def _split_path(path):
"""
A wrapper around the normal split function that ignores any trailing /.
:return: A tuple of the form (dirname, last) where last is the last element
in the path.
"""
# Get around a quirk in path_split where a / at the end will make the
# dirname (split[0]) the entire path
path = path[:-1] if path[-1] == '/' else path
split = path_split(path)
return split | [
"def",
"_split_path",
"(",
"path",
")",
":",
"# Get around a quirk in path_split where a / at the end will make the",
"# dirname (split[0]) the entire path",
"path",
"=",
"path",
"[",
":",
"-",
"1",
"]",
"if",
"path",
"[",
"-",
"1",
"]",
"==",
"'/'",
"else",
"path",
"split",
"=",
"path_split",
"(",
"path",
")",
"return",
"split"
] | A wrapper around the normal split function that ignores any trailing /.
:return: A tuple of the form (dirname, last) where last is the last element
in the path. | [
"A",
"wrapper",
"around",
"the",
"normal",
"split",
"function",
"that",
"ignores",
"any",
"trailing",
"/",
"."
] | e4bae503efa997660fb3f34fe166699569653157 | https://github.com/datacats/datacats/blob/e4bae503efa997660fb3f34fe166699569653157/datacats/migrate.py#L43-L54 | train |
datacats/datacats | datacats/migrate.py | _one_to_two | def _one_to_two(datadir):
"""After this command, your environment will be converted to format version {}.
and will only work with datacats version exceeding and including 1.0.0.
This migration is necessary to support multiple sites within the same environment.
Your current site will be kept and will be named "primary".
Would you like to continue the migration? (y/n) [n]:"""
new_site_name = 'primary'
split = _split_path(datadir)
print 'Making sure that containers are stopped...'
env_name = split[1]
# Old-style names on purpose! We need to stop old containers!
remove_container('datacats_web_' + env_name)
remove_container('datacats_solr_' + env_name)
remove_container('datacats_postgres_' + env_name)
print 'Doing conversion...'
# Begin the actual conversion
to_move = (['files', 'passwords.ini', 'run', 'solr'] +
(['postgres'] if not is_boot2docker() else []))
# Make a primary site
site_path = path_join(datadir, 'sites', new_site_name)
if not exists(site_path):
makedirs(site_path)
web_command(
command=['/scripts/migrate.sh',
'/project/data',
'/project/data/sites/' + new_site_name] +
to_move,
ro={scripts.get_script_path('migrate.sh'): '/scripts/migrate.sh'},
rw={datadir: '/project/data'},
clean_up=True
)
if is_boot2docker():
rename_container('datacats_pgdata_' + env_name,
'datacats_pgdata_' + env_name + '_' + new_site_name)
# Lastly, grab the project directory and update the ini file
with open(path_join(datadir, 'project-dir')) as pd:
project = pd.read()
cp = SafeConfigParser()
config_loc = path_join(project, '.datacats-environment')
cp.read([config_loc])
new_section = 'site_' + new_site_name
cp.add_section(new_section)
# Ports need to be moved into the new section
port = cp.get('datacats', 'port')
cp.remove_option('datacats', 'port')
cp.set(new_section, 'port', port)
with open(config_loc, 'w') as config:
cp.write(config)
# Make a session secret for it (make it per-site)
cp = SafeConfigParser()
config_loc = path_join(site_path, 'passwords.ini')
cp.read([config_loc])
# Generate a new secret
cp.set('passwords', 'beaker_session_secret', generate_password())
with open(config_loc, 'w') as config:
cp.write(config)
with open(path_join(datadir, '.version'), 'w') as f:
f.write('2') | python | def _one_to_two(datadir):
"""After this command, your environment will be converted to format version {}.
and will only work with datacats version exceeding and including 1.0.0.
This migration is necessary to support multiple sites within the same environment.
Your current site will be kept and will be named "primary".
Would you like to continue the migration? (y/n) [n]:"""
new_site_name = 'primary'
split = _split_path(datadir)
print 'Making sure that containers are stopped...'
env_name = split[1]
# Old-style names on purpose! We need to stop old containers!
remove_container('datacats_web_' + env_name)
remove_container('datacats_solr_' + env_name)
remove_container('datacats_postgres_' + env_name)
print 'Doing conversion...'
# Begin the actual conversion
to_move = (['files', 'passwords.ini', 'run', 'solr'] +
(['postgres'] if not is_boot2docker() else []))
# Make a primary site
site_path = path_join(datadir, 'sites', new_site_name)
if not exists(site_path):
makedirs(site_path)
web_command(
command=['/scripts/migrate.sh',
'/project/data',
'/project/data/sites/' + new_site_name] +
to_move,
ro={scripts.get_script_path('migrate.sh'): '/scripts/migrate.sh'},
rw={datadir: '/project/data'},
clean_up=True
)
if is_boot2docker():
rename_container('datacats_pgdata_' + env_name,
'datacats_pgdata_' + env_name + '_' + new_site_name)
# Lastly, grab the project directory and update the ini file
with open(path_join(datadir, 'project-dir')) as pd:
project = pd.read()
cp = SafeConfigParser()
config_loc = path_join(project, '.datacats-environment')
cp.read([config_loc])
new_section = 'site_' + new_site_name
cp.add_section(new_section)
# Ports need to be moved into the new section
port = cp.get('datacats', 'port')
cp.remove_option('datacats', 'port')
cp.set(new_section, 'port', port)
with open(config_loc, 'w') as config:
cp.write(config)
# Make a session secret for it (make it per-site)
cp = SafeConfigParser()
config_loc = path_join(site_path, 'passwords.ini')
cp.read([config_loc])
# Generate a new secret
cp.set('passwords', 'beaker_session_secret', generate_password())
with open(config_loc, 'w') as config:
cp.write(config)
with open(path_join(datadir, '.version'), 'w') as f:
f.write('2') | [
"def",
"_one_to_two",
"(",
"datadir",
")",
":",
"new_site_name",
"=",
"'primary'",
"split",
"=",
"_split_path",
"(",
"datadir",
")",
"print",
"'Making sure that containers are stopped...'",
"env_name",
"=",
"split",
"[",
"1",
"]",
"# Old-style names on purpose! We need to stop old containers!",
"remove_container",
"(",
"'datacats_web_'",
"+",
"env_name",
")",
"remove_container",
"(",
"'datacats_solr_'",
"+",
"env_name",
")",
"remove_container",
"(",
"'datacats_postgres_'",
"+",
"env_name",
")",
"print",
"'Doing conversion...'",
"# Begin the actual conversion",
"to_move",
"=",
"(",
"[",
"'files'",
",",
"'passwords.ini'",
",",
"'run'",
",",
"'solr'",
"]",
"+",
"(",
"[",
"'postgres'",
"]",
"if",
"not",
"is_boot2docker",
"(",
")",
"else",
"[",
"]",
")",
")",
"# Make a primary site",
"site_path",
"=",
"path_join",
"(",
"datadir",
",",
"'sites'",
",",
"new_site_name",
")",
"if",
"not",
"exists",
"(",
"site_path",
")",
":",
"makedirs",
"(",
"site_path",
")",
"web_command",
"(",
"command",
"=",
"[",
"'/scripts/migrate.sh'",
",",
"'/project/data'",
",",
"'/project/data/sites/'",
"+",
"new_site_name",
"]",
"+",
"to_move",
",",
"ro",
"=",
"{",
"scripts",
".",
"get_script_path",
"(",
"'migrate.sh'",
")",
":",
"'/scripts/migrate.sh'",
"}",
",",
"rw",
"=",
"{",
"datadir",
":",
"'/project/data'",
"}",
",",
"clean_up",
"=",
"True",
")",
"if",
"is_boot2docker",
"(",
")",
":",
"rename_container",
"(",
"'datacats_pgdata_'",
"+",
"env_name",
",",
"'datacats_pgdata_'",
"+",
"env_name",
"+",
"'_'",
"+",
"new_site_name",
")",
"# Lastly, grab the project directory and update the ini file",
"with",
"open",
"(",
"path_join",
"(",
"datadir",
",",
"'project-dir'",
")",
")",
"as",
"pd",
":",
"project",
"=",
"pd",
".",
"read",
"(",
")",
"cp",
"=",
"SafeConfigParser",
"(",
")",
"config_loc",
"=",
"path_join",
"(",
"project",
",",
"'.datacats-environment'",
")",
"cp",
".",
"read",
"(",
"[",
"config_loc",
"]",
")",
"new_section",
"=",
"'site_'",
"+",
"new_site_name",
"cp",
".",
"add_section",
"(",
"new_section",
")",
"# Ports need to be moved into the new section",
"port",
"=",
"cp",
".",
"get",
"(",
"'datacats'",
",",
"'port'",
")",
"cp",
".",
"remove_option",
"(",
"'datacats'",
",",
"'port'",
")",
"cp",
".",
"set",
"(",
"new_section",
",",
"'port'",
",",
"port",
")",
"with",
"open",
"(",
"config_loc",
",",
"'w'",
")",
"as",
"config",
":",
"cp",
".",
"write",
"(",
"config",
")",
"# Make a session secret for it (make it per-site)",
"cp",
"=",
"SafeConfigParser",
"(",
")",
"config_loc",
"=",
"path_join",
"(",
"site_path",
",",
"'passwords.ini'",
")",
"cp",
".",
"read",
"(",
"[",
"config_loc",
"]",
")",
"# Generate a new secret",
"cp",
".",
"set",
"(",
"'passwords'",
",",
"'beaker_session_secret'",
",",
"generate_password",
"(",
")",
")",
"with",
"open",
"(",
"config_loc",
",",
"'w'",
")",
"as",
"config",
":",
"cp",
".",
"write",
"(",
"config",
")",
"with",
"open",
"(",
"path_join",
"(",
"datadir",
",",
"'.version'",
")",
",",
"'w'",
")",
"as",
"f",
":",
"f",
".",
"write",
"(",
"'2'",
")"
] | After this command, your environment will be converted to format version {}.
and will only work with datacats version exceeding and including 1.0.0.
This migration is necessary to support multiple sites within the same environment.
Your current site will be kept and will be named "primary".
Would you like to continue the migration? (y/n) [n]: | [
"After",
"this",
"command",
"your",
"environment",
"will",
"be",
"converted",
"to",
"format",
"version",
"{}",
".",
"and",
"will",
"only",
"work",
"with",
"datacats",
"version",
"exceeding",
"and",
"including",
"1",
".",
"0",
".",
"0",
".",
"This",
"migration",
"is",
"necessary",
"to",
"support",
"multiple",
"sites",
"within",
"the",
"same",
"environment",
".",
"Your",
"current",
"site",
"will",
"be",
"kept",
"and",
"will",
"be",
"named",
"primary",
"."
] | e4bae503efa997660fb3f34fe166699569653157 | https://github.com/datacats/datacats/blob/e4bae503efa997660fb3f34fe166699569653157/datacats/migrate.py#L57-L130 | train |
datacats/datacats | datacats/migrate.py | _two_to_one | def _two_to_one(datadir):
"""After this command, your environment will be converted to format version {}
and will not work with Datacats versions beyond and including 1.0.0.
This format version doesn't support multiple sites, and after this only your
"primary" site will be usable, though other sites will be maintained if you
wish to do a migration back to a version which supports multisite.
Would you like to continue the migration? (y/n) [n]:"""
_, env_name = _split_path(datadir)
print 'Making sure that containers are stopped...'
# New-style names
remove_container('datacats_web_{}_primary'.format(env_name))
remove_container('datacats_postgres_{}_primary'.format(env_name))
remove_container('datacats_solr_{}_primary'.format(env_name))
print 'Doing conversion...'
if exists(path_join(datadir, '.version')):
os.remove(path_join(datadir, '.version'))
to_move = (['files', 'passwords.ini', 'run', 'solr'] +
(['postgres'] if not is_boot2docker() else []))
web_command(
command=['/scripts/migrate.sh',
'/project/data/sites/primary',
'/project/data'] + to_move,
ro={scripts.get_script_path('migrate.sh'): '/scripts/migrate.sh'},
rw={datadir: '/project/data'}
)
pgdata_name = 'datacats_pgdata_{}_primary'.format(env_name)
if is_boot2docker() and inspect_container(pgdata_name):
rename_container(pgdata_name, 'datacats_pgdata_{}'.format(env_name))
print 'Doing cleanup...'
with open(path_join(datadir, 'project-dir')) as pd:
datacats_env_location = path_join(pd.read(), '.datacats-environment')
cp = SafeConfigParser()
cp.read(datacats_env_location)
# We need to move the port OUT of site_primary section and INTO datacats
cp.set('datacats', 'port', cp.get('site_primary', 'port'))
cp.remove_section('site_primary')
with open(datacats_env_location, 'w') as config:
cp.write(config)
cp = SafeConfigParser()
cp.read(path_join(datadir, 'passwords.ini'))
# This isn't needed in this version
cp.remove_option('passwords', 'beaker_session_secret')
with open(path_join(datadir, 'passwords.ini'), 'w') as config:
cp.write(config) | python | def _two_to_one(datadir):
"""After this command, your environment will be converted to format version {}
and will not work with Datacats versions beyond and including 1.0.0.
This format version doesn't support multiple sites, and after this only your
"primary" site will be usable, though other sites will be maintained if you
wish to do a migration back to a version which supports multisite.
Would you like to continue the migration? (y/n) [n]:"""
_, env_name = _split_path(datadir)
print 'Making sure that containers are stopped...'
# New-style names
remove_container('datacats_web_{}_primary'.format(env_name))
remove_container('datacats_postgres_{}_primary'.format(env_name))
remove_container('datacats_solr_{}_primary'.format(env_name))
print 'Doing conversion...'
if exists(path_join(datadir, '.version')):
os.remove(path_join(datadir, '.version'))
to_move = (['files', 'passwords.ini', 'run', 'solr'] +
(['postgres'] if not is_boot2docker() else []))
web_command(
command=['/scripts/migrate.sh',
'/project/data/sites/primary',
'/project/data'] + to_move,
ro={scripts.get_script_path('migrate.sh'): '/scripts/migrate.sh'},
rw={datadir: '/project/data'}
)
pgdata_name = 'datacats_pgdata_{}_primary'.format(env_name)
if is_boot2docker() and inspect_container(pgdata_name):
rename_container(pgdata_name, 'datacats_pgdata_{}'.format(env_name))
print 'Doing cleanup...'
with open(path_join(datadir, 'project-dir')) as pd:
datacats_env_location = path_join(pd.read(), '.datacats-environment')
cp = SafeConfigParser()
cp.read(datacats_env_location)
# We need to move the port OUT of site_primary section and INTO datacats
cp.set('datacats', 'port', cp.get('site_primary', 'port'))
cp.remove_section('site_primary')
with open(datacats_env_location, 'w') as config:
cp.write(config)
cp = SafeConfigParser()
cp.read(path_join(datadir, 'passwords.ini'))
# This isn't needed in this version
cp.remove_option('passwords', 'beaker_session_secret')
with open(path_join(datadir, 'passwords.ini'), 'w') as config:
cp.write(config) | [
"def",
"_two_to_one",
"(",
"datadir",
")",
":",
"_",
",",
"env_name",
"=",
"_split_path",
"(",
"datadir",
")",
"print",
"'Making sure that containers are stopped...'",
"# New-style names",
"remove_container",
"(",
"'datacats_web_{}_primary'",
".",
"format",
"(",
"env_name",
")",
")",
"remove_container",
"(",
"'datacats_postgres_{}_primary'",
".",
"format",
"(",
"env_name",
")",
")",
"remove_container",
"(",
"'datacats_solr_{}_primary'",
".",
"format",
"(",
"env_name",
")",
")",
"print",
"'Doing conversion...'",
"if",
"exists",
"(",
"path_join",
"(",
"datadir",
",",
"'.version'",
")",
")",
":",
"os",
".",
"remove",
"(",
"path_join",
"(",
"datadir",
",",
"'.version'",
")",
")",
"to_move",
"=",
"(",
"[",
"'files'",
",",
"'passwords.ini'",
",",
"'run'",
",",
"'solr'",
"]",
"+",
"(",
"[",
"'postgres'",
"]",
"if",
"not",
"is_boot2docker",
"(",
")",
"else",
"[",
"]",
")",
")",
"web_command",
"(",
"command",
"=",
"[",
"'/scripts/migrate.sh'",
",",
"'/project/data/sites/primary'",
",",
"'/project/data'",
"]",
"+",
"to_move",
",",
"ro",
"=",
"{",
"scripts",
".",
"get_script_path",
"(",
"'migrate.sh'",
")",
":",
"'/scripts/migrate.sh'",
"}",
",",
"rw",
"=",
"{",
"datadir",
":",
"'/project/data'",
"}",
")",
"pgdata_name",
"=",
"'datacats_pgdata_{}_primary'",
".",
"format",
"(",
"env_name",
")",
"if",
"is_boot2docker",
"(",
")",
"and",
"inspect_container",
"(",
"pgdata_name",
")",
":",
"rename_container",
"(",
"pgdata_name",
",",
"'datacats_pgdata_{}'",
".",
"format",
"(",
"env_name",
")",
")",
"print",
"'Doing cleanup...'",
"with",
"open",
"(",
"path_join",
"(",
"datadir",
",",
"'project-dir'",
")",
")",
"as",
"pd",
":",
"datacats_env_location",
"=",
"path_join",
"(",
"pd",
".",
"read",
"(",
")",
",",
"'.datacats-environment'",
")",
"cp",
"=",
"SafeConfigParser",
"(",
")",
"cp",
".",
"read",
"(",
"datacats_env_location",
")",
"# We need to move the port OUT of site_primary section and INTO datacats",
"cp",
".",
"set",
"(",
"'datacats'",
",",
"'port'",
",",
"cp",
".",
"get",
"(",
"'site_primary'",
",",
"'port'",
")",
")",
"cp",
".",
"remove_section",
"(",
"'site_primary'",
")",
"with",
"open",
"(",
"datacats_env_location",
",",
"'w'",
")",
"as",
"config",
":",
"cp",
".",
"write",
"(",
"config",
")",
"cp",
"=",
"SafeConfigParser",
"(",
")",
"cp",
".",
"read",
"(",
"path_join",
"(",
"datadir",
",",
"'passwords.ini'",
")",
")",
"# This isn't needed in this version",
"cp",
".",
"remove_option",
"(",
"'passwords'",
",",
"'beaker_session_secret'",
")",
"with",
"open",
"(",
"path_join",
"(",
"datadir",
",",
"'passwords.ini'",
")",
",",
"'w'",
")",
"as",
"config",
":",
"cp",
".",
"write",
"(",
"config",
")"
] | After this command, your environment will be converted to format version {}
and will not work with Datacats versions beyond and including 1.0.0.
This format version doesn't support multiple sites, and after this only your
"primary" site will be usable, though other sites will be maintained if you
wish to do a migration back to a version which supports multisite.
Would you like to continue the migration? (y/n) [n]: | [
"After",
"this",
"command",
"your",
"environment",
"will",
"be",
"converted",
"to",
"format",
"version",
"{}",
"and",
"will",
"not",
"work",
"with",
"Datacats",
"versions",
"beyond",
"and",
"including",
"1",
".",
"0",
".",
"0",
".",
"This",
"format",
"version",
"doesn",
"t",
"support",
"multiple",
"sites",
"and",
"after",
"this",
"only",
"your",
"primary",
"site",
"will",
"be",
"usable",
"though",
"other",
"sites",
"will",
"be",
"maintained",
"if",
"you",
"wish",
"to",
"do",
"a",
"migration",
"back",
"to",
"a",
"version",
"which",
"supports",
"multisite",
"."
] | e4bae503efa997660fb3f34fe166699569653157 | https://github.com/datacats/datacats/blob/e4bae503efa997660fb3f34fe166699569653157/datacats/migrate.py#L133-L190 | train |
datacats/datacats | datacats/migrate.py | convert_environment | def convert_environment(datadir, version, always_yes):
"""
Converts an environment TO the version specified by `version`.
:param datadir: The datadir to convert.
:param version: The version to convert TO.
:param always_yes: True if the user shouldn't be prompted about the migration.
"""
# Since we don't call either load() or new() we have to call require_images ourselves.
require_images()
inp = None
old_version = _get_current_format(datadir)
migration_func = migrations[(old_version, version)]
if version > CURRENT_FORMAT_VERSION:
raise DatacatsError('Cannot migrate to a version higher than the '
'current one.')
if version < 1:
raise DatacatsError('Datadir versioning starts at 1.')
if not always_yes:
while inp != 'y' and inp != 'n':
inp = raw_input(migration_func.__doc__.format(version))
if inp == 'n':
sys.exit(1)
lockfile = LockFile(path_join(datadir, '.migration_lock'))
lockfile.acquire()
try:
# FIXME: If we wanted to, we could find a set of conversions which
# would bring us up to the one we want if there's no direct path.
# This isn't necessary with just two formats, but it may be useful
# at 3.
# Call the appropriate conversion function
migration_func(datadir)
finally:
lockfile.release() | python | def convert_environment(datadir, version, always_yes):
"""
Converts an environment TO the version specified by `version`.
:param datadir: The datadir to convert.
:param version: The version to convert TO.
:param always_yes: True if the user shouldn't be prompted about the migration.
"""
# Since we don't call either load() or new() we have to call require_images ourselves.
require_images()
inp = None
old_version = _get_current_format(datadir)
migration_func = migrations[(old_version, version)]
if version > CURRENT_FORMAT_VERSION:
raise DatacatsError('Cannot migrate to a version higher than the '
'current one.')
if version < 1:
raise DatacatsError('Datadir versioning starts at 1.')
if not always_yes:
while inp != 'y' and inp != 'n':
inp = raw_input(migration_func.__doc__.format(version))
if inp == 'n':
sys.exit(1)
lockfile = LockFile(path_join(datadir, '.migration_lock'))
lockfile.acquire()
try:
# FIXME: If we wanted to, we could find a set of conversions which
# would bring us up to the one we want if there's no direct path.
# This isn't necessary with just two formats, but it may be useful
# at 3.
# Call the appropriate conversion function
migration_func(datadir)
finally:
lockfile.release() | [
"def",
"convert_environment",
"(",
"datadir",
",",
"version",
",",
"always_yes",
")",
":",
"# Since we don't call either load() or new() we have to call require_images ourselves.",
"require_images",
"(",
")",
"inp",
"=",
"None",
"old_version",
"=",
"_get_current_format",
"(",
"datadir",
")",
"migration_func",
"=",
"migrations",
"[",
"(",
"old_version",
",",
"version",
")",
"]",
"if",
"version",
">",
"CURRENT_FORMAT_VERSION",
":",
"raise",
"DatacatsError",
"(",
"'Cannot migrate to a version higher than the '",
"'current one.'",
")",
"if",
"version",
"<",
"1",
":",
"raise",
"DatacatsError",
"(",
"'Datadir versioning starts at 1.'",
")",
"if",
"not",
"always_yes",
":",
"while",
"inp",
"!=",
"'y'",
"and",
"inp",
"!=",
"'n'",
":",
"inp",
"=",
"raw_input",
"(",
"migration_func",
".",
"__doc__",
".",
"format",
"(",
"version",
")",
")",
"if",
"inp",
"==",
"'n'",
":",
"sys",
".",
"exit",
"(",
"1",
")",
"lockfile",
"=",
"LockFile",
"(",
"path_join",
"(",
"datadir",
",",
"'.migration_lock'",
")",
")",
"lockfile",
".",
"acquire",
"(",
")",
"try",
":",
"# FIXME: If we wanted to, we could find a set of conversions which",
"# would bring us up to the one we want if there's no direct path.",
"# This isn't necessary with just two formats, but it may be useful",
"# at 3.",
"# Call the appropriate conversion function",
"migration_func",
"(",
"datadir",
")",
"finally",
":",
"lockfile",
".",
"release",
"(",
")"
] | Converts an environment TO the version specified by `version`.
:param datadir: The datadir to convert.
:param version: The version to convert TO.
:param always_yes: True if the user shouldn't be prompted about the migration. | [
"Converts",
"an",
"environment",
"TO",
"the",
"version",
"specified",
"by",
"version",
".",
":",
"param",
"datadir",
":",
"The",
"datadir",
"to",
"convert",
".",
":",
"param",
"version",
":",
"The",
"version",
"to",
"convert",
"TO",
".",
":",
"param",
"always_yes",
":",
"True",
"if",
"the",
"user",
"shouldn",
"t",
"be",
"prompted",
"about",
"the",
"migration",
"."
] | e4bae503efa997660fb3f34fe166699569653157 | https://github.com/datacats/datacats/blob/e4bae503efa997660fb3f34fe166699569653157/datacats/migrate.py#L199-L237 | train |
supercoderz/pyflightdata | pyflightdata/flightdata.py | FlightData.get_history_by_flight_number | def get_history_by_flight_number(self, flight_number, page=1, limit=100):
"""Fetch the history of a flight by its number.
This method can be used to get the history of a flight route by the number.
It checks the user authentication and returns the data accordingly.
Args:
flight_number (str): The flight number, e.g. AI101
page (int): Optional page number; for users who are on a plan with flightradar24 they can pass in higher page numbers to get more data
limit (int): Optional limit on number of records returned
Returns:
A list of dicts with the data; one dict for each row of data from flightradar24
Example::
from pyflightdata import FlightData
f=FlightData()
#optional login
f.login(myemail,mypassword)
f.get_history_by_flight_number('AI101')
f.get_history_by_flight_number('AI101',page=1,limit=10)
"""
url = FLT_BASE.format(flight_number, str(self.AUTH_TOKEN), page, limit)
return self._fr24.get_data(url) | python | def get_history_by_flight_number(self, flight_number, page=1, limit=100):
"""Fetch the history of a flight by its number.
This method can be used to get the history of a flight route by the number.
It checks the user authentication and returns the data accordingly.
Args:
flight_number (str): The flight number, e.g. AI101
page (int): Optional page number; for users who are on a plan with flightradar24 they can pass in higher page numbers to get more data
limit (int): Optional limit on number of records returned
Returns:
A list of dicts with the data; one dict for each row of data from flightradar24
Example::
from pyflightdata import FlightData
f=FlightData()
#optional login
f.login(myemail,mypassword)
f.get_history_by_flight_number('AI101')
f.get_history_by_flight_number('AI101',page=1,limit=10)
"""
url = FLT_BASE.format(flight_number, str(self.AUTH_TOKEN), page, limit)
return self._fr24.get_data(url) | [
"def",
"get_history_by_flight_number",
"(",
"self",
",",
"flight_number",
",",
"page",
"=",
"1",
",",
"limit",
"=",
"100",
")",
":",
"url",
"=",
"FLT_BASE",
".",
"format",
"(",
"flight_number",
",",
"str",
"(",
"self",
".",
"AUTH_TOKEN",
")",
",",
"page",
",",
"limit",
")",
"return",
"self",
".",
"_fr24",
".",
"get_data",
"(",
"url",
")"
] | Fetch the history of a flight by its number.
This method can be used to get the history of a flight route by the number.
It checks the user authentication and returns the data accordingly.
Args:
flight_number (str): The flight number, e.g. AI101
page (int): Optional page number; for users who are on a plan with flightradar24 they can pass in higher page numbers to get more data
limit (int): Optional limit on number of records returned
Returns:
A list of dicts with the data; one dict for each row of data from flightradar24
Example::
from pyflightdata import FlightData
f=FlightData()
#optional login
f.login(myemail,mypassword)
f.get_history_by_flight_number('AI101')
f.get_history_by_flight_number('AI101',page=1,limit=10) | [
"Fetch",
"the",
"history",
"of",
"a",
"flight",
"by",
"its",
"number",
"."
] | 2caf9f429288f9a171893d1b8377d0c6244541cc | https://github.com/supercoderz/pyflightdata/blob/2caf9f429288f9a171893d1b8377d0c6244541cc/pyflightdata/flightdata.py#L58-L83 | train |
supercoderz/pyflightdata | pyflightdata/flightdata.py | FlightData.get_history_by_tail_number | def get_history_by_tail_number(self, tail_number, page=1, limit=100):
"""Fetch the history of a particular aircraft by its tail number.
This method can be used to get the history of a particular aircraft by its tail number.
It checks the user authentication and returns the data accordingly.
Args:
tail_number (str): The tail number, e.g. VT-ANL
page (int): Optional page number; for users who are on a plan with flightradar24 they can pass in higher page numbers to get more data
limit (int): Optional limit on number of records returned
Returns:
A list of dicts with the data; one dict for each row of data from flightradar24
Example::
from pyflightdata import FlightData
f=FlightData()
#optional login
f.login(myemail,mypassword)
f.get_history_by_flight_number('VT-ANL')
f.get_history_by_flight_number('VT-ANL',page=1,limit=10)
"""
url = REG_BASE.format(tail_number, str(self.AUTH_TOKEN), page, limit)
return self._fr24.get_data(url, True) | python | def get_history_by_tail_number(self, tail_number, page=1, limit=100):
"""Fetch the history of a particular aircraft by its tail number.
This method can be used to get the history of a particular aircraft by its tail number.
It checks the user authentication and returns the data accordingly.
Args:
tail_number (str): The tail number, e.g. VT-ANL
page (int): Optional page number; for users who are on a plan with flightradar24 they can pass in higher page numbers to get more data
limit (int): Optional limit on number of records returned
Returns:
A list of dicts with the data; one dict for each row of data from flightradar24
Example::
from pyflightdata import FlightData
f=FlightData()
#optional login
f.login(myemail,mypassword)
f.get_history_by_flight_number('VT-ANL')
f.get_history_by_flight_number('VT-ANL',page=1,limit=10)
"""
url = REG_BASE.format(tail_number, str(self.AUTH_TOKEN), page, limit)
return self._fr24.get_data(url, True) | [
"def",
"get_history_by_tail_number",
"(",
"self",
",",
"tail_number",
",",
"page",
"=",
"1",
",",
"limit",
"=",
"100",
")",
":",
"url",
"=",
"REG_BASE",
".",
"format",
"(",
"tail_number",
",",
"str",
"(",
"self",
".",
"AUTH_TOKEN",
")",
",",
"page",
",",
"limit",
")",
"return",
"self",
".",
"_fr24",
".",
"get_data",
"(",
"url",
",",
"True",
")"
] | Fetch the history of a particular aircraft by its tail number.
This method can be used to get the history of a particular aircraft by its tail number.
It checks the user authentication and returns the data accordingly.
Args:
tail_number (str): The tail number, e.g. VT-ANL
page (int): Optional page number; for users who are on a plan with flightradar24 they can pass in higher page numbers to get more data
limit (int): Optional limit on number of records returned
Returns:
A list of dicts with the data; one dict for each row of data from flightradar24
Example::
from pyflightdata import FlightData
f=FlightData()
#optional login
f.login(myemail,mypassword)
f.get_history_by_flight_number('VT-ANL')
f.get_history_by_flight_number('VT-ANL',page=1,limit=10) | [
"Fetch",
"the",
"history",
"of",
"a",
"particular",
"aircraft",
"by",
"its",
"tail",
"number",
"."
] | 2caf9f429288f9a171893d1b8377d0c6244541cc | https://github.com/supercoderz/pyflightdata/blob/2caf9f429288f9a171893d1b8377d0c6244541cc/pyflightdata/flightdata.py#L85-L110 | train |
supercoderz/pyflightdata | pyflightdata/flightdata.py | FlightData.get_airports | def get_airports(self, country):
"""Returns a list of all the airports
For a given country this returns a list of dicts, one for each airport, with information like the iata code of the airport etc
Args:
country (str): The country for which the airports will be fetched
Example::
from pyflightdata import FlightData
f=FlightData()
f.get_airports('India')
"""
url = AIRPORT_BASE.format(country.replace(" ", "-"))
return self._fr24.get_airports_data(url) | python | def get_airports(self, country):
"""Returns a list of all the airports
For a given country this returns a list of dicts, one for each airport, with information like the iata code of the airport etc
Args:
country (str): The country for which the airports will be fetched
Example::
from pyflightdata import FlightData
f=FlightData()
f.get_airports('India')
"""
url = AIRPORT_BASE.format(country.replace(" ", "-"))
return self._fr24.get_airports_data(url) | [
"def",
"get_airports",
"(",
"self",
",",
"country",
")",
":",
"url",
"=",
"AIRPORT_BASE",
".",
"format",
"(",
"country",
".",
"replace",
"(",
"\" \"",
",",
"\"-\"",
")",
")",
"return",
"self",
".",
"_fr24",
".",
"get_airports_data",
"(",
"url",
")"
] | Returns a list of all the airports
For a given country this returns a list of dicts, one for each airport, with information like the iata code of the airport etc
Args:
country (str): The country for which the airports will be fetched
Example::
from pyflightdata import FlightData
f=FlightData()
f.get_airports('India') | [
"Returns",
"a",
"list",
"of",
"all",
"the",
"airports",
"For",
"a",
"given",
"country",
"this",
"returns",
"a",
"list",
"of",
"dicts",
"one",
"for",
"each",
"airport",
"with",
"information",
"like",
"the",
"iata",
"code",
"of",
"the",
"airport",
"etc"
] | 2caf9f429288f9a171893d1b8377d0c6244541cc | https://github.com/supercoderz/pyflightdata/blob/2caf9f429288f9a171893d1b8377d0c6244541cc/pyflightdata/flightdata.py#L118-L133 | train |
supercoderz/pyflightdata | pyflightdata/flightdata.py | FlightData.get_info_by_tail_number | def get_info_by_tail_number(self, tail_number, page=1, limit=100):
"""Fetch the details of a particular aircraft by its tail number.
This method can be used to get the details of a particular aircraft by its tail number.
Details include the serial number, age etc along with links to the images of the aircraft.
It checks the user authentication and returns the data accordingly.
Args:
tail_number (str): The tail number, e.g. VT-ANL
page (int): Optional page number; for users who are on a plan with flightradar24 they can pass in higher page numbers to get more data
limit (int): Optional limit on number of records returned
Returns:
A list of dicts with the data; one dict for each row of data from flightradar24
Example::
from pyflightdata import FlightData
f=FlightData()
#optional login
f.login(myemail,mypassword)
f.get_info_by_flight_number('VT-ANL')
f.get_info_by_flight_number('VT-ANL',page=1,limit=10)
"""
url = REG_BASE.format(tail_number, str(self.AUTH_TOKEN), page, limit)
return self._fr24.get_aircraft_data(url) | python | def get_info_by_tail_number(self, tail_number, page=1, limit=100):
"""Fetch the details of a particular aircraft by its tail number.
This method can be used to get the details of a particular aircraft by its tail number.
Details include the serial number, age etc along with links to the images of the aircraft.
It checks the user authentication and returns the data accordingly.
Args:
tail_number (str): The tail number, e.g. VT-ANL
page (int): Optional page number; for users who are on a plan with flightradar24 they can pass in higher page numbers to get more data
limit (int): Optional limit on number of records returned
Returns:
A list of dicts with the data; one dict for each row of data from flightradar24
Example::
from pyflightdata import FlightData
f=FlightData()
#optional login
f.login(myemail,mypassword)
f.get_info_by_flight_number('VT-ANL')
f.get_info_by_flight_number('VT-ANL',page=1,limit=10)
"""
url = REG_BASE.format(tail_number, str(self.AUTH_TOKEN), page, limit)
return self._fr24.get_aircraft_data(url) | [
"def",
"get_info_by_tail_number",
"(",
"self",
",",
"tail_number",
",",
"page",
"=",
"1",
",",
"limit",
"=",
"100",
")",
":",
"url",
"=",
"REG_BASE",
".",
"format",
"(",
"tail_number",
",",
"str",
"(",
"self",
".",
"AUTH_TOKEN",
")",
",",
"page",
",",
"limit",
")",
"return",
"self",
".",
"_fr24",
".",
"get_aircraft_data",
"(",
"url",
")"
] | Fetch the details of a particular aircraft by its tail number.
This method can be used to get the details of a particular aircraft by its tail number.
Details include the serial number, age etc along with links to the images of the aircraft.
It checks the user authentication and returns the data accordingly.
Args:
tail_number (str): The tail number, e.g. VT-ANL
page (int): Optional page number; for users who are on a plan with flightradar24 they can pass in higher page numbers to get more data
limit (int): Optional limit on number of records returned
Returns:
A list of dicts with the data; one dict for each row of data from flightradar24
Example::
from pyflightdata import FlightData
f=FlightData()
#optional login
f.login(myemail,mypassword)
f.get_info_by_flight_number('VT-ANL')
f.get_info_by_flight_number('VT-ANL',page=1,limit=10) | [
"Fetch",
"the",
"details",
"of",
"a",
"particular",
"aircraft",
"by",
"its",
"tail",
"number",
"."
] | 2caf9f429288f9a171893d1b8377d0c6244541cc | https://github.com/supercoderz/pyflightdata/blob/2caf9f429288f9a171893d1b8377d0c6244541cc/pyflightdata/flightdata.py#L135-L160 | train |
supercoderz/pyflightdata | pyflightdata/flightdata.py | FlightData.get_fleet | def get_fleet(self, airline_key):
"""Get the fleet for a particular airline.
Given a airline code form the get_airlines() method output, this method returns the fleet for the airline.
Args:
airline_key (str): The code for the airline on flightradar24
Returns:
A list of dicts, one for each aircraft in the airlines fleet
Example::
from pyflightdata import FlightData
f=FlightData()
#optional login
f.login(myemail,mypassword)
f.get_fleet('ai-aic')
"""
url = AIRLINE_FLEET_BASE.format(airline_key)
return self._fr24.get_airline_fleet_data(url, self.AUTH_TOKEN != '') | python | def get_fleet(self, airline_key):
"""Get the fleet for a particular airline.
Given a airline code form the get_airlines() method output, this method returns the fleet for the airline.
Args:
airline_key (str): The code for the airline on flightradar24
Returns:
A list of dicts, one for each aircraft in the airlines fleet
Example::
from pyflightdata import FlightData
f=FlightData()
#optional login
f.login(myemail,mypassword)
f.get_fleet('ai-aic')
"""
url = AIRLINE_FLEET_BASE.format(airline_key)
return self._fr24.get_airline_fleet_data(url, self.AUTH_TOKEN != '') | [
"def",
"get_fleet",
"(",
"self",
",",
"airline_key",
")",
":",
"url",
"=",
"AIRLINE_FLEET_BASE",
".",
"format",
"(",
"airline_key",
")",
"return",
"self",
".",
"_fr24",
".",
"get_airline_fleet_data",
"(",
"url",
",",
"self",
".",
"AUTH_TOKEN",
"!=",
"''",
")"
] | Get the fleet for a particular airline.
Given a airline code form the get_airlines() method output, this method returns the fleet for the airline.
Args:
airline_key (str): The code for the airline on flightradar24
Returns:
A list of dicts, one for each aircraft in the airlines fleet
Example::
from pyflightdata import FlightData
f=FlightData()
#optional login
f.login(myemail,mypassword)
f.get_fleet('ai-aic') | [
"Get",
"the",
"fleet",
"for",
"a",
"particular",
"airline",
"."
] | 2caf9f429288f9a171893d1b8377d0c6244541cc | https://github.com/supercoderz/pyflightdata/blob/2caf9f429288f9a171893d1b8377d0c6244541cc/pyflightdata/flightdata.py#L172-L191 | train |
supercoderz/pyflightdata | pyflightdata/flightdata.py | FlightData.get_flights | def get_flights(self, search_key):
"""Get the flights for a particular airline.
Given a full or partial flight number string, this method returns the first 100 flights matching that string.
Please note this method was different in earlier versions. The older versions took an airline code and returned all scheduled flights for that airline
Args:
search_key (str): Full or partial flight number for any airline e.g. MI47 to get all SilkAir flights starting with MI47
Returns:
A list of dicts, one for each scheduled flight in the airlines network
Example::
from pyflightdata import FlightData
f=FlightData()
#optional login
f.login(myemail,mypassword)
f.get_flights('MI47')
"""
# assume limit 100 to return first 100 of any wild card search
url = AIRLINE_FLT_BASE.format(search_key, 100)
return self._fr24.get_airline_flight_data(url) | python | def get_flights(self, search_key):
"""Get the flights for a particular airline.
Given a full or partial flight number string, this method returns the first 100 flights matching that string.
Please note this method was different in earlier versions. The older versions took an airline code and returned all scheduled flights for that airline
Args:
search_key (str): Full or partial flight number for any airline e.g. MI47 to get all SilkAir flights starting with MI47
Returns:
A list of dicts, one for each scheduled flight in the airlines network
Example::
from pyflightdata import FlightData
f=FlightData()
#optional login
f.login(myemail,mypassword)
f.get_flights('MI47')
"""
# assume limit 100 to return first 100 of any wild card search
url = AIRLINE_FLT_BASE.format(search_key, 100)
return self._fr24.get_airline_flight_data(url) | [
"def",
"get_flights",
"(",
"self",
",",
"search_key",
")",
":",
"# assume limit 100 to return first 100 of any wild card search",
"url",
"=",
"AIRLINE_FLT_BASE",
".",
"format",
"(",
"search_key",
",",
"100",
")",
"return",
"self",
".",
"_fr24",
".",
"get_airline_flight_data",
"(",
"url",
")"
] | Get the flights for a particular airline.
Given a full or partial flight number string, this method returns the first 100 flights matching that string.
Please note this method was different in earlier versions. The older versions took an airline code and returned all scheduled flights for that airline
Args:
search_key (str): Full or partial flight number for any airline e.g. MI47 to get all SilkAir flights starting with MI47
Returns:
A list of dicts, one for each scheduled flight in the airlines network
Example::
from pyflightdata import FlightData
f=FlightData()
#optional login
f.login(myemail,mypassword)
f.get_flights('MI47') | [
"Get",
"the",
"flights",
"for",
"a",
"particular",
"airline",
"."
] | 2caf9f429288f9a171893d1b8377d0c6244541cc | https://github.com/supercoderz/pyflightdata/blob/2caf9f429288f9a171893d1b8377d0c6244541cc/pyflightdata/flightdata.py#L193-L215 | train |
supercoderz/pyflightdata | pyflightdata/flightdata.py | FlightData.get_flights_from_to | def get_flights_from_to(self, origin, destination):
"""Get the flights for a particular origin and destination.
Given an origin and destination this method returns the upcoming scheduled flights between these two points.
The data returned has the airline, airport and schedule information - this is subject to change in future.
Args:
origin (str): The origin airport code
destination (str): The destination airport code
Returns:
A list of dicts, one for each scheduled flight between the two points.
Example::
from pyflightdata import FlightData
f=FlightData()
#optional login
f.login(myemail,mypassword)
f.get_flights_from_to('SIN','HYD')
"""
# assume limit 100 to return first 100 of any wild card search
url = AIRLINE_FLT_BASE_POINTS.format(origin, destination)
return self._fr24.get_airline_flight_data(url, by_airports=True) | python | def get_flights_from_to(self, origin, destination):
"""Get the flights for a particular origin and destination.
Given an origin and destination this method returns the upcoming scheduled flights between these two points.
The data returned has the airline, airport and schedule information - this is subject to change in future.
Args:
origin (str): The origin airport code
destination (str): The destination airport code
Returns:
A list of dicts, one for each scheduled flight between the two points.
Example::
from pyflightdata import FlightData
f=FlightData()
#optional login
f.login(myemail,mypassword)
f.get_flights_from_to('SIN','HYD')
"""
# assume limit 100 to return first 100 of any wild card search
url = AIRLINE_FLT_BASE_POINTS.format(origin, destination)
return self._fr24.get_airline_flight_data(url, by_airports=True) | [
"def",
"get_flights_from_to",
"(",
"self",
",",
"origin",
",",
"destination",
")",
":",
"# assume limit 100 to return first 100 of any wild card search",
"url",
"=",
"AIRLINE_FLT_BASE_POINTS",
".",
"format",
"(",
"origin",
",",
"destination",
")",
"return",
"self",
".",
"_fr24",
".",
"get_airline_flight_data",
"(",
"url",
",",
"by_airports",
"=",
"True",
")"
] | Get the flights for a particular origin and destination.
Given an origin and destination this method returns the upcoming scheduled flights between these two points.
The data returned has the airline, airport and schedule information - this is subject to change in future.
Args:
origin (str): The origin airport code
destination (str): The destination airport code
Returns:
A list of dicts, one for each scheduled flight between the two points.
Example::
from pyflightdata import FlightData
f=FlightData()
#optional login
f.login(myemail,mypassword)
f.get_flights_from_to('SIN','HYD') | [
"Get",
"the",
"flights",
"for",
"a",
"particular",
"origin",
"and",
"destination",
"."
] | 2caf9f429288f9a171893d1b8377d0c6244541cc | https://github.com/supercoderz/pyflightdata/blob/2caf9f429288f9a171893d1b8377d0c6244541cc/pyflightdata/flightdata.py#L217-L239 | train |
supercoderz/pyflightdata | pyflightdata/flightdata.py | FlightData.get_airport_weather | def get_airport_weather(self, iata, page=1, limit=100):
"""Retrieve the weather at an airport
Given the IATA code of an airport, this method returns the weather information.
Args:
iata (str): The IATA code for an airport, e.g. HYD
page (int): Optional page number; for users who are on a plan with flightradar24 they can pass in higher page numbers to get more data
limit (int): Optional limit on number of records returned
Returns:
A list of dicts with the data; one dict for each row of data from flightradar24
Example::
from pyflightdata import FlightData
f=FlightData()
#optional login
f.login(myemail,mypassword)
f.get_airport_weather('HYD')
f.get_airport_weather('HYD',page=1,limit=10)
"""
url = AIRPORT_DATA_BASE.format(iata, str(self.AUTH_TOKEN), page, limit)
weather = self._fr24.get_airport_weather(url)
mi = weather['sky']['visibility']['mi']
if (mi is not None) and (mi != "None"):
mi = float(mi)
km = mi * 1.6094
weather['sky']['visibility']['km'] = km
return weather | python | def get_airport_weather(self, iata, page=1, limit=100):
"""Retrieve the weather at an airport
Given the IATA code of an airport, this method returns the weather information.
Args:
iata (str): The IATA code for an airport, e.g. HYD
page (int): Optional page number; for users who are on a plan with flightradar24 they can pass in higher page numbers to get more data
limit (int): Optional limit on number of records returned
Returns:
A list of dicts with the data; one dict for each row of data from flightradar24
Example::
from pyflightdata import FlightData
f=FlightData()
#optional login
f.login(myemail,mypassword)
f.get_airport_weather('HYD')
f.get_airport_weather('HYD',page=1,limit=10)
"""
url = AIRPORT_DATA_BASE.format(iata, str(self.AUTH_TOKEN), page, limit)
weather = self._fr24.get_airport_weather(url)
mi = weather['sky']['visibility']['mi']
if (mi is not None) and (mi != "None"):
mi = float(mi)
km = mi * 1.6094
weather['sky']['visibility']['km'] = km
return weather | [
"def",
"get_airport_weather",
"(",
"self",
",",
"iata",
",",
"page",
"=",
"1",
",",
"limit",
"=",
"100",
")",
":",
"url",
"=",
"AIRPORT_DATA_BASE",
".",
"format",
"(",
"iata",
",",
"str",
"(",
"self",
".",
"AUTH_TOKEN",
")",
",",
"page",
",",
"limit",
")",
"weather",
"=",
"self",
".",
"_fr24",
".",
"get_airport_weather",
"(",
"url",
")",
"mi",
"=",
"weather",
"[",
"'sky'",
"]",
"[",
"'visibility'",
"]",
"[",
"'mi'",
"]",
"if",
"(",
"mi",
"is",
"not",
"None",
")",
"and",
"(",
"mi",
"!=",
"\"None\"",
")",
":",
"mi",
"=",
"float",
"(",
"mi",
")",
"km",
"=",
"mi",
"*",
"1.6094",
"weather",
"[",
"'sky'",
"]",
"[",
"'visibility'",
"]",
"[",
"'km'",
"]",
"=",
"km",
"return",
"weather"
] | Retrieve the weather at an airport
Given the IATA code of an airport, this method returns the weather information.
Args:
iata (str): The IATA code for an airport, e.g. HYD
page (int): Optional page number; for users who are on a plan with flightradar24 they can pass in higher page numbers to get more data
limit (int): Optional limit on number of records returned
Returns:
A list of dicts with the data; one dict for each row of data from flightradar24
Example::
from pyflightdata import FlightData
f=FlightData()
#optional login
f.login(myemail,mypassword)
f.get_airport_weather('HYD')
f.get_airport_weather('HYD',page=1,limit=10) | [
"Retrieve",
"the",
"weather",
"at",
"an",
"airport"
] | 2caf9f429288f9a171893d1b8377d0c6244541cc | https://github.com/supercoderz/pyflightdata/blob/2caf9f429288f9a171893d1b8377d0c6244541cc/pyflightdata/flightdata.py#L241-L271 | train |
supercoderz/pyflightdata | pyflightdata/flightdata.py | FlightData.get_airport_metars | def get_airport_metars(self, iata, page=1, limit=100):
"""Retrieve the metar data at the current time
Given the IATA code of an airport, this method returns the metar information.
Args:
iata (str): The IATA code for an airport, e.g. HYD
page (int): Optional page number; for users who are on a plan with flightradar24 they can pass in higher page numbers to get more data
limit (int): Optional limit on number of records returned
Returns:
The metar data for the airport
Example::
from pyflightdata import FlightData
f=FlightData()
#optional login
f.login(myemail,mypassword)
f.get_airport_metars('HYD')
"""
url = AIRPORT_DATA_BASE.format(iata, str(self.AUTH_TOKEN), page, limit)
w = self._fr24.get_airport_weather(url)
return w['metar'] | python | def get_airport_metars(self, iata, page=1, limit=100):
"""Retrieve the metar data at the current time
Given the IATA code of an airport, this method returns the metar information.
Args:
iata (str): The IATA code for an airport, e.g. HYD
page (int): Optional page number; for users who are on a plan with flightradar24 they can pass in higher page numbers to get more data
limit (int): Optional limit on number of records returned
Returns:
The metar data for the airport
Example::
from pyflightdata import FlightData
f=FlightData()
#optional login
f.login(myemail,mypassword)
f.get_airport_metars('HYD')
"""
url = AIRPORT_DATA_BASE.format(iata, str(self.AUTH_TOKEN), page, limit)
w = self._fr24.get_airport_weather(url)
return w['metar'] | [
"def",
"get_airport_metars",
"(",
"self",
",",
"iata",
",",
"page",
"=",
"1",
",",
"limit",
"=",
"100",
")",
":",
"url",
"=",
"AIRPORT_DATA_BASE",
".",
"format",
"(",
"iata",
",",
"str",
"(",
"self",
".",
"AUTH_TOKEN",
")",
",",
"page",
",",
"limit",
")",
"w",
"=",
"self",
".",
"_fr24",
".",
"get_airport_weather",
"(",
"url",
")",
"return",
"w",
"[",
"'metar'",
"]"
] | Retrieve the metar data at the current time
Given the IATA code of an airport, this method returns the metar information.
Args:
iata (str): The IATA code for an airport, e.g. HYD
page (int): Optional page number; for users who are on a plan with flightradar24 they can pass in higher page numbers to get more data
limit (int): Optional limit on number of records returned
Returns:
The metar data for the airport
Example::
from pyflightdata import FlightData
f=FlightData()
#optional login
f.login(myemail,mypassword)
f.get_airport_metars('HYD') | [
"Retrieve",
"the",
"metar",
"data",
"at",
"the",
"current",
"time"
] | 2caf9f429288f9a171893d1b8377d0c6244541cc | https://github.com/supercoderz/pyflightdata/blob/2caf9f429288f9a171893d1b8377d0c6244541cc/pyflightdata/flightdata.py#L273-L297 | train |
supercoderz/pyflightdata | pyflightdata/flightdata.py | FlightData.get_airport_metars_hist | def get_airport_metars_hist(self, iata):
"""Retrieve the metar data for past 72 hours. The data will not be parsed to readable format.
Given the IATA code of an airport, this method returns the metar information for last 72 hours.
Args:
iata (str): The IATA code for an airport, e.g. HYD
Returns:
The metar data for the airport
Example::
from pyflightdata import FlightData
f=FlightData()
#optional login
f.login(myemail,mypassword)
f.get_airport_metars_hist('HYD')
"""
url = AIRPORT_BASE.format(iata) + "/weather"
return self._fr24.get_airport_metars_hist(url) | python | def get_airport_metars_hist(self, iata):
"""Retrieve the metar data for past 72 hours. The data will not be parsed to readable format.
Given the IATA code of an airport, this method returns the metar information for last 72 hours.
Args:
iata (str): The IATA code for an airport, e.g. HYD
Returns:
The metar data for the airport
Example::
from pyflightdata import FlightData
f=FlightData()
#optional login
f.login(myemail,mypassword)
f.get_airport_metars_hist('HYD')
"""
url = AIRPORT_BASE.format(iata) + "/weather"
return self._fr24.get_airport_metars_hist(url) | [
"def",
"get_airport_metars_hist",
"(",
"self",
",",
"iata",
")",
":",
"url",
"=",
"AIRPORT_BASE",
".",
"format",
"(",
"iata",
")",
"+",
"\"/weather\"",
"return",
"self",
".",
"_fr24",
".",
"get_airport_metars_hist",
"(",
"url",
")"
] | Retrieve the metar data for past 72 hours. The data will not be parsed to readable format.
Given the IATA code of an airport, this method returns the metar information for last 72 hours.
Args:
iata (str): The IATA code for an airport, e.g. HYD
Returns:
The metar data for the airport
Example::
from pyflightdata import FlightData
f=FlightData()
#optional login
f.login(myemail,mypassword)
f.get_airport_metars_hist('HYD') | [
"Retrieve",
"the",
"metar",
"data",
"for",
"past",
"72",
"hours",
".",
"The",
"data",
"will",
"not",
"be",
"parsed",
"to",
"readable",
"format",
"."
] | 2caf9f429288f9a171893d1b8377d0c6244541cc | https://github.com/supercoderz/pyflightdata/blob/2caf9f429288f9a171893d1b8377d0c6244541cc/pyflightdata/flightdata.py#L299-L320 | train |
supercoderz/pyflightdata | pyflightdata/flightdata.py | FlightData.get_airport_stats | def get_airport_stats(self, iata, page=1, limit=100):
"""Retrieve the performance statistics at an airport
Given the IATA code of an airport, this method returns the performance statistics for the airport.
Args:
iata (str): The IATA code for an airport, e.g. HYD
page (int): Optional page number; for users who are on a plan with flightradar24 they can pass in higher page numbers to get more data
limit (int): Optional limit on number of records returned
Returns:
A list of dicts with the data; one dict for each row of data from flightradar24
Example::
from pyflightdata import FlightData
f=FlightData()
#optional login
f.login(myemail,mypassword)
f.get_airport_stats('HYD')
f.get_airport_stats('HYD',page=1,limit=10)
"""
url = AIRPORT_DATA_BASE.format(iata, str(self.AUTH_TOKEN), page, limit)
return self._fr24.get_airport_stats(url) | python | def get_airport_stats(self, iata, page=1, limit=100):
"""Retrieve the performance statistics at an airport
Given the IATA code of an airport, this method returns the performance statistics for the airport.
Args:
iata (str): The IATA code for an airport, e.g. HYD
page (int): Optional page number; for users who are on a plan with flightradar24 they can pass in higher page numbers to get more data
limit (int): Optional limit on number of records returned
Returns:
A list of dicts with the data; one dict for each row of data from flightradar24
Example::
from pyflightdata import FlightData
f=FlightData()
#optional login
f.login(myemail,mypassword)
f.get_airport_stats('HYD')
f.get_airport_stats('HYD',page=1,limit=10)
"""
url = AIRPORT_DATA_BASE.format(iata, str(self.AUTH_TOKEN), page, limit)
return self._fr24.get_airport_stats(url) | [
"def",
"get_airport_stats",
"(",
"self",
",",
"iata",
",",
"page",
"=",
"1",
",",
"limit",
"=",
"100",
")",
":",
"url",
"=",
"AIRPORT_DATA_BASE",
".",
"format",
"(",
"iata",
",",
"str",
"(",
"self",
".",
"AUTH_TOKEN",
")",
",",
"page",
",",
"limit",
")",
"return",
"self",
".",
"_fr24",
".",
"get_airport_stats",
"(",
"url",
")"
] | Retrieve the performance statistics at an airport
Given the IATA code of an airport, this method returns the performance statistics for the airport.
Args:
iata (str): The IATA code for an airport, e.g. HYD
page (int): Optional page number; for users who are on a plan with flightradar24 they can pass in higher page numbers to get more data
limit (int): Optional limit on number of records returned
Returns:
A list of dicts with the data; one dict for each row of data from flightradar24
Example::
from pyflightdata import FlightData
f=FlightData()
#optional login
f.login(myemail,mypassword)
f.get_airport_stats('HYD')
f.get_airport_stats('HYD',page=1,limit=10) | [
"Retrieve",
"the",
"performance",
"statistics",
"at",
"an",
"airport"
] | 2caf9f429288f9a171893d1b8377d0c6244541cc | https://github.com/supercoderz/pyflightdata/blob/2caf9f429288f9a171893d1b8377d0c6244541cc/pyflightdata/flightdata.py#L322-L346 | train |
supercoderz/pyflightdata | pyflightdata/flightdata.py | FlightData.get_airport_details | def get_airport_details(self, iata, page=1, limit=100):
"""Retrieve the details of an airport
Given the IATA code of an airport, this method returns the detailed information like lat lon, full name, URL, codes etc.
Args:
iata (str): The IATA code for an airport, e.g. HYD
page (int): Optional page number; for users who are on a plan with flightradar24 they can pass in higher page numbers to get more data
limit (int): Optional limit on number of records returned
Returns:
A list of dicts with the data; one dict for each row of data from flightradar24
Example::
from pyflightdata import FlightData
f=FlightData()
#optional login
f.login(myemail,mypassword)
f.get_airport_details('HYD')
f.get_airport_details('HYD',page=1,limit=10)
"""
url = AIRPORT_DATA_BASE.format(iata, str(self.AUTH_TOKEN), page, limit)
details = self._fr24.get_airport_details(url)
weather = self._fr24.get_airport_weather(url)
# weather has more correct and standard elevation details in feet and meters
details['position']['elevation'] = weather['elevation']
return details | python | def get_airport_details(self, iata, page=1, limit=100):
"""Retrieve the details of an airport
Given the IATA code of an airport, this method returns the detailed information like lat lon, full name, URL, codes etc.
Args:
iata (str): The IATA code for an airport, e.g. HYD
page (int): Optional page number; for users who are on a plan with flightradar24 they can pass in higher page numbers to get more data
limit (int): Optional limit on number of records returned
Returns:
A list of dicts with the data; one dict for each row of data from flightradar24
Example::
from pyflightdata import FlightData
f=FlightData()
#optional login
f.login(myemail,mypassword)
f.get_airport_details('HYD')
f.get_airport_details('HYD',page=1,limit=10)
"""
url = AIRPORT_DATA_BASE.format(iata, str(self.AUTH_TOKEN), page, limit)
details = self._fr24.get_airport_details(url)
weather = self._fr24.get_airport_weather(url)
# weather has more correct and standard elevation details in feet and meters
details['position']['elevation'] = weather['elevation']
return details | [
"def",
"get_airport_details",
"(",
"self",
",",
"iata",
",",
"page",
"=",
"1",
",",
"limit",
"=",
"100",
")",
":",
"url",
"=",
"AIRPORT_DATA_BASE",
".",
"format",
"(",
"iata",
",",
"str",
"(",
"self",
".",
"AUTH_TOKEN",
")",
",",
"page",
",",
"limit",
")",
"details",
"=",
"self",
".",
"_fr24",
".",
"get_airport_details",
"(",
"url",
")",
"weather",
"=",
"self",
".",
"_fr24",
".",
"get_airport_weather",
"(",
"url",
")",
"# weather has more correct and standard elevation details in feet and meters",
"details",
"[",
"'position'",
"]",
"[",
"'elevation'",
"]",
"=",
"weather",
"[",
"'elevation'",
"]",
"return",
"details"
] | Retrieve the details of an airport
Given the IATA code of an airport, this method returns the detailed information like lat lon, full name, URL, codes etc.
Args:
iata (str): The IATA code for an airport, e.g. HYD
page (int): Optional page number; for users who are on a plan with flightradar24 they can pass in higher page numbers to get more data
limit (int): Optional limit on number of records returned
Returns:
A list of dicts with the data; one dict for each row of data from flightradar24
Example::
from pyflightdata import FlightData
f=FlightData()
#optional login
f.login(myemail,mypassword)
f.get_airport_details('HYD')
f.get_airport_details('HYD',page=1,limit=10) | [
"Retrieve",
"the",
"details",
"of",
"an",
"airport"
] | 2caf9f429288f9a171893d1b8377d0c6244541cc | https://github.com/supercoderz/pyflightdata/blob/2caf9f429288f9a171893d1b8377d0c6244541cc/pyflightdata/flightdata.py#L348-L376 | train |
supercoderz/pyflightdata | pyflightdata/flightdata.py | FlightData.get_images_by_tail_number | def get_images_by_tail_number(self, tail_number, page=1, limit=100):
"""Fetch the images of a particular aircraft by its tail number.
This method can be used to get the images of the aircraft. The images are in 3 sizes and you can use what suits your need.
Args:
tail_number (str): The tail number, e.g. VT-ANL
page (int): Optional page number; for users who are on a plan with flightradar24 they can pass in higher page numbers to get more data
limit (int): Optional limit on number of records returned
Returns:
A dict with the images of the aircraft in various sizes
Example::
from pyflightdata import FlightData
f=FlightData()
#optional login
f.login(myemail,mypassword)
f.get_images_by_flight_number('VT-ANL')
f.get_images_by_flight_number('VT-ANL',page=1,limit=10)
"""
url = REG_BASE.format(tail_number, str(self.AUTH_TOKEN), page, limit)
return self._fr24.get_aircraft_image_data(url) | python | def get_images_by_tail_number(self, tail_number, page=1, limit=100):
"""Fetch the images of a particular aircraft by its tail number.
This method can be used to get the images of the aircraft. The images are in 3 sizes and you can use what suits your need.
Args:
tail_number (str): The tail number, e.g. VT-ANL
page (int): Optional page number; for users who are on a plan with flightradar24 they can pass in higher page numbers to get more data
limit (int): Optional limit on number of records returned
Returns:
A dict with the images of the aircraft in various sizes
Example::
from pyflightdata import FlightData
f=FlightData()
#optional login
f.login(myemail,mypassword)
f.get_images_by_flight_number('VT-ANL')
f.get_images_by_flight_number('VT-ANL',page=1,limit=10)
"""
url = REG_BASE.format(tail_number, str(self.AUTH_TOKEN), page, limit)
return self._fr24.get_aircraft_image_data(url) | [
"def",
"get_images_by_tail_number",
"(",
"self",
",",
"tail_number",
",",
"page",
"=",
"1",
",",
"limit",
"=",
"100",
")",
":",
"url",
"=",
"REG_BASE",
".",
"format",
"(",
"tail_number",
",",
"str",
"(",
"self",
".",
"AUTH_TOKEN",
")",
",",
"page",
",",
"limit",
")",
"return",
"self",
".",
"_fr24",
".",
"get_aircraft_image_data",
"(",
"url",
")"
] | Fetch the images of a particular aircraft by its tail number.
This method can be used to get the images of the aircraft. The images are in 3 sizes and you can use what suits your need.
Args:
tail_number (str): The tail number, e.g. VT-ANL
page (int): Optional page number; for users who are on a plan with flightradar24 they can pass in higher page numbers to get more data
limit (int): Optional limit on number of records returned
Returns:
A dict with the images of the aircraft in various sizes
Example::
from pyflightdata import FlightData
f=FlightData()
#optional login
f.login(myemail,mypassword)
f.get_images_by_flight_number('VT-ANL')
f.get_images_by_flight_number('VT-ANL',page=1,limit=10) | [
"Fetch",
"the",
"images",
"of",
"a",
"particular",
"aircraft",
"by",
"its",
"tail",
"number",
"."
] | 2caf9f429288f9a171893d1b8377d0c6244541cc | https://github.com/supercoderz/pyflightdata/blob/2caf9f429288f9a171893d1b8377d0c6244541cc/pyflightdata/flightdata.py#L482-L505 | train |
supercoderz/pyflightdata | pyflightdata/flightdata.py | FlightData.login | def login(self, email, password):
"""Login to the flightradar24 session
The API currently uses flightradar24 as the primary data source. The site provides different levels of data based on user plans.
For users who have signed up for a plan, this method allows to login with the credentials from flightradar24. The API obtains
a token that will be passed on all the requests; this obtains the data as per the plan limits.
Args:
email (str): The email ID which is used to login to flightradar24
password (str): The password for the user ID
Example::
from pyflightdata import FlightData
f=FlightData()
f.login(myemail,mypassword)
"""
response = FlightData.session.post(
url=LOGIN_URL,
data={
'email': email,
'password': password,
'remember': 'true',
'type': 'web'
},
headers={
'Origin': 'https://www.flightradar24.com',
'Referer': 'https://www.flightradar24.com',
'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:28.0) Gecko/20100101 Firefox/28.0'
}
)
response = self._fr24.json_loads_byteified(
response.content) if response.status_code == 200 else None
if response:
token = response['userData']['subscriptionKey']
self.AUTH_TOKEN = token | python | def login(self, email, password):
"""Login to the flightradar24 session
The API currently uses flightradar24 as the primary data source. The site provides different levels of data based on user plans.
For users who have signed up for a plan, this method allows to login with the credentials from flightradar24. The API obtains
a token that will be passed on all the requests; this obtains the data as per the plan limits.
Args:
email (str): The email ID which is used to login to flightradar24
password (str): The password for the user ID
Example::
from pyflightdata import FlightData
f=FlightData()
f.login(myemail,mypassword)
"""
response = FlightData.session.post(
url=LOGIN_URL,
data={
'email': email,
'password': password,
'remember': 'true',
'type': 'web'
},
headers={
'Origin': 'https://www.flightradar24.com',
'Referer': 'https://www.flightradar24.com',
'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:28.0) Gecko/20100101 Firefox/28.0'
}
)
response = self._fr24.json_loads_byteified(
response.content) if response.status_code == 200 else None
if response:
token = response['userData']['subscriptionKey']
self.AUTH_TOKEN = token | [
"def",
"login",
"(",
"self",
",",
"email",
",",
"password",
")",
":",
"response",
"=",
"FlightData",
".",
"session",
".",
"post",
"(",
"url",
"=",
"LOGIN_URL",
",",
"data",
"=",
"{",
"'email'",
":",
"email",
",",
"'password'",
":",
"password",
",",
"'remember'",
":",
"'true'",
",",
"'type'",
":",
"'web'",
"}",
",",
"headers",
"=",
"{",
"'Origin'",
":",
"'https://www.flightradar24.com'",
",",
"'Referer'",
":",
"'https://www.flightradar24.com'",
",",
"'User-Agent'",
":",
"'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:28.0) Gecko/20100101 Firefox/28.0'",
"}",
")",
"response",
"=",
"self",
".",
"_fr24",
".",
"json_loads_byteified",
"(",
"response",
".",
"content",
")",
"if",
"response",
".",
"status_code",
"==",
"200",
"else",
"None",
"if",
"response",
":",
"token",
"=",
"response",
"[",
"'userData'",
"]",
"[",
"'subscriptionKey'",
"]",
"self",
".",
"AUTH_TOKEN",
"=",
"token"
] | Login to the flightradar24 session
The API currently uses flightradar24 as the primary data source. The site provides different levels of data based on user plans.
For users who have signed up for a plan, this method allows to login with the credentials from flightradar24. The API obtains
a token that will be passed on all the requests; this obtains the data as per the plan limits.
Args:
email (str): The email ID which is used to login to flightradar24
password (str): The password for the user ID
Example::
from pyflightdata import FlightData
f=FlightData()
f.login(myemail,mypassword) | [
"Login",
"to",
"the",
"flightradar24",
"session"
] | 2caf9f429288f9a171893d1b8377d0c6244541cc | https://github.com/supercoderz/pyflightdata/blob/2caf9f429288f9a171893d1b8377d0c6244541cc/pyflightdata/flightdata.py#L507-L543 | train |
supercoderz/pyflightdata | pyflightdata/flightdata.py | FlightData.decode_metar | def decode_metar(self, metar):
"""
Simple method that decodes a given metar string.
Args:
metar (str): The metar data
Returns:
The metar data in readable format
Example::
from pyflightdata import FlightData
f=FlightData()
f.decode_metar('WSSS 181030Z 04009KT 010V080 9999 FEW018TCU BKN300 29/22 Q1007 NOSIG')
"""
try:
from metar import Metar
except:
return "Unable to parse metars. Please install parser from https://github.com/tomp/python-metar."
m = Metar.Metar(metar)
return m.string() | python | def decode_metar(self, metar):
"""
Simple method that decodes a given metar string.
Args:
metar (str): The metar data
Returns:
The metar data in readable format
Example::
from pyflightdata import FlightData
f=FlightData()
f.decode_metar('WSSS 181030Z 04009KT 010V080 9999 FEW018TCU BKN300 29/22 Q1007 NOSIG')
"""
try:
from metar import Metar
except:
return "Unable to parse metars. Please install parser from https://github.com/tomp/python-metar."
m = Metar.Metar(metar)
return m.string() | [
"def",
"decode_metar",
"(",
"self",
",",
"metar",
")",
":",
"try",
":",
"from",
"metar",
"import",
"Metar",
"except",
":",
"return",
"\"Unable to parse metars. Please install parser from https://github.com/tomp/python-metar.\"",
"m",
"=",
"Metar",
".",
"Metar",
"(",
"metar",
")",
"return",
"m",
".",
"string",
"(",
")"
] | Simple method that decodes a given metar string.
Args:
metar (str): The metar data
Returns:
The metar data in readable format
Example::
from pyflightdata import FlightData
f=FlightData()
f.decode_metar('WSSS 181030Z 04009KT 010V080 9999 FEW018TCU BKN300 29/22 Q1007 NOSIG') | [
"Simple",
"method",
"that",
"decodes",
"a",
"given",
"metar",
"string",
"."
] | 2caf9f429288f9a171893d1b8377d0c6244541cc | https://github.com/supercoderz/pyflightdata/blob/2caf9f429288f9a171893d1b8377d0c6244541cc/pyflightdata/flightdata.py#L556-L577 | train |
robgolding/django-radius | radiusauth/backends/radius.py | RADIUSBackend._get_auth_packet | def _get_auth_packet(self, username, password, client):
"""
Get the pyrad authentication packet for the username/password and the
given pyrad client.
"""
pkt = client.CreateAuthPacket(code=AccessRequest,
User_Name=username)
pkt["User-Password"] = pkt.PwCrypt(password)
pkt["NAS-Identifier"] = 'django-radius'
for key, val in list(getattr(settings, 'RADIUS_ATTRIBUTES', {}).items()):
pkt[key] = val
return pkt | python | def _get_auth_packet(self, username, password, client):
"""
Get the pyrad authentication packet for the username/password and the
given pyrad client.
"""
pkt = client.CreateAuthPacket(code=AccessRequest,
User_Name=username)
pkt["User-Password"] = pkt.PwCrypt(password)
pkt["NAS-Identifier"] = 'django-radius'
for key, val in list(getattr(settings, 'RADIUS_ATTRIBUTES', {}).items()):
pkt[key] = val
return pkt | [
"def",
"_get_auth_packet",
"(",
"self",
",",
"username",
",",
"password",
",",
"client",
")",
":",
"pkt",
"=",
"client",
".",
"CreateAuthPacket",
"(",
"code",
"=",
"AccessRequest",
",",
"User_Name",
"=",
"username",
")",
"pkt",
"[",
"\"User-Password\"",
"]",
"=",
"pkt",
".",
"PwCrypt",
"(",
"password",
")",
"pkt",
"[",
"\"NAS-Identifier\"",
"]",
"=",
"'django-radius'",
"for",
"key",
",",
"val",
"in",
"list",
"(",
"getattr",
"(",
"settings",
",",
"'RADIUS_ATTRIBUTES'",
",",
"{",
"}",
")",
".",
"items",
"(",
")",
")",
":",
"pkt",
"[",
"key",
"]",
"=",
"val",
"return",
"pkt"
] | Get the pyrad authentication packet for the username/password and the
given pyrad client. | [
"Get",
"the",
"pyrad",
"authentication",
"packet",
"for",
"the",
"username",
"/",
"password",
"and",
"the",
"given",
"pyrad",
"client",
"."
] | 5b90f4ae4cbd680988197386d882491317e6b20c | https://github.com/robgolding/django-radius/blob/5b90f4ae4cbd680988197386d882491317e6b20c/radiusauth/backends/radius.py#L75-L86 | train |
robgolding/django-radius | radiusauth/backends/radius.py | RADIUSBackend._get_client | def _get_client(self, server):
"""
Get the pyrad client for a given server. RADIUS server is described by
a 3-tuple: (<hostname>, <port>, <secret>).
"""
return Client(
server=server[0],
authport=server[1],
secret=server[2],
dict=self._get_dictionary(),
) | python | def _get_client(self, server):
"""
Get the pyrad client for a given server. RADIUS server is described by
a 3-tuple: (<hostname>, <port>, <secret>).
"""
return Client(
server=server[0],
authport=server[1],
secret=server[2],
dict=self._get_dictionary(),
) | [
"def",
"_get_client",
"(",
"self",
",",
"server",
")",
":",
"return",
"Client",
"(",
"server",
"=",
"server",
"[",
"0",
"]",
",",
"authport",
"=",
"server",
"[",
"1",
"]",
",",
"secret",
"=",
"server",
"[",
"2",
"]",
",",
"dict",
"=",
"self",
".",
"_get_dictionary",
"(",
")",
",",
")"
] | Get the pyrad client for a given server. RADIUS server is described by
a 3-tuple: (<hostname>, <port>, <secret>). | [
"Get",
"the",
"pyrad",
"client",
"for",
"a",
"given",
"server",
".",
"RADIUS",
"server",
"is",
"described",
"by",
"a",
"3",
"-",
"tuple",
":",
"(",
"<hostname",
">",
"<port",
">",
"<secret",
">",
")",
"."
] | 5b90f4ae4cbd680988197386d882491317e6b20c | https://github.com/robgolding/django-radius/blob/5b90f4ae4cbd680988197386d882491317e6b20c/radiusauth/backends/radius.py#L88-L98 | train |
robgolding/django-radius | radiusauth/backends/radius.py | RADIUSBackend._perform_radius_auth | def _perform_radius_auth(self, client, packet):
"""
Perform the actual radius authentication by passing the given packet
to the server which `client` is bound to.
Returns True or False depending on whether the user is authenticated
successfully.
"""
try:
reply = client.SendPacket(packet)
except Timeout as e:
logging.error("RADIUS timeout occurred contacting %s:%s" % (
client.server, client.authport))
return False
except Exception as e:
logging.error("RADIUS error: %s" % e)
return False
if reply.code == AccessReject:
logging.warning("RADIUS access rejected for user '%s'" % (
packet['User-Name']))
return False
elif reply.code != AccessAccept:
logging.error("RADIUS access error for user '%s' (code %s)" % (
packet['User-Name'], reply.code))
return False
logging.info("RADIUS access granted for user '%s'" % (
packet['User-Name']))
return True | python | def _perform_radius_auth(self, client, packet):
"""
Perform the actual radius authentication by passing the given packet
to the server which `client` is bound to.
Returns True or False depending on whether the user is authenticated
successfully.
"""
try:
reply = client.SendPacket(packet)
except Timeout as e:
logging.error("RADIUS timeout occurred contacting %s:%s" % (
client.server, client.authport))
return False
except Exception as e:
logging.error("RADIUS error: %s" % e)
return False
if reply.code == AccessReject:
logging.warning("RADIUS access rejected for user '%s'" % (
packet['User-Name']))
return False
elif reply.code != AccessAccept:
logging.error("RADIUS access error for user '%s' (code %s)" % (
packet['User-Name'], reply.code))
return False
logging.info("RADIUS access granted for user '%s'" % (
packet['User-Name']))
return True | [
"def",
"_perform_radius_auth",
"(",
"self",
",",
"client",
",",
"packet",
")",
":",
"try",
":",
"reply",
"=",
"client",
".",
"SendPacket",
"(",
"packet",
")",
"except",
"Timeout",
"as",
"e",
":",
"logging",
".",
"error",
"(",
"\"RADIUS timeout occurred contacting %s:%s\"",
"%",
"(",
"client",
".",
"server",
",",
"client",
".",
"authport",
")",
")",
"return",
"False",
"except",
"Exception",
"as",
"e",
":",
"logging",
".",
"error",
"(",
"\"RADIUS error: %s\"",
"%",
"e",
")",
"return",
"False",
"if",
"reply",
".",
"code",
"==",
"AccessReject",
":",
"logging",
".",
"warning",
"(",
"\"RADIUS access rejected for user '%s'\"",
"%",
"(",
"packet",
"[",
"'User-Name'",
"]",
")",
")",
"return",
"False",
"elif",
"reply",
".",
"code",
"!=",
"AccessAccept",
":",
"logging",
".",
"error",
"(",
"\"RADIUS access error for user '%s' (code %s)\"",
"%",
"(",
"packet",
"[",
"'User-Name'",
"]",
",",
"reply",
".",
"code",
")",
")",
"return",
"False",
"logging",
".",
"info",
"(",
"\"RADIUS access granted for user '%s'\"",
"%",
"(",
"packet",
"[",
"'User-Name'",
"]",
")",
")",
"return",
"True"
] | Perform the actual radius authentication by passing the given packet
to the server which `client` is bound to.
Returns True or False depending on whether the user is authenticated
successfully. | [
"Perform",
"the",
"actual",
"radius",
"authentication",
"by",
"passing",
"the",
"given",
"packet",
"to",
"the",
"server",
"which",
"client",
"is",
"bound",
"to",
".",
"Returns",
"True",
"or",
"False",
"depending",
"on",
"whether",
"the",
"user",
"is",
"authenticated",
"successfully",
"."
] | 5b90f4ae4cbd680988197386d882491317e6b20c | https://github.com/robgolding/django-radius/blob/5b90f4ae4cbd680988197386d882491317e6b20c/radiusauth/backends/radius.py#L110-L138 | train |
robgolding/django-radius | radiusauth/backends/radius.py | RADIUSBackend._radius_auth | def _radius_auth(self, server, username, password):
"""
Authenticate the given username/password against the RADIUS server
described by `server`.
"""
client = self._get_client(server)
packet = self._get_auth_packet(username, password, client)
return self._perform_radius_auth(client, packet) | python | def _radius_auth(self, server, username, password):
"""
Authenticate the given username/password against the RADIUS server
described by `server`.
"""
client = self._get_client(server)
packet = self._get_auth_packet(username, password, client)
return self._perform_radius_auth(client, packet) | [
"def",
"_radius_auth",
"(",
"self",
",",
"server",
",",
"username",
",",
"password",
")",
":",
"client",
"=",
"self",
".",
"_get_client",
"(",
"server",
")",
"packet",
"=",
"self",
".",
"_get_auth_packet",
"(",
"username",
",",
"password",
",",
"client",
")",
"return",
"self",
".",
"_perform_radius_auth",
"(",
"client",
",",
"packet",
")"
] | Authenticate the given username/password against the RADIUS server
described by `server`. | [
"Authenticate",
"the",
"given",
"username",
"/",
"password",
"against",
"the",
"RADIUS",
"server",
"described",
"by",
"server",
"."
] | 5b90f4ae4cbd680988197386d882491317e6b20c | https://github.com/robgolding/django-radius/blob/5b90f4ae4cbd680988197386d882491317e6b20c/radiusauth/backends/radius.py#L140-L147 | train |
robgolding/django-radius | radiusauth/backends/radius.py | RADIUSBackend.get_django_user | def get_django_user(self, username, password=None):
"""
Get the Django user with the given username, or create one if it
doesn't already exist. If `password` is given, then set the user's
password to that (regardless of whether the user was created or not).
"""
try:
user = User.objects.get(username=username)
except User.DoesNotExist:
user = User(username=username)
if password is not None:
user.set_password(password)
user.save()
return user | python | def get_django_user(self, username, password=None):
"""
Get the Django user with the given username, or create one if it
doesn't already exist. If `password` is given, then set the user's
password to that (regardless of whether the user was created or not).
"""
try:
user = User.objects.get(username=username)
except User.DoesNotExist:
user = User(username=username)
if password is not None:
user.set_password(password)
user.save()
return user | [
"def",
"get_django_user",
"(",
"self",
",",
"username",
",",
"password",
"=",
"None",
")",
":",
"try",
":",
"user",
"=",
"User",
".",
"objects",
".",
"get",
"(",
"username",
"=",
"username",
")",
"except",
"User",
".",
"DoesNotExist",
":",
"user",
"=",
"User",
"(",
"username",
"=",
"username",
")",
"if",
"password",
"is",
"not",
"None",
":",
"user",
".",
"set_password",
"(",
"password",
")",
"user",
".",
"save",
"(",
")",
"return",
"user"
] | Get the Django user with the given username, or create one if it
doesn't already exist. If `password` is given, then set the user's
password to that (regardless of whether the user was created or not). | [
"Get",
"the",
"Django",
"user",
"with",
"the",
"given",
"username",
"or",
"create",
"one",
"if",
"it",
"doesn",
"t",
"already",
"exist",
".",
"If",
"password",
"is",
"given",
"then",
"set",
"the",
"user",
"s",
"password",
"to",
"that",
"(",
"regardless",
"of",
"whether",
"the",
"user",
"was",
"created",
"or",
"not",
")",
"."
] | 5b90f4ae4cbd680988197386d882491317e6b20c | https://github.com/robgolding/django-radius/blob/5b90f4ae4cbd680988197386d882491317e6b20c/radiusauth/backends/radius.py#L149-L164 | train |
robgolding/django-radius | radiusauth/backends/radius.py | RADIUSBackend.authenticate | def authenticate(self, request, username=None, password=None):
"""
Check credentials against RADIUS server and return a User object or
None.
"""
if isinstance(username, basestring):
username = username.encode('utf-8')
if isinstance(password, basestring):
password = password.encode('utf-8')
server = self._get_server_from_settings()
result = self._radius_auth(server, username, password)
if result:
return self.get_django_user(username, password)
return None | python | def authenticate(self, request, username=None, password=None):
"""
Check credentials against RADIUS server and return a User object or
None.
"""
if isinstance(username, basestring):
username = username.encode('utf-8')
if isinstance(password, basestring):
password = password.encode('utf-8')
server = self._get_server_from_settings()
result = self._radius_auth(server, username, password)
if result:
return self.get_django_user(username, password)
return None | [
"def",
"authenticate",
"(",
"self",
",",
"request",
",",
"username",
"=",
"None",
",",
"password",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"username",
",",
"basestring",
")",
":",
"username",
"=",
"username",
".",
"encode",
"(",
"'utf-8'",
")",
"if",
"isinstance",
"(",
"password",
",",
"basestring",
")",
":",
"password",
"=",
"password",
".",
"encode",
"(",
"'utf-8'",
")",
"server",
"=",
"self",
".",
"_get_server_from_settings",
"(",
")",
"result",
"=",
"self",
".",
"_radius_auth",
"(",
"server",
",",
"username",
",",
"password",
")",
"if",
"result",
":",
"return",
"self",
".",
"get_django_user",
"(",
"username",
",",
"password",
")",
"return",
"None"
] | Check credentials against RADIUS server and return a User object or
None. | [
"Check",
"credentials",
"against",
"RADIUS",
"server",
"and",
"return",
"a",
"User",
"object",
"or",
"None",
"."
] | 5b90f4ae4cbd680988197386d882491317e6b20c | https://github.com/robgolding/django-radius/blob/5b90f4ae4cbd680988197386d882491317e6b20c/radiusauth/backends/radius.py#L166-L183 | train |
robgolding/django-radius | radiusauth/backends/radius.py | RADIUSRealmBackend.authenticate | def authenticate(self, request, username=None, password=None, realm=None):
"""
Check credentials against the RADIUS server identified by `realm` and
return a User object or None. If no argument is supplied, Django will
skip this backend and try the next one (as a TypeError will be raised
and caught).
"""
if isinstance(username, basestring):
username = username.encode('utf-8')
if isinstance(password, basestring):
password = password.encode('utf-8')
server = self.get_server(realm)
if not server:
return None
result = self._radius_auth(server, username, password)
if result:
full_username = self.construct_full_username(username, realm)
return self.get_django_user(full_username, password)
return None | python | def authenticate(self, request, username=None, password=None, realm=None):
"""
Check credentials against the RADIUS server identified by `realm` and
return a User object or None. If no argument is supplied, Django will
skip this backend and try the next one (as a TypeError will be raised
and caught).
"""
if isinstance(username, basestring):
username = username.encode('utf-8')
if isinstance(password, basestring):
password = password.encode('utf-8')
server = self.get_server(realm)
if not server:
return None
result = self._radius_auth(server, username, password)
if result:
full_username = self.construct_full_username(username, realm)
return self.get_django_user(full_username, password)
return None | [
"def",
"authenticate",
"(",
"self",
",",
"request",
",",
"username",
"=",
"None",
",",
"password",
"=",
"None",
",",
"realm",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"username",
",",
"basestring",
")",
":",
"username",
"=",
"username",
".",
"encode",
"(",
"'utf-8'",
")",
"if",
"isinstance",
"(",
"password",
",",
"basestring",
")",
":",
"password",
"=",
"password",
".",
"encode",
"(",
"'utf-8'",
")",
"server",
"=",
"self",
".",
"get_server",
"(",
"realm",
")",
"if",
"not",
"server",
":",
"return",
"None",
"result",
"=",
"self",
".",
"_radius_auth",
"(",
"server",
",",
"username",
",",
"password",
")",
"if",
"result",
":",
"full_username",
"=",
"self",
".",
"construct_full_username",
"(",
"username",
",",
"realm",
")",
"return",
"self",
".",
"get_django_user",
"(",
"full_username",
",",
"password",
")",
"return",
"None"
] | Check credentials against the RADIUS server identified by `realm` and
return a User object or None. If no argument is supplied, Django will
skip this backend and try the next one (as a TypeError will be raised
and caught). | [
"Check",
"credentials",
"against",
"the",
"RADIUS",
"server",
"identified",
"by",
"realm",
"and",
"return",
"a",
"User",
"object",
"or",
"None",
".",
"If",
"no",
"argument",
"is",
"supplied",
"Django",
"will",
"skip",
"this",
"backend",
"and",
"try",
"the",
"next",
"one",
"(",
"as",
"a",
"TypeError",
"will",
"be",
"raised",
"and",
"caught",
")",
"."
] | 5b90f4ae4cbd680988197386d882491317e6b20c | https://github.com/robgolding/django-radius/blob/5b90f4ae4cbd680988197386d882491317e6b20c/radiusauth/backends/radius.py#L229-L253 | train |
smartfile/django-transfer | django_transfer/__init__.py | ProxyUploadedFile.move | def move(self, dst):
"Closes then moves the file to dst."
self.close()
shutil.move(self.path, dst) | python | def move(self, dst):
"Closes then moves the file to dst."
self.close()
shutil.move(self.path, dst) | [
"def",
"move",
"(",
"self",
",",
"dst",
")",
":",
"self",
".",
"close",
"(",
")",
"shutil",
".",
"move",
"(",
"self",
".",
"path",
",",
"dst",
")"
] | Closes then moves the file to dst. | [
"Closes",
"then",
"moves",
"the",
"file",
"to",
"dst",
"."
] | 65ef60e011c1b98d7f5a195debd81b3efde897dd | https://github.com/smartfile/django-transfer/blob/65ef60e011c1b98d7f5a195debd81b3efde897dd/django_transfer/__init__.py#L110-L113 | train |
dwkim78/upsilon | upsilon/utils/utils.py | sigma_clipping | def sigma_clipping(date, mag, err, threshold=3, iteration=1):
"""
Remove any fluctuated data points by magnitudes.
Parameters
----------
date : array_like
An array of dates.
mag : array_like
An array of magnitudes.
err : array_like
An array of magnitude errors.
threshold : float, optional
Threshold for sigma-clipping.
iteration : int, optional
The number of iteration.
Returns
-------
date : array_like
Sigma-clipped dates.
mag : array_like
Sigma-clipped magnitudes.
err : array_like
Sigma-clipped magnitude errors.
"""
# Check length.
if (len(date) != len(mag)) \
or (len(date) != len(err)) \
or (len(mag) != len(err)):
raise RuntimeError('The length of date, mag, and err must be same.')
# By magnitudes
for i in range(int(iteration)):
mean = np.median(mag)
std = np.std(mag)
index = (mag >= mean - threshold*std) & (mag <= mean + threshold*std)
date = date[index]
mag = mag[index]
err = err[index]
return date, mag, err | python | def sigma_clipping(date, mag, err, threshold=3, iteration=1):
"""
Remove any fluctuated data points by magnitudes.
Parameters
----------
date : array_like
An array of dates.
mag : array_like
An array of magnitudes.
err : array_like
An array of magnitude errors.
threshold : float, optional
Threshold for sigma-clipping.
iteration : int, optional
The number of iteration.
Returns
-------
date : array_like
Sigma-clipped dates.
mag : array_like
Sigma-clipped magnitudes.
err : array_like
Sigma-clipped magnitude errors.
"""
# Check length.
if (len(date) != len(mag)) \
or (len(date) != len(err)) \
or (len(mag) != len(err)):
raise RuntimeError('The length of date, mag, and err must be same.')
# By magnitudes
for i in range(int(iteration)):
mean = np.median(mag)
std = np.std(mag)
index = (mag >= mean - threshold*std) & (mag <= mean + threshold*std)
date = date[index]
mag = mag[index]
err = err[index]
return date, mag, err | [
"def",
"sigma_clipping",
"(",
"date",
",",
"mag",
",",
"err",
",",
"threshold",
"=",
"3",
",",
"iteration",
"=",
"1",
")",
":",
"# Check length.",
"if",
"(",
"len",
"(",
"date",
")",
"!=",
"len",
"(",
"mag",
")",
")",
"or",
"(",
"len",
"(",
"date",
")",
"!=",
"len",
"(",
"err",
")",
")",
"or",
"(",
"len",
"(",
"mag",
")",
"!=",
"len",
"(",
"err",
")",
")",
":",
"raise",
"RuntimeError",
"(",
"'The length of date, mag, and err must be same.'",
")",
"# By magnitudes",
"for",
"i",
"in",
"range",
"(",
"int",
"(",
"iteration",
")",
")",
":",
"mean",
"=",
"np",
".",
"median",
"(",
"mag",
")",
"std",
"=",
"np",
".",
"std",
"(",
"mag",
")",
"index",
"=",
"(",
"mag",
">=",
"mean",
"-",
"threshold",
"*",
"std",
")",
"&",
"(",
"mag",
"<=",
"mean",
"+",
"threshold",
"*",
"std",
")",
"date",
"=",
"date",
"[",
"index",
"]",
"mag",
"=",
"mag",
"[",
"index",
"]",
"err",
"=",
"err",
"[",
"index",
"]",
"return",
"date",
",",
"mag",
",",
"err"
] | Remove any fluctuated data points by magnitudes.
Parameters
----------
date : array_like
An array of dates.
mag : array_like
An array of magnitudes.
err : array_like
An array of magnitude errors.
threshold : float, optional
Threshold for sigma-clipping.
iteration : int, optional
The number of iteration.
Returns
-------
date : array_like
Sigma-clipped dates.
mag : array_like
Sigma-clipped magnitudes.
err : array_like
Sigma-clipped magnitude errors. | [
"Remove",
"any",
"fluctuated",
"data",
"points",
"by",
"magnitudes",
"."
] | 5f381453f26582ef56e62fb8fed7317ce67861af | https://github.com/dwkim78/upsilon/blob/5f381453f26582ef56e62fb8fed7317ce67861af/upsilon/utils/utils.py#L4-L47 | train |
rix0rrr/gcl | gcl/schema.py | from_spec | def from_spec(spec):
"""Return a schema object from a spec.
A spec is either a string for a scalar type, or a list of 0 or 1 specs,
or a dictionary with two elements: {'fields': { ... }, required: [...]}.
"""
if spec == '':
return any_schema
if framework.is_str(spec):
# Scalar type
if spec not in SCALAR_TYPES:
raise exceptions.SchemaError('Not a valid schema type: %r' % spec)
return ScalarSchema(spec)
if framework.is_list(spec):
return ListSchema(spec[0] if len(spec) else any_schema)
if framework.is_tuple(spec):
return TupleSchema(spec.get('fields', {}), spec.get('required', []))
raise exceptions.SchemaError('Not valid schema spec; %r' % spec) | python | def from_spec(spec):
"""Return a schema object from a spec.
A spec is either a string for a scalar type, or a list of 0 or 1 specs,
or a dictionary with two elements: {'fields': { ... }, required: [...]}.
"""
if spec == '':
return any_schema
if framework.is_str(spec):
# Scalar type
if spec not in SCALAR_TYPES:
raise exceptions.SchemaError('Not a valid schema type: %r' % spec)
return ScalarSchema(spec)
if framework.is_list(spec):
return ListSchema(spec[0] if len(spec) else any_schema)
if framework.is_tuple(spec):
return TupleSchema(spec.get('fields', {}), spec.get('required', []))
raise exceptions.SchemaError('Not valid schema spec; %r' % spec) | [
"def",
"from_spec",
"(",
"spec",
")",
":",
"if",
"spec",
"==",
"''",
":",
"return",
"any_schema",
"if",
"framework",
".",
"is_str",
"(",
"spec",
")",
":",
"# Scalar type",
"if",
"spec",
"not",
"in",
"SCALAR_TYPES",
":",
"raise",
"exceptions",
".",
"SchemaError",
"(",
"'Not a valid schema type: %r'",
"%",
"spec",
")",
"return",
"ScalarSchema",
"(",
"spec",
")",
"if",
"framework",
".",
"is_list",
"(",
"spec",
")",
":",
"return",
"ListSchema",
"(",
"spec",
"[",
"0",
"]",
"if",
"len",
"(",
"spec",
")",
"else",
"any_schema",
")",
"if",
"framework",
".",
"is_tuple",
"(",
"spec",
")",
":",
"return",
"TupleSchema",
"(",
"spec",
".",
"get",
"(",
"'fields'",
",",
"{",
"}",
")",
",",
"spec",
".",
"get",
"(",
"'required'",
",",
"[",
"]",
")",
")",
"raise",
"exceptions",
".",
"SchemaError",
"(",
"'Not valid schema spec; %r'",
"%",
"spec",
")"
] | Return a schema object from a spec.
A spec is either a string for a scalar type, or a list of 0 or 1 specs,
or a dictionary with two elements: {'fields': { ... }, required: [...]}. | [
"Return",
"a",
"schema",
"object",
"from",
"a",
"spec",
"."
] | 4e3bccc978a9c60aaaffd20f6f291c4d23775cdf | https://github.com/rix0rrr/gcl/blob/4e3bccc978a9c60aaaffd20f6f291c4d23775cdf/gcl/schema.py#L178-L199 | train |
rix0rrr/gcl | gcl/schema.py | validate | def validate(obj, schema):
"""Validate an object according to its own AND an externally imposed schema."""
if not framework.EvaluationContext.current().validate:
# Short circuit evaluation when disabled
return obj
# Validate returned object according to its own schema
if hasattr(obj, 'tuple_schema'):
obj.tuple_schema.validate(obj)
# Validate object according to externally imposed schema
if schema:
schema.validate(obj)
return obj | python | def validate(obj, schema):
"""Validate an object according to its own AND an externally imposed schema."""
if not framework.EvaluationContext.current().validate:
# Short circuit evaluation when disabled
return obj
# Validate returned object according to its own schema
if hasattr(obj, 'tuple_schema'):
obj.tuple_schema.validate(obj)
# Validate object according to externally imposed schema
if schema:
schema.validate(obj)
return obj | [
"def",
"validate",
"(",
"obj",
",",
"schema",
")",
":",
"if",
"not",
"framework",
".",
"EvaluationContext",
".",
"current",
"(",
")",
".",
"validate",
":",
"# Short circuit evaluation when disabled",
"return",
"obj",
"# Validate returned object according to its own schema",
"if",
"hasattr",
"(",
"obj",
",",
"'tuple_schema'",
")",
":",
"obj",
".",
"tuple_schema",
".",
"validate",
"(",
"obj",
")",
"# Validate object according to externally imposed schema",
"if",
"schema",
":",
"schema",
".",
"validate",
"(",
"obj",
")",
"return",
"obj"
] | Validate an object according to its own AND an externally imposed schema. | [
"Validate",
"an",
"object",
"according",
"to",
"its",
"own",
"AND",
"an",
"externally",
"imposed",
"schema",
"."
] | 4e3bccc978a9c60aaaffd20f6f291c4d23775cdf | https://github.com/rix0rrr/gcl/blob/4e3bccc978a9c60aaaffd20f6f291c4d23775cdf/gcl/schema.py#L208-L220 | train |
rix0rrr/gcl | gcl/schema.py | attach | def attach(obj, schema):
"""Attach the given schema to the given object."""
# We have a silly exception for lists, since they have no 'attach_schema'
# method, and I don't feel like making a subclass for List just to add it.
# So, we recursively search the list for tuples and attach the schema in
# there.
if framework.is_list(obj) and isinstance(schema, ListSchema):
for x in obj:
attach(x, schema.element_schema)
return
# Otherwise, the object should be able to handle its own schema attachment.
getattr(obj, 'attach_schema', nop)(schema) | python | def attach(obj, schema):
"""Attach the given schema to the given object."""
# We have a silly exception for lists, since they have no 'attach_schema'
# method, and I don't feel like making a subclass for List just to add it.
# So, we recursively search the list for tuples and attach the schema in
# there.
if framework.is_list(obj) and isinstance(schema, ListSchema):
for x in obj:
attach(x, schema.element_schema)
return
# Otherwise, the object should be able to handle its own schema attachment.
getattr(obj, 'attach_schema', nop)(schema) | [
"def",
"attach",
"(",
"obj",
",",
"schema",
")",
":",
"# We have a silly exception for lists, since they have no 'attach_schema'",
"# method, and I don't feel like making a subclass for List just to add it.",
"# So, we recursively search the list for tuples and attach the schema in",
"# there.",
"if",
"framework",
".",
"is_list",
"(",
"obj",
")",
"and",
"isinstance",
"(",
"schema",
",",
"ListSchema",
")",
":",
"for",
"x",
"in",
"obj",
":",
"attach",
"(",
"x",
",",
"schema",
".",
"element_schema",
")",
"return",
"# Otherwise, the object should be able to handle its own schema attachment.",
"getattr",
"(",
"obj",
",",
"'attach_schema'",
",",
"nop",
")",
"(",
"schema",
")"
] | Attach the given schema to the given object. | [
"Attach",
"the",
"given",
"schema",
"to",
"the",
"given",
"object",
"."
] | 4e3bccc978a9c60aaaffd20f6f291c4d23775cdf | https://github.com/rix0rrr/gcl/blob/4e3bccc978a9c60aaaffd20f6f291c4d23775cdf/gcl/schema.py#L223-L236 | train |
dwkim78/upsilon | upsilon/extract_features/feature_set.py | get_feature_set_all | def get_feature_set_all():
"""
Return a list of entire features.
A set of entire features regardless of being used to train a model or
predict a class.
Returns
-------
feature_names : list
A list of features' names.
"""
features = get_feature_set()
features.append('cusum')
features.append('eta')
features.append('n_points')
features.append('period_SNR')
features.append('period_log10FAP')
features.append('period_uncertainty')
features.append('weighted_mean')
features.append('weighted_std')
features.sort()
return features | python | def get_feature_set_all():
"""
Return a list of entire features.
A set of entire features regardless of being used to train a model or
predict a class.
Returns
-------
feature_names : list
A list of features' names.
"""
features = get_feature_set()
features.append('cusum')
features.append('eta')
features.append('n_points')
features.append('period_SNR')
features.append('period_log10FAP')
features.append('period_uncertainty')
features.append('weighted_mean')
features.append('weighted_std')
features.sort()
return features | [
"def",
"get_feature_set_all",
"(",
")",
":",
"features",
"=",
"get_feature_set",
"(",
")",
"features",
".",
"append",
"(",
"'cusum'",
")",
"features",
".",
"append",
"(",
"'eta'",
")",
"features",
".",
"append",
"(",
"'n_points'",
")",
"features",
".",
"append",
"(",
"'period_SNR'",
")",
"features",
".",
"append",
"(",
"'period_log10FAP'",
")",
"features",
".",
"append",
"(",
"'period_uncertainty'",
")",
"features",
".",
"append",
"(",
"'weighted_mean'",
")",
"features",
".",
"append",
"(",
"'weighted_std'",
")",
"features",
".",
"sort",
"(",
")",
"return",
"features"
] | Return a list of entire features.
A set of entire features regardless of being used to train a model or
predict a class.
Returns
-------
feature_names : list
A list of features' names. | [
"Return",
"a",
"list",
"of",
"entire",
"features",
"."
] | 5f381453f26582ef56e62fb8fed7317ce67861af | https://github.com/dwkim78/upsilon/blob/5f381453f26582ef56e62fb8fed7317ce67861af/upsilon/extract_features/feature_set.py#L23-L49 | train |
hannes-brt/hebel | hebel/models/neural_net.py | NeuralNet.parameters | def parameters(self):
""" A property that returns all of the model's parameters. """
parameters = []
for hl in self.hidden_layers:
parameters.extend(hl.parameters)
parameters.extend(self.top_layer.parameters)
return parameters | python | def parameters(self):
""" A property that returns all of the model's parameters. """
parameters = []
for hl in self.hidden_layers:
parameters.extend(hl.parameters)
parameters.extend(self.top_layer.parameters)
return parameters | [
"def",
"parameters",
"(",
"self",
")",
":",
"parameters",
"=",
"[",
"]",
"for",
"hl",
"in",
"self",
".",
"hidden_layers",
":",
"parameters",
".",
"extend",
"(",
"hl",
".",
"parameters",
")",
"parameters",
".",
"extend",
"(",
"self",
".",
"top_layer",
".",
"parameters",
")",
"return",
"parameters"
] | A property that returns all of the model's parameters. | [
"A",
"property",
"that",
"returns",
"all",
"of",
"the",
"model",
"s",
"parameters",
"."
] | 1e2c3a9309c2646103901b26a55be4e312dd5005 | https://github.com/hannes-brt/hebel/blob/1e2c3a9309c2646103901b26a55be4e312dd5005/hebel/models/neural_net.py#L185-L191 | train |
hannes-brt/hebel | hebel/models/neural_net.py | NeuralNet.parameters | def parameters(self, value):
""" Used to set all of the model's parameters to new values.
**Parameters:**
value : array_like
New values for the model parameters. Must be of length
``self.n_parameters``.
"""
if len(value) != self.n_parameters:
raise ValueError("Incorrect length of parameter vector. "
"Model has %d parameters, but got %d" %
(self.n_parameters, len(value)))
i = 0
for hl in self.hidden_layers:
hl.parameters = value[i:i + hl.n_parameters]
i += hl.n_parameters
self.top_layer.parameters = value[-self.top_layer.n_parameters:] | python | def parameters(self, value):
""" Used to set all of the model's parameters to new values.
**Parameters:**
value : array_like
New values for the model parameters. Must be of length
``self.n_parameters``.
"""
if len(value) != self.n_parameters:
raise ValueError("Incorrect length of parameter vector. "
"Model has %d parameters, but got %d" %
(self.n_parameters, len(value)))
i = 0
for hl in self.hidden_layers:
hl.parameters = value[i:i + hl.n_parameters]
i += hl.n_parameters
self.top_layer.parameters = value[-self.top_layer.n_parameters:] | [
"def",
"parameters",
"(",
"self",
",",
"value",
")",
":",
"if",
"len",
"(",
"value",
")",
"!=",
"self",
".",
"n_parameters",
":",
"raise",
"ValueError",
"(",
"\"Incorrect length of parameter vector. \"",
"\"Model has %d parameters, but got %d\"",
"%",
"(",
"self",
".",
"n_parameters",
",",
"len",
"(",
"value",
")",
")",
")",
"i",
"=",
"0",
"for",
"hl",
"in",
"self",
".",
"hidden_layers",
":",
"hl",
".",
"parameters",
"=",
"value",
"[",
"i",
":",
"i",
"+",
"hl",
".",
"n_parameters",
"]",
"i",
"+=",
"hl",
".",
"n_parameters",
"self",
".",
"top_layer",
".",
"parameters",
"=",
"value",
"[",
"-",
"self",
".",
"top_layer",
".",
"n_parameters",
":",
"]"
] | Used to set all of the model's parameters to new values.
**Parameters:**
value : array_like
New values for the model parameters. Must be of length
``self.n_parameters``. | [
"Used",
"to",
"set",
"all",
"of",
"the",
"model",
"s",
"parameters",
"to",
"new",
"values",
"."
] | 1e2c3a9309c2646103901b26a55be4e312dd5005 | https://github.com/hannes-brt/hebel/blob/1e2c3a9309c2646103901b26a55be4e312dd5005/hebel/models/neural_net.py#L194-L214 | train |
hannes-brt/hebel | hebel/models/neural_net.py | NeuralNet.checksum | def checksum(self):
""" Returns an MD5 digest of the model.
This can be used to easily identify whether two models have the
same architecture.
"""
m = md5()
for hl in self.hidden_layers:
m.update(str(hl.architecture))
m.update(str(self.top_layer.architecture))
return m.hexdigest() | python | def checksum(self):
""" Returns an MD5 digest of the model.
This can be used to easily identify whether two models have the
same architecture.
"""
m = md5()
for hl in self.hidden_layers:
m.update(str(hl.architecture))
m.update(str(self.top_layer.architecture))
return m.hexdigest() | [
"def",
"checksum",
"(",
"self",
")",
":",
"m",
"=",
"md5",
"(",
")",
"for",
"hl",
"in",
"self",
".",
"hidden_layers",
":",
"m",
".",
"update",
"(",
"str",
"(",
"hl",
".",
"architecture",
")",
")",
"m",
".",
"update",
"(",
"str",
"(",
"self",
".",
"top_layer",
".",
"architecture",
")",
")",
"return",
"m",
".",
"hexdigest",
"(",
")"
] | Returns an MD5 digest of the model.
This can be used to easily identify whether two models have the
same architecture. | [
"Returns",
"an",
"MD5",
"digest",
"of",
"the",
"model",
"."
] | 1e2c3a9309c2646103901b26a55be4e312dd5005 | https://github.com/hannes-brt/hebel/blob/1e2c3a9309c2646103901b26a55be4e312dd5005/hebel/models/neural_net.py#L243-L254 | train |
hannes-brt/hebel | hebel/models/neural_net.py | NeuralNet.evaluate | def evaluate(self, input_data, targets,
return_cache=False, prediction=True):
""" Evaluate the loss function without computing gradients.
**Parameters:**
input_data : GPUArray
Data to evaluate
targets: GPUArray
Targets
return_cache : bool, optional
Whether to return intermediary variables from the
computation and the hidden activations.
prediction : bool, optional
Whether to use prediction model. Only relevant when using
dropout. If true, then weights are multiplied by
1 - dropout if the layer uses dropout.
**Returns:**
loss : float
The value of the loss function.
hidden_cache : list, only returned if ``return_cache == True``
Cache as returned by :meth:`hebel.models.NeuralNet.feed_forward`.
activations : list, only returned if ``return_cache == True``
Hidden activations as returned by
:meth:`hebel.models.NeuralNet.feed_forward`.
"""
# Forward pass
activations, hidden_cache = self.feed_forward(
input_data, return_cache=True, prediction=prediction)
loss = self.top_layer.train_error(None,
targets, average=False, cache=activations,
prediction=prediction)
for hl in self.hidden_layers:
if hl.l1_penalty_weight: loss += hl.l1_penalty
if hl.l2_penalty_weight: loss += hl.l2_penalty
if self.top_layer.l1_penalty_weight: loss += self.top_layer.l1_penalty
if self.top_layer.l2_penalty_weight: loss += self.top_layer.l2_penalty
if not return_cache:
return loss
else:
return loss, hidden_cache, activations | python | def evaluate(self, input_data, targets,
return_cache=False, prediction=True):
""" Evaluate the loss function without computing gradients.
**Parameters:**
input_data : GPUArray
Data to evaluate
targets: GPUArray
Targets
return_cache : bool, optional
Whether to return intermediary variables from the
computation and the hidden activations.
prediction : bool, optional
Whether to use prediction model. Only relevant when using
dropout. If true, then weights are multiplied by
1 - dropout if the layer uses dropout.
**Returns:**
loss : float
The value of the loss function.
hidden_cache : list, only returned if ``return_cache == True``
Cache as returned by :meth:`hebel.models.NeuralNet.feed_forward`.
activations : list, only returned if ``return_cache == True``
Hidden activations as returned by
:meth:`hebel.models.NeuralNet.feed_forward`.
"""
# Forward pass
activations, hidden_cache = self.feed_forward(
input_data, return_cache=True, prediction=prediction)
loss = self.top_layer.train_error(None,
targets, average=False, cache=activations,
prediction=prediction)
for hl in self.hidden_layers:
if hl.l1_penalty_weight: loss += hl.l1_penalty
if hl.l2_penalty_weight: loss += hl.l2_penalty
if self.top_layer.l1_penalty_weight: loss += self.top_layer.l1_penalty
if self.top_layer.l2_penalty_weight: loss += self.top_layer.l2_penalty
if not return_cache:
return loss
else:
return loss, hidden_cache, activations | [
"def",
"evaluate",
"(",
"self",
",",
"input_data",
",",
"targets",
",",
"return_cache",
"=",
"False",
",",
"prediction",
"=",
"True",
")",
":",
"# Forward pass",
"activations",
",",
"hidden_cache",
"=",
"self",
".",
"feed_forward",
"(",
"input_data",
",",
"return_cache",
"=",
"True",
",",
"prediction",
"=",
"prediction",
")",
"loss",
"=",
"self",
".",
"top_layer",
".",
"train_error",
"(",
"None",
",",
"targets",
",",
"average",
"=",
"False",
",",
"cache",
"=",
"activations",
",",
"prediction",
"=",
"prediction",
")",
"for",
"hl",
"in",
"self",
".",
"hidden_layers",
":",
"if",
"hl",
".",
"l1_penalty_weight",
":",
"loss",
"+=",
"hl",
".",
"l1_penalty",
"if",
"hl",
".",
"l2_penalty_weight",
":",
"loss",
"+=",
"hl",
".",
"l2_penalty",
"if",
"self",
".",
"top_layer",
".",
"l1_penalty_weight",
":",
"loss",
"+=",
"self",
".",
"top_layer",
".",
"l1_penalty",
"if",
"self",
".",
"top_layer",
".",
"l2_penalty_weight",
":",
"loss",
"+=",
"self",
".",
"top_layer",
".",
"l2_penalty",
"if",
"not",
"return_cache",
":",
"return",
"loss",
"else",
":",
"return",
"loss",
",",
"hidden_cache",
",",
"activations"
] | Evaluate the loss function without computing gradients.
**Parameters:**
input_data : GPUArray
Data to evaluate
targets: GPUArray
Targets
return_cache : bool, optional
Whether to return intermediary variables from the
computation and the hidden activations.
prediction : bool, optional
Whether to use prediction model. Only relevant when using
dropout. If true, then weights are multiplied by
1 - dropout if the layer uses dropout.
**Returns:**
loss : float
The value of the loss function.
hidden_cache : list, only returned if ``return_cache == True``
Cache as returned by :meth:`hebel.models.NeuralNet.feed_forward`.
activations : list, only returned if ``return_cache == True``
Hidden activations as returned by
:meth:`hebel.models.NeuralNet.feed_forward`. | [
"Evaluate",
"the",
"loss",
"function",
"without",
"computing",
"gradients",
"."
] | 1e2c3a9309c2646103901b26a55be4e312dd5005 | https://github.com/hannes-brt/hebel/blob/1e2c3a9309c2646103901b26a55be4e312dd5005/hebel/models/neural_net.py#L256-L308 | train |
hannes-brt/hebel | hebel/models/neural_net.py | NeuralNet.training_pass | def training_pass(self, input_data, targets):
""" Perform a full forward and backward pass through the model.
**Parameters:**
input_data : GPUArray
Data to train the model with.
targets : GPUArray
Training targets.
**Returns:**
loss : float
Value of loss function as evaluated on the data and targets.
gradients : list of GPUArray
Gradients obtained from backpropagation in the backward pass.
"""
# Forward pass
loss, hidden_cache, logistic_cache = self.evaluate(
input_data, targets, return_cache=True, prediction=False)
if not np.isfinite(loss):
raise ValueError('Infinite activations!')
# Backpropagation
if self.hidden_layers:
hidden_activations = hidden_cache[-1][0]
else:
hidden_activations = input_data
df_top_layer = \
self.top_layer.backprop(hidden_activations, targets,
cache=logistic_cache)
gradients = list(df_top_layer[0][::-1])
df_hidden = df_top_layer[1]
if self.hidden_layers:
hidden_inputs = [input_data] + [c[0] for c in hidden_cache[:-1]]
for hl, hc, hi in \
zip(self.hidden_layers[::-1], hidden_cache[::-1],
hidden_inputs[::-1]):
g, df_hidden = hl.backprop(hi, df_hidden, cache=hc)
gradients.extend(g[::-1])
gradients.reverse()
return loss, gradients | python | def training_pass(self, input_data, targets):
""" Perform a full forward and backward pass through the model.
**Parameters:**
input_data : GPUArray
Data to train the model with.
targets : GPUArray
Training targets.
**Returns:**
loss : float
Value of loss function as evaluated on the data and targets.
gradients : list of GPUArray
Gradients obtained from backpropagation in the backward pass.
"""
# Forward pass
loss, hidden_cache, logistic_cache = self.evaluate(
input_data, targets, return_cache=True, prediction=False)
if not np.isfinite(loss):
raise ValueError('Infinite activations!')
# Backpropagation
if self.hidden_layers:
hidden_activations = hidden_cache[-1][0]
else:
hidden_activations = input_data
df_top_layer = \
self.top_layer.backprop(hidden_activations, targets,
cache=logistic_cache)
gradients = list(df_top_layer[0][::-1])
df_hidden = df_top_layer[1]
if self.hidden_layers:
hidden_inputs = [input_data] + [c[0] for c in hidden_cache[:-1]]
for hl, hc, hi in \
zip(self.hidden_layers[::-1], hidden_cache[::-1],
hidden_inputs[::-1]):
g, df_hidden = hl.backprop(hi, df_hidden, cache=hc)
gradients.extend(g[::-1])
gradients.reverse()
return loss, gradients | [
"def",
"training_pass",
"(",
"self",
",",
"input_data",
",",
"targets",
")",
":",
"# Forward pass",
"loss",
",",
"hidden_cache",
",",
"logistic_cache",
"=",
"self",
".",
"evaluate",
"(",
"input_data",
",",
"targets",
",",
"return_cache",
"=",
"True",
",",
"prediction",
"=",
"False",
")",
"if",
"not",
"np",
".",
"isfinite",
"(",
"loss",
")",
":",
"raise",
"ValueError",
"(",
"'Infinite activations!'",
")",
"# Backpropagation",
"if",
"self",
".",
"hidden_layers",
":",
"hidden_activations",
"=",
"hidden_cache",
"[",
"-",
"1",
"]",
"[",
"0",
"]",
"else",
":",
"hidden_activations",
"=",
"input_data",
"df_top_layer",
"=",
"self",
".",
"top_layer",
".",
"backprop",
"(",
"hidden_activations",
",",
"targets",
",",
"cache",
"=",
"logistic_cache",
")",
"gradients",
"=",
"list",
"(",
"df_top_layer",
"[",
"0",
"]",
"[",
":",
":",
"-",
"1",
"]",
")",
"df_hidden",
"=",
"df_top_layer",
"[",
"1",
"]",
"if",
"self",
".",
"hidden_layers",
":",
"hidden_inputs",
"=",
"[",
"input_data",
"]",
"+",
"[",
"c",
"[",
"0",
"]",
"for",
"c",
"in",
"hidden_cache",
"[",
":",
"-",
"1",
"]",
"]",
"for",
"hl",
",",
"hc",
",",
"hi",
"in",
"zip",
"(",
"self",
".",
"hidden_layers",
"[",
":",
":",
"-",
"1",
"]",
",",
"hidden_cache",
"[",
":",
":",
"-",
"1",
"]",
",",
"hidden_inputs",
"[",
":",
":",
"-",
"1",
"]",
")",
":",
"g",
",",
"df_hidden",
"=",
"hl",
".",
"backprop",
"(",
"hi",
",",
"df_hidden",
",",
"cache",
"=",
"hc",
")",
"gradients",
".",
"extend",
"(",
"g",
"[",
":",
":",
"-",
"1",
"]",
")",
"gradients",
".",
"reverse",
"(",
")",
"return",
"loss",
",",
"gradients"
] | Perform a full forward and backward pass through the model.
**Parameters:**
input_data : GPUArray
Data to train the model with.
targets : GPUArray
Training targets.
**Returns:**
loss : float
Value of loss function as evaluated on the data and targets.
gradients : list of GPUArray
Gradients obtained from backpropagation in the backward pass. | [
"Perform",
"a",
"full",
"forward",
"and",
"backward",
"pass",
"through",
"the",
"model",
"."
] | 1e2c3a9309c2646103901b26a55be4e312dd5005 | https://github.com/hannes-brt/hebel/blob/1e2c3a9309c2646103901b26a55be4e312dd5005/hebel/models/neural_net.py#L310-L359 | train |
hannes-brt/hebel | hebel/models/neural_net.py | NeuralNet.feed_forward | def feed_forward(self, input_data, return_cache=False, prediction=True):
""" Run data forward through the model.
**Parameters:**
input_data : GPUArray
Data to run through the model.
return_cache : bool, optional
Whether to return the intermediary results.
prediction : bool, optional
Whether to run in prediction mode. Only relevant when
using dropout. If true, weights are multiplied by 1 - dropout.
If false, then half of hidden units are randomly dropped and
the dropout mask is returned in case ``return_cache==True``.
**Returns:**
prediction : GPUArray
Predictions from the model.
cache : list of GPUArray, only returned if ``return_cache == True``
Results of intermediary computations.
"""
hidden_cache = None # Create variable in case there are no hidden layers
if self.hidden_layers:
# Forward pass
hidden_cache = []
for i in range(len(self.hidden_layers)):
hidden_activations = hidden_cache[i - 1][0] if i else input_data
# Use dropout predict if previous layer has dropout
hidden_cache.append(self.hidden_layers[i]
.feed_forward(hidden_activations,
prediction=prediction))
hidden_activations = hidden_cache[-1][0]
else:
hidden_activations = input_data
# Use dropout_predict if last hidden layer has dropout
activations = \
self.top_layer.feed_forward(hidden_activations,
prediction=False)
if return_cache:
return activations, hidden_cache
return activations | python | def feed_forward(self, input_data, return_cache=False, prediction=True):
""" Run data forward through the model.
**Parameters:**
input_data : GPUArray
Data to run through the model.
return_cache : bool, optional
Whether to return the intermediary results.
prediction : bool, optional
Whether to run in prediction mode. Only relevant when
using dropout. If true, weights are multiplied by 1 - dropout.
If false, then half of hidden units are randomly dropped and
the dropout mask is returned in case ``return_cache==True``.
**Returns:**
prediction : GPUArray
Predictions from the model.
cache : list of GPUArray, only returned if ``return_cache == True``
Results of intermediary computations.
"""
hidden_cache = None # Create variable in case there are no hidden layers
if self.hidden_layers:
# Forward pass
hidden_cache = []
for i in range(len(self.hidden_layers)):
hidden_activations = hidden_cache[i - 1][0] if i else input_data
# Use dropout predict if previous layer has dropout
hidden_cache.append(self.hidden_layers[i]
.feed_forward(hidden_activations,
prediction=prediction))
hidden_activations = hidden_cache[-1][0]
else:
hidden_activations = input_data
# Use dropout_predict if last hidden layer has dropout
activations = \
self.top_layer.feed_forward(hidden_activations,
prediction=False)
if return_cache:
return activations, hidden_cache
return activations | [
"def",
"feed_forward",
"(",
"self",
",",
"input_data",
",",
"return_cache",
"=",
"False",
",",
"prediction",
"=",
"True",
")",
":",
"hidden_cache",
"=",
"None",
"# Create variable in case there are no hidden layers",
"if",
"self",
".",
"hidden_layers",
":",
"# Forward pass",
"hidden_cache",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"self",
".",
"hidden_layers",
")",
")",
":",
"hidden_activations",
"=",
"hidden_cache",
"[",
"i",
"-",
"1",
"]",
"[",
"0",
"]",
"if",
"i",
"else",
"input_data",
"# Use dropout predict if previous layer has dropout",
"hidden_cache",
".",
"append",
"(",
"self",
".",
"hidden_layers",
"[",
"i",
"]",
".",
"feed_forward",
"(",
"hidden_activations",
",",
"prediction",
"=",
"prediction",
")",
")",
"hidden_activations",
"=",
"hidden_cache",
"[",
"-",
"1",
"]",
"[",
"0",
"]",
"else",
":",
"hidden_activations",
"=",
"input_data",
"# Use dropout_predict if last hidden layer has dropout",
"activations",
"=",
"self",
".",
"top_layer",
".",
"feed_forward",
"(",
"hidden_activations",
",",
"prediction",
"=",
"False",
")",
"if",
"return_cache",
":",
"return",
"activations",
",",
"hidden_cache",
"return",
"activations"
] | Run data forward through the model.
**Parameters:**
input_data : GPUArray
Data to run through the model.
return_cache : bool, optional
Whether to return the intermediary results.
prediction : bool, optional
Whether to run in prediction mode. Only relevant when
using dropout. If true, weights are multiplied by 1 - dropout.
If false, then half of hidden units are randomly dropped and
the dropout mask is returned in case ``return_cache==True``.
**Returns:**
prediction : GPUArray
Predictions from the model.
cache : list of GPUArray, only returned if ``return_cache == True``
Results of intermediary computations. | [
"Run",
"data",
"forward",
"through",
"the",
"model",
"."
] | 1e2c3a9309c2646103901b26a55be4e312dd5005 | https://github.com/hannes-brt/hebel/blob/1e2c3a9309c2646103901b26a55be4e312dd5005/hebel/models/neural_net.py#L399-L448 | train |
dwkim78/upsilon | upsilon/extract_features/extract_features.py | ExtractFeatures.shallow_run | def shallow_run(self):
"""Derive not-period-based features."""
# Number of data points
self.n_points = len(self.date)
# Weight calculation.
# All zero values.
if not self.err.any():
self.err = np.ones(len(self.mag)) * np.std(self.mag)
# Some zero values.
elif not self.err.all():
np.putmask(self.err, self.err==0, np.median(self.err))
self.weight = 1. / self.err
self.weighted_sum = np.sum(self.weight)
# Simple statistics, mean, median and std.
self.mean = np.mean(self.mag)
self.median = np.median(self.mag)
self.std = np.std(self.mag)
# Weighted mean and std.
self.weighted_mean = np.sum(self.mag * self.weight) / self.weighted_sum
self.weighted_std = np.sqrt(np.sum((self.mag - self.weighted_mean) ** 2 \
* self.weight) / self.weighted_sum)
# Skewness and kurtosis.
self.skewness = ss.skew(self.mag)
self.kurtosis = ss.kurtosis(self.mag)
# Normalization-test. Shapiro-Wilk test.
shapiro = ss.shapiro(self.mag)
self.shapiro_w = shapiro[0]
# self.shapiro_log10p = np.log10(shapiro[1])
# Percentile features.
self.quartile31 = np.percentile(self.mag, 75) \
- np.percentile(self.mag, 25)
# Stetson K.
self.stetson_k = self.get_stetson_k(self.mag, self.median, self.err)
# Ratio between higher and lower amplitude than average.
self.hl_amp_ratio = self.half_mag_amplitude_ratio(
self.mag, self.median, self.weight)
# This second function's value is very similar with the above one.
# self.hl_amp_ratio2 = self.half_mag_amplitude_ratio2(
# self.mag, self.median)
# Cusum
self.cusum = self.get_cusum(self.mag)
# Eta
self.eta = self.get_eta(self.mag, self.weighted_std) | python | def shallow_run(self):
"""Derive not-period-based features."""
# Number of data points
self.n_points = len(self.date)
# Weight calculation.
# All zero values.
if not self.err.any():
self.err = np.ones(len(self.mag)) * np.std(self.mag)
# Some zero values.
elif not self.err.all():
np.putmask(self.err, self.err==0, np.median(self.err))
self.weight = 1. / self.err
self.weighted_sum = np.sum(self.weight)
# Simple statistics, mean, median and std.
self.mean = np.mean(self.mag)
self.median = np.median(self.mag)
self.std = np.std(self.mag)
# Weighted mean and std.
self.weighted_mean = np.sum(self.mag * self.weight) / self.weighted_sum
self.weighted_std = np.sqrt(np.sum((self.mag - self.weighted_mean) ** 2 \
* self.weight) / self.weighted_sum)
# Skewness and kurtosis.
self.skewness = ss.skew(self.mag)
self.kurtosis = ss.kurtosis(self.mag)
# Normalization-test. Shapiro-Wilk test.
shapiro = ss.shapiro(self.mag)
self.shapiro_w = shapiro[0]
# self.shapiro_log10p = np.log10(shapiro[1])
# Percentile features.
self.quartile31 = np.percentile(self.mag, 75) \
- np.percentile(self.mag, 25)
# Stetson K.
self.stetson_k = self.get_stetson_k(self.mag, self.median, self.err)
# Ratio between higher and lower amplitude than average.
self.hl_amp_ratio = self.half_mag_amplitude_ratio(
self.mag, self.median, self.weight)
# This second function's value is very similar with the above one.
# self.hl_amp_ratio2 = self.half_mag_amplitude_ratio2(
# self.mag, self.median)
# Cusum
self.cusum = self.get_cusum(self.mag)
# Eta
self.eta = self.get_eta(self.mag, self.weighted_std) | [
"def",
"shallow_run",
"(",
"self",
")",
":",
"# Number of data points",
"self",
".",
"n_points",
"=",
"len",
"(",
"self",
".",
"date",
")",
"# Weight calculation.",
"# All zero values.",
"if",
"not",
"self",
".",
"err",
".",
"any",
"(",
")",
":",
"self",
".",
"err",
"=",
"np",
".",
"ones",
"(",
"len",
"(",
"self",
".",
"mag",
")",
")",
"*",
"np",
".",
"std",
"(",
"self",
".",
"mag",
")",
"# Some zero values.",
"elif",
"not",
"self",
".",
"err",
".",
"all",
"(",
")",
":",
"np",
".",
"putmask",
"(",
"self",
".",
"err",
",",
"self",
".",
"err",
"==",
"0",
",",
"np",
".",
"median",
"(",
"self",
".",
"err",
")",
")",
"self",
".",
"weight",
"=",
"1.",
"/",
"self",
".",
"err",
"self",
".",
"weighted_sum",
"=",
"np",
".",
"sum",
"(",
"self",
".",
"weight",
")",
"# Simple statistics, mean, median and std.",
"self",
".",
"mean",
"=",
"np",
".",
"mean",
"(",
"self",
".",
"mag",
")",
"self",
".",
"median",
"=",
"np",
".",
"median",
"(",
"self",
".",
"mag",
")",
"self",
".",
"std",
"=",
"np",
".",
"std",
"(",
"self",
".",
"mag",
")",
"# Weighted mean and std.",
"self",
".",
"weighted_mean",
"=",
"np",
".",
"sum",
"(",
"self",
".",
"mag",
"*",
"self",
".",
"weight",
")",
"/",
"self",
".",
"weighted_sum",
"self",
".",
"weighted_std",
"=",
"np",
".",
"sqrt",
"(",
"np",
".",
"sum",
"(",
"(",
"self",
".",
"mag",
"-",
"self",
".",
"weighted_mean",
")",
"**",
"2",
"*",
"self",
".",
"weight",
")",
"/",
"self",
".",
"weighted_sum",
")",
"# Skewness and kurtosis.",
"self",
".",
"skewness",
"=",
"ss",
".",
"skew",
"(",
"self",
".",
"mag",
")",
"self",
".",
"kurtosis",
"=",
"ss",
".",
"kurtosis",
"(",
"self",
".",
"mag",
")",
"# Normalization-test. Shapiro-Wilk test.",
"shapiro",
"=",
"ss",
".",
"shapiro",
"(",
"self",
".",
"mag",
")",
"self",
".",
"shapiro_w",
"=",
"shapiro",
"[",
"0",
"]",
"# self.shapiro_log10p = np.log10(shapiro[1])",
"# Percentile features.",
"self",
".",
"quartile31",
"=",
"np",
".",
"percentile",
"(",
"self",
".",
"mag",
",",
"75",
")",
"-",
"np",
".",
"percentile",
"(",
"self",
".",
"mag",
",",
"25",
")",
"# Stetson K.",
"self",
".",
"stetson_k",
"=",
"self",
".",
"get_stetson_k",
"(",
"self",
".",
"mag",
",",
"self",
".",
"median",
",",
"self",
".",
"err",
")",
"# Ratio between higher and lower amplitude than average.",
"self",
".",
"hl_amp_ratio",
"=",
"self",
".",
"half_mag_amplitude_ratio",
"(",
"self",
".",
"mag",
",",
"self",
".",
"median",
",",
"self",
".",
"weight",
")",
"# This second function's value is very similar with the above one.",
"# self.hl_amp_ratio2 = self.half_mag_amplitude_ratio2(",
"# self.mag, self.median)",
"# Cusum",
"self",
".",
"cusum",
"=",
"self",
".",
"get_cusum",
"(",
"self",
".",
"mag",
")",
"# Eta",
"self",
".",
"eta",
"=",
"self",
".",
"get_eta",
"(",
"self",
".",
"mag",
",",
"self",
".",
"weighted_std",
")"
] | Derive not-period-based features. | [
"Derive",
"not",
"-",
"period",
"-",
"based",
"features",
"."
] | 5f381453f26582ef56e62fb8fed7317ce67861af | https://github.com/dwkim78/upsilon/blob/5f381453f26582ef56e62fb8fed7317ce67861af/upsilon/extract_features/extract_features.py#L86-L139 | train |
dwkim78/upsilon | upsilon/extract_features/extract_features.py | ExtractFeatures.deep_run | def deep_run(self):
"""Derive period-based features."""
# Lomb-Scargle period finding.
self.get_period_LS(self.date, self.mag, self.n_threads, self.min_period)
# Features based on a phase-folded light curve
# such as Eta, slope-percentile, etc.
# Should be called after the getPeriodLS() is called.
# Created phased a folded light curve.
# We use period * 2 to take eclipsing binaries into account.
phase_folded_date = self.date % (self.period * 2.)
sorted_index = np.argsort(phase_folded_date)
folded_date = phase_folded_date[sorted_index]
folded_mag = self.mag[sorted_index]
# phase Eta
self.phase_eta = self.get_eta(folded_mag, self.weighted_std)
# Slope percentile.
self.slope_per10, self.slope_per90 = \
self.slope_percentile(folded_date, folded_mag)
# phase Cusum
self.phase_cusum = self.get_cusum(folded_mag) | python | def deep_run(self):
"""Derive period-based features."""
# Lomb-Scargle period finding.
self.get_period_LS(self.date, self.mag, self.n_threads, self.min_period)
# Features based on a phase-folded light curve
# such as Eta, slope-percentile, etc.
# Should be called after the getPeriodLS() is called.
# Created phased a folded light curve.
# We use period * 2 to take eclipsing binaries into account.
phase_folded_date = self.date % (self.period * 2.)
sorted_index = np.argsort(phase_folded_date)
folded_date = phase_folded_date[sorted_index]
folded_mag = self.mag[sorted_index]
# phase Eta
self.phase_eta = self.get_eta(folded_mag, self.weighted_std)
# Slope percentile.
self.slope_per10, self.slope_per90 = \
self.slope_percentile(folded_date, folded_mag)
# phase Cusum
self.phase_cusum = self.get_cusum(folded_mag) | [
"def",
"deep_run",
"(",
"self",
")",
":",
"# Lomb-Scargle period finding.",
"self",
".",
"get_period_LS",
"(",
"self",
".",
"date",
",",
"self",
".",
"mag",
",",
"self",
".",
"n_threads",
",",
"self",
".",
"min_period",
")",
"# Features based on a phase-folded light curve",
"# such as Eta, slope-percentile, etc.",
"# Should be called after the getPeriodLS() is called.",
"# Created phased a folded light curve.",
"# We use period * 2 to take eclipsing binaries into account.",
"phase_folded_date",
"=",
"self",
".",
"date",
"%",
"(",
"self",
".",
"period",
"*",
"2.",
")",
"sorted_index",
"=",
"np",
".",
"argsort",
"(",
"phase_folded_date",
")",
"folded_date",
"=",
"phase_folded_date",
"[",
"sorted_index",
"]",
"folded_mag",
"=",
"self",
".",
"mag",
"[",
"sorted_index",
"]",
"# phase Eta",
"self",
".",
"phase_eta",
"=",
"self",
".",
"get_eta",
"(",
"folded_mag",
",",
"self",
".",
"weighted_std",
")",
"# Slope percentile.",
"self",
".",
"slope_per10",
",",
"self",
".",
"slope_per90",
"=",
"self",
".",
"slope_percentile",
"(",
"folded_date",
",",
"folded_mag",
")",
"# phase Cusum",
"self",
".",
"phase_cusum",
"=",
"self",
".",
"get_cusum",
"(",
"folded_mag",
")"
] | Derive period-based features. | [
"Derive",
"period",
"-",
"based",
"features",
"."
] | 5f381453f26582ef56e62fb8fed7317ce67861af | https://github.com/dwkim78/upsilon/blob/5f381453f26582ef56e62fb8fed7317ce67861af/upsilon/extract_features/extract_features.py#L141-L166 | train |
dwkim78/upsilon | upsilon/extract_features/extract_features.py | ExtractFeatures.get_period_LS | def get_period_LS(self, date, mag, n_threads, min_period):
"""
Period finding using the Lomb-Scargle algorithm.
Finding two periods. The second period is estimated after whitening
the first period. Calculating various other features as well
using derived periods.
Parameters
----------
date : array_like
An array of observed date, in days.
mag : array_like
An array of observed magnitude.
n_threads : int
The number of threads to use.
min_period : float
The minimum period to calculate.
"""
# DO NOT CHANGE THESE PARAMETERS.
oversampling = 3.
hifac = int((max(date) - min(date)) / len(date) / min_period * 2.)
# Minimum hifac
if hifac < 100:
hifac = 100
# Lomb-Scargle.
fx, fy, nout, jmax, prob = pLS.fasper(date, mag, oversampling, hifac,
n_threads)
self.f = fx[jmax]
self.period = 1. / self.f
self.period_uncertainty = self.get_period_uncertainty(fx, fy, jmax)
self.period_log10FAP = \
np.log10(pLS.getSignificance(fx, fy, nout, oversampling)[jmax])
# self.f_SNR1 = fy[jmax] / np.median(fy)
self.period_SNR = (fy[jmax] - np.median(fy)) / np.std(fy)
# Fit Fourier Series of order 3.
order = 3
# Initial guess of Fourier coefficients.
p0 = np.ones(order * 2 + 1)
date_period = (date % self.period) / self.period
p1, success = leastsq(self.residuals, p0,
args=(date_period, mag, order))
# fitted_y = self.FourierSeries(p1, date_period, order)
# print p1, self.mean, self.median
# plt.plot(date_period, self.mag, 'b+')
# plt.show()
# Derive Fourier features for the first period.
# Petersen, J. O., 1986, A&A
self.amplitude = np.sqrt(p1[1] ** 2 + p1[2] ** 2)
self.r21 = np.sqrt(p1[3] ** 2 + p1[4] ** 2) / self.amplitude
self.r31 = np.sqrt(p1[5] ** 2 + p1[6] ** 2) / self.amplitude
self.f_phase = np.arctan(-p1[1] / p1[2])
self.phi21 = np.arctan(-p1[3] / p1[4]) - 2. * self.f_phase
self.phi31 = np.arctan(-p1[5] / p1[6]) - 3. * self.f_phase
"""
# Derive a second period.
# Whitening a light curve.
residual_mag = mag - fitted_y
# Lomb-Scargle again to find the second period.
omega_top, power_top = search_frequencies(date, residual_mag, err,
#LS_kwargs={'generalized':True, 'subtract_mean':True},
n_eval=5000, n_retry=3, n_save=50)
self.period2 = 2*np.pi/omega_top[np.where(power_top==np.max(power_top))][0]
self.f2 = 1. / self.period2
self.f2_SNR = power_top[np.where(power_top==np.max(power_top))][0] \
* (len(self.date) - 1) / 2.
# Fit Fourier Series again.
p0 = [1.] * order * 2
date_period = (date % self.period) / self.period
p2, success = leastsq(self.residuals, p0,
args=(date_period, residual_mag, order))
fitted_y = self.FourierSeries(p2, date_period, order)
#plt.plot(date%self.period2, residual_mag, 'b+')
#plt.show()
# Derive Fourier features for the first second.
self.f2_amp = 2. * np.sqrt(p2[1]**2 + p2[2]**2)
self.f2_R21 = np.sqrt(p2[3]**2 + p2[4]**2) / self.f2_amp
self.f2_R31 = np.sqrt(p2[5]**2 + p2[6]**2) / self.f2_amp
self.f2_R41 = np.sqrt(p2[7]**2 + p2[8]**2) / self.f2_amp
self.f2_R51 = np.sqrt(p2[9]**2 + p2[10]**2) / self.f2_amp
self.f2_phase = np.arctan(-p2[1] / p2[2])
self.f2_phi21 = np.arctan(-p2[3] / p2[4]) - 2. * self.f2_phase
self.f2_phi31 = np.arctan(-p2[5] / p2[6]) - 3. * self.f2_phase
self.f2_phi41 = np.arctan(-p2[7] / p2[8]) - 4. * self.f2_phase
self.f2_phi51 = np.arctan(-p2[9] / p2[10]) - 5. * self.f2_phase
# Calculate features using the first and second periods.
self.f12_ratio = self.f2 / self.f1
self.f12_remain = self.f1 % self.f2 \
if self.f1 > self.f2 else self.f2 % self.f1
self.f12_amp = self.f2_amp / self.f1_amp
self.f12_phase = self.f2_phase - self.f1_phase
""" | python | def get_period_LS(self, date, mag, n_threads, min_period):
"""
Period finding using the Lomb-Scargle algorithm.
Finding two periods. The second period is estimated after whitening
the first period. Calculating various other features as well
using derived periods.
Parameters
----------
date : array_like
An array of observed date, in days.
mag : array_like
An array of observed magnitude.
n_threads : int
The number of threads to use.
min_period : float
The minimum period to calculate.
"""
# DO NOT CHANGE THESE PARAMETERS.
oversampling = 3.
hifac = int((max(date) - min(date)) / len(date) / min_period * 2.)
# Minimum hifac
if hifac < 100:
hifac = 100
# Lomb-Scargle.
fx, fy, nout, jmax, prob = pLS.fasper(date, mag, oversampling, hifac,
n_threads)
self.f = fx[jmax]
self.period = 1. / self.f
self.period_uncertainty = self.get_period_uncertainty(fx, fy, jmax)
self.period_log10FAP = \
np.log10(pLS.getSignificance(fx, fy, nout, oversampling)[jmax])
# self.f_SNR1 = fy[jmax] / np.median(fy)
self.period_SNR = (fy[jmax] - np.median(fy)) / np.std(fy)
# Fit Fourier Series of order 3.
order = 3
# Initial guess of Fourier coefficients.
p0 = np.ones(order * 2 + 1)
date_period = (date % self.period) / self.period
p1, success = leastsq(self.residuals, p0,
args=(date_period, mag, order))
# fitted_y = self.FourierSeries(p1, date_period, order)
# print p1, self.mean, self.median
# plt.plot(date_period, self.mag, 'b+')
# plt.show()
# Derive Fourier features for the first period.
# Petersen, J. O., 1986, A&A
self.amplitude = np.sqrt(p1[1] ** 2 + p1[2] ** 2)
self.r21 = np.sqrt(p1[3] ** 2 + p1[4] ** 2) / self.amplitude
self.r31 = np.sqrt(p1[5] ** 2 + p1[6] ** 2) / self.amplitude
self.f_phase = np.arctan(-p1[1] / p1[2])
self.phi21 = np.arctan(-p1[3] / p1[4]) - 2. * self.f_phase
self.phi31 = np.arctan(-p1[5] / p1[6]) - 3. * self.f_phase
"""
# Derive a second period.
# Whitening a light curve.
residual_mag = mag - fitted_y
# Lomb-Scargle again to find the second period.
omega_top, power_top = search_frequencies(date, residual_mag, err,
#LS_kwargs={'generalized':True, 'subtract_mean':True},
n_eval=5000, n_retry=3, n_save=50)
self.period2 = 2*np.pi/omega_top[np.where(power_top==np.max(power_top))][0]
self.f2 = 1. / self.period2
self.f2_SNR = power_top[np.where(power_top==np.max(power_top))][0] \
* (len(self.date) - 1) / 2.
# Fit Fourier Series again.
p0 = [1.] * order * 2
date_period = (date % self.period) / self.period
p2, success = leastsq(self.residuals, p0,
args=(date_period, residual_mag, order))
fitted_y = self.FourierSeries(p2, date_period, order)
#plt.plot(date%self.period2, residual_mag, 'b+')
#plt.show()
# Derive Fourier features for the first second.
self.f2_amp = 2. * np.sqrt(p2[1]**2 + p2[2]**2)
self.f2_R21 = np.sqrt(p2[3]**2 + p2[4]**2) / self.f2_amp
self.f2_R31 = np.sqrt(p2[5]**2 + p2[6]**2) / self.f2_amp
self.f2_R41 = np.sqrt(p2[7]**2 + p2[8]**2) / self.f2_amp
self.f2_R51 = np.sqrt(p2[9]**2 + p2[10]**2) / self.f2_amp
self.f2_phase = np.arctan(-p2[1] / p2[2])
self.f2_phi21 = np.arctan(-p2[3] / p2[4]) - 2. * self.f2_phase
self.f2_phi31 = np.arctan(-p2[5] / p2[6]) - 3. * self.f2_phase
self.f2_phi41 = np.arctan(-p2[7] / p2[8]) - 4. * self.f2_phase
self.f2_phi51 = np.arctan(-p2[9] / p2[10]) - 5. * self.f2_phase
# Calculate features using the first and second periods.
self.f12_ratio = self.f2 / self.f1
self.f12_remain = self.f1 % self.f2 \
if self.f1 > self.f2 else self.f2 % self.f1
self.f12_amp = self.f2_amp / self.f1_amp
self.f12_phase = self.f2_phase - self.f1_phase
""" | [
"def",
"get_period_LS",
"(",
"self",
",",
"date",
",",
"mag",
",",
"n_threads",
",",
"min_period",
")",
":",
"# DO NOT CHANGE THESE PARAMETERS.",
"oversampling",
"=",
"3.",
"hifac",
"=",
"int",
"(",
"(",
"max",
"(",
"date",
")",
"-",
"min",
"(",
"date",
")",
")",
"/",
"len",
"(",
"date",
")",
"/",
"min_period",
"*",
"2.",
")",
"# Minimum hifac",
"if",
"hifac",
"<",
"100",
":",
"hifac",
"=",
"100",
"# Lomb-Scargle.",
"fx",
",",
"fy",
",",
"nout",
",",
"jmax",
",",
"prob",
"=",
"pLS",
".",
"fasper",
"(",
"date",
",",
"mag",
",",
"oversampling",
",",
"hifac",
",",
"n_threads",
")",
"self",
".",
"f",
"=",
"fx",
"[",
"jmax",
"]",
"self",
".",
"period",
"=",
"1.",
"/",
"self",
".",
"f",
"self",
".",
"period_uncertainty",
"=",
"self",
".",
"get_period_uncertainty",
"(",
"fx",
",",
"fy",
",",
"jmax",
")",
"self",
".",
"period_log10FAP",
"=",
"np",
".",
"log10",
"(",
"pLS",
".",
"getSignificance",
"(",
"fx",
",",
"fy",
",",
"nout",
",",
"oversampling",
")",
"[",
"jmax",
"]",
")",
"# self.f_SNR1 = fy[jmax] / np.median(fy)",
"self",
".",
"period_SNR",
"=",
"(",
"fy",
"[",
"jmax",
"]",
"-",
"np",
".",
"median",
"(",
"fy",
")",
")",
"/",
"np",
".",
"std",
"(",
"fy",
")",
"# Fit Fourier Series of order 3.",
"order",
"=",
"3",
"# Initial guess of Fourier coefficients.",
"p0",
"=",
"np",
".",
"ones",
"(",
"order",
"*",
"2",
"+",
"1",
")",
"date_period",
"=",
"(",
"date",
"%",
"self",
".",
"period",
")",
"/",
"self",
".",
"period",
"p1",
",",
"success",
"=",
"leastsq",
"(",
"self",
".",
"residuals",
",",
"p0",
",",
"args",
"=",
"(",
"date_period",
",",
"mag",
",",
"order",
")",
")",
"# fitted_y = self.FourierSeries(p1, date_period, order)",
"# print p1, self.mean, self.median",
"# plt.plot(date_period, self.mag, 'b+')",
"# plt.show()",
"# Derive Fourier features for the first period.",
"# Petersen, J. O., 1986, A&A",
"self",
".",
"amplitude",
"=",
"np",
".",
"sqrt",
"(",
"p1",
"[",
"1",
"]",
"**",
"2",
"+",
"p1",
"[",
"2",
"]",
"**",
"2",
")",
"self",
".",
"r21",
"=",
"np",
".",
"sqrt",
"(",
"p1",
"[",
"3",
"]",
"**",
"2",
"+",
"p1",
"[",
"4",
"]",
"**",
"2",
")",
"/",
"self",
".",
"amplitude",
"self",
".",
"r31",
"=",
"np",
".",
"sqrt",
"(",
"p1",
"[",
"5",
"]",
"**",
"2",
"+",
"p1",
"[",
"6",
"]",
"**",
"2",
")",
"/",
"self",
".",
"amplitude",
"self",
".",
"f_phase",
"=",
"np",
".",
"arctan",
"(",
"-",
"p1",
"[",
"1",
"]",
"/",
"p1",
"[",
"2",
"]",
")",
"self",
".",
"phi21",
"=",
"np",
".",
"arctan",
"(",
"-",
"p1",
"[",
"3",
"]",
"/",
"p1",
"[",
"4",
"]",
")",
"-",
"2.",
"*",
"self",
".",
"f_phase",
"self",
".",
"phi31",
"=",
"np",
".",
"arctan",
"(",
"-",
"p1",
"[",
"5",
"]",
"/",
"p1",
"[",
"6",
"]",
")",
"-",
"3.",
"*",
"self",
".",
"f_phase",
"\"\"\"\n # Derive a second period.\n # Whitening a light curve.\n residual_mag = mag - fitted_y\n\n # Lomb-Scargle again to find the second period.\n omega_top, power_top = search_frequencies(date, residual_mag, err,\n #LS_kwargs={'generalized':True, 'subtract_mean':True},\n n_eval=5000, n_retry=3, n_save=50)\n\n self.period2 = 2*np.pi/omega_top[np.where(power_top==np.max(power_top))][0]\n self.f2 = 1. / self.period2\n self.f2_SNR = power_top[np.where(power_top==np.max(power_top))][0] \\\n * (len(self.date) - 1) / 2.\n\n # Fit Fourier Series again.\n p0 = [1.] * order * 2\n date_period = (date % self.period) / self.period\n p2, success = leastsq(self.residuals, p0,\n args=(date_period, residual_mag, order))\n fitted_y = self.FourierSeries(p2, date_period, order)\n\n #plt.plot(date%self.period2, residual_mag, 'b+')\n #plt.show()\n\n # Derive Fourier features for the first second.\n self.f2_amp = 2. * np.sqrt(p2[1]**2 + p2[2]**2)\n self.f2_R21 = np.sqrt(p2[3]**2 + p2[4]**2) / self.f2_amp\n self.f2_R31 = np.sqrt(p2[5]**2 + p2[6]**2) / self.f2_amp\n self.f2_R41 = np.sqrt(p2[7]**2 + p2[8]**2) / self.f2_amp\n self.f2_R51 = np.sqrt(p2[9]**2 + p2[10]**2) / self.f2_amp\n self.f2_phase = np.arctan(-p2[1] / p2[2])\n self.f2_phi21 = np.arctan(-p2[3] / p2[4]) - 2. * self.f2_phase\n self.f2_phi31 = np.arctan(-p2[5] / p2[6]) - 3. * self.f2_phase\n self.f2_phi41 = np.arctan(-p2[7] / p2[8]) - 4. * self.f2_phase\n self.f2_phi51 = np.arctan(-p2[9] / p2[10]) - 5. * self.f2_phase\n\n # Calculate features using the first and second periods.\n self.f12_ratio = self.f2 / self.f1\n self.f12_remain = self.f1 % self.f2 \\\n if self.f1 > self.f2 else self.f2 % self.f1\n self.f12_amp = self.f2_amp / self.f1_amp\n self.f12_phase = self.f2_phase - self.f1_phase\n \"\"\""
] | Period finding using the Lomb-Scargle algorithm.
Finding two periods. The second period is estimated after whitening
the first period. Calculating various other features as well
using derived periods.
Parameters
----------
date : array_like
An array of observed date, in days.
mag : array_like
An array of observed magnitude.
n_threads : int
The number of threads to use.
min_period : float
The minimum period to calculate. | [
"Period",
"finding",
"using",
"the",
"Lomb",
"-",
"Scargle",
"algorithm",
"."
] | 5f381453f26582ef56e62fb8fed7317ce67861af | https://github.com/dwkim78/upsilon/blob/5f381453f26582ef56e62fb8fed7317ce67861af/upsilon/extract_features/extract_features.py#L168-L273 | train |
dwkim78/upsilon | upsilon/extract_features/extract_features.py | ExtractFeatures.get_period_uncertainty | def get_period_uncertainty(self, fx, fy, jmax, fx_width=100):
"""
Get uncertainty of a period.
The uncertainty is defined as the half width of the frequencies
around the peak, that becomes lower than average + standard deviation
of the power spectrum.
Since we may not have fine resolution around the peak,
we do not assume it is gaussian. So, no scaling factor of
2.355 (= 2 * sqrt(2 * ln2)) is applied.
Parameters
----------
fx : array_like
An array of frequencies.
fy : array_like
An array of amplitudes.
jmax : int
An index at the peak frequency.
fx_width : int, optional
Width of power spectrum to calculate uncertainty.
Returns
-------
p_uncertain : float
Period uncertainty.
"""
# Get subset
start_index = jmax - fx_width
end_index = jmax + fx_width
if start_index < 0:
start_index = 0
if end_index > len(fx) - 1:
end_index = len(fx) - 1
fx_subset = fx[start_index:end_index]
fy_subset = fy[start_index:end_index]
fy_mean = np.median(fy_subset)
fy_std = np.std(fy_subset)
# Find peak
max_index = np.argmax(fy_subset)
# Find list whose powers become lower than average + std.
index = np.where(fy_subset <= fy_mean + fy_std)[0]
# Find the edge at left and right. This is the full width.
left_index = index[(index < max_index)]
if len(left_index) == 0:
left_index = 0
else:
left_index = left_index[-1]
right_index = index[(index > max_index)]
if len(right_index) == 0:
right_index = len(fy_subset) - 1
else:
right_index = right_index[0]
# We assume the half of the full width is the period uncertainty.
half_width = (1. / fx_subset[left_index]
- 1. / fx_subset[right_index]) / 2.
period_uncertainty = half_width
return period_uncertainty | python | def get_period_uncertainty(self, fx, fy, jmax, fx_width=100):
"""
Get uncertainty of a period.
The uncertainty is defined as the half width of the frequencies
around the peak, that becomes lower than average + standard deviation
of the power spectrum.
Since we may not have fine resolution around the peak,
we do not assume it is gaussian. So, no scaling factor of
2.355 (= 2 * sqrt(2 * ln2)) is applied.
Parameters
----------
fx : array_like
An array of frequencies.
fy : array_like
An array of amplitudes.
jmax : int
An index at the peak frequency.
fx_width : int, optional
Width of power spectrum to calculate uncertainty.
Returns
-------
p_uncertain : float
Period uncertainty.
"""
# Get subset
start_index = jmax - fx_width
end_index = jmax + fx_width
if start_index < 0:
start_index = 0
if end_index > len(fx) - 1:
end_index = len(fx) - 1
fx_subset = fx[start_index:end_index]
fy_subset = fy[start_index:end_index]
fy_mean = np.median(fy_subset)
fy_std = np.std(fy_subset)
# Find peak
max_index = np.argmax(fy_subset)
# Find list whose powers become lower than average + std.
index = np.where(fy_subset <= fy_mean + fy_std)[0]
# Find the edge at left and right. This is the full width.
left_index = index[(index < max_index)]
if len(left_index) == 0:
left_index = 0
else:
left_index = left_index[-1]
right_index = index[(index > max_index)]
if len(right_index) == 0:
right_index = len(fy_subset) - 1
else:
right_index = right_index[0]
# We assume the half of the full width is the period uncertainty.
half_width = (1. / fx_subset[left_index]
- 1. / fx_subset[right_index]) / 2.
period_uncertainty = half_width
return period_uncertainty | [
"def",
"get_period_uncertainty",
"(",
"self",
",",
"fx",
",",
"fy",
",",
"jmax",
",",
"fx_width",
"=",
"100",
")",
":",
"# Get subset",
"start_index",
"=",
"jmax",
"-",
"fx_width",
"end_index",
"=",
"jmax",
"+",
"fx_width",
"if",
"start_index",
"<",
"0",
":",
"start_index",
"=",
"0",
"if",
"end_index",
">",
"len",
"(",
"fx",
")",
"-",
"1",
":",
"end_index",
"=",
"len",
"(",
"fx",
")",
"-",
"1",
"fx_subset",
"=",
"fx",
"[",
"start_index",
":",
"end_index",
"]",
"fy_subset",
"=",
"fy",
"[",
"start_index",
":",
"end_index",
"]",
"fy_mean",
"=",
"np",
".",
"median",
"(",
"fy_subset",
")",
"fy_std",
"=",
"np",
".",
"std",
"(",
"fy_subset",
")",
"# Find peak",
"max_index",
"=",
"np",
".",
"argmax",
"(",
"fy_subset",
")",
"# Find list whose powers become lower than average + std.",
"index",
"=",
"np",
".",
"where",
"(",
"fy_subset",
"<=",
"fy_mean",
"+",
"fy_std",
")",
"[",
"0",
"]",
"# Find the edge at left and right. This is the full width.",
"left_index",
"=",
"index",
"[",
"(",
"index",
"<",
"max_index",
")",
"]",
"if",
"len",
"(",
"left_index",
")",
"==",
"0",
":",
"left_index",
"=",
"0",
"else",
":",
"left_index",
"=",
"left_index",
"[",
"-",
"1",
"]",
"right_index",
"=",
"index",
"[",
"(",
"index",
">",
"max_index",
")",
"]",
"if",
"len",
"(",
"right_index",
")",
"==",
"0",
":",
"right_index",
"=",
"len",
"(",
"fy_subset",
")",
"-",
"1",
"else",
":",
"right_index",
"=",
"right_index",
"[",
"0",
"]",
"# We assume the half of the full width is the period uncertainty.",
"half_width",
"=",
"(",
"1.",
"/",
"fx_subset",
"[",
"left_index",
"]",
"-",
"1.",
"/",
"fx_subset",
"[",
"right_index",
"]",
")",
"/",
"2.",
"period_uncertainty",
"=",
"half_width",
"return",
"period_uncertainty"
] | Get uncertainty of a period.
The uncertainty is defined as the half width of the frequencies
around the peak, that becomes lower than average + standard deviation
of the power spectrum.
Since we may not have fine resolution around the peak,
we do not assume it is gaussian. So, no scaling factor of
2.355 (= 2 * sqrt(2 * ln2)) is applied.
Parameters
----------
fx : array_like
An array of frequencies.
fy : array_like
An array of amplitudes.
jmax : int
An index at the peak frequency.
fx_width : int, optional
Width of power spectrum to calculate uncertainty.
Returns
-------
p_uncertain : float
Period uncertainty. | [
"Get",
"uncertainty",
"of",
"a",
"period",
"."
] | 5f381453f26582ef56e62fb8fed7317ce67861af | https://github.com/dwkim78/upsilon/blob/5f381453f26582ef56e62fb8fed7317ce67861af/upsilon/extract_features/extract_features.py#L275-L340 | train |
dwkim78/upsilon | upsilon/extract_features/extract_features.py | ExtractFeatures.residuals | def residuals(self, pars, x, y, order):
"""
Residual of Fourier Series.
Parameters
----------
pars : array_like
Fourier series parameters.
x : array_like
An array of date.
y : array_like
An array of true values to fit.
order : int
An order of Fourier Series.
"""
return y - self.fourier_series(pars, x, order) | python | def residuals(self, pars, x, y, order):
"""
Residual of Fourier Series.
Parameters
----------
pars : array_like
Fourier series parameters.
x : array_like
An array of date.
y : array_like
An array of true values to fit.
order : int
An order of Fourier Series.
"""
return y - self.fourier_series(pars, x, order) | [
"def",
"residuals",
"(",
"self",
",",
"pars",
",",
"x",
",",
"y",
",",
"order",
")",
":",
"return",
"y",
"-",
"self",
".",
"fourier_series",
"(",
"pars",
",",
"x",
",",
"order",
")"
] | Residual of Fourier Series.
Parameters
----------
pars : array_like
Fourier series parameters.
x : array_like
An array of date.
y : array_like
An array of true values to fit.
order : int
An order of Fourier Series. | [
"Residual",
"of",
"Fourier",
"Series",
"."
] | 5f381453f26582ef56e62fb8fed7317ce67861af | https://github.com/dwkim78/upsilon/blob/5f381453f26582ef56e62fb8fed7317ce67861af/upsilon/extract_features/extract_features.py#L342-L358 | train |
dwkim78/upsilon | upsilon/extract_features/extract_features.py | ExtractFeatures.fourier_series | def fourier_series(self, pars, x, order):
"""
Function to fit Fourier Series.
Parameters
----------
x : array_like
An array of date divided by period. It doesn't need to be sorted.
pars : array_like
Fourier series parameters.
order : int
An order of Fourier series.
"""
sum = pars[0]
for i in range(order):
sum += pars[i * 2 + 1] * np.sin(2 * np.pi * (i + 1) * x) \
+ pars[i * 2 + 2] * np.cos(2 * np.pi * (i + 1) * x)
return sum | python | def fourier_series(self, pars, x, order):
"""
Function to fit Fourier Series.
Parameters
----------
x : array_like
An array of date divided by period. It doesn't need to be sorted.
pars : array_like
Fourier series parameters.
order : int
An order of Fourier series.
"""
sum = pars[0]
for i in range(order):
sum += pars[i * 2 + 1] * np.sin(2 * np.pi * (i + 1) * x) \
+ pars[i * 2 + 2] * np.cos(2 * np.pi * (i + 1) * x)
return sum | [
"def",
"fourier_series",
"(",
"self",
",",
"pars",
",",
"x",
",",
"order",
")",
":",
"sum",
"=",
"pars",
"[",
"0",
"]",
"for",
"i",
"in",
"range",
"(",
"order",
")",
":",
"sum",
"+=",
"pars",
"[",
"i",
"*",
"2",
"+",
"1",
"]",
"*",
"np",
".",
"sin",
"(",
"2",
"*",
"np",
".",
"pi",
"*",
"(",
"i",
"+",
"1",
")",
"*",
"x",
")",
"+",
"pars",
"[",
"i",
"*",
"2",
"+",
"2",
"]",
"*",
"np",
".",
"cos",
"(",
"2",
"*",
"np",
".",
"pi",
"*",
"(",
"i",
"+",
"1",
")",
"*",
"x",
")",
"return",
"sum"
] | Function to fit Fourier Series.
Parameters
----------
x : array_like
An array of date divided by period. It doesn't need to be sorted.
pars : array_like
Fourier series parameters.
order : int
An order of Fourier series. | [
"Function",
"to",
"fit",
"Fourier",
"Series",
"."
] | 5f381453f26582ef56e62fb8fed7317ce67861af | https://github.com/dwkim78/upsilon/blob/5f381453f26582ef56e62fb8fed7317ce67861af/upsilon/extract_features/extract_features.py#L360-L379 | train |
dwkim78/upsilon | upsilon/extract_features/extract_features.py | ExtractFeatures.get_stetson_k | def get_stetson_k(self, mag, avg, err):
"""
Return Stetson K feature.
Parameters
----------
mag : array_like
An array of magnitude.
avg : float
An average value of magnitudes.
err : array_like
An array of magnitude errors.
Returns
-------
stetson_k : float
Stetson K value.
"""
residual = (mag - avg) / err
stetson_k = np.sum(np.fabs(residual)) \
/ np.sqrt(np.sum(residual * residual)) / np.sqrt(len(mag))
return stetson_k | python | def get_stetson_k(self, mag, avg, err):
"""
Return Stetson K feature.
Parameters
----------
mag : array_like
An array of magnitude.
avg : float
An average value of magnitudes.
err : array_like
An array of magnitude errors.
Returns
-------
stetson_k : float
Stetson K value.
"""
residual = (mag - avg) / err
stetson_k = np.sum(np.fabs(residual)) \
/ np.sqrt(np.sum(residual * residual)) / np.sqrt(len(mag))
return stetson_k | [
"def",
"get_stetson_k",
"(",
"self",
",",
"mag",
",",
"avg",
",",
"err",
")",
":",
"residual",
"=",
"(",
"mag",
"-",
"avg",
")",
"/",
"err",
"stetson_k",
"=",
"np",
".",
"sum",
"(",
"np",
".",
"fabs",
"(",
"residual",
")",
")",
"/",
"np",
".",
"sqrt",
"(",
"np",
".",
"sum",
"(",
"residual",
"*",
"residual",
")",
")",
"/",
"np",
".",
"sqrt",
"(",
"len",
"(",
"mag",
")",
")",
"return",
"stetson_k"
] | Return Stetson K feature.
Parameters
----------
mag : array_like
An array of magnitude.
avg : float
An average value of magnitudes.
err : array_like
An array of magnitude errors.
Returns
-------
stetson_k : float
Stetson K value. | [
"Return",
"Stetson",
"K",
"feature",
"."
] | 5f381453f26582ef56e62fb8fed7317ce67861af | https://github.com/dwkim78/upsilon/blob/5f381453f26582ef56e62fb8fed7317ce67861af/upsilon/extract_features/extract_features.py#L381-L404 | train |
dwkim78/upsilon | upsilon/extract_features/extract_features.py | ExtractFeatures.half_mag_amplitude_ratio | def half_mag_amplitude_ratio(self, mag, avg, weight):
"""
Return ratio of amplitude of higher and lower magnitudes.
A ratio of amplitude of higher and lower magnitudes than average,
considering weights. This ratio, by definition, should be higher
for EB than for others.
Parameters
----------
mag : array_like
An array of magnitudes.
avg : float
An average value of magnitudes.
weight : array_like
An array of weight.
Returns
-------
hl_ratio : float
Ratio of amplitude of higher and lower magnitudes than average.
"""
# For lower (fainter) magnitude than average.
index = np.where(mag > avg)
lower_weight = weight[index]
lower_weight_sum = np.sum(lower_weight)
lower_mag = mag[index]
lower_weighted_std = np.sum((lower_mag
- avg) ** 2 * lower_weight) / \
lower_weight_sum
# For higher (brighter) magnitude than average.
index = np.where(mag <= avg)
higher_weight = weight[index]
higher_weight_sum = np.sum(higher_weight)
higher_mag = mag[index]
higher_weighted_std = np.sum((higher_mag
- avg) ** 2 * higher_weight) / \
higher_weight_sum
# Return ratio.
return np.sqrt(lower_weighted_std / higher_weighted_std) | python | def half_mag_amplitude_ratio(self, mag, avg, weight):
"""
Return ratio of amplitude of higher and lower magnitudes.
A ratio of amplitude of higher and lower magnitudes than average,
considering weights. This ratio, by definition, should be higher
for EB than for others.
Parameters
----------
mag : array_like
An array of magnitudes.
avg : float
An average value of magnitudes.
weight : array_like
An array of weight.
Returns
-------
hl_ratio : float
Ratio of amplitude of higher and lower magnitudes than average.
"""
# For lower (fainter) magnitude than average.
index = np.where(mag > avg)
lower_weight = weight[index]
lower_weight_sum = np.sum(lower_weight)
lower_mag = mag[index]
lower_weighted_std = np.sum((lower_mag
- avg) ** 2 * lower_weight) / \
lower_weight_sum
# For higher (brighter) magnitude than average.
index = np.where(mag <= avg)
higher_weight = weight[index]
higher_weight_sum = np.sum(higher_weight)
higher_mag = mag[index]
higher_weighted_std = np.sum((higher_mag
- avg) ** 2 * higher_weight) / \
higher_weight_sum
# Return ratio.
return np.sqrt(lower_weighted_std / higher_weighted_std) | [
"def",
"half_mag_amplitude_ratio",
"(",
"self",
",",
"mag",
",",
"avg",
",",
"weight",
")",
":",
"# For lower (fainter) magnitude than average.",
"index",
"=",
"np",
".",
"where",
"(",
"mag",
">",
"avg",
")",
"lower_weight",
"=",
"weight",
"[",
"index",
"]",
"lower_weight_sum",
"=",
"np",
".",
"sum",
"(",
"lower_weight",
")",
"lower_mag",
"=",
"mag",
"[",
"index",
"]",
"lower_weighted_std",
"=",
"np",
".",
"sum",
"(",
"(",
"lower_mag",
"-",
"avg",
")",
"**",
"2",
"*",
"lower_weight",
")",
"/",
"lower_weight_sum",
"# For higher (brighter) magnitude than average.",
"index",
"=",
"np",
".",
"where",
"(",
"mag",
"<=",
"avg",
")",
"higher_weight",
"=",
"weight",
"[",
"index",
"]",
"higher_weight_sum",
"=",
"np",
".",
"sum",
"(",
"higher_weight",
")",
"higher_mag",
"=",
"mag",
"[",
"index",
"]",
"higher_weighted_std",
"=",
"np",
".",
"sum",
"(",
"(",
"higher_mag",
"-",
"avg",
")",
"**",
"2",
"*",
"higher_weight",
")",
"/",
"higher_weight_sum",
"# Return ratio.",
"return",
"np",
".",
"sqrt",
"(",
"lower_weighted_std",
"/",
"higher_weighted_std",
")"
] | Return ratio of amplitude of higher and lower magnitudes.
A ratio of amplitude of higher and lower magnitudes than average,
considering weights. This ratio, by definition, should be higher
for EB than for others.
Parameters
----------
mag : array_like
An array of magnitudes.
avg : float
An average value of magnitudes.
weight : array_like
An array of weight.
Returns
-------
hl_ratio : float
Ratio of amplitude of higher and lower magnitudes than average. | [
"Return",
"ratio",
"of",
"amplitude",
"of",
"higher",
"and",
"lower",
"magnitudes",
"."
] | 5f381453f26582ef56e62fb8fed7317ce67861af | https://github.com/dwkim78/upsilon/blob/5f381453f26582ef56e62fb8fed7317ce67861af/upsilon/extract_features/extract_features.py#L406-L449 | train |
dwkim78/upsilon | upsilon/extract_features/extract_features.py | ExtractFeatures.half_mag_amplitude_ratio2 | def half_mag_amplitude_ratio2(self, mag, avg):
"""
Return ratio of amplitude of higher and lower magnitudes.
A ratio of amplitude of higher and lower magnitudes than average,
considering weights. This ratio, by definition, should be higher
for EB than for others.
Parameters
----------
mag : array_like
An array of magnitudes.
avg : float
An average value of magnitudes.
Returns
-------
hl_ratio : float
Ratio of amplitude of higher and lower magnitudes than average.
"""
# For lower (fainter) magnitude than average.
index = np.where(mag > avg)
fainter_mag = mag[index]
lower_sum = np.sum((fainter_mag - avg) ** 2) / len(fainter_mag)
# For higher (brighter) magnitude than average.
index = np.where(mag <= avg)
brighter_mag = mag[index]
higher_sum = np.sum((avg - brighter_mag) ** 2) / len(brighter_mag)
# Return ratio.
return np.sqrt(lower_sum / higher_sum) | python | def half_mag_amplitude_ratio2(self, mag, avg):
"""
Return ratio of amplitude of higher and lower magnitudes.
A ratio of amplitude of higher and lower magnitudes than average,
considering weights. This ratio, by definition, should be higher
for EB than for others.
Parameters
----------
mag : array_like
An array of magnitudes.
avg : float
An average value of magnitudes.
Returns
-------
hl_ratio : float
Ratio of amplitude of higher and lower magnitudes than average.
"""
# For lower (fainter) magnitude than average.
index = np.where(mag > avg)
fainter_mag = mag[index]
lower_sum = np.sum((fainter_mag - avg) ** 2) / len(fainter_mag)
# For higher (brighter) magnitude than average.
index = np.where(mag <= avg)
brighter_mag = mag[index]
higher_sum = np.sum((avg - brighter_mag) ** 2) / len(brighter_mag)
# Return ratio.
return np.sqrt(lower_sum / higher_sum) | [
"def",
"half_mag_amplitude_ratio2",
"(",
"self",
",",
"mag",
",",
"avg",
")",
":",
"# For lower (fainter) magnitude than average.",
"index",
"=",
"np",
".",
"where",
"(",
"mag",
">",
"avg",
")",
"fainter_mag",
"=",
"mag",
"[",
"index",
"]",
"lower_sum",
"=",
"np",
".",
"sum",
"(",
"(",
"fainter_mag",
"-",
"avg",
")",
"**",
"2",
")",
"/",
"len",
"(",
"fainter_mag",
")",
"# For higher (brighter) magnitude than average.",
"index",
"=",
"np",
".",
"where",
"(",
"mag",
"<=",
"avg",
")",
"brighter_mag",
"=",
"mag",
"[",
"index",
"]",
"higher_sum",
"=",
"np",
".",
"sum",
"(",
"(",
"avg",
"-",
"brighter_mag",
")",
"**",
"2",
")",
"/",
"len",
"(",
"brighter_mag",
")",
"# Return ratio.",
"return",
"np",
".",
"sqrt",
"(",
"lower_sum",
"/",
"higher_sum",
")"
] | Return ratio of amplitude of higher and lower magnitudes.
A ratio of amplitude of higher and lower magnitudes than average,
considering weights. This ratio, by definition, should be higher
for EB than for others.
Parameters
----------
mag : array_like
An array of magnitudes.
avg : float
An average value of magnitudes.
Returns
-------
hl_ratio : float
Ratio of amplitude of higher and lower magnitudes than average. | [
"Return",
"ratio",
"of",
"amplitude",
"of",
"higher",
"and",
"lower",
"magnitudes",
"."
] | 5f381453f26582ef56e62fb8fed7317ce67861af | https://github.com/dwkim78/upsilon/blob/5f381453f26582ef56e62fb8fed7317ce67861af/upsilon/extract_features/extract_features.py#L451-L486 | train |
dwkim78/upsilon | upsilon/extract_features/extract_features.py | ExtractFeatures.get_eta | def get_eta(self, mag, std):
"""
Return Eta feature.
Parameters
----------
mag : array_like
An array of magnitudes.
std : array_like
A standard deviation of magnitudes.
Returns
-------
eta : float
The value of Eta index.
"""
diff = mag[1:] - mag[:len(mag) - 1]
eta = np.sum(diff * diff) / (len(mag) - 1.) / std / std
return eta | python | def get_eta(self, mag, std):
"""
Return Eta feature.
Parameters
----------
mag : array_like
An array of magnitudes.
std : array_like
A standard deviation of magnitudes.
Returns
-------
eta : float
The value of Eta index.
"""
diff = mag[1:] - mag[:len(mag) - 1]
eta = np.sum(diff * diff) / (len(mag) - 1.) / std / std
return eta | [
"def",
"get_eta",
"(",
"self",
",",
"mag",
",",
"std",
")",
":",
"diff",
"=",
"mag",
"[",
"1",
":",
"]",
"-",
"mag",
"[",
":",
"len",
"(",
"mag",
")",
"-",
"1",
"]",
"eta",
"=",
"np",
".",
"sum",
"(",
"diff",
"*",
"diff",
")",
"/",
"(",
"len",
"(",
"mag",
")",
"-",
"1.",
")",
"/",
"std",
"/",
"std",
"return",
"eta"
] | Return Eta feature.
Parameters
----------
mag : array_like
An array of magnitudes.
std : array_like
A standard deviation of magnitudes.
Returns
-------
eta : float
The value of Eta index. | [
"Return",
"Eta",
"feature",
"."
] | 5f381453f26582ef56e62fb8fed7317ce67861af | https://github.com/dwkim78/upsilon/blob/5f381453f26582ef56e62fb8fed7317ce67861af/upsilon/extract_features/extract_features.py#L488-L508 | train |
dwkim78/upsilon | upsilon/extract_features/extract_features.py | ExtractFeatures.slope_percentile | def slope_percentile(self, date, mag):
"""
Return 10% and 90% percentile of slope.
Parameters
----------
date : array_like
An array of phase-folded date. Sorted.
mag : array_like
An array of phase-folded magnitudes. Sorted by date.
Returns
-------
per_10 : float
10% percentile values of slope.
per_90 : float
90% percentile values of slope.
"""
date_diff = date[1:] - date[:len(date) - 1]
mag_diff = mag[1:] - mag[:len(mag) - 1]
# Remove zero mag_diff.
index = np.where(mag_diff != 0.)
date_diff = date_diff[index]
mag_diff = mag_diff[index]
# Derive slope.
slope = date_diff / mag_diff
percentile_10 = np.percentile(slope, 10.)
percentile_90 = np.percentile(slope, 90.)
return percentile_10, percentile_90 | python | def slope_percentile(self, date, mag):
"""
Return 10% and 90% percentile of slope.
Parameters
----------
date : array_like
An array of phase-folded date. Sorted.
mag : array_like
An array of phase-folded magnitudes. Sorted by date.
Returns
-------
per_10 : float
10% percentile values of slope.
per_90 : float
90% percentile values of slope.
"""
date_diff = date[1:] - date[:len(date) - 1]
mag_diff = mag[1:] - mag[:len(mag) - 1]
# Remove zero mag_diff.
index = np.where(mag_diff != 0.)
date_diff = date_diff[index]
mag_diff = mag_diff[index]
# Derive slope.
slope = date_diff / mag_diff
percentile_10 = np.percentile(slope, 10.)
percentile_90 = np.percentile(slope, 90.)
return percentile_10, percentile_90 | [
"def",
"slope_percentile",
"(",
"self",
",",
"date",
",",
"mag",
")",
":",
"date_diff",
"=",
"date",
"[",
"1",
":",
"]",
"-",
"date",
"[",
":",
"len",
"(",
"date",
")",
"-",
"1",
"]",
"mag_diff",
"=",
"mag",
"[",
"1",
":",
"]",
"-",
"mag",
"[",
":",
"len",
"(",
"mag",
")",
"-",
"1",
"]",
"# Remove zero mag_diff.",
"index",
"=",
"np",
".",
"where",
"(",
"mag_diff",
"!=",
"0.",
")",
"date_diff",
"=",
"date_diff",
"[",
"index",
"]",
"mag_diff",
"=",
"mag_diff",
"[",
"index",
"]",
"# Derive slope.",
"slope",
"=",
"date_diff",
"/",
"mag_diff",
"percentile_10",
"=",
"np",
".",
"percentile",
"(",
"slope",
",",
"10.",
")",
"percentile_90",
"=",
"np",
".",
"percentile",
"(",
"slope",
",",
"90.",
")",
"return",
"percentile_10",
",",
"percentile_90"
] | Return 10% and 90% percentile of slope.
Parameters
----------
date : array_like
An array of phase-folded date. Sorted.
mag : array_like
An array of phase-folded magnitudes. Sorted by date.
Returns
-------
per_10 : float
10% percentile values of slope.
per_90 : float
90% percentile values of slope. | [
"Return",
"10%",
"and",
"90%",
"percentile",
"of",
"slope",
"."
] | 5f381453f26582ef56e62fb8fed7317ce67861af | https://github.com/dwkim78/upsilon/blob/5f381453f26582ef56e62fb8fed7317ce67861af/upsilon/extract_features/extract_features.py#L510-L543 | train |
dwkim78/upsilon | upsilon/extract_features/extract_features.py | ExtractFeatures.get_cusum | def get_cusum(self, mag):
"""
Return max - min of cumulative sum.
Parameters
----------
mag : array_like
An array of magnitudes.
Returns
-------
mm_cusum : float
Max - min of cumulative sum.
"""
c = np.cumsum(mag - self.weighted_mean) / len(mag) / self.weighted_std
return np.max(c) - np.min(c) | python | def get_cusum(self, mag):
"""
Return max - min of cumulative sum.
Parameters
----------
mag : array_like
An array of magnitudes.
Returns
-------
mm_cusum : float
Max - min of cumulative sum.
"""
c = np.cumsum(mag - self.weighted_mean) / len(mag) / self.weighted_std
return np.max(c) - np.min(c) | [
"def",
"get_cusum",
"(",
"self",
",",
"mag",
")",
":",
"c",
"=",
"np",
".",
"cumsum",
"(",
"mag",
"-",
"self",
".",
"weighted_mean",
")",
"/",
"len",
"(",
"mag",
")",
"/",
"self",
".",
"weighted_std",
"return",
"np",
".",
"max",
"(",
"c",
")",
"-",
"np",
".",
"min",
"(",
"c",
")"
] | Return max - min of cumulative sum.
Parameters
----------
mag : array_like
An array of magnitudes.
Returns
-------
mm_cusum : float
Max - min of cumulative sum. | [
"Return",
"max",
"-",
"min",
"of",
"cumulative",
"sum",
"."
] | 5f381453f26582ef56e62fb8fed7317ce67861af | https://github.com/dwkim78/upsilon/blob/5f381453f26582ef56e62fb8fed7317ce67861af/upsilon/extract_features/extract_features.py#L545-L562 | train |
dwkim78/upsilon | upsilon/extract_features/extract_features.py | ExtractFeatures.get_features2 | def get_features2(self):
"""
Return all features with its names.
Returns
-------
names : list
Feature names.
values : list
Feature values
"""
feature_names = []
feature_values = []
# Get all the names of features.
all_vars = vars(self)
for name in all_vars.keys():
# Omit input variables such as date, mag, err, etc.
if not (name == 'date' or name == 'mag' or name == 'err'
or name == 'n_threads' or name == 'min_period'):
# Filter some other unnecessary features.
if not (name == 'f' or name == 'f_phase'
or name == 'period_log10FAP'
or name == 'weight' or name == 'weighted_sum'
or name == 'median' or name == 'mean' or name == 'std'):
feature_names.append(name)
# Sort by the names.
# Sorting should be done to keep maintaining the same order of features.
feature_names.sort()
# Get feature values.
for name in feature_names:
feature_values.append(all_vars[name])
return feature_names, feature_values | python | def get_features2(self):
"""
Return all features with its names.
Returns
-------
names : list
Feature names.
values : list
Feature values
"""
feature_names = []
feature_values = []
# Get all the names of features.
all_vars = vars(self)
for name in all_vars.keys():
# Omit input variables such as date, mag, err, etc.
if not (name == 'date' or name == 'mag' or name == 'err'
or name == 'n_threads' or name == 'min_period'):
# Filter some other unnecessary features.
if not (name == 'f' or name == 'f_phase'
or name == 'period_log10FAP'
or name == 'weight' or name == 'weighted_sum'
or name == 'median' or name == 'mean' or name == 'std'):
feature_names.append(name)
# Sort by the names.
# Sorting should be done to keep maintaining the same order of features.
feature_names.sort()
# Get feature values.
for name in feature_names:
feature_values.append(all_vars[name])
return feature_names, feature_values | [
"def",
"get_features2",
"(",
"self",
")",
":",
"feature_names",
"=",
"[",
"]",
"feature_values",
"=",
"[",
"]",
"# Get all the names of features.",
"all_vars",
"=",
"vars",
"(",
"self",
")",
"for",
"name",
"in",
"all_vars",
".",
"keys",
"(",
")",
":",
"# Omit input variables such as date, mag, err, etc.",
"if",
"not",
"(",
"name",
"==",
"'date'",
"or",
"name",
"==",
"'mag'",
"or",
"name",
"==",
"'err'",
"or",
"name",
"==",
"'n_threads'",
"or",
"name",
"==",
"'min_period'",
")",
":",
"# Filter some other unnecessary features.",
"if",
"not",
"(",
"name",
"==",
"'f'",
"or",
"name",
"==",
"'f_phase'",
"or",
"name",
"==",
"'period_log10FAP'",
"or",
"name",
"==",
"'weight'",
"or",
"name",
"==",
"'weighted_sum'",
"or",
"name",
"==",
"'median'",
"or",
"name",
"==",
"'mean'",
"or",
"name",
"==",
"'std'",
")",
":",
"feature_names",
".",
"append",
"(",
"name",
")",
"# Sort by the names.",
"# Sorting should be done to keep maintaining the same order of features.",
"feature_names",
".",
"sort",
"(",
")",
"# Get feature values.",
"for",
"name",
"in",
"feature_names",
":",
"feature_values",
".",
"append",
"(",
"all_vars",
"[",
"name",
"]",
")",
"return",
"feature_names",
",",
"feature_values"
] | Return all features with its names.
Returns
-------
names : list
Feature names.
values : list
Feature values | [
"Return",
"all",
"features",
"with",
"its",
"names",
"."
] | 5f381453f26582ef56e62fb8fed7317ce67861af | https://github.com/dwkim78/upsilon/blob/5f381453f26582ef56e62fb8fed7317ce67861af/upsilon/extract_features/extract_features.py#L564-L600 | train |
dwkim78/upsilon | upsilon/extract_features/extract_features.py | ExtractFeatures.get_features_all | def get_features_all(self):
"""
Return all features with its names.
Regardless of being used for train and prediction. Sorted by the names.
Returns
-------
all_features : OrderedDict
Features dictionary.
"""
features = {}
# Get all the names of features.
all_vars = vars(self)
for name in all_vars.keys():
if name in feature_names_list_all:
features[name] = all_vars[name]
# Sort by the keys (i.e. feature names).
features = OrderedDict(sorted(features.items(), key=lambda t: t[0]))
return features | python | def get_features_all(self):
"""
Return all features with its names.
Regardless of being used for train and prediction. Sorted by the names.
Returns
-------
all_features : OrderedDict
Features dictionary.
"""
features = {}
# Get all the names of features.
all_vars = vars(self)
for name in all_vars.keys():
if name in feature_names_list_all:
features[name] = all_vars[name]
# Sort by the keys (i.e. feature names).
features = OrderedDict(sorted(features.items(), key=lambda t: t[0]))
return features | [
"def",
"get_features_all",
"(",
"self",
")",
":",
"features",
"=",
"{",
"}",
"# Get all the names of features.",
"all_vars",
"=",
"vars",
"(",
"self",
")",
"for",
"name",
"in",
"all_vars",
".",
"keys",
"(",
")",
":",
"if",
"name",
"in",
"feature_names_list_all",
":",
"features",
"[",
"name",
"]",
"=",
"all_vars",
"[",
"name",
"]",
"# Sort by the keys (i.e. feature names).",
"features",
"=",
"OrderedDict",
"(",
"sorted",
"(",
"features",
".",
"items",
"(",
")",
",",
"key",
"=",
"lambda",
"t",
":",
"t",
"[",
"0",
"]",
")",
")",
"return",
"features"
] | Return all features with its names.
Regardless of being used for train and prediction. Sorted by the names.
Returns
-------
all_features : OrderedDict
Features dictionary. | [
"Return",
"all",
"features",
"with",
"its",
"names",
"."
] | 5f381453f26582ef56e62fb8fed7317ce67861af | https://github.com/dwkim78/upsilon/blob/5f381453f26582ef56e62fb8fed7317ce67861af/upsilon/extract_features/extract_features.py#L631-L654 | train |
hannes-brt/hebel | hebel/__init__.py | init | def init(device_id=None, random_seed=None):
"""Initialize Hebel.
This function creates a CUDA context, CUBLAS context and
initializes and seeds the pseudo-random number generator.
**Parameters:**
device_id : integer, optional
The ID of the GPU device to use. If this is omitted, PyCUDA's
default context is used, which by default uses the fastest
available device on the system. Alternatively, you can put the
device id in the environment variable ``CUDA_DEVICE`` or into
the file ``.cuda-device`` in the user's home directory.
random_seed : integer, optional
The seed to use for the pseudo-random number generator. If
this is omitted, the seed is taken from the environment
variable ``RANDOM_SEED`` and if that is not defined, a random
integer is used as a seed.
"""
if device_id is None:
random_seed = _os.environ.get('CUDA_DEVICE')
if random_seed is None:
random_seed = _os.environ.get('RANDOM_SEED')
global is_initialized
if not is_initialized:
is_initialized = True
global context
context.init_context(device_id)
from pycuda import gpuarray, driver, curandom
# Initialize memory pool
global memory_pool
memory_pool.init()
# Initialize PRG
global sampler
sampler.set_seed(random_seed)
# Initialize pycuda_ops
from hebel import pycuda_ops
pycuda_ops.init() | python | def init(device_id=None, random_seed=None):
"""Initialize Hebel.
This function creates a CUDA context, CUBLAS context and
initializes and seeds the pseudo-random number generator.
**Parameters:**
device_id : integer, optional
The ID of the GPU device to use. If this is omitted, PyCUDA's
default context is used, which by default uses the fastest
available device on the system. Alternatively, you can put the
device id in the environment variable ``CUDA_DEVICE`` or into
the file ``.cuda-device`` in the user's home directory.
random_seed : integer, optional
The seed to use for the pseudo-random number generator. If
this is omitted, the seed is taken from the environment
variable ``RANDOM_SEED`` and if that is not defined, a random
integer is used as a seed.
"""
if device_id is None:
random_seed = _os.environ.get('CUDA_DEVICE')
if random_seed is None:
random_seed = _os.environ.get('RANDOM_SEED')
global is_initialized
if not is_initialized:
is_initialized = True
global context
context.init_context(device_id)
from pycuda import gpuarray, driver, curandom
# Initialize memory pool
global memory_pool
memory_pool.init()
# Initialize PRG
global sampler
sampler.set_seed(random_seed)
# Initialize pycuda_ops
from hebel import pycuda_ops
pycuda_ops.init() | [
"def",
"init",
"(",
"device_id",
"=",
"None",
",",
"random_seed",
"=",
"None",
")",
":",
"if",
"device_id",
"is",
"None",
":",
"random_seed",
"=",
"_os",
".",
"environ",
".",
"get",
"(",
"'CUDA_DEVICE'",
")",
"if",
"random_seed",
"is",
"None",
":",
"random_seed",
"=",
"_os",
".",
"environ",
".",
"get",
"(",
"'RANDOM_SEED'",
")",
"global",
"is_initialized",
"if",
"not",
"is_initialized",
":",
"is_initialized",
"=",
"True",
"global",
"context",
"context",
".",
"init_context",
"(",
"device_id",
")",
"from",
"pycuda",
"import",
"gpuarray",
",",
"driver",
",",
"curandom",
"# Initialize memory pool",
"global",
"memory_pool",
"memory_pool",
".",
"init",
"(",
")",
"# Initialize PRG",
"global",
"sampler",
"sampler",
".",
"set_seed",
"(",
"random_seed",
")",
"# Initialize pycuda_ops",
"from",
"hebel",
"import",
"pycuda_ops",
"pycuda_ops",
".",
"init",
"(",
")"
] | Initialize Hebel.
This function creates a CUDA context, CUBLAS context and
initializes and seeds the pseudo-random number generator.
**Parameters:**
device_id : integer, optional
The ID of the GPU device to use. If this is omitted, PyCUDA's
default context is used, which by default uses the fastest
available device on the system. Alternatively, you can put the
device id in the environment variable ``CUDA_DEVICE`` or into
the file ``.cuda-device`` in the user's home directory.
random_seed : integer, optional
The seed to use for the pseudo-random number generator. If
this is omitted, the seed is taken from the environment
variable ``RANDOM_SEED`` and if that is not defined, a random
integer is used as a seed. | [
"Initialize",
"Hebel",
"."
] | 1e2c3a9309c2646103901b26a55be4e312dd5005 | https://github.com/hannes-brt/hebel/blob/1e2c3a9309c2646103901b26a55be4e312dd5005/hebel/__init__.py#L96-L143 | train |
rix0rrr/gcl | gcl/ast_util.py | inflate_context_tuple | def inflate_context_tuple(ast_rootpath, root_env):
"""Instantiate a Tuple from a TupleNode.
Walking the AST tree upwards, evaluate from the root down again.
"""
with util.LogTime('inflate_context_tuple'):
# We only need to look at tuple members going down.
inflated = ast_rootpath[0].eval(root_env)
current = inflated
env = root_env
try:
for node in ast_rootpath[1:]:
if is_tuple_member_node(node):
assert framework.is_tuple(current)
with util.LogTime('into tuple'):
thunk, env = inflated.get_thunk_env(node.name)
current = framework.eval(thunk, env)
elif framework.is_list(current):
with util.LogTime('eval thing'):
current = framework.eval(node, env)
if framework.is_tuple(current):
inflated = current
except (gcl.EvaluationError, ast.UnparseableAccess):
# Eat evaluation error, probably means the rightmost tuplemember wasn't complete.
# Return what we have so far.
pass
return inflated | python | def inflate_context_tuple(ast_rootpath, root_env):
"""Instantiate a Tuple from a TupleNode.
Walking the AST tree upwards, evaluate from the root down again.
"""
with util.LogTime('inflate_context_tuple'):
# We only need to look at tuple members going down.
inflated = ast_rootpath[0].eval(root_env)
current = inflated
env = root_env
try:
for node in ast_rootpath[1:]:
if is_tuple_member_node(node):
assert framework.is_tuple(current)
with util.LogTime('into tuple'):
thunk, env = inflated.get_thunk_env(node.name)
current = framework.eval(thunk, env)
elif framework.is_list(current):
with util.LogTime('eval thing'):
current = framework.eval(node, env)
if framework.is_tuple(current):
inflated = current
except (gcl.EvaluationError, ast.UnparseableAccess):
# Eat evaluation error, probably means the rightmost tuplemember wasn't complete.
# Return what we have so far.
pass
return inflated | [
"def",
"inflate_context_tuple",
"(",
"ast_rootpath",
",",
"root_env",
")",
":",
"with",
"util",
".",
"LogTime",
"(",
"'inflate_context_tuple'",
")",
":",
"# We only need to look at tuple members going down.",
"inflated",
"=",
"ast_rootpath",
"[",
"0",
"]",
".",
"eval",
"(",
"root_env",
")",
"current",
"=",
"inflated",
"env",
"=",
"root_env",
"try",
":",
"for",
"node",
"in",
"ast_rootpath",
"[",
"1",
":",
"]",
":",
"if",
"is_tuple_member_node",
"(",
"node",
")",
":",
"assert",
"framework",
".",
"is_tuple",
"(",
"current",
")",
"with",
"util",
".",
"LogTime",
"(",
"'into tuple'",
")",
":",
"thunk",
",",
"env",
"=",
"inflated",
".",
"get_thunk_env",
"(",
"node",
".",
"name",
")",
"current",
"=",
"framework",
".",
"eval",
"(",
"thunk",
",",
"env",
")",
"elif",
"framework",
".",
"is_list",
"(",
"current",
")",
":",
"with",
"util",
".",
"LogTime",
"(",
"'eval thing'",
")",
":",
"current",
"=",
"framework",
".",
"eval",
"(",
"node",
",",
"env",
")",
"if",
"framework",
".",
"is_tuple",
"(",
"current",
")",
":",
"inflated",
"=",
"current",
"except",
"(",
"gcl",
".",
"EvaluationError",
",",
"ast",
".",
"UnparseableAccess",
")",
":",
"# Eat evaluation error, probably means the rightmost tuplemember wasn't complete.",
"# Return what we have so far.",
"pass",
"return",
"inflated"
] | Instantiate a Tuple from a TupleNode.
Walking the AST tree upwards, evaluate from the root down again. | [
"Instantiate",
"a",
"Tuple",
"from",
"a",
"TupleNode",
"."
] | 4e3bccc978a9c60aaaffd20f6f291c4d23775cdf | https://github.com/rix0rrr/gcl/blob/4e3bccc978a9c60aaaffd20f6f291c4d23775cdf/gcl/ast_util.py#L24-L52 | train |
rix0rrr/gcl | gcl/ast_util.py | enumerate_scope | def enumerate_scope(ast_rootpath, root_env=None, include_default_builtins=False):
"""Return a dict of { name => Completions } for the given tuple node.
Enumerates all keys that are in scope in a given tuple. The node
part of the tuple may be None, in case the binding is a built-in.
"""
with util.LogTime('enumerate_scope'):
scope = {}
for node in reversed(ast_rootpath):
if is_tuple_node(node):
for member in node.members:
if member.name not in scope:
scope[member.name] = Completion(member.name, False, member.comment.as_string(), member.location)
if include_default_builtins: # Backwards compat flag
root_env = gcl.default_env
if root_env:
for k in root_env.keys():
if k not in scope and not hide_from_autocomplete(root_env[k]):
v = root_env[k]
scope[k] = Completion(k, True, dedent(v.__doc__ or ''), None)
return scope | python | def enumerate_scope(ast_rootpath, root_env=None, include_default_builtins=False):
"""Return a dict of { name => Completions } for the given tuple node.
Enumerates all keys that are in scope in a given tuple. The node
part of the tuple may be None, in case the binding is a built-in.
"""
with util.LogTime('enumerate_scope'):
scope = {}
for node in reversed(ast_rootpath):
if is_tuple_node(node):
for member in node.members:
if member.name not in scope:
scope[member.name] = Completion(member.name, False, member.comment.as_string(), member.location)
if include_default_builtins: # Backwards compat flag
root_env = gcl.default_env
if root_env:
for k in root_env.keys():
if k not in scope and not hide_from_autocomplete(root_env[k]):
v = root_env[k]
scope[k] = Completion(k, True, dedent(v.__doc__ or ''), None)
return scope | [
"def",
"enumerate_scope",
"(",
"ast_rootpath",
",",
"root_env",
"=",
"None",
",",
"include_default_builtins",
"=",
"False",
")",
":",
"with",
"util",
".",
"LogTime",
"(",
"'enumerate_scope'",
")",
":",
"scope",
"=",
"{",
"}",
"for",
"node",
"in",
"reversed",
"(",
"ast_rootpath",
")",
":",
"if",
"is_tuple_node",
"(",
"node",
")",
":",
"for",
"member",
"in",
"node",
".",
"members",
":",
"if",
"member",
".",
"name",
"not",
"in",
"scope",
":",
"scope",
"[",
"member",
".",
"name",
"]",
"=",
"Completion",
"(",
"member",
".",
"name",
",",
"False",
",",
"member",
".",
"comment",
".",
"as_string",
"(",
")",
",",
"member",
".",
"location",
")",
"if",
"include_default_builtins",
":",
"# Backwards compat flag",
"root_env",
"=",
"gcl",
".",
"default_env",
"if",
"root_env",
":",
"for",
"k",
"in",
"root_env",
".",
"keys",
"(",
")",
":",
"if",
"k",
"not",
"in",
"scope",
"and",
"not",
"hide_from_autocomplete",
"(",
"root_env",
"[",
"k",
"]",
")",
":",
"v",
"=",
"root_env",
"[",
"k",
"]",
"scope",
"[",
"k",
"]",
"=",
"Completion",
"(",
"k",
",",
"True",
",",
"dedent",
"(",
"v",
".",
"__doc__",
"or",
"''",
")",
",",
"None",
")",
"return",
"scope"
] | Return a dict of { name => Completions } for the given tuple node.
Enumerates all keys that are in scope in a given tuple. The node
part of the tuple may be None, in case the binding is a built-in. | [
"Return",
"a",
"dict",
"of",
"{",
"name",
"=",
">",
"Completions",
"}",
"for",
"the",
"given",
"tuple",
"node",
"."
] | 4e3bccc978a9c60aaaffd20f6f291c4d23775cdf | https://github.com/rix0rrr/gcl/blob/4e3bccc978a9c60aaaffd20f6f291c4d23775cdf/gcl/ast_util.py#L75-L98 | train |
rix0rrr/gcl | gcl/ast_util.py | find_deref_completions | def find_deref_completions(ast_rootpath, root_env=gcl.default_env):
"""Returns a dict of { name => Completions }."""
with util.LogTime('find_deref_completions'):
tup = inflate_context_tuple(ast_rootpath, root_env)
path = path_until(ast_rootpath, is_deref_node)
if not path:
return {}
deref = path[-1]
haystack = deref.haystack(tup.env(tup))
if not hasattr(haystack, 'keys'):
return {}
return {n: get_completion(haystack, n) for n in haystack.keys()} | python | def find_deref_completions(ast_rootpath, root_env=gcl.default_env):
"""Returns a dict of { name => Completions }."""
with util.LogTime('find_deref_completions'):
tup = inflate_context_tuple(ast_rootpath, root_env)
path = path_until(ast_rootpath, is_deref_node)
if not path:
return {}
deref = path[-1]
haystack = deref.haystack(tup.env(tup))
if not hasattr(haystack, 'keys'):
return {}
return {n: get_completion(haystack, n) for n in haystack.keys()} | [
"def",
"find_deref_completions",
"(",
"ast_rootpath",
",",
"root_env",
"=",
"gcl",
".",
"default_env",
")",
":",
"with",
"util",
".",
"LogTime",
"(",
"'find_deref_completions'",
")",
":",
"tup",
"=",
"inflate_context_tuple",
"(",
"ast_rootpath",
",",
"root_env",
")",
"path",
"=",
"path_until",
"(",
"ast_rootpath",
",",
"is_deref_node",
")",
"if",
"not",
"path",
":",
"return",
"{",
"}",
"deref",
"=",
"path",
"[",
"-",
"1",
"]",
"haystack",
"=",
"deref",
".",
"haystack",
"(",
"tup",
".",
"env",
"(",
"tup",
")",
")",
"if",
"not",
"hasattr",
"(",
"haystack",
",",
"'keys'",
")",
":",
"return",
"{",
"}",
"return",
"{",
"n",
":",
"get_completion",
"(",
"haystack",
",",
"n",
")",
"for",
"n",
"in",
"haystack",
".",
"keys",
"(",
")",
"}"
] | Returns a dict of { name => Completions }. | [
"Returns",
"a",
"dict",
"of",
"{",
"name",
"=",
">",
"Completions",
"}",
"."
] | 4e3bccc978a9c60aaaffd20f6f291c4d23775cdf | https://github.com/rix0rrr/gcl/blob/4e3bccc978a9c60aaaffd20f6f291c4d23775cdf/gcl/ast_util.py#L122-L133 | train |
rix0rrr/gcl | gcl/ast_util.py | is_identifier_position | def is_identifier_position(rootpath):
"""Return whether the cursor is in identifier-position in a member declaration."""
if len(rootpath) >= 2 and is_tuple_member_node(rootpath[-2]) and is_identifier(rootpath[-1]):
return True
if len(rootpath) >= 1 and is_tuple_node(rootpath[-1]):
# No deeper node than tuple? Must be identifier position, otherwise we'd have a TupleMemberNode.
return True
return False | python | def is_identifier_position(rootpath):
"""Return whether the cursor is in identifier-position in a member declaration."""
if len(rootpath) >= 2 and is_tuple_member_node(rootpath[-2]) and is_identifier(rootpath[-1]):
return True
if len(rootpath) >= 1 and is_tuple_node(rootpath[-1]):
# No deeper node than tuple? Must be identifier position, otherwise we'd have a TupleMemberNode.
return True
return False | [
"def",
"is_identifier_position",
"(",
"rootpath",
")",
":",
"if",
"len",
"(",
"rootpath",
")",
">=",
"2",
"and",
"is_tuple_member_node",
"(",
"rootpath",
"[",
"-",
"2",
"]",
")",
"and",
"is_identifier",
"(",
"rootpath",
"[",
"-",
"1",
"]",
")",
":",
"return",
"True",
"if",
"len",
"(",
"rootpath",
")",
">=",
"1",
"and",
"is_tuple_node",
"(",
"rootpath",
"[",
"-",
"1",
"]",
")",
":",
"# No deeper node than tuple? Must be identifier position, otherwise we'd have a TupleMemberNode.",
"return",
"True",
"return",
"False"
] | Return whether the cursor is in identifier-position in a member declaration. | [
"Return",
"whether",
"the",
"cursor",
"is",
"in",
"identifier",
"-",
"position",
"in",
"a",
"member",
"declaration",
"."
] | 4e3bccc978a9c60aaaffd20f6f291c4d23775cdf | https://github.com/rix0rrr/gcl/blob/4e3bccc978a9c60aaaffd20f6f291c4d23775cdf/gcl/ast_util.py#L141-L148 | train |
rix0rrr/gcl | gcl/ast_util.py | find_completions_at_cursor | def find_completions_at_cursor(ast_tree, filename, line, col, root_env=gcl.default_env):
"""Find completions at the cursor.
Return a dict of { name => Completion } objects.
"""
q = gcl.SourceQuery(filename, line, col - 1)
rootpath = ast_tree.find_tokens(q)
if is_identifier_position(rootpath):
return find_inherited_key_completions(rootpath, root_env)
try:
ret = find_deref_completions(rootpath, root_env) or enumerate_scope(rootpath, root_env=root_env)
assert isinstance(ret, dict)
return ret
except gcl.EvaluationError:
# Probably an unbound value or something--just return an empty list
return {} | python | def find_completions_at_cursor(ast_tree, filename, line, col, root_env=gcl.default_env):
"""Find completions at the cursor.
Return a dict of { name => Completion } objects.
"""
q = gcl.SourceQuery(filename, line, col - 1)
rootpath = ast_tree.find_tokens(q)
if is_identifier_position(rootpath):
return find_inherited_key_completions(rootpath, root_env)
try:
ret = find_deref_completions(rootpath, root_env) or enumerate_scope(rootpath, root_env=root_env)
assert isinstance(ret, dict)
return ret
except gcl.EvaluationError:
# Probably an unbound value or something--just return an empty list
return {} | [
"def",
"find_completions_at_cursor",
"(",
"ast_tree",
",",
"filename",
",",
"line",
",",
"col",
",",
"root_env",
"=",
"gcl",
".",
"default_env",
")",
":",
"q",
"=",
"gcl",
".",
"SourceQuery",
"(",
"filename",
",",
"line",
",",
"col",
"-",
"1",
")",
"rootpath",
"=",
"ast_tree",
".",
"find_tokens",
"(",
"q",
")",
"if",
"is_identifier_position",
"(",
"rootpath",
")",
":",
"return",
"find_inherited_key_completions",
"(",
"rootpath",
",",
"root_env",
")",
"try",
":",
"ret",
"=",
"find_deref_completions",
"(",
"rootpath",
",",
"root_env",
")",
"or",
"enumerate_scope",
"(",
"rootpath",
",",
"root_env",
"=",
"root_env",
")",
"assert",
"isinstance",
"(",
"ret",
",",
"dict",
")",
"return",
"ret",
"except",
"gcl",
".",
"EvaluationError",
":",
"# Probably an unbound value or something--just return an empty list",
"return",
"{",
"}"
] | Find completions at the cursor.
Return a dict of { name => Completion } objects. | [
"Find",
"completions",
"at",
"the",
"cursor",
"."
] | 4e3bccc978a9c60aaaffd20f6f291c4d23775cdf | https://github.com/rix0rrr/gcl/blob/4e3bccc978a9c60aaaffd20f6f291c4d23775cdf/gcl/ast_util.py#L151-L168 | train |
rix0rrr/gcl | gcl/ast_util.py | find_inherited_key_completions | def find_inherited_key_completions(rootpath, root_env):
"""Return completion keys from INHERITED tuples.
Easiest way to get those is to evaluate the tuple, check if it is a CompositeTuple,
then enumerate the keys that are NOT in the rightmost tuple.
"""
tup = inflate_context_tuple(rootpath, root_env)
if isinstance(tup, runtime.CompositeTuple):
keys = set(k for t in tup.tuples[:-1] for k in t.keys())
return {n: get_completion(tup, n) for n in keys}
return {} | python | def find_inherited_key_completions(rootpath, root_env):
"""Return completion keys from INHERITED tuples.
Easiest way to get those is to evaluate the tuple, check if it is a CompositeTuple,
then enumerate the keys that are NOT in the rightmost tuple.
"""
tup = inflate_context_tuple(rootpath, root_env)
if isinstance(tup, runtime.CompositeTuple):
keys = set(k for t in tup.tuples[:-1] for k in t.keys())
return {n: get_completion(tup, n) for n in keys}
return {} | [
"def",
"find_inherited_key_completions",
"(",
"rootpath",
",",
"root_env",
")",
":",
"tup",
"=",
"inflate_context_tuple",
"(",
"rootpath",
",",
"root_env",
")",
"if",
"isinstance",
"(",
"tup",
",",
"runtime",
".",
"CompositeTuple",
")",
":",
"keys",
"=",
"set",
"(",
"k",
"for",
"t",
"in",
"tup",
".",
"tuples",
"[",
":",
"-",
"1",
"]",
"for",
"k",
"in",
"t",
".",
"keys",
"(",
")",
")",
"return",
"{",
"n",
":",
"get_completion",
"(",
"tup",
",",
"n",
")",
"for",
"n",
"in",
"keys",
"}",
"return",
"{",
"}"
] | Return completion keys from INHERITED tuples.
Easiest way to get those is to evaluate the tuple, check if it is a CompositeTuple,
then enumerate the keys that are NOT in the rightmost tuple. | [
"Return",
"completion",
"keys",
"from",
"INHERITED",
"tuples",
"."
] | 4e3bccc978a9c60aaaffd20f6f291c4d23775cdf | https://github.com/rix0rrr/gcl/blob/4e3bccc978a9c60aaaffd20f6f291c4d23775cdf/gcl/ast_util.py#L171-L181 | train |
rix0rrr/gcl | gcl/ast_util.py | find_value_at_cursor | def find_value_at_cursor(ast_tree, filename, line, col, root_env=gcl.default_env):
"""Find the value of the object under the cursor."""
q = gcl.SourceQuery(filename, line, col)
rootpath = ast_tree.find_tokens(q)
rootpath = path_until(rootpath, is_thunk)
if len(rootpath) <= 1:
# Just the file tuple itself, or some non-thunk element at the top level
return None
tup = inflate_context_tuple(rootpath, root_env)
try:
if isinstance(rootpath[-1], ast.Inherit):
# Special case handling of 'Inherit' nodes, show the value that's being
# inherited.
return tup[rootpath[-1].name]
return rootpath[-1].eval(tup.env(tup))
except gcl.EvaluationError as e:
return e | python | def find_value_at_cursor(ast_tree, filename, line, col, root_env=gcl.default_env):
"""Find the value of the object under the cursor."""
q = gcl.SourceQuery(filename, line, col)
rootpath = ast_tree.find_tokens(q)
rootpath = path_until(rootpath, is_thunk)
if len(rootpath) <= 1:
# Just the file tuple itself, or some non-thunk element at the top level
return None
tup = inflate_context_tuple(rootpath, root_env)
try:
if isinstance(rootpath[-1], ast.Inherit):
# Special case handling of 'Inherit' nodes, show the value that's being
# inherited.
return tup[rootpath[-1].name]
return rootpath[-1].eval(tup.env(tup))
except gcl.EvaluationError as e:
return e | [
"def",
"find_value_at_cursor",
"(",
"ast_tree",
",",
"filename",
",",
"line",
",",
"col",
",",
"root_env",
"=",
"gcl",
".",
"default_env",
")",
":",
"q",
"=",
"gcl",
".",
"SourceQuery",
"(",
"filename",
",",
"line",
",",
"col",
")",
"rootpath",
"=",
"ast_tree",
".",
"find_tokens",
"(",
"q",
")",
"rootpath",
"=",
"path_until",
"(",
"rootpath",
",",
"is_thunk",
")",
"if",
"len",
"(",
"rootpath",
")",
"<=",
"1",
":",
"# Just the file tuple itself, or some non-thunk element at the top level",
"return",
"None",
"tup",
"=",
"inflate_context_tuple",
"(",
"rootpath",
",",
"root_env",
")",
"try",
":",
"if",
"isinstance",
"(",
"rootpath",
"[",
"-",
"1",
"]",
",",
"ast",
".",
"Inherit",
")",
":",
"# Special case handling of 'Inherit' nodes, show the value that's being",
"# inherited.",
"return",
"tup",
"[",
"rootpath",
"[",
"-",
"1",
"]",
".",
"name",
"]",
"return",
"rootpath",
"[",
"-",
"1",
"]",
".",
"eval",
"(",
"tup",
".",
"env",
"(",
"tup",
")",
")",
"except",
"gcl",
".",
"EvaluationError",
"as",
"e",
":",
"return",
"e"
] | Find the value of the object under the cursor. | [
"Find",
"the",
"value",
"of",
"the",
"object",
"under",
"the",
"cursor",
"."
] | 4e3bccc978a9c60aaaffd20f6f291c4d23775cdf | https://github.com/rix0rrr/gcl/blob/4e3bccc978a9c60aaaffd20f6f291c4d23775cdf/gcl/ast_util.py#L184-L202 | train |
hannes-brt/hebel | hebel/pycuda_ops/matrix.py | add_vec_to_mat | def add_vec_to_mat(mat, vec, axis=None, inplace=False,
target=None, substract=False):
""" Add a vector to a matrix
"""
assert mat.flags.c_contiguous
if axis is None:
if vec.shape[0] == mat.shape[0]:
axis = 0
elif vec.shape[0] == mat.shape[1]:
axis = 1
else:
raise ValueError('Vector length must be equal '
'to one side of the matrix')
n, m = mat.shape
block = (_compilation_constants['add_vec_block_size'],
_compilation_constants['add_vec_block_size'], 1)
gridx = ceil_div(n, block[0])
gridy = ceil_div(m, block[1])
grid = (gridx, gridy, 1)
if inplace:
target = mat
elif target is None:
target = gpuarray.empty_like(mat)
if axis == 0:
assert vec.shape[0] == mat.shape[0]
add_col_vec_kernel.prepared_call(
grid, block,
mat.gpudata,
vec.gpudata,
target.gpudata,
np.uint32(n),
np.uint32(m),
np.int32(substract))
elif axis == 1:
assert vec.shape[0] == mat.shape[1]
add_row_vec_kernel.prepared_call(
grid, block,
mat.gpudata,
vec.gpudata,
target.gpudata,
np.uint32(n),
np.uint32(m),
np.int32(substract))
return target | python | def add_vec_to_mat(mat, vec, axis=None, inplace=False,
target=None, substract=False):
""" Add a vector to a matrix
"""
assert mat.flags.c_contiguous
if axis is None:
if vec.shape[0] == mat.shape[0]:
axis = 0
elif vec.shape[0] == mat.shape[1]:
axis = 1
else:
raise ValueError('Vector length must be equal '
'to one side of the matrix')
n, m = mat.shape
block = (_compilation_constants['add_vec_block_size'],
_compilation_constants['add_vec_block_size'], 1)
gridx = ceil_div(n, block[0])
gridy = ceil_div(m, block[1])
grid = (gridx, gridy, 1)
if inplace:
target = mat
elif target is None:
target = gpuarray.empty_like(mat)
if axis == 0:
assert vec.shape[0] == mat.shape[0]
add_col_vec_kernel.prepared_call(
grid, block,
mat.gpudata,
vec.gpudata,
target.gpudata,
np.uint32(n),
np.uint32(m),
np.int32(substract))
elif axis == 1:
assert vec.shape[0] == mat.shape[1]
add_row_vec_kernel.prepared_call(
grid, block,
mat.gpudata,
vec.gpudata,
target.gpudata,
np.uint32(n),
np.uint32(m),
np.int32(substract))
return target | [
"def",
"add_vec_to_mat",
"(",
"mat",
",",
"vec",
",",
"axis",
"=",
"None",
",",
"inplace",
"=",
"False",
",",
"target",
"=",
"None",
",",
"substract",
"=",
"False",
")",
":",
"assert",
"mat",
".",
"flags",
".",
"c_contiguous",
"if",
"axis",
"is",
"None",
":",
"if",
"vec",
".",
"shape",
"[",
"0",
"]",
"==",
"mat",
".",
"shape",
"[",
"0",
"]",
":",
"axis",
"=",
"0",
"elif",
"vec",
".",
"shape",
"[",
"0",
"]",
"==",
"mat",
".",
"shape",
"[",
"1",
"]",
":",
"axis",
"=",
"1",
"else",
":",
"raise",
"ValueError",
"(",
"'Vector length must be equal '",
"'to one side of the matrix'",
")",
"n",
",",
"m",
"=",
"mat",
".",
"shape",
"block",
"=",
"(",
"_compilation_constants",
"[",
"'add_vec_block_size'",
"]",
",",
"_compilation_constants",
"[",
"'add_vec_block_size'",
"]",
",",
"1",
")",
"gridx",
"=",
"ceil_div",
"(",
"n",
",",
"block",
"[",
"0",
"]",
")",
"gridy",
"=",
"ceil_div",
"(",
"m",
",",
"block",
"[",
"1",
"]",
")",
"grid",
"=",
"(",
"gridx",
",",
"gridy",
",",
"1",
")",
"if",
"inplace",
":",
"target",
"=",
"mat",
"elif",
"target",
"is",
"None",
":",
"target",
"=",
"gpuarray",
".",
"empty_like",
"(",
"mat",
")",
"if",
"axis",
"==",
"0",
":",
"assert",
"vec",
".",
"shape",
"[",
"0",
"]",
"==",
"mat",
".",
"shape",
"[",
"0",
"]",
"add_col_vec_kernel",
".",
"prepared_call",
"(",
"grid",
",",
"block",
",",
"mat",
".",
"gpudata",
",",
"vec",
".",
"gpudata",
",",
"target",
".",
"gpudata",
",",
"np",
".",
"uint32",
"(",
"n",
")",
",",
"np",
".",
"uint32",
"(",
"m",
")",
",",
"np",
".",
"int32",
"(",
"substract",
")",
")",
"elif",
"axis",
"==",
"1",
":",
"assert",
"vec",
".",
"shape",
"[",
"0",
"]",
"==",
"mat",
".",
"shape",
"[",
"1",
"]",
"add_row_vec_kernel",
".",
"prepared_call",
"(",
"grid",
",",
"block",
",",
"mat",
".",
"gpudata",
",",
"vec",
".",
"gpudata",
",",
"target",
".",
"gpudata",
",",
"np",
".",
"uint32",
"(",
"n",
")",
",",
"np",
".",
"uint32",
"(",
"m",
")",
",",
"np",
".",
"int32",
"(",
"substract",
")",
")",
"return",
"target"
] | Add a vector to a matrix | [
"Add",
"a",
"vector",
"to",
"a",
"matrix"
] | 1e2c3a9309c2646103901b26a55be4e312dd5005 | https://github.com/hannes-brt/hebel/blob/1e2c3a9309c2646103901b26a55be4e312dd5005/hebel/pycuda_ops/matrix.py#L130-L179 | train |
hannes-brt/hebel | hebel/pycuda_ops/matrix.py | vector_normalize | def vector_normalize(mat, max_vec_norm=1.):
""" Normalize each column vector in mat to length
max_vec_norm if it is longer than max_vec_norm
"""
assert mat.flags.c_contiguous
n, m = mat.shape
vector_normalize_kernel.prepared_call(
(m, 1, 1), (32, 1, 1),
mat.gpudata,
np.float32(max_vec_norm),
np.int32(m),
np.int32(n)) | python | def vector_normalize(mat, max_vec_norm=1.):
""" Normalize each column vector in mat to length
max_vec_norm if it is longer than max_vec_norm
"""
assert mat.flags.c_contiguous
n, m = mat.shape
vector_normalize_kernel.prepared_call(
(m, 1, 1), (32, 1, 1),
mat.gpudata,
np.float32(max_vec_norm),
np.int32(m),
np.int32(n)) | [
"def",
"vector_normalize",
"(",
"mat",
",",
"max_vec_norm",
"=",
"1.",
")",
":",
"assert",
"mat",
".",
"flags",
".",
"c_contiguous",
"n",
",",
"m",
"=",
"mat",
".",
"shape",
"vector_normalize_kernel",
".",
"prepared_call",
"(",
"(",
"m",
",",
"1",
",",
"1",
")",
",",
"(",
"32",
",",
"1",
",",
"1",
")",
",",
"mat",
".",
"gpudata",
",",
"np",
".",
"float32",
"(",
"max_vec_norm",
")",
",",
"np",
".",
"int32",
"(",
"m",
")",
",",
"np",
".",
"int32",
"(",
"n",
")",
")"
] | Normalize each column vector in mat to length
max_vec_norm if it is longer than max_vec_norm | [
"Normalize",
"each",
"column",
"vector",
"in",
"mat",
"to",
"length",
"max_vec_norm",
"if",
"it",
"is",
"longer",
"than",
"max_vec_norm"
] | 1e2c3a9309c2646103901b26a55be4e312dd5005 | https://github.com/hannes-brt/hebel/blob/1e2c3a9309c2646103901b26a55be4e312dd5005/hebel/pycuda_ops/matrix.py#L182-L194 | train |
hannes-brt/hebel | hebel/utils/string_utils.py | preprocess | def preprocess(string):
"""
Preprocesses a string, by replacing ${VARNAME} with
os.environ['VARNAME']
Parameters
----------
string: the str object to preprocess
Returns
-------
the preprocessed string
"""
split = string.split('${')
rval = [split[0]]
for candidate in split[1:]:
subsplit = candidate.split('}')
if len(subsplit) < 2:
raise ValueError('Open ${ not followed by } before ' \
+ 'end of string or next ${ in "' \
+ string + '"')
varname = subsplit[0]
if varname == 'PYLEARN2_TRAIN_FILE_NAME':
warnings.warn("PYLEARN2_TRAIN_FILE_NAME is deprecated and may be "
"removed from the library on or after Oct 22, 2013. Switch"
" to PYLEARN2_TRAIN_FILE_FULL_STEM")
try:
val = os.environ[varname]
except KeyError:
if varname == 'PYLEARN2_DATA_PATH':
raise NoDataPathError()
if varname == 'PYLEARN2_VIEWER_COMMAND':
raise EnvironmentVariableError(environment_variable_essay)
raise ValueError('Unrecognized environment variable "' + varname
+ '". Did you mean ' + match(varname, os.environ.keys())
+ '?')
rval.append(val)
rval.append('}'.join(subsplit[1:]))
rval = ''.join(rval)
return rval | python | def preprocess(string):
"""
Preprocesses a string, by replacing ${VARNAME} with
os.environ['VARNAME']
Parameters
----------
string: the str object to preprocess
Returns
-------
the preprocessed string
"""
split = string.split('${')
rval = [split[0]]
for candidate in split[1:]:
subsplit = candidate.split('}')
if len(subsplit) < 2:
raise ValueError('Open ${ not followed by } before ' \
+ 'end of string or next ${ in "' \
+ string + '"')
varname = subsplit[0]
if varname == 'PYLEARN2_TRAIN_FILE_NAME':
warnings.warn("PYLEARN2_TRAIN_FILE_NAME is deprecated and may be "
"removed from the library on or after Oct 22, 2013. Switch"
" to PYLEARN2_TRAIN_FILE_FULL_STEM")
try:
val = os.environ[varname]
except KeyError:
if varname == 'PYLEARN2_DATA_PATH':
raise NoDataPathError()
if varname == 'PYLEARN2_VIEWER_COMMAND':
raise EnvironmentVariableError(environment_variable_essay)
raise ValueError('Unrecognized environment variable "' + varname
+ '". Did you mean ' + match(varname, os.environ.keys())
+ '?')
rval.append(val)
rval.append('}'.join(subsplit[1:]))
rval = ''.join(rval)
return rval | [
"def",
"preprocess",
"(",
"string",
")",
":",
"split",
"=",
"string",
".",
"split",
"(",
"'${'",
")",
"rval",
"=",
"[",
"split",
"[",
"0",
"]",
"]",
"for",
"candidate",
"in",
"split",
"[",
"1",
":",
"]",
":",
"subsplit",
"=",
"candidate",
".",
"split",
"(",
"'}'",
")",
"if",
"len",
"(",
"subsplit",
")",
"<",
"2",
":",
"raise",
"ValueError",
"(",
"'Open ${ not followed by } before '",
"+",
"'end of string or next ${ in \"'",
"+",
"string",
"+",
"'\"'",
")",
"varname",
"=",
"subsplit",
"[",
"0",
"]",
"if",
"varname",
"==",
"'PYLEARN2_TRAIN_FILE_NAME'",
":",
"warnings",
".",
"warn",
"(",
"\"PYLEARN2_TRAIN_FILE_NAME is deprecated and may be \"",
"\"removed from the library on or after Oct 22, 2013. Switch\"",
"\" to PYLEARN2_TRAIN_FILE_FULL_STEM\"",
")",
"try",
":",
"val",
"=",
"os",
".",
"environ",
"[",
"varname",
"]",
"except",
"KeyError",
":",
"if",
"varname",
"==",
"'PYLEARN2_DATA_PATH'",
":",
"raise",
"NoDataPathError",
"(",
")",
"if",
"varname",
"==",
"'PYLEARN2_VIEWER_COMMAND'",
":",
"raise",
"EnvironmentVariableError",
"(",
"environment_variable_essay",
")",
"raise",
"ValueError",
"(",
"'Unrecognized environment variable \"'",
"+",
"varname",
"+",
"'\". Did you mean '",
"+",
"match",
"(",
"varname",
",",
"os",
".",
"environ",
".",
"keys",
"(",
")",
")",
"+",
"'?'",
")",
"rval",
".",
"append",
"(",
"val",
")",
"rval",
".",
"append",
"(",
"'}'",
".",
"join",
"(",
"subsplit",
"[",
"1",
":",
"]",
")",
")",
"rval",
"=",
"''",
".",
"join",
"(",
"rval",
")",
"return",
"rval"
] | Preprocesses a string, by replacing ${VARNAME} with
os.environ['VARNAME']
Parameters
----------
string: the str object to preprocess
Returns
-------
the preprocessed string | [
"Preprocesses",
"a",
"string",
"by",
"replacing",
"$",
"{",
"VARNAME",
"}",
"with",
"os",
".",
"environ",
"[",
"VARNAME",
"]"
] | 1e2c3a9309c2646103901b26a55be4e312dd5005 | https://github.com/hannes-brt/hebel/blob/1e2c3a9309c2646103901b26a55be4e312dd5005/hebel/utils/string_utils.py#L26-L77 | train |
hannes-brt/hebel | hebel/utils/string_utils.py | tokenize_by_number | def tokenize_by_number(s):
""" splits a string into a list of tokens
each is either a string containing no numbers
or a float """
r = find_number(s)
if r == None:
return [ s ]
else:
tokens = []
if r[0] > 0:
tokens.append(s[0:r[0]])
tokens.append( float(s[r[0]:r[1]]) )
if r[1] < len(s):
tokens.extend(tokenize_by_number(s[r[1]:]))
return tokens
assert False | python | def tokenize_by_number(s):
""" splits a string into a list of tokens
each is either a string containing no numbers
or a float """
r = find_number(s)
if r == None:
return [ s ]
else:
tokens = []
if r[0] > 0:
tokens.append(s[0:r[0]])
tokens.append( float(s[r[0]:r[1]]) )
if r[1] < len(s):
tokens.extend(tokenize_by_number(s[r[1]:]))
return tokens
assert False | [
"def",
"tokenize_by_number",
"(",
"s",
")",
":",
"r",
"=",
"find_number",
"(",
"s",
")",
"if",
"r",
"==",
"None",
":",
"return",
"[",
"s",
"]",
"else",
":",
"tokens",
"=",
"[",
"]",
"if",
"r",
"[",
"0",
"]",
">",
"0",
":",
"tokens",
".",
"append",
"(",
"s",
"[",
"0",
":",
"r",
"[",
"0",
"]",
"]",
")",
"tokens",
".",
"append",
"(",
"float",
"(",
"s",
"[",
"r",
"[",
"0",
"]",
":",
"r",
"[",
"1",
"]",
"]",
")",
")",
"if",
"r",
"[",
"1",
"]",
"<",
"len",
"(",
"s",
")",
":",
"tokens",
".",
"extend",
"(",
"tokenize_by_number",
"(",
"s",
"[",
"r",
"[",
"1",
"]",
":",
"]",
")",
")",
"return",
"tokens",
"assert",
"False"
] | splits a string into a list of tokens
each is either a string containing no numbers
or a float | [
"splits",
"a",
"string",
"into",
"a",
"list",
"of",
"tokens",
"each",
"is",
"either",
"a",
"string",
"containing",
"no",
"numbers",
"or",
"a",
"float"
] | 1e2c3a9309c2646103901b26a55be4e312dd5005 | https://github.com/hannes-brt/hebel/blob/1e2c3a9309c2646103901b26a55be4e312dd5005/hebel/utils/string_utils.py#L93-L110 | train |
hannes-brt/hebel | hebel/utils/string_utils.py | number_aware_alphabetical_cmp | def number_aware_alphabetical_cmp(str1, str2):
""" cmp function for sorting a list of strings by alphabetical order, but with
numbers sorted numerically.
i.e., foo1, foo2, foo10, foo11
instead of foo1, foo10
"""
def flatten_tokens(tokens):
l = []
for token in tokens:
if isinstance(token, str):
for char in token:
l.append(char)
else:
assert isinstance(token, float)
l.append(token)
return l
seq1 = flatten_tokens(tokenize_by_number(str1))
seq2 = flatten_tokens(tokenize_by_number(str2))
l = min(len(seq1),len(seq2))
i = 0
while i < l:
if seq1[i] < seq2[i]:
return -1
elif seq1[i] > seq2[i]:
return 1
i += 1
if len(seq1) < len(seq2):
return -1
elif len(seq1) > len(seq2):
return 1
return 0 | python | def number_aware_alphabetical_cmp(str1, str2):
""" cmp function for sorting a list of strings by alphabetical order, but with
numbers sorted numerically.
i.e., foo1, foo2, foo10, foo11
instead of foo1, foo10
"""
def flatten_tokens(tokens):
l = []
for token in tokens:
if isinstance(token, str):
for char in token:
l.append(char)
else:
assert isinstance(token, float)
l.append(token)
return l
seq1 = flatten_tokens(tokenize_by_number(str1))
seq2 = flatten_tokens(tokenize_by_number(str2))
l = min(len(seq1),len(seq2))
i = 0
while i < l:
if seq1[i] < seq2[i]:
return -1
elif seq1[i] > seq2[i]:
return 1
i += 1
if len(seq1) < len(seq2):
return -1
elif len(seq1) > len(seq2):
return 1
return 0 | [
"def",
"number_aware_alphabetical_cmp",
"(",
"str1",
",",
"str2",
")",
":",
"def",
"flatten_tokens",
"(",
"tokens",
")",
":",
"l",
"=",
"[",
"]",
"for",
"token",
"in",
"tokens",
":",
"if",
"isinstance",
"(",
"token",
",",
"str",
")",
":",
"for",
"char",
"in",
"token",
":",
"l",
".",
"append",
"(",
"char",
")",
"else",
":",
"assert",
"isinstance",
"(",
"token",
",",
"float",
")",
"l",
".",
"append",
"(",
"token",
")",
"return",
"l",
"seq1",
"=",
"flatten_tokens",
"(",
"tokenize_by_number",
"(",
"str1",
")",
")",
"seq2",
"=",
"flatten_tokens",
"(",
"tokenize_by_number",
"(",
"str2",
")",
")",
"l",
"=",
"min",
"(",
"len",
"(",
"seq1",
")",
",",
"len",
"(",
"seq2",
")",
")",
"i",
"=",
"0",
"while",
"i",
"<",
"l",
":",
"if",
"seq1",
"[",
"i",
"]",
"<",
"seq2",
"[",
"i",
"]",
":",
"return",
"-",
"1",
"elif",
"seq1",
"[",
"i",
"]",
">",
"seq2",
"[",
"i",
"]",
":",
"return",
"1",
"i",
"+=",
"1",
"if",
"len",
"(",
"seq1",
")",
"<",
"len",
"(",
"seq2",
")",
":",
"return",
"-",
"1",
"elif",
"len",
"(",
"seq1",
")",
">",
"len",
"(",
"seq2",
")",
":",
"return",
"1",
"return",
"0"
] | cmp function for sorting a list of strings by alphabetical order, but with
numbers sorted numerically.
i.e., foo1, foo2, foo10, foo11
instead of foo1, foo10 | [
"cmp",
"function",
"for",
"sorting",
"a",
"list",
"of",
"strings",
"by",
"alphabetical",
"order",
"but",
"with",
"numbers",
"sorted",
"numerically",
"."
] | 1e2c3a9309c2646103901b26a55be4e312dd5005 | https://github.com/hannes-brt/hebel/blob/1e2c3a9309c2646103901b26a55be4e312dd5005/hebel/utils/string_utils.py#L113-L151 | train |
hannes-brt/hebel | hebel/utils/string_utils.py | match | def match(wrong, candidates):
"""
wrong: a mispelling
candidates: a set of correct words
returns a guess of which candidate is the right one
This should be used with a small number of candidates and a high potential
edit distance.
ie, use it to correct a wrong filename in a directory, wrong class name
in a module, etc. Don't use it to correct small typos of freeform natural
language words.
"""
assert len(candidates) > 0
# Current implementation tries all candidates and outputs the one
# with the min score
# Could try to do something smarter
def score(w1,w2):
# Current implementation returns negative dot product of
# the two words mapped into a feature space by mapping phi
# w -> [ phi(w1), .1 phi(first letter of w), .1 phi(last letter of w) ]
# Could try to do something smarter
w1 = w1.lower()
w2 = w2.lower()
def phi(w):
# Current feature mapping is to the vector of counts of
# all letters and two-letter sequences
# Could try to do something smarter
rval = {}
for i in xrange(len(w)):
l = w[i]
rval[l] = rval.get(l,0.) + 1.
if i < len(w)-1:
b = w[i:i+2]
rval[b] = rval.get(b,0.) + 1.
return rval
d1 = phi(w1)
d2 = phi(w2)
def mul(d1, d2):
rval = 0
for key in set(d1).union(d2):
rval += d1.get(key,0) * d2.get(key,0)
return rval
tot_score = mul(phi(w1),phi(w2)) / float(len(w1)*len(w2)) + \
0.1 * mul(phi(w1[0:1]), phi(w2[0:1])) + \
0.1 * mul(phi(w1[-1:]), phi(w2[-1:]))
return tot_score
scored_candidates = [ (-score(wrong, candidate), candidate)
for candidate in candidates ]
scored_candidates.sort()
return scored_candidates[0][1] | python | def match(wrong, candidates):
"""
wrong: a mispelling
candidates: a set of correct words
returns a guess of which candidate is the right one
This should be used with a small number of candidates and a high potential
edit distance.
ie, use it to correct a wrong filename in a directory, wrong class name
in a module, etc. Don't use it to correct small typos of freeform natural
language words.
"""
assert len(candidates) > 0
# Current implementation tries all candidates and outputs the one
# with the min score
# Could try to do something smarter
def score(w1,w2):
# Current implementation returns negative dot product of
# the two words mapped into a feature space by mapping phi
# w -> [ phi(w1), .1 phi(first letter of w), .1 phi(last letter of w) ]
# Could try to do something smarter
w1 = w1.lower()
w2 = w2.lower()
def phi(w):
# Current feature mapping is to the vector of counts of
# all letters and two-letter sequences
# Could try to do something smarter
rval = {}
for i in xrange(len(w)):
l = w[i]
rval[l] = rval.get(l,0.) + 1.
if i < len(w)-1:
b = w[i:i+2]
rval[b] = rval.get(b,0.) + 1.
return rval
d1 = phi(w1)
d2 = phi(w2)
def mul(d1, d2):
rval = 0
for key in set(d1).union(d2):
rval += d1.get(key,0) * d2.get(key,0)
return rval
tot_score = mul(phi(w1),phi(w2)) / float(len(w1)*len(w2)) + \
0.1 * mul(phi(w1[0:1]), phi(w2[0:1])) + \
0.1 * mul(phi(w1[-1:]), phi(w2[-1:]))
return tot_score
scored_candidates = [ (-score(wrong, candidate), candidate)
for candidate in candidates ]
scored_candidates.sort()
return scored_candidates[0][1] | [
"def",
"match",
"(",
"wrong",
",",
"candidates",
")",
":",
"assert",
"len",
"(",
"candidates",
")",
">",
"0",
"# Current implementation tries all candidates and outputs the one",
"# with the min score",
"# Could try to do something smarter",
"def",
"score",
"(",
"w1",
",",
"w2",
")",
":",
"# Current implementation returns negative dot product of",
"# the two words mapped into a feature space by mapping phi",
"# w -> [ phi(w1), .1 phi(first letter of w), .1 phi(last letter of w) ]",
"# Could try to do something smarter",
"w1",
"=",
"w1",
".",
"lower",
"(",
")",
"w2",
"=",
"w2",
".",
"lower",
"(",
")",
"def",
"phi",
"(",
"w",
")",
":",
"# Current feature mapping is to the vector of counts of",
"# all letters and two-letter sequences",
"# Could try to do something smarter",
"rval",
"=",
"{",
"}",
"for",
"i",
"in",
"xrange",
"(",
"len",
"(",
"w",
")",
")",
":",
"l",
"=",
"w",
"[",
"i",
"]",
"rval",
"[",
"l",
"]",
"=",
"rval",
".",
"get",
"(",
"l",
",",
"0.",
")",
"+",
"1.",
"if",
"i",
"<",
"len",
"(",
"w",
")",
"-",
"1",
":",
"b",
"=",
"w",
"[",
"i",
":",
"i",
"+",
"2",
"]",
"rval",
"[",
"b",
"]",
"=",
"rval",
".",
"get",
"(",
"b",
",",
"0.",
")",
"+",
"1.",
"return",
"rval",
"d1",
"=",
"phi",
"(",
"w1",
")",
"d2",
"=",
"phi",
"(",
"w2",
")",
"def",
"mul",
"(",
"d1",
",",
"d2",
")",
":",
"rval",
"=",
"0",
"for",
"key",
"in",
"set",
"(",
"d1",
")",
".",
"union",
"(",
"d2",
")",
":",
"rval",
"+=",
"d1",
".",
"get",
"(",
"key",
",",
"0",
")",
"*",
"d2",
".",
"get",
"(",
"key",
",",
"0",
")",
"return",
"rval",
"tot_score",
"=",
"mul",
"(",
"phi",
"(",
"w1",
")",
",",
"phi",
"(",
"w2",
")",
")",
"/",
"float",
"(",
"len",
"(",
"w1",
")",
"*",
"len",
"(",
"w2",
")",
")",
"+",
"0.1",
"*",
"mul",
"(",
"phi",
"(",
"w1",
"[",
"0",
":",
"1",
"]",
")",
",",
"phi",
"(",
"w2",
"[",
"0",
":",
"1",
"]",
")",
")",
"+",
"0.1",
"*",
"mul",
"(",
"phi",
"(",
"w1",
"[",
"-",
"1",
":",
"]",
")",
",",
"phi",
"(",
"w2",
"[",
"-",
"1",
":",
"]",
")",
")",
"return",
"tot_score",
"scored_candidates",
"=",
"[",
"(",
"-",
"score",
"(",
"wrong",
",",
"candidate",
")",
",",
"candidate",
")",
"for",
"candidate",
"in",
"candidates",
"]",
"scored_candidates",
".",
"sort",
"(",
")",
"return",
"scored_candidates",
"[",
"0",
"]",
"[",
"1",
"]"
] | wrong: a mispelling
candidates: a set of correct words
returns a guess of which candidate is the right one
This should be used with a small number of candidates and a high potential
edit distance.
ie, use it to correct a wrong filename in a directory, wrong class name
in a module, etc. Don't use it to correct small typos of freeform natural
language words. | [
"wrong",
":",
"a",
"mispelling",
"candidates",
":",
"a",
"set",
"of",
"correct",
"words"
] | 1e2c3a9309c2646103901b26a55be4e312dd5005 | https://github.com/hannes-brt/hebel/blob/1e2c3a9309c2646103901b26a55be4e312dd5005/hebel/utils/string_utils.py#L153-L219 | train |
hannes-brt/hebel | hebel/utils/string_utils.py | censor_non_alphanum | def censor_non_alphanum(s):
"""
Returns s with all non-alphanumeric characters replaced with *
"""
def censor(ch):
if (ch >= 'A' and ch <= 'z') or (ch >= '0' and ch <= '9'):
return ch
return '*'
return ''.join([censor(ch) for ch in s]) | python | def censor_non_alphanum(s):
"""
Returns s with all non-alphanumeric characters replaced with *
"""
def censor(ch):
if (ch >= 'A' and ch <= 'z') or (ch >= '0' and ch <= '9'):
return ch
return '*'
return ''.join([censor(ch) for ch in s]) | [
"def",
"censor_non_alphanum",
"(",
"s",
")",
":",
"def",
"censor",
"(",
"ch",
")",
":",
"if",
"(",
"ch",
">=",
"'A'",
"and",
"ch",
"<=",
"'z'",
")",
"or",
"(",
"ch",
">=",
"'0'",
"and",
"ch",
"<=",
"'9'",
")",
":",
"return",
"ch",
"return",
"'*'",
"return",
"''",
".",
"join",
"(",
"[",
"censor",
"(",
"ch",
")",
"for",
"ch",
"in",
"s",
"]",
")"
] | Returns s with all non-alphanumeric characters replaced with * | [
"Returns",
"s",
"with",
"all",
"non",
"-",
"alphanumeric",
"characters",
"replaced",
"with",
"*"
] | 1e2c3a9309c2646103901b26a55be4e312dd5005 | https://github.com/hannes-brt/hebel/blob/1e2c3a9309c2646103901b26a55be4e312dd5005/hebel/utils/string_utils.py#L221-L231 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.