repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
DarkEnergySurvey/ugali
ugali/utils/skymap.py
surveyPixel
def surveyPixel(lon, lat, nside_pix, nside_subpix = None): """ Return the set of HEALPix pixels that cover the given coordinates at resolution nside. Optionally return the set of subpixels within those pixels at resolution nside_subpix """ pix = np.unique(ang2pix(nside_pix, lon, lat)) if nside_s...
python
def surveyPixel(lon, lat, nside_pix, nside_subpix = None): """ Return the set of HEALPix pixels that cover the given coordinates at resolution nside. Optionally return the set of subpixels within those pixels at resolution nside_subpix """ pix = np.unique(ang2pix(nside_pix, lon, lat)) if nside_s...
[ "def", "surveyPixel", "(", "lon", ",", "lat", ",", "nside_pix", ",", "nside_subpix", "=", "None", ")", ":", "pix", "=", "np", ".", "unique", "(", "ang2pix", "(", "nside_pix", ",", "lon", ",", "lat", ")", ")", "if", "nside_subpix", "is", "None", ":", ...
Return the set of HEALPix pixels that cover the given coordinates at resolution nside. Optionally return the set of subpixels within those pixels at resolution nside_subpix
[ "Return", "the", "set", "of", "HEALPix", "pixels", "that", "cover", "the", "given", "coordinates", "at", "resolution", "nside", ".", "Optionally", "return", "the", "set", "of", "subpixels", "within", "those", "pixels", "at", "resolution", "nside_subpix" ]
21e890b4117fc810afb6fb058e8055d564f03382
https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/utils/skymap.py#L17-L30
train
DarkEnergySurvey/ugali
ugali/utils/skymap.py
allSkyCoordinates
def allSkyCoordinates(nside): """ Generate a set of coordinates at the centers of pixels of resolutions nside across the full sky. """ lon,lat = pix2ang(nside, np.arange(0, hp.nside2npix(nside))) return lon, lat
python
def allSkyCoordinates(nside): """ Generate a set of coordinates at the centers of pixels of resolutions nside across the full sky. """ lon,lat = pix2ang(nside, np.arange(0, hp.nside2npix(nside))) return lon, lat
[ "def", "allSkyCoordinates", "(", "nside", ")", ":", "lon", ",", "lat", "=", "pix2ang", "(", "nside", ",", "np", ".", "arange", "(", "0", ",", "hp", ".", "nside2npix", "(", "nside", ")", ")", ")", "return", "lon", ",", "lat" ]
Generate a set of coordinates at the centers of pixels of resolutions nside across the full sky.
[ "Generate", "a", "set", "of", "coordinates", "at", "the", "centers", "of", "pixels", "of", "resolutions", "nside", "across", "the", "full", "sky", "." ]
21e890b4117fc810afb6fb058e8055d564f03382
https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/utils/skymap.py#L86-L91
train
DarkEnergySurvey/ugali
ugali/utils/skymap.py
randomPositionsMask
def randomPositionsMask(mask, nside_pix, n): """ Generate n random positions within a HEALPix mask of booleans. KCB: Likely superceded by the randomPositions function, but more generic. """ npix = len(mask) nside = hp.npix2nside(npix) # Estimate the number of points that need to be th...
python
def randomPositionsMask(mask, nside_pix, n): """ Generate n random positions within a HEALPix mask of booleans. KCB: Likely superceded by the randomPositions function, but more generic. """ npix = len(mask) nside = hp.npix2nside(npix) # Estimate the number of points that need to be th...
[ "def", "randomPositionsMask", "(", "mask", ",", "nside_pix", ",", "n", ")", ":", "npix", "=", "len", "(", "mask", ")", "nside", "=", "hp", ".", "npix2nside", "(", "npix", ")", "# Estimate the number of points that need to be thrown based off", "# coverage fraction o...
Generate n random positions within a HEALPix mask of booleans. KCB: Likely superceded by the randomPositions function, but more generic.
[ "Generate", "n", "random", "positions", "within", "a", "HEALPix", "mask", "of", "booleans", "." ]
21e890b4117fc810afb6fb058e8055d564f03382
https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/utils/skymap.py#L153-L185
train
dwavesystems/dwave_embedding_utilities
dwave_embedding_utilities.py
embed_ising
def embed_ising(source_linear, source_quadratic, embedding, target_adjacency, chain_strength=1.0): """Embeds a logical Ising model onto another graph via an embedding. Args: source_linear (dict): The linear biases to be embedded. Should be a dict of the form {v: bias, ...} where v is a vari...
python
def embed_ising(source_linear, source_quadratic, embedding, target_adjacency, chain_strength=1.0): """Embeds a logical Ising model onto another graph via an embedding. Args: source_linear (dict): The linear biases to be embedded. Should be a dict of the form {v: bias, ...} where v is a vari...
[ "def", "embed_ising", "(", "source_linear", ",", "source_quadratic", ",", "embedding", ",", "target_adjacency", ",", "chain_strength", "=", "1.0", ")", ":", "# store variables in the target graph that the embedding hasn't used", "unused", "=", "{", "v", "for", "v", "in"...
Embeds a logical Ising model onto another graph via an embedding. Args: source_linear (dict): The linear biases to be embedded. Should be a dict of the form {v: bias, ...} where v is a variable in the source model and bias is the linear bias associated with v. source_quadrat...
[ "Embeds", "a", "logical", "Ising", "model", "onto", "another", "graph", "via", "an", "embedding", "." ]
2e485e0ae89d96f3c0005f144bab4b465a3039a3
https://github.com/dwavesystems/dwave_embedding_utilities/blob/2e485e0ae89d96f3c0005f144bab4b465a3039a3/dwave_embedding_utilities.py#L163-L278
train
dwavesystems/dwave_embedding_utilities
dwave_embedding_utilities.py
chain_break_frequency
def chain_break_frequency(samples, embedding): """Determines the frequency of chain breaks in the given samples. Args: samples (iterable): An iterable of samples where each sample is a dict of the form {v: val, ...} where v is a variable in the target graph and val is the associ...
python
def chain_break_frequency(samples, embedding): """Determines the frequency of chain breaks in the given samples. Args: samples (iterable): An iterable of samples where each sample is a dict of the form {v: val, ...} where v is a variable in the target graph and val is the associ...
[ "def", "chain_break_frequency", "(", "samples", ",", "embedding", ")", ":", "counts", "=", "{", "v", ":", "0", "for", "v", "in", "embedding", "}", "total", "=", "0", "for", "sample", "in", "samples", ":", "for", "v", ",", "chain", "in", "iteritems", ...
Determines the frequency of chain breaks in the given samples. Args: samples (iterable): An iterable of samples where each sample is a dict of the form {v: val, ...} where v is a variable in the target graph and val is the associated value as determined by a binary quadr...
[ "Determines", "the", "frequency", "of", "chain", "breaks", "in", "the", "given", "samples", "." ]
2e485e0ae89d96f3c0005f144bab4b465a3039a3
https://github.com/dwavesystems/dwave_embedding_utilities/blob/2e485e0ae89d96f3c0005f144bab4b465a3039a3/dwave_embedding_utilities.py#L331-L359
train
dwavesystems/dwave_embedding_utilities
dwave_embedding_utilities.py
unembed_samples
def unembed_samples(samples, embedding, chain_break_method=None): """Return samples over the variables in the source graph. Args: samples (iterable): An iterable of samples where each sample is a dict of the form {v: val, ...} where v is a variable in the target model and val is...
python
def unembed_samples(samples, embedding, chain_break_method=None): """Return samples over the variables in the source graph. Args: samples (iterable): An iterable of samples where each sample is a dict of the form {v: val, ...} where v is a variable in the target model and val is...
[ "def", "unembed_samples", "(", "samples", ",", "embedding", ",", "chain_break_method", "=", "None", ")", ":", "if", "chain_break_method", "is", "None", ":", "chain_break_method", "=", "majority_vote", "return", "list", "(", "itertools", ".", "chain", "(", "*", ...
Return samples over the variables in the source graph. Args: samples (iterable): An iterable of samples where each sample is a dict of the form {v: val, ...} where v is a variable in the target model and val is the associated value as determined by a binary quadratic mod...
[ "Return", "samples", "over", "the", "variables", "in", "the", "source", "graph", "." ]
2e485e0ae89d96f3c0005f144bab4b465a3039a3
https://github.com/dwavesystems/dwave_embedding_utilities/blob/2e485e0ae89d96f3c0005f144bab4b465a3039a3/dwave_embedding_utilities.py#L362-L384
train
dwavesystems/dwave_embedding_utilities
dwave_embedding_utilities.py
discard
def discard(sample, embedding): """Discards the sample if broken. Args: sample (dict): A sample of the form {v: val, ...} where v is a variable in the target graph and val is the associated value as determined by a binary quadratic model sampler. embedding (dict): The ma...
python
def discard(sample, embedding): """Discards the sample if broken. Args: sample (dict): A sample of the form {v: val, ...} where v is a variable in the target graph and val is the associated value as determined by a binary quadratic model sampler. embedding (dict): The ma...
[ "def", "discard", "(", "sample", ",", "embedding", ")", ":", "unembeded", "=", "{", "}", "for", "v", ",", "chain", "in", "iteritems", "(", "embedding", ")", ":", "vals", "=", "[", "sample", "[", "u", "]", "for", "u", "in", "chain", "]", "if", "_a...
Discards the sample if broken. Args: sample (dict): A sample of the form {v: val, ...} where v is a variable in the target graph and val is the associated value as determined by a binary quadratic model sampler. embedding (dict): The mapping from the source graph to the targ...
[ "Discards", "the", "sample", "if", "broken", "." ]
2e485e0ae89d96f3c0005f144bab4b465a3039a3
https://github.com/dwavesystems/dwave_embedding_utilities/blob/2e485e0ae89d96f3c0005f144bab4b465a3039a3/dwave_embedding_utilities.py#L387-L412
train
dwavesystems/dwave_embedding_utilities
dwave_embedding_utilities.py
majority_vote
def majority_vote(sample, embedding): """Determines the sample values by majority vote. Args: sample (dict): A sample of the form {v: val, ...} where v is a variable in the target graph and val is the associated value as determined by a binary quadratic model sampler. em...
python
def majority_vote(sample, embedding): """Determines the sample values by majority vote. Args: sample (dict): A sample of the form {v: val, ...} where v is a variable in the target graph and val is the associated value as determined by a binary quadratic model sampler. em...
[ "def", "majority_vote", "(", "sample", ",", "embedding", ")", ":", "unembeded", "=", "{", "}", "for", "v", ",", "chain", "in", "iteritems", "(", "embedding", ")", ":", "vals", "=", "[", "sample", "[", "u", "]", "for", "u", "in", "chain", "]", "if",...
Determines the sample values by majority vote. Args: sample (dict): A sample of the form {v: val, ...} where v is a variable in the target graph and val is the associated value as determined by a binary quadratic model sampler. embedding (dict): The mapping from the source g...
[ "Determines", "the", "sample", "values", "by", "majority", "vote", "." ]
2e485e0ae89d96f3c0005f144bab4b465a3039a3
https://github.com/dwavesystems/dwave_embedding_utilities/blob/2e485e0ae89d96f3c0005f144bab4b465a3039a3/dwave_embedding_utilities.py#L415-L441
train
dwavesystems/dwave_embedding_utilities
dwave_embedding_utilities.py
weighted_random
def weighted_random(sample, embedding): """Determines the sample values by weighed random choice. Args: sample (dict): A sample of the form {v: val, ...} where v is a variable in the target graph and val is the associated value as determined by a binary quadratic model sampler. ...
python
def weighted_random(sample, embedding): """Determines the sample values by weighed random choice. Args: sample (dict): A sample of the form {v: val, ...} where v is a variable in the target graph and val is the associated value as determined by a binary quadratic model sampler. ...
[ "def", "weighted_random", "(", "sample", ",", "embedding", ")", ":", "unembeded", "=", "{", "}", "for", "v", ",", "chain", "in", "iteritems", "(", "embedding", ")", ":", "vals", "=", "[", "sample", "[", "u", "]", "for", "u", "in", "chain", "]", "# ...
Determines the sample values by weighed random choice. Args: sample (dict): A sample of the form {v: val, ...} where v is a variable in the target graph and val is the associated value as determined by a binary quadratic model sampler. embedding (dict): The mapping from the ...
[ "Determines", "the", "sample", "values", "by", "weighed", "random", "choice", "." ]
2e485e0ae89d96f3c0005f144bab4b465a3039a3
https://github.com/dwavesystems/dwave_embedding_utilities/blob/2e485e0ae89d96f3c0005f144bab4b465a3039a3/dwave_embedding_utilities.py#L444-L470
train
dwavesystems/dwave_embedding_utilities
dwave_embedding_utilities.py
_all_equal
def _all_equal(iterable): """True if all values in `iterable` are equal, else False.""" iterator = iter(iterable) first = next(iterator) return all(first == rest for rest in iterator)
python
def _all_equal(iterable): """True if all values in `iterable` are equal, else False.""" iterator = iter(iterable) first = next(iterator) return all(first == rest for rest in iterator)
[ "def", "_all_equal", "(", "iterable", ")", ":", "iterator", "=", "iter", "(", "iterable", ")", "first", "=", "next", "(", "iterator", ")", "return", "all", "(", "first", "==", "rest", "for", "rest", "in", "iterator", ")" ]
True if all values in `iterable` are equal, else False.
[ "True", "if", "all", "values", "in", "iterable", "are", "equal", "else", "False", "." ]
2e485e0ae89d96f3c0005f144bab4b465a3039a3
https://github.com/dwavesystems/dwave_embedding_utilities/blob/2e485e0ae89d96f3c0005f144bab4b465a3039a3/dwave_embedding_utilities.py#L549-L553
train
dwavesystems/dwave_embedding_utilities
dwave_embedding_utilities.py
_most_common
def _most_common(iterable): """Returns the most common element in `iterable`.""" data = Counter(iterable) return max(data, key=data.__getitem__)
python
def _most_common(iterable): """Returns the most common element in `iterable`.""" data = Counter(iterable) return max(data, key=data.__getitem__)
[ "def", "_most_common", "(", "iterable", ")", ":", "data", "=", "Counter", "(", "iterable", ")", "return", "max", "(", "data", ",", "key", "=", "data", ".", "__getitem__", ")" ]
Returns the most common element in `iterable`.
[ "Returns", "the", "most", "common", "element", "in", "iterable", "." ]
2e485e0ae89d96f3c0005f144bab4b465a3039a3
https://github.com/dwavesystems/dwave_embedding_utilities/blob/2e485e0ae89d96f3c0005f144bab4b465a3039a3/dwave_embedding_utilities.py#L556-L559
train
DarkEnergySurvey/ugali
ugali/analysis/mcmc.py
MCMC.lnlike
def lnlike(self, theta): """ Logarithm of the likelihood """ params,loglike = self.params,self.loglike kwargs = dict(list(zip(params,theta))) try: lnlike = loglike.value(**kwargs) except ValueError as AssertionError: lnlike = -np.inf return lnlike
python
def lnlike(self, theta): """ Logarithm of the likelihood """ params,loglike = self.params,self.loglike kwargs = dict(list(zip(params,theta))) try: lnlike = loglike.value(**kwargs) except ValueError as AssertionError: lnlike = -np.inf return lnlike
[ "def", "lnlike", "(", "self", ",", "theta", ")", ":", "params", ",", "loglike", "=", "self", ".", "params", ",", "self", ".", "loglike", "kwargs", "=", "dict", "(", "list", "(", "zip", "(", "params", ",", "theta", ")", ")", ")", "try", ":", "lnli...
Logarithm of the likelihood
[ "Logarithm", "of", "the", "likelihood" ]
21e890b4117fc810afb6fb058e8055d564f03382
https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/analysis/mcmc.py#L150-L158
train
DarkEnergySurvey/ugali
ugali/analysis/mcmc.py
MCMC.lnprior
def lnprior(self,theta): """ Logarithm of the prior """ params,priors = self.params,self.priors kwargs = dict(list(zip(params,theta))) err = np.seterr(invalid='raise') try: lnprior = np.sum(np.log([priors[k](v) for k,v in list(kwargs.items())])) except (Floati...
python
def lnprior(self,theta): """ Logarithm of the prior """ params,priors = self.params,self.priors kwargs = dict(list(zip(params,theta))) err = np.seterr(invalid='raise') try: lnprior = np.sum(np.log([priors[k](v) for k,v in list(kwargs.items())])) except (Floati...
[ "def", "lnprior", "(", "self", ",", "theta", ")", ":", "params", ",", "priors", "=", "self", ".", "params", ",", "self", ".", "priors", "kwargs", "=", "dict", "(", "list", "(", "zip", "(", "params", ",", "theta", ")", ")", ")", "err", "=", "np", ...
Logarithm of the prior
[ "Logarithm", "of", "the", "prior" ]
21e890b4117fc810afb6fb058e8055d564f03382
https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/analysis/mcmc.py#L160-L170
train
DarkEnergySurvey/ugali
ugali/analysis/mcmc.py
MCMC.lnprob
def lnprob(self,theta): """ Logarithm of the probability """ global niter params,priors,loglike = self.params,self.priors,self.loglike # Avoid extra likelihood calls with bad priors _lnprior = self.lnprior(theta) if np.isfinite(_lnprior): _lnlike = self.lnlike...
python
def lnprob(self,theta): """ Logarithm of the probability """ global niter params,priors,loglike = self.params,self.priors,self.loglike # Avoid extra likelihood calls with bad priors _lnprior = self.lnprior(theta) if np.isfinite(_lnprior): _lnlike = self.lnlike...
[ "def", "lnprob", "(", "self", ",", "theta", ")", ":", "global", "niter", "params", ",", "priors", ",", "loglike", "=", "self", ".", "params", ",", "self", ".", "priors", ",", "self", ".", "loglike", "# Avoid extra likelihood calls with bad priors", "_lnprior",...
Logarithm of the probability
[ "Logarithm", "of", "the", "probability" ]
21e890b4117fc810afb6fb058e8055d564f03382
https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/analysis/mcmc.py#L172-L192
train
DarkEnergySurvey/ugali
ugali/analysis/loglike.py
write_membership
def write_membership(filename,config,srcfile,section=None): """ Top level interface to write the membership from a config and source model. """ source = Source() source.load(srcfile,section=section) loglike = createLoglike(config,source) loglike.write_membership(filename)
python
def write_membership(filename,config,srcfile,section=None): """ Top level interface to write the membership from a config and source model. """ source = Source() source.load(srcfile,section=section) loglike = createLoglike(config,source) loglike.write_membership(filename)
[ "def", "write_membership", "(", "filename", ",", "config", ",", "srcfile", ",", "section", "=", "None", ")", ":", "source", "=", "Source", "(", ")", "source", ".", "load", "(", "srcfile", ",", "section", "=", "section", ")", "loglike", "=", "createLoglik...
Top level interface to write the membership from a config and source model.
[ "Top", "level", "interface", "to", "write", "the", "membership", "from", "a", "config", "and", "source", "model", "." ]
21e890b4117fc810afb6fb058e8055d564f03382
https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/analysis/loglike.py#L512-L519
train
DarkEnergySurvey/ugali
ugali/analysis/loglike.py
createCatalog
def createCatalog(config,roi=None,lon=None,lat=None): """ Create a catalog object """ import ugali.observation.catalog if roi is None: roi = createROI(config,lon,lat) catalog = ugali.observation.catalog.Catalog(config,roi=roi) return catalog
python
def createCatalog(config,roi=None,lon=None,lat=None): """ Create a catalog object """ import ugali.observation.catalog if roi is None: roi = createROI(config,lon,lat) catalog = ugali.observation.catalog.Catalog(config,roi=roi) return catalog
[ "def", "createCatalog", "(", "config", ",", "roi", "=", "None", ",", "lon", "=", "None", ",", "lat", "=", "None", ")", ":", "import", "ugali", ".", "observation", ".", "catalog", "if", "roi", "is", "None", ":", "roi", "=", "createROI", "(", "config",...
Create a catalog object
[ "Create", "a", "catalog", "object" ]
21e890b4117fc810afb6fb058e8055d564f03382
https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/analysis/loglike.py#L566-L573
train
DarkEnergySurvey/ugali
ugali/analysis/loglike.py
simulateCatalog
def simulateCatalog(config,roi=None,lon=None,lat=None): """ Simulate a catalog object. """ import ugali.simulation.simulator if roi is None: roi = createROI(config,lon,lat) sim = ugali.simulation.simulator.Simulator(config,roi) return sim.catalog()
python
def simulateCatalog(config,roi=None,lon=None,lat=None): """ Simulate a catalog object. """ import ugali.simulation.simulator if roi is None: roi = createROI(config,lon,lat) sim = ugali.simulation.simulator.Simulator(config,roi) return sim.catalog()
[ "def", "simulateCatalog", "(", "config", ",", "roi", "=", "None", ",", "lon", "=", "None", ",", "lat", "=", "None", ")", ":", "import", "ugali", ".", "simulation", ".", "simulator", "if", "roi", "is", "None", ":", "roi", "=", "createROI", "(", "confi...
Simulate a catalog object.
[ "Simulate", "a", "catalog", "object", "." ]
21e890b4117fc810afb6fb058e8055d564f03382
https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/analysis/loglike.py#L576-L583
train
DarkEnergySurvey/ugali
ugali/analysis/loglike.py
LogLikelihood.calc_observable_fraction
def calc_observable_fraction(self,distance_modulus): """ Calculated observable fraction within each pixel of the target region. """ # This is the observable fraction after magnitude cuts in each # pixel of the ROI. observable_fraction = self.isochrone.observableFraction(...
python
def calc_observable_fraction(self,distance_modulus): """ Calculated observable fraction within each pixel of the target region. """ # This is the observable fraction after magnitude cuts in each # pixel of the ROI. observable_fraction = self.isochrone.observableFraction(...
[ "def", "calc_observable_fraction", "(", "self", ",", "distance_modulus", ")", ":", "# This is the observable fraction after magnitude cuts in each ", "# pixel of the ROI.", "observable_fraction", "=", "self", ".", "isochrone", ".", "observableFraction", "(", "self", ".", "mas...
Calculated observable fraction within each pixel of the target region.
[ "Calculated", "observable", "fraction", "within", "each", "pixel", "of", "the", "target", "region", "." ]
21e890b4117fc810afb6fb058e8055d564f03382
https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/analysis/loglike.py#L265-L277
train
DarkEnergySurvey/ugali
ugali/analysis/loglike.py
LogLikelihood.calc_signal_spatial
def calc_signal_spatial(self): """ Calculate the spatial signal probability for each catalog object. Parameters: ----------- None Returns: -------- u_spatial : array of spatial probabilities per object """ # Calculate the surface intensit...
python
def calc_signal_spatial(self): """ Calculate the spatial signal probability for each catalog object. Parameters: ----------- None Returns: -------- u_spatial : array of spatial probabilities per object """ # Calculate the surface intensit...
[ "def", "calc_signal_spatial", "(", "self", ")", ":", "# Calculate the surface intensity", "self", ".", "surface_intensity_sparse", "=", "self", ".", "calc_surface_intensity", "(", ")", "# Calculate the probability per object-by-object level", "self", ".", "surface_intensity_obj...
Calculate the spatial signal probability for each catalog object. Parameters: ----------- None Returns: -------- u_spatial : array of spatial probabilities per object
[ "Calculate", "the", "spatial", "signal", "probability", "for", "each", "catalog", "object", "." ]
21e890b4117fc810afb6fb058e8055d564f03382
https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/analysis/loglike.py#L350-L371
train
DarkEnergySurvey/ugali
ugali/analysis/loglike.py
LogLikelihood.fit_richness
def fit_richness(self, atol=1.e-3, maxiter=50): """ Maximize the log-likelihood as a function of richness. ADW 2018-06-04: Does it make sense to set the richness to the mle? Parameters: ----------- atol : absolute tolerence for conversion maxiter : maximum numbe...
python
def fit_richness(self, atol=1.e-3, maxiter=50): """ Maximize the log-likelihood as a function of richness. ADW 2018-06-04: Does it make sense to set the richness to the mle? Parameters: ----------- atol : absolute tolerence for conversion maxiter : maximum numbe...
[ "def", "fit_richness", "(", "self", ",", "atol", "=", "1.e-3", ",", "maxiter", "=", "50", ")", ":", "# Check whether the signal probability for all objects are zero", "# This can occur for finite kernels on the edge of the survey footprint", "if", "np", ".", "isnan", "(", "...
Maximize the log-likelihood as a function of richness. ADW 2018-06-04: Does it make sense to set the richness to the mle? Parameters: ----------- atol : absolute tolerence for conversion maxiter : maximum number of iterations Returns: -------- loglike, ...
[ "Maximize", "the", "log", "-", "likelihood", "as", "a", "function", "of", "richness", "." ]
21e890b4117fc810afb6fb058e8055d564f03382
https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/analysis/loglike.py#L380-L431
train
akx/lepo
lepo/apidef/doc.py
APIDefinition.resolve_reference
def resolve_reference(self, ref): """ Resolve a JSON Pointer object reference to the object itself. :param ref: Reference string (`#/foo/bar`, for instance) :return: The object, if found :raises jsonschema.exceptions.RefResolutionError: if there is trouble resolving the referenc...
python
def resolve_reference(self, ref): """ Resolve a JSON Pointer object reference to the object itself. :param ref: Reference string (`#/foo/bar`, for instance) :return: The object, if found :raises jsonschema.exceptions.RefResolutionError: if there is trouble resolving the referenc...
[ "def", "resolve_reference", "(", "self", ",", "ref", ")", ":", "url", ",", "resolved", "=", "self", ".", "resolver", ".", "resolve", "(", "ref", ")", "return", "resolved" ]
Resolve a JSON Pointer object reference to the object itself. :param ref: Reference string (`#/foo/bar`, for instance) :return: The object, if found :raises jsonschema.exceptions.RefResolutionError: if there is trouble resolving the reference
[ "Resolve", "a", "JSON", "Pointer", "object", "reference", "to", "the", "object", "itself", "." ]
34cfb24a40f18ea40f672c1ea9a0734ee1816b7d
https://github.com/akx/lepo/blob/34cfb24a40f18ea40f672c1ea9a0734ee1816b7d/lepo/apidef/doc.py#L25-L34
train
akx/lepo
lepo/apidef/doc.py
APIDefinition.get_path
def get_path(self, path): """ Construct a Path object from a path string. The Path string must be declared in the API. :type path: str :rtype: lepo.path.Path """ mapping = self.get_path_mapping(path) return self.path_class(api=self, path=path, mapping=ma...
python
def get_path(self, path): """ Construct a Path object from a path string. The Path string must be declared in the API. :type path: str :rtype: lepo.path.Path """ mapping = self.get_path_mapping(path) return self.path_class(api=self, path=path, mapping=ma...
[ "def", "get_path", "(", "self", ",", "path", ")", ":", "mapping", "=", "self", ".", "get_path_mapping", "(", "path", ")", "return", "self", ".", "path_class", "(", "api", "=", "self", ",", "path", "=", "path", ",", "mapping", "=", "mapping", ")" ]
Construct a Path object from a path string. The Path string must be declared in the API. :type path: str :rtype: lepo.path.Path
[ "Construct", "a", "Path", "object", "from", "a", "path", "string", "." ]
34cfb24a40f18ea40f672c1ea9a0734ee1816b7d
https://github.com/akx/lepo/blob/34cfb24a40f18ea40f672c1ea9a0734ee1816b7d/lepo/apidef/doc.py#L43-L53
train
akx/lepo
lepo/apidef/doc.py
APIDefinition.from_file
def from_file(cls, filename): """ Construct an APIDefinition by parsing the given `filename`. If PyYAML is installed, YAML files are supported. JSON files are always supported. :param filename: The filename to read. :rtype: APIDefinition """ with open(fi...
python
def from_file(cls, filename): """ Construct an APIDefinition by parsing the given `filename`. If PyYAML is installed, YAML files are supported. JSON files are always supported. :param filename: The filename to read. :rtype: APIDefinition """ with open(fi...
[ "def", "from_file", "(", "cls", ",", "filename", ")", ":", "with", "open", "(", "filename", ")", "as", "infp", ":", "if", "filename", ".", "endswith", "(", "'.yaml'", ")", "or", "filename", ".", "endswith", "(", "'.yml'", ")", ":", "import", "yaml", ...
Construct an APIDefinition by parsing the given `filename`. If PyYAML is installed, YAML files are supported. JSON files are always supported. :param filename: The filename to read. :rtype: APIDefinition
[ "Construct", "an", "APIDefinition", "by", "parsing", "the", "given", "filename", "." ]
34cfb24a40f18ea40f672c1ea9a0734ee1816b7d
https://github.com/akx/lepo/blob/34cfb24a40f18ea40f672c1ea9a0734ee1816b7d/lepo/apidef/doc.py#L65-L82
train
juju/theblues
theblues/utils.py
_server_error_message
def _server_error_message(url, message): """Log and return a server error message.""" msg = _error_message.format(url=url, message=message) log.error(msg) return msg
python
def _server_error_message(url, message): """Log and return a server error message.""" msg = _error_message.format(url=url, message=message) log.error(msg) return msg
[ "def", "_server_error_message", "(", "url", ",", "message", ")", ":", "msg", "=", "_error_message", ".", "format", "(", "url", "=", "url", ",", "message", "=", "message", ")", "log", ".", "error", "(", "msg", ")", "return", "msg" ]
Log and return a server error message.
[ "Log", "and", "return", "a", "server", "error", "message", "." ]
f4431f29e43d04fc32f38f4f86cea45cd4e6ae98
https://github.com/juju/theblues/blob/f4431f29e43d04fc32f38f4f86cea45cd4e6ae98/theblues/utils.py#L23-L27
train
juju/theblues
theblues/utils.py
make_request
def make_request( url, method='GET', query=None, body=None, auth=None, timeout=10, client=None, macaroons=None): """Make a request with the provided data. @param url The url to make the request to. @param method The HTTP request method (defaulting to "GET"). @param query A dict of the q...
python
def make_request( url, method='GET', query=None, body=None, auth=None, timeout=10, client=None, macaroons=None): """Make a request with the provided data. @param url The url to make the request to. @param method The HTTP request method (defaulting to "GET"). @param query A dict of the q...
[ "def", "make_request", "(", "url", ",", "method", "=", "'GET'", ",", "query", "=", "None", ",", "body", "=", "None", ",", "auth", "=", "None", ",", "timeout", "=", "10", ",", "client", "=", "None", ",", "macaroons", "=", "None", ")", ":", "headers"...
Make a request with the provided data. @param url The url to make the request to. @param method The HTTP request method (defaulting to "GET"). @param query A dict of the query key and values. @param body The optional body as a string or as a JSON decoded dict. @param auth The optional username and ...
[ "Make", "a", "request", "with", "the", "provided", "data", "." ]
f4431f29e43d04fc32f38f4f86cea45cd4e6ae98
https://github.com/juju/theblues/blob/f4431f29e43d04fc32f38f4f86cea45cd4e6ae98/theblues/utils.py#L30-L99
train
juju/theblues
theblues/plans.py
Plans.get_plans
def get_plans(self, reference): """Get the plans for a given charm. @param the Reference to a charm. @return a tuple of plans or an empty tuple if no plans. @raise ServerError """ response = make_request( '{}charm?charm-url={}'.format(self.url, ...
python
def get_plans(self, reference): """Get the plans for a given charm. @param the Reference to a charm. @return a tuple of plans or an empty tuple if no plans. @raise ServerError """ response = make_request( '{}charm?charm-url={}'.format(self.url, ...
[ "def", "get_plans", "(", "self", ",", "reference", ")", ":", "response", "=", "make_request", "(", "'{}charm?charm-url={}'", ".", "format", "(", "self", ".", "url", ",", "'cs:'", "+", "reference", ".", "path", "(", ")", ")", ",", "timeout", "=", "self", ...
Get the plans for a given charm. @param the Reference to a charm. @return a tuple of plans or an empty tuple if no plans. @raise ServerError
[ "Get", "the", "plans", "for", "a", "given", "charm", "." ]
f4431f29e43d04fc32f38f4f86cea45cd4e6ae98
https://github.com/juju/theblues/blob/f4431f29e43d04fc32f38f4f86cea45cd4e6ae98/theblues/plans.py#L46-L72
train
juju/theblues
theblues/plans.py
Plans.list_wallets
def list_wallets(self): """Get the list of wallets. @return an dict containing a list of wallets, a total, and available credit. @raise ServerError """ response = make_request( '{}wallet'.format(self.url), timeout=self.timeout, cli...
python
def list_wallets(self): """Get the list of wallets. @return an dict containing a list of wallets, a total, and available credit. @raise ServerError """ response = make_request( '{}wallet'.format(self.url), timeout=self.timeout, cli...
[ "def", "list_wallets", "(", "self", ")", ":", "response", "=", "make_request", "(", "'{}wallet'", ".", "format", "(", "self", ".", "url", ")", ",", "timeout", "=", "self", ".", "timeout", ",", "client", "=", "self", ".", "_client", ")", "try", ":", "...
Get the list of wallets. @return an dict containing a list of wallets, a total, and available credit. @raise ServerError
[ "Get", "the", "list", "of", "wallets", "." ]
f4431f29e43d04fc32f38f4f86cea45cd4e6ae98
https://github.com/juju/theblues/blob/f4431f29e43d04fc32f38f4f86cea45cd4e6ae98/theblues/plans.py#L74-L112
train
juju/theblues
theblues/plans.py
Plans.get_wallet
def get_wallet(self, wallet_name): """Get a single wallet. @param the name of the wallet. @return the wallet's total. @raise ServerError """ response = make_request( '{}wallet/{}'.format(self.url, wallet_name), timeout=self.timeout, cl...
python
def get_wallet(self, wallet_name): """Get a single wallet. @param the name of the wallet. @return the wallet's total. @raise ServerError """ response = make_request( '{}wallet/{}'.format(self.url, wallet_name), timeout=self.timeout, cl...
[ "def", "get_wallet", "(", "self", ",", "wallet_name", ")", ":", "response", "=", "make_request", "(", "'{}wallet/{}'", ".", "format", "(", "self", ".", "url", ",", "wallet_name", ")", ",", "timeout", "=", "self", ".", "timeout", ",", "client", "=", "self...
Get a single wallet. @param the name of the wallet. @return the wallet's total. @raise ServerError
[ "Get", "a", "single", "wallet", "." ]
f4431f29e43d04fc32f38f4f86cea45cd4e6ae98
https://github.com/juju/theblues/blob/f4431f29e43d04fc32f38f4f86cea45cd4e6ae98/theblues/plans.py#L114-L142
train
juju/theblues
theblues/plans.py
Plans.update_wallet
def update_wallet(self, wallet_name, limit): """Update a wallet with a new limit. @param the name of the wallet. @param the new value of the limit. @return a success string from the plans server. @raise ServerError via make_request. """ request = { 'u...
python
def update_wallet(self, wallet_name, limit): """Update a wallet with a new limit. @param the name of the wallet. @param the new value of the limit. @return a success string from the plans server. @raise ServerError via make_request. """ request = { 'u...
[ "def", "update_wallet", "(", "self", ",", "wallet_name", ",", "limit", ")", ":", "request", "=", "{", "'update'", ":", "{", "'limit'", ":", "str", "(", "limit", ")", ",", "}", "}", "return", "make_request", "(", "'{}wallet/{}'", ".", "format", "(", "se...
Update a wallet with a new limit. @param the name of the wallet. @param the new value of the limit. @return a success string from the plans server. @raise ServerError via make_request.
[ "Update", "a", "wallet", "with", "a", "new", "limit", "." ]
f4431f29e43d04fc32f38f4f86cea45cd4e6ae98
https://github.com/juju/theblues/blob/f4431f29e43d04fc32f38f4f86cea45cd4e6ae98/theblues/plans.py#L144-L162
train
juju/theblues
theblues/plans.py
Plans.delete_wallet
def delete_wallet(self, wallet_name): """Delete a wallet. @param the name of the wallet. @return a success string from the plans server. @raise ServerError via make_request. """ return make_request( '{}wallet/{}'.format(self.url, wallet_name), met...
python
def delete_wallet(self, wallet_name): """Delete a wallet. @param the name of the wallet. @return a success string from the plans server. @raise ServerError via make_request. """ return make_request( '{}wallet/{}'.format(self.url, wallet_name), met...
[ "def", "delete_wallet", "(", "self", ",", "wallet_name", ")", ":", "return", "make_request", "(", "'{}wallet/{}'", ".", "format", "(", "self", ".", "url", ",", "wallet_name", ")", ",", "method", "=", "'DELETE'", ",", "timeout", "=", "self", ".", "timeout",...
Delete a wallet. @param the name of the wallet. @return a success string from the plans server. @raise ServerError via make_request.
[ "Delete", "a", "wallet", "." ]
f4431f29e43d04fc32f38f4f86cea45cd4e6ae98
https://github.com/juju/theblues/blob/f4431f29e43d04fc32f38f4f86cea45cd4e6ae98/theblues/plans.py#L183-L194
train
juju/theblues
theblues/plans.py
Plans.create_budget
def create_budget(self, wallet_name, model_uuid, limit): """Create a new budget for a model and wallet. @param the name of the wallet. @param the model UUID. @param the new value of the limit. @return a success string from the plans server. @raise ServerError via make_re...
python
def create_budget(self, wallet_name, model_uuid, limit): """Create a new budget for a model and wallet. @param the name of the wallet. @param the model UUID. @param the new value of the limit. @return a success string from the plans server. @raise ServerError via make_re...
[ "def", "create_budget", "(", "self", ",", "wallet_name", ",", "model_uuid", ",", "limit", ")", ":", "request", "=", "{", "'model'", ":", "model_uuid", ",", "'limit'", ":", "limit", ",", "}", "return", "make_request", "(", "'{}wallet/{}/budget'", ".", "format...
Create a new budget for a model and wallet. @param the name of the wallet. @param the model UUID. @param the new value of the limit. @return a success string from the plans server. @raise ServerError via make_request.
[ "Create", "a", "new", "budget", "for", "a", "model", "and", "wallet", "." ]
f4431f29e43d04fc32f38f4f86cea45cd4e6ae98
https://github.com/juju/theblues/blob/f4431f29e43d04fc32f38f4f86cea45cd4e6ae98/theblues/plans.py#L196-L214
train
juju/theblues
theblues/plans.py
Plans.delete_budget
def delete_budget(self, model_uuid): """Delete a budget. @param the name of the wallet. @param the model UUID. @return a success string from the plans server. @raise ServerError via make_request. """ return make_request( '{}model/{}/budget'.format(sel...
python
def delete_budget(self, model_uuid): """Delete a budget. @param the name of the wallet. @param the model UUID. @return a success string from the plans server. @raise ServerError via make_request. """ return make_request( '{}model/{}/budget'.format(sel...
[ "def", "delete_budget", "(", "self", ",", "model_uuid", ")", ":", "return", "make_request", "(", "'{}model/{}/budget'", ".", "format", "(", "self", ".", "url", ",", "model_uuid", ")", ",", "method", "=", "'DELETE'", ",", "timeout", "=", "self", ".", "timeo...
Delete a budget. @param the name of the wallet. @param the model UUID. @return a success string from the plans server. @raise ServerError via make_request.
[ "Delete", "a", "budget", "." ]
f4431f29e43d04fc32f38f4f86cea45cd4e6ae98
https://github.com/juju/theblues/blob/f4431f29e43d04fc32f38f4f86cea45cd4e6ae98/theblues/plans.py#L238-L250
train
totalgood/pugnlp
src/pugnlp/stats.py
confusion
def confusion(df, labels=['neg', 'pos']): """ Binary classification confusion """ c = pd.DataFrame(np.zeros((2, 2)), dtype=int) a, b = df.columns[:2] # labels[df.columns[:2]] c.columns = sorted(set(df[a]))[:2] c.columns.name = a c.index = list(c.columns) c.index.name = b c1, c2 = c.colu...
python
def confusion(df, labels=['neg', 'pos']): """ Binary classification confusion """ c = pd.DataFrame(np.zeros((2, 2)), dtype=int) a, b = df.columns[:2] # labels[df.columns[:2]] c.columns = sorted(set(df[a]))[:2] c.columns.name = a c.index = list(c.columns) c.index.name = b c1, c2 = c.colu...
[ "def", "confusion", "(", "df", ",", "labels", "=", "[", "'neg'", ",", "'pos'", "]", ")", ":", "c", "=", "pd", ".", "DataFrame", "(", "np", ".", "zeros", "(", "(", "2", ",", "2", ")", ")", ",", "dtype", "=", "int", ")", "a", ",", "b", "=", ...
Binary classification confusion
[ "Binary", "classification", "confusion" ]
c43445b14afddfdeadc5f3076675c9e8fc1ee67c
https://github.com/totalgood/pugnlp/blob/c43445b14afddfdeadc5f3076675c9e8fc1ee67c/src/pugnlp/stats.py#L227-L240
train
totalgood/pugnlp
src/pugnlp/stats.py
thresh_from_spec
def thresh_from_spec(spec, labels, scores, **kwargs): r"""Find the threshold level that accomplishes the desired specificity""" cost_fun.verbose = kwargs.pop('verbose', cost_fun.verbose) cost_fun.target = spec return minimize(cost_fun, x0=[.5], args=(labels, score...
python
def thresh_from_spec(spec, labels, scores, **kwargs): r"""Find the threshold level that accomplishes the desired specificity""" cost_fun.verbose = kwargs.pop('verbose', cost_fun.verbose) cost_fun.target = spec return minimize(cost_fun, x0=[.5], args=(labels, score...
[ "def", "thresh_from_spec", "(", "spec", ",", "labels", ",", "scores", ",", "*", "*", "kwargs", ")", ":", "cost_fun", ".", "verbose", "=", "kwargs", ".", "pop", "(", "'verbose'", ",", "cost_fun", ".", "verbose", ")", "cost_fun", ".", "target", "=", "spe...
r"""Find the threshold level that accomplishes the desired specificity
[ "r", "Find", "the", "threshold", "level", "that", "accomplishes", "the", "desired", "specificity" ]
c43445b14afddfdeadc5f3076675c9e8fc1ee67c
https://github.com/totalgood/pugnlp/blob/c43445b14afddfdeadc5f3076675c9e8fc1ee67c/src/pugnlp/stats.py#L938-L951
train
stevearc/dynamo3
dynamo3/result.py
add_dicts
def add_dicts(d1, d2): """ Merge two dicts of addable values """ if d1 is None: return d2 if d2 is None: return d1 keys = set(d1) keys.update(set(d2)) ret = {} for key in keys: v1 = d1.get(key) v2 = d2.get(key) if v1 is None: ret[key] = v2 ...
python
def add_dicts(d1, d2): """ Merge two dicts of addable values """ if d1 is None: return d2 if d2 is None: return d1 keys = set(d1) keys.update(set(d2)) ret = {} for key in keys: v1 = d1.get(key) v2 = d2.get(key) if v1 is None: ret[key] = v2 ...
[ "def", "add_dicts", "(", "d1", ",", "d2", ")", ":", "if", "d1", "is", "None", ":", "return", "d2", "if", "d2", "is", "None", ":", "return", "d1", "keys", "=", "set", "(", "d1", ")", "keys", ".", "update", "(", "set", "(", "d2", ")", ")", "ret...
Merge two dicts of addable values
[ "Merge", "two", "dicts", "of", "addable", "values" ]
f897c40ece28586272dbcab8f0d99a14a1831dda
https://github.com/stevearc/dynamo3/blob/f897c40ece28586272dbcab8f0d99a14a1831dda/dynamo3/result.py#L7-L25
train
stevearc/dynamo3
dynamo3/result.py
PagedIterator._update_capacity
def _update_capacity(self, data): """ Update the consumed capacity metrics """ if 'ConsumedCapacity' in data: # This is all for backwards compatibility consumed = data['ConsumedCapacity'] if not isinstance(consumed, list): consumed = [consumed] ...
python
def _update_capacity(self, data): """ Update the consumed capacity metrics """ if 'ConsumedCapacity' in data: # This is all for backwards compatibility consumed = data['ConsumedCapacity'] if not isinstance(consumed, list): consumed = [consumed] ...
[ "def", "_update_capacity", "(", "self", ",", "data", ")", ":", "if", "'ConsumedCapacity'", "in", "data", ":", "# This is all for backwards compatibility", "consumed", "=", "data", "[", "'ConsumedCapacity'", "]", "if", "not", "isinstance", "(", "consumed", ",", "li...
Update the consumed capacity metrics
[ "Update", "the", "consumed", "capacity", "metrics" ]
f897c40ece28586272dbcab8f0d99a14a1831dda
https://github.com/stevearc/dynamo3/blob/f897c40ece28586272dbcab8f0d99a14a1831dda/dynamo3/result.py#L233-L251
train
stevearc/dynamo3
dynamo3/result.py
ResultSet.fetch
def fetch(self): """ Fetch more results from Dynamo """ self.limit.set_request_args(self.kwargs) data = self.connection.call(*self.args, **self.kwargs) self.limit.post_fetch(data) self.last_evaluated_key = data.get('LastEvaluatedKey') if self.last_evaluated_key is None: ...
python
def fetch(self): """ Fetch more results from Dynamo """ self.limit.set_request_args(self.kwargs) data = self.connection.call(*self.args, **self.kwargs) self.limit.post_fetch(data) self.last_evaluated_key = data.get('LastEvaluatedKey') if self.last_evaluated_key is None: ...
[ "def", "fetch", "(", "self", ")", ":", "self", ".", "limit", ".", "set_request_args", "(", "self", ".", "kwargs", ")", "data", "=", "self", ".", "connection", ".", "call", "(", "*", "self", ".", "args", ",", "*", "*", "self", ".", "kwargs", ")", ...
Fetch more results from Dynamo
[ "Fetch", "more", "results", "from", "Dynamo" ]
f897c40ece28586272dbcab8f0d99a14a1831dda
https://github.com/stevearc/dynamo3/blob/f897c40ece28586272dbcab8f0d99a14a1831dda/dynamo3/result.py#L288-L304
train
stevearc/dynamo3
dynamo3/result.py
GetResultSet.build_kwargs
def build_kwargs(self): """ Construct the kwargs to pass to batch_get_item """ keys, self.keys = self.keys[:MAX_GET_BATCH], self.keys[MAX_GET_BATCH:] query = {'ConsistentRead': self.consistent} if self.attributes is not None: query['ProjectionExpression'] = self.attributes ...
python
def build_kwargs(self): """ Construct the kwargs to pass to batch_get_item """ keys, self.keys = self.keys[:MAX_GET_BATCH], self.keys[MAX_GET_BATCH:] query = {'ConsistentRead': self.consistent} if self.attributes is not None: query['ProjectionExpression'] = self.attributes ...
[ "def", "build_kwargs", "(", "self", ")", ":", "keys", ",", "self", ".", "keys", "=", "self", ".", "keys", "[", ":", "MAX_GET_BATCH", "]", ",", "self", ".", "keys", "[", "MAX_GET_BATCH", ":", "]", "query", "=", "{", "'ConsistentRead'", ":", "self", "....
Construct the kwargs to pass to batch_get_item
[ "Construct", "the", "kwargs", "to", "pass", "to", "batch_get_item" ]
f897c40ece28586272dbcab8f0d99a14a1831dda
https://github.com/stevearc/dynamo3/blob/f897c40ece28586272dbcab8f0d99a14a1831dda/dynamo3/result.py#L331-L345
train
stevearc/dynamo3
dynamo3/result.py
GetResultSet.fetch
def fetch(self): """ Fetch a set of items from their keys """ kwargs = self.build_kwargs() data = self.connection.call('batch_get_item', **kwargs) if 'UnprocessedKeys' in data: for items in six.itervalues(data['UnprocessedKeys']): self.keys.extend(items['Keys'...
python
def fetch(self): """ Fetch a set of items from their keys """ kwargs = self.build_kwargs() data = self.connection.call('batch_get_item', **kwargs) if 'UnprocessedKeys' in data: for items in six.itervalues(data['UnprocessedKeys']): self.keys.extend(items['Keys'...
[ "def", "fetch", "(", "self", ")", ":", "kwargs", "=", "self", ".", "build_kwargs", "(", ")", "data", "=", "self", ".", "connection", ".", "call", "(", "'batch_get_item'", ",", "*", "*", "kwargs", ")", "if", "'UnprocessedKeys'", "in", "data", ":", "for"...
Fetch a set of items from their keys
[ "Fetch", "a", "set", "of", "items", "from", "their", "keys" ]
f897c40ece28586272dbcab8f0d99a14a1831dda
https://github.com/stevearc/dynamo3/blob/f897c40ece28586272dbcab8f0d99a14a1831dda/dynamo3/result.py#L347-L367
train
stevearc/dynamo3
dynamo3/result.py
Limit.copy
def copy(self): """ Return a copy of the limit """ return Limit(self.scan_limit, self.item_limit, self.min_scan_limit, self.strict, self.filter)
python
def copy(self): """ Return a copy of the limit """ return Limit(self.scan_limit, self.item_limit, self.min_scan_limit, self.strict, self.filter)
[ "def", "copy", "(", "self", ")", ":", "return", "Limit", "(", "self", ".", "scan_limit", ",", "self", ".", "item_limit", ",", "self", ".", "min_scan_limit", ",", "self", ".", "strict", ",", "self", ".", "filter", ")" ]
Return a copy of the limit
[ "Return", "a", "copy", "of", "the", "limit" ]
f897c40ece28586272dbcab8f0d99a14a1831dda
https://github.com/stevearc/dynamo3/blob/f897c40ece28586272dbcab8f0d99a14a1831dda/dynamo3/result.py#L494-L497
train
stevearc/dynamo3
dynamo3/result.py
Limit.set_request_args
def set_request_args(self, args): """ Set the Limit parameter into the request args """ if self.scan_limit is not None: args['Limit'] = self.scan_limit elif self.item_limit is not None: args['Limit'] = max(self.item_limit, self.min_scan_limit) else: ar...
python
def set_request_args(self, args): """ Set the Limit parameter into the request args """ if self.scan_limit is not None: args['Limit'] = self.scan_limit elif self.item_limit is not None: args['Limit'] = max(self.item_limit, self.min_scan_limit) else: ar...
[ "def", "set_request_args", "(", "self", ",", "args", ")", ":", "if", "self", ".", "scan_limit", "is", "not", "None", ":", "args", "[", "'Limit'", "]", "=", "self", ".", "scan_limit", "elif", "self", ".", "item_limit", "is", "not", "None", ":", "args", ...
Set the Limit parameter into the request args
[ "Set", "the", "Limit", "parameter", "into", "the", "request", "args" ]
f897c40ece28586272dbcab8f0d99a14a1831dda
https://github.com/stevearc/dynamo3/blob/f897c40ece28586272dbcab8f0d99a14a1831dda/dynamo3/result.py#L499-L506
train
stevearc/dynamo3
dynamo3/result.py
Limit.complete
def complete(self): """ Return True if the limit has been reached """ if self.scan_limit is not None and self.scan_limit == 0: return True if self.item_limit is not None and self.item_limit == 0: return True return False
python
def complete(self): """ Return True if the limit has been reached """ if self.scan_limit is not None and self.scan_limit == 0: return True if self.item_limit is not None and self.item_limit == 0: return True return False
[ "def", "complete", "(", "self", ")", ":", "if", "self", ".", "scan_limit", "is", "not", "None", "and", "self", ".", "scan_limit", "==", "0", ":", "return", "True", "if", "self", ".", "item_limit", "is", "not", "None", "and", "self", ".", "item_limit", ...
Return True if the limit has been reached
[ "Return", "True", "if", "the", "limit", "has", "been", "reached" ]
f897c40ece28586272dbcab8f0d99a14a1831dda
https://github.com/stevearc/dynamo3/blob/f897c40ece28586272dbcab8f0d99a14a1831dda/dynamo3/result.py#L509-L515
train
stevearc/dynamo3
dynamo3/result.py
Limit.accept
def accept(self, item): """ Apply the filter and item_limit, and return True to accept """ accept = self.filter(item) if accept and self.item_limit is not None: if self.item_limit > 0: self.item_limit -= 1 elif self.strict: return False ...
python
def accept(self, item): """ Apply the filter and item_limit, and return True to accept """ accept = self.filter(item) if accept and self.item_limit is not None: if self.item_limit > 0: self.item_limit -= 1 elif self.strict: return False ...
[ "def", "accept", "(", "self", ",", "item", ")", ":", "accept", "=", "self", ".", "filter", "(", "item", ")", "if", "accept", "and", "self", ".", "item_limit", "is", "not", "None", ":", "if", "self", ".", "item_limit", ">", "0", ":", "self", ".", ...
Apply the filter and item_limit, and return True to accept
[ "Apply", "the", "filter", "and", "item_limit", "and", "return", "True", "to", "accept" ]
f897c40ece28586272dbcab8f0d99a14a1831dda
https://github.com/stevearc/dynamo3/blob/f897c40ece28586272dbcab8f0d99a14a1831dda/dynamo3/result.py#L522-L530
train
aht/stream.py
example/randwalk.py
returned
def returned(n): """Generate a random walk and return True if the walker has returned to the origin after taking `n` steps. """ ## `takei` yield lazily so we can short-circuit and avoid computing the rest of the walk for pos in randwalk() >> drop(1) >> takei(xrange(n-1)): if pos == Origin: return True return...
python
def returned(n): """Generate a random walk and return True if the walker has returned to the origin after taking `n` steps. """ ## `takei` yield lazily so we can short-circuit and avoid computing the rest of the walk for pos in randwalk() >> drop(1) >> takei(xrange(n-1)): if pos == Origin: return True return...
[ "def", "returned", "(", "n", ")", ":", "## `takei` yield lazily so we can short-circuit and avoid computing the rest of the walk", "for", "pos", "in", "randwalk", "(", ")", ">>", "drop", "(", "1", ")", ">>", "takei", "(", "xrange", "(", "n", "-", "1", ")", ")", ...
Generate a random walk and return True if the walker has returned to the origin after taking `n` steps.
[ "Generate", "a", "random", "walk", "and", "return", "True", "if", "the", "walker", "has", "returned", "to", "the", "origin", "after", "taking", "n", "steps", "." ]
6a4945cbddaf74138eee5ba33eee3988cfceb84d
https://github.com/aht/stream.py/blob/6a4945cbddaf74138eee5ba33eee3988cfceb84d/example/randwalk.py#L16-L24
train
aht/stream.py
example/randwalk.py
first_return
def first_return(): """Generate a random walk and return its length upto the moment that the walker first returns to the origin. It is mathematically provable that the walker will eventually return, meaning that the function call will halt, although it may take a *very* long time and your computer may run out of ...
python
def first_return(): """Generate a random walk and return its length upto the moment that the walker first returns to the origin. It is mathematically provable that the walker will eventually return, meaning that the function call will halt, although it may take a *very* long time and your computer may run out of ...
[ "def", "first_return", "(", ")", ":", "walk", "=", "randwalk", "(", ")", ">>", "drop", "(", "1", ")", ">>", "takewhile", "(", "lambda", "v", ":", "v", "!=", "Origin", ")", ">>", "list", "return", "len", "(", "walk", ")" ]
Generate a random walk and return its length upto the moment that the walker first returns to the origin. It is mathematically provable that the walker will eventually return, meaning that the function call will halt, although it may take a *very* long time and your computer may run out of memory! Thus, try this ...
[ "Generate", "a", "random", "walk", "and", "return", "its", "length", "upto", "the", "moment", "that", "the", "walker", "first", "returns", "to", "the", "origin", "." ]
6a4945cbddaf74138eee5ba33eee3988cfceb84d
https://github.com/aht/stream.py/blob/6a4945cbddaf74138eee5ba33eee3988cfceb84d/example/randwalk.py#L26-L36
train
aht/stream.py
stream.py
seq
def seq(start=0, step=1): """An arithmetic sequence generator. Works with any type with + defined. >>> seq(1, 0.25) >> item[:10] [1, 1.25, 1.5, 1.75, 2.0, 2.25, 2.5, 2.75, 3.0, 3.25] """ def seq(a, d): while 1: yield a a += d return seq(start, step)
python
def seq(start=0, step=1): """An arithmetic sequence generator. Works with any type with + defined. >>> seq(1, 0.25) >> item[:10] [1, 1.25, 1.5, 1.75, 2.0, 2.25, 2.5, 2.75, 3.0, 3.25] """ def seq(a, d): while 1: yield a a += d return seq(start, step)
[ "def", "seq", "(", "start", "=", "0", ",", "step", "=", "1", ")", ":", "def", "seq", "(", "a", ",", "d", ")", ":", "while", "1", ":", "yield", "a", "a", "+=", "d", "return", "seq", "(", "start", ",", "step", ")" ]
An arithmetic sequence generator. Works with any type with + defined. >>> seq(1, 0.25) >> item[:10] [1, 1.25, 1.5, 1.75, 2.0, 2.25, 2.5, 2.75, 3.0, 3.25]
[ "An", "arithmetic", "sequence", "generator", ".", "Works", "with", "any", "type", "with", "+", "defined", "." ]
6a4945cbddaf74138eee5ba33eee3988cfceb84d
https://github.com/aht/stream.py/blob/6a4945cbddaf74138eee5ba33eee3988cfceb84d/stream.py#L1194-L1204
train
aht/stream.py
stream.py
Stream.pipe
def pipe(inpipe, outpipe): """Connect inpipe and outpipe. If outpipe is not a Stream instance, it should be an function callable on an iterable. """ if hasattr(outpipe, '__pipe__'): return outpipe.__pipe__(inpipe) elif hasattr(outpipe, '__call__'): return outpipe(inpipe) else: raise BrokenPipe('No...
python
def pipe(inpipe, outpipe): """Connect inpipe and outpipe. If outpipe is not a Stream instance, it should be an function callable on an iterable. """ if hasattr(outpipe, '__pipe__'): return outpipe.__pipe__(inpipe) elif hasattr(outpipe, '__call__'): return outpipe(inpipe) else: raise BrokenPipe('No...
[ "def", "pipe", "(", "inpipe", ",", "outpipe", ")", ":", "if", "hasattr", "(", "outpipe", ",", "'__pipe__'", ")", ":", "return", "outpipe", ".", "__pipe__", "(", "inpipe", ")", "elif", "hasattr", "(", "outpipe", ",", "'__call__'", ")", ":", "return", "o...
Connect inpipe and outpipe. If outpipe is not a Stream instance, it should be an function callable on an iterable.
[ "Connect", "inpipe", "and", "outpipe", ".", "If", "outpipe", "is", "not", "a", "Stream", "instance", "it", "should", "be", "an", "function", "callable", "on", "an", "iterable", "." ]
6a4945cbddaf74138eee5ba33eee3988cfceb84d
https://github.com/aht/stream.py/blob/6a4945cbddaf74138eee5ba33eee3988cfceb84d/stream.py#L170-L179
train
aht/stream.py
stream.py
Executor.submit
def submit(self, *items): """Return job ids assigned to the submitted items.""" with self.lock: if self.closed: raise BrokenPipe('Job submission has been closed.') id = self.jobcount self._status += ['SUBMITTED'] * len(items) self.jobcount += len(items) for item in items: self.waitqueue.put((...
python
def submit(self, *items): """Return job ids assigned to the submitted items.""" with self.lock: if self.closed: raise BrokenPipe('Job submission has been closed.') id = self.jobcount self._status += ['SUBMITTED'] * len(items) self.jobcount += len(items) for item in items: self.waitqueue.put((...
[ "def", "submit", "(", "self", ",", "*", "items", ")", ":", "with", "self", ".", "lock", ":", "if", "self", ".", "closed", ":", "raise", "BrokenPipe", "(", "'Job submission has been closed.'", ")", "id", "=", "self", ".", "jobcount", "self", ".", "_status...
Return job ids assigned to the submitted items.
[ "Return", "job", "ids", "assigned", "to", "the", "submitted", "items", "." ]
6a4945cbddaf74138eee5ba33eee3988cfceb84d
https://github.com/aht/stream.py/blob/6a4945cbddaf74138eee5ba33eee3988cfceb84d/stream.py#L980-L994
train
aht/stream.py
stream.py
Executor.cancel
def cancel(self, *ids): """Try to cancel jobs with associated ids. Return the actual number of jobs cancelled. """ ncancelled = 0 with self.lock: for id in ids: try: if self._status[id] == 'SUBMITTED': self._status[id] = 'CANCELLED' ncancelled += 1 except IndexError: pass ...
python
def cancel(self, *ids): """Try to cancel jobs with associated ids. Return the actual number of jobs cancelled. """ ncancelled = 0 with self.lock: for id in ids: try: if self._status[id] == 'SUBMITTED': self._status[id] = 'CANCELLED' ncancelled += 1 except IndexError: pass ...
[ "def", "cancel", "(", "self", ",", "*", "ids", ")", ":", "ncancelled", "=", "0", "with", "self", ".", "lock", ":", "for", "id", "in", "ids", ":", "try", ":", "if", "self", ".", "_status", "[", "id", "]", "==", "'SUBMITTED'", ":", "self", ".", "...
Try to cancel jobs with associated ids. Return the actual number of jobs cancelled.
[ "Try", "to", "cancel", "jobs", "with", "associated", "ids", ".", "Return", "the", "actual", "number", "of", "jobs", "cancelled", "." ]
6a4945cbddaf74138eee5ba33eee3988cfceb84d
https://github.com/aht/stream.py/blob/6a4945cbddaf74138eee5ba33eee3988cfceb84d/stream.py#L996-L1010
train
aht/stream.py
stream.py
Executor.shutdown
def shutdown(self): """Shut down the Executor. Suspend all waiting jobs. Running workers will terminate after finishing their current job items. The call will block until all workers are terminated. """ with self.lock: self.pool.inqueue.put(StopIteration) # Stop the pool workers self.waitqueue.put...
python
def shutdown(self): """Shut down the Executor. Suspend all waiting jobs. Running workers will terminate after finishing their current job items. The call will block until all workers are terminated. """ with self.lock: self.pool.inqueue.put(StopIteration) # Stop the pool workers self.waitqueue.put...
[ "def", "shutdown", "(", "self", ")", ":", "with", "self", ".", "lock", ":", "self", ".", "pool", ".", "inqueue", ".", "put", "(", "StopIteration", ")", "# Stop the pool workers", "self", ".", "waitqueue", ".", "put", "(", "StopIteration", ")", "# Stop the ...
Shut down the Executor. Suspend all waiting jobs. Running workers will terminate after finishing their current job items. The call will block until all workers are terminated.
[ "Shut", "down", "the", "Executor", ".", "Suspend", "all", "waiting", "jobs", ".", "Running", "workers", "will", "terminate", "after", "finishing", "their", "current", "job", "items", ".", "The", "call", "will", "block", "until", "all", "workers", "are", "ter...
6a4945cbddaf74138eee5ba33eee3988cfceb84d
https://github.com/aht/stream.py/blob/6a4945cbddaf74138eee5ba33eee3988cfceb84d/stream.py#L1045-L1056
train
Zephrys/monica
monica/monica.py
main
def main(): '''monica helps you order food from the timeline''' arguments = docopt(__doc__, version=__version__) if arguments['configure'] and flag: configure() if arguments['cuisine']: if arguments['list']: cuisine('list') else: cuisine(arguments['<cuisine-id>']) elif arguments['surp...
python
def main(): '''monica helps you order food from the timeline''' arguments = docopt(__doc__, version=__version__) if arguments['configure'] and flag: configure() if arguments['cuisine']: if arguments['list']: cuisine('list') else: cuisine(arguments['<cuisine-id>']) elif arguments['surp...
[ "def", "main", "(", ")", ":", "arguments", "=", "docopt", "(", "__doc__", ",", "version", "=", "__version__", ")", "if", "arguments", "[", "'configure'", "]", "and", "flag", ":", "configure", "(", ")", "if", "arguments", "[", "'cuisine'", "]", ":", "if...
monica helps you order food from the timeline
[ "monica", "helps", "you", "order", "food", "from", "the", "timeline" ]
ff0bc7df18d86ad66af6c655cdd292ddceb84fd7
https://github.com/Zephrys/monica/blob/ff0bc7df18d86ad66af6c655cdd292ddceb84fd7/monica/monica.py#L214-L241
train
alphagov/performanceplatform-collector
setup.py
_get_requirements
def _get_requirements(fname): """ Create a list of requirements from the output of the pip freeze command saved in a text file. """ packages = _read(fname).split('\n') packages = (p.strip() for p in packages) packages = (p for p in packages if p and not p.startswith('#')) return list(pac...
python
def _get_requirements(fname): """ Create a list of requirements from the output of the pip freeze command saved in a text file. """ packages = _read(fname).split('\n') packages = (p.strip() for p in packages) packages = (p for p in packages if p and not p.startswith('#')) return list(pac...
[ "def", "_get_requirements", "(", "fname", ")", ":", "packages", "=", "_read", "(", "fname", ")", ".", "split", "(", "'\\n'", ")", "packages", "=", "(", "p", ".", "strip", "(", ")", "for", "p", "in", "packages", ")", "packages", "=", "(", "p", "for"...
Create a list of requirements from the output of the pip freeze command saved in a text file.
[ "Create", "a", "list", "of", "requirements", "from", "the", "output", "of", "the", "pip", "freeze", "command", "saved", "in", "a", "text", "file", "." ]
de68ab4aa500c31e436e050fa1268fa928c522a5
https://github.com/alphagov/performanceplatform-collector/blob/de68ab4aa500c31e436e050fa1268fa928c522a5/setup.py#L41-L49
train
BertrandBordage/django-terms
terms/cms_plugin_processors.py
TermsProcessor
def TermsProcessor(instance, placeholder, rendered_content, original_context): """ Adds links all placeholders plugins except django-terms plugins """ if 'terms' in original_context: return rendered_content return mark_safe(replace_terms(rendered_content))
python
def TermsProcessor(instance, placeholder, rendered_content, original_context): """ Adds links all placeholders plugins except django-terms plugins """ if 'terms' in original_context: return rendered_content return mark_safe(replace_terms(rendered_content))
[ "def", "TermsProcessor", "(", "instance", ",", "placeholder", ",", "rendered_content", ",", "original_context", ")", ":", "if", "'terms'", "in", "original_context", ":", "return", "rendered_content", "return", "mark_safe", "(", "replace_terms", "(", "rendered_content"...
Adds links all placeholders plugins except django-terms plugins
[ "Adds", "links", "all", "placeholders", "plugins", "except", "django", "-", "terms", "plugins" ]
2555c2cf5abf14adef9a8e2dd22c4a9076396a10
https://github.com/BertrandBordage/django-terms/blob/2555c2cf5abf14adef9a8e2dd22c4a9076396a10/terms/cms_plugin_processors.py#L7-L14
train
consbio/ncdjango
ncdjango/models.py
Variable.time_stops
def time_stops(self): """ Valid time steps for this service as a list of datetime objects. """ if not self.supports_time: return [] if self.service.calendar == 'standard': units = self.service.time_interval_units interval = self.service.time_interval ...
python
def time_stops(self): """ Valid time steps for this service as a list of datetime objects. """ if not self.supports_time: return [] if self.service.calendar == 'standard': units = self.service.time_interval_units interval = self.service.time_interval ...
[ "def", "time_stops", "(", "self", ")", ":", "if", "not", "self", ".", "supports_time", ":", "return", "[", "]", "if", "self", ".", "service", ".", "calendar", "==", "'standard'", ":", "units", "=", "self", ".", "service", ".", "time_interval_units", "int...
Valid time steps for this service as a list of datetime objects.
[ "Valid", "time", "steps", "for", "this", "service", "as", "a", "list", "of", "datetime", "objects", "." ]
f807bfd1e4083ab29fbc3c4d4418be108383a710
https://github.com/consbio/ncdjango/blob/f807bfd1e4083ab29fbc3c4d4418be108383a710/ncdjango/models.py#L98-L155
train
DarkEnergySurvey/ugali
ugali/utils/parser.py
Parser._parse_coords
def _parse_coords(self,opts): """ Parse target coordinates in various ways... """ # The coordinates are mutually exclusive, so # shouldn't have to worry about over-writing them. if 'coords' in vars(opts): return radius = vars(opts).get('radius',0) gal = None ...
python
def _parse_coords(self,opts): """ Parse target coordinates in various ways... """ # The coordinates are mutually exclusive, so # shouldn't have to worry about over-writing them. if 'coords' in vars(opts): return radius = vars(opts).get('radius',0) gal = None ...
[ "def", "_parse_coords", "(", "self", ",", "opts", ")", ":", "# The coordinates are mutually exclusive, so", "# shouldn't have to worry about over-writing them.", "if", "'coords'", "in", "vars", "(", "opts", ")", ":", "return", "radius", "=", "vars", "(", "opts", ")", ...
Parse target coordinates in various ways...
[ "Parse", "target", "coordinates", "in", "various", "ways", "..." ]
21e890b4117fc810afb6fb058e8055d564f03382
https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/utils/parser.py#L87-L112
train
Genida/django-appsettings
src/appsettings/settings.py
Setting.default_value
def default_value(self): """ Property to return the default value. If the default value is callable and call_default is True, return the result of default(). Else return default. Returns: object: the default value. """ if callable(self.default) and s...
python
def default_value(self): """ Property to return the default value. If the default value is callable and call_default is True, return the result of default(). Else return default. Returns: object: the default value. """ if callable(self.default) and s...
[ "def", "default_value", "(", "self", ")", ":", "if", "callable", "(", "self", ".", "default", ")", "and", "self", ".", "call_default", ":", "return", "self", ".", "default", "(", ")", "return", "self", ".", "default" ]
Property to return the default value. If the default value is callable and call_default is True, return the result of default(). Else return default. Returns: object: the default value.
[ "Property", "to", "return", "the", "default", "value", "." ]
f98867d133558af7dc067f12b44fc1ee4edd4239
https://github.com/Genida/django-appsettings/blob/f98867d133558af7dc067f12b44fc1ee4edd4239/src/appsettings/settings.py#L446-L458
train
Genida/django-appsettings
src/appsettings/settings.py
Setting.raw_value
def raw_value(self): """ Property to return the variable defined in ``django.conf.settings``. Returns: object: the variable defined in ``django.conf.settings``. Raises: AttributeError: if the variable is missing. KeyError: if the item is missing from...
python
def raw_value(self): """ Property to return the variable defined in ``django.conf.settings``. Returns: object: the variable defined in ``django.conf.settings``. Raises: AttributeError: if the variable is missing. KeyError: if the item is missing from...
[ "def", "raw_value", "(", "self", ")", ":", "if", "self", ".", "parent_setting", "is", "not", "None", ":", "return", "self", ".", "parent_setting", ".", "raw_value", "[", "self", ".", "full_name", "]", "else", ":", "return", "getattr", "(", "settings", ",...
Property to return the variable defined in ``django.conf.settings``. Returns: object: the variable defined in ``django.conf.settings``. Raises: AttributeError: if the variable is missing. KeyError: if the item is missing from nested setting.
[ "Property", "to", "return", "the", "variable", "defined", "in", "django", ".", "conf", ".", "settings", "." ]
f98867d133558af7dc067f12b44fc1ee4edd4239
https://github.com/Genida/django-appsettings/blob/f98867d133558af7dc067f12b44fc1ee4edd4239/src/appsettings/settings.py#L461-L475
train
Genida/django-appsettings
src/appsettings/settings.py
Setting.get_value
def get_value(self): """ Return the transformed raw or default value. If the variable is missing from the project settings, and the setting is required, re-raise an AttributeError. If it is not required, return the (optionally transformed) default value. Returns: ...
python
def get_value(self): """ Return the transformed raw or default value. If the variable is missing from the project settings, and the setting is required, re-raise an AttributeError. If it is not required, return the (optionally transformed) default value. Returns: ...
[ "def", "get_value", "(", "self", ")", ":", "try", ":", "value", "=", "self", ".", "raw_value", "except", "(", "AttributeError", ",", "KeyError", ")", "as", "err", ":", "self", ".", "_reraise_if_required", "(", "err", ")", "default_value", "=", "self", "....
Return the transformed raw or default value. If the variable is missing from the project settings, and the setting is required, re-raise an AttributeError. If it is not required, return the (optionally transformed) default value. Returns: object: the transformed raw value.
[ "Return", "the", "transformed", "raw", "or", "default", "value", "." ]
f98867d133558af7dc067f12b44fc1ee4edd4239
https://github.com/Genida/django-appsettings/blob/f98867d133558af7dc067f12b44fc1ee4edd4239/src/appsettings/settings.py#L489-L509
train
Genida/django-appsettings
src/appsettings/settings.py
Setting.run_validators
def run_validators(self, value): """Run the validators on the setting value.""" errors = [] for validator in self.validators: try: validator(value) except ValidationError as error: errors.extend(error.messages) if errors: ...
python
def run_validators(self, value): """Run the validators on the setting value.""" errors = [] for validator in self.validators: try: validator(value) except ValidationError as error: errors.extend(error.messages) if errors: ...
[ "def", "run_validators", "(", "self", ",", "value", ")", ":", "errors", "=", "[", "]", "for", "validator", "in", "self", ".", "validators", ":", "try", ":", "validator", "(", "value", ")", "except", "ValidationError", "as", "error", ":", "errors", ".", ...
Run the validators on the setting value.
[ "Run", "the", "validators", "on", "the", "setting", "value", "." ]
f98867d133558af7dc067f12b44fc1ee4edd4239
https://github.com/Genida/django-appsettings/blob/f98867d133558af7dc067f12b44fc1ee4edd4239/src/appsettings/settings.py#L522-L531
train
Genida/django-appsettings
src/appsettings/settings.py
ObjectSetting.transform
def transform(self, path): """ Transform a path into an actual Python object. The path can be arbitrary long. You can pass the path to a package, a module, a class, a function or a global variable, as deep as you want, as long as the deepest module is importable through ...
python
def transform(self, path): """ Transform a path into an actual Python object. The path can be arbitrary long. You can pass the path to a package, a module, a class, a function or a global variable, as deep as you want, as long as the deepest module is importable through ...
[ "def", "transform", "(", "self", ",", "path", ")", ":", "if", "path", "is", "None", "or", "not", "path", ":", "return", "None", "obj_parent_modules", "=", "path", ".", "split", "(", "\".\"", ")", "objects", "=", "[", "obj_parent_modules", ".", "pop", "...
Transform a path into an actual Python object. The path can be arbitrary long. You can pass the path to a package, a module, a class, a function or a global variable, as deep as you want, as long as the deepest module is importable through ``importlib.import_module`` and each object is ...
[ "Transform", "a", "path", "into", "an", "actual", "Python", "object", "." ]
f98867d133558af7dc067f12b44fc1ee4edd4239
https://github.com/Genida/django-appsettings/blob/f98867d133558af7dc067f12b44fc1ee4edd4239/src/appsettings/settings.py#L1085-L1120
train
Genida/django-appsettings
src/appsettings/settings.py
NestedSetting.get_value
def get_value(self): """ Return dictionary with values of subsettings. Returns: dict: values of subsettings. """ try: self.raw_value except (AttributeError, KeyError) as err: self._reraise_if_required(err) default_value = s...
python
def get_value(self): """ Return dictionary with values of subsettings. Returns: dict: values of subsettings. """ try: self.raw_value except (AttributeError, KeyError) as err: self._reraise_if_required(err) default_value = s...
[ "def", "get_value", "(", "self", ")", ":", "try", ":", "self", ".", "raw_value", "except", "(", "AttributeError", ",", "KeyError", ")", "as", "err", ":", "self", ".", "_reraise_if_required", "(", "err", ")", "default_value", "=", "self", ".", "default_valu...
Return dictionary with values of subsettings. Returns: dict: values of subsettings.
[ "Return", "dictionary", "with", "values", "of", "subsettings", "." ]
f98867d133558af7dc067f12b44fc1ee4edd4239
https://github.com/Genida/django-appsettings/blob/f98867d133558af7dc067f12b44fc1ee4edd4239/src/appsettings/settings.py#L1154-L1174
train
DarkEnergySurvey/ugali
ugali/isochrone/model.py
sum_mags
def sum_mags(mags, weights=None): """ Sum an array of magnitudes in flux space. Parameters: ----------- mags : array of magnitudes weights : array of weights for each magnitude (i.e. from a pdf) Returns: -------- sum_mag : the summed magnitude of all the stars """ fl...
python
def sum_mags(mags, weights=None): """ Sum an array of magnitudes in flux space. Parameters: ----------- mags : array of magnitudes weights : array of weights for each magnitude (i.e. from a pdf) Returns: -------- sum_mag : the summed magnitude of all the stars """ fl...
[ "def", "sum_mags", "(", "mags", ",", "weights", "=", "None", ")", ":", "flux", "=", "10", "**", "(", "-", "np", ".", "asarray", "(", "mags", ")", "/", "2.5", ")", "if", "weights", "is", "None", ":", "return", "-", "2.5", "*", "np", ".", "log10"...
Sum an array of magnitudes in flux space. Parameters: ----------- mags : array of magnitudes weights : array of weights for each magnitude (i.e. from a pdf) Returns: -------- sum_mag : the summed magnitude of all the stars
[ "Sum", "an", "array", "of", "magnitudes", "in", "flux", "space", "." ]
21e890b4117fc810afb6fb058e8055d564f03382
https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/isochrone/model.py#L57-L74
train
DarkEnergySurvey/ugali
ugali/isochrone/model.py
absolute_magnitude
def absolute_magnitude(distance_modulus,g,r,prob=None): """ Calculate the absolute magnitude from a set of bands """ V = g - 0.487*(g - r) - 0.0249 flux = np.sum(10**(-(V-distance_modulus)/2.5)) Mv = -2.5*np.log10(flux) return Mv
python
def absolute_magnitude(distance_modulus,g,r,prob=None): """ Calculate the absolute magnitude from a set of bands """ V = g - 0.487*(g - r) - 0.0249 flux = np.sum(10**(-(V-distance_modulus)/2.5)) Mv = -2.5*np.log10(flux) return Mv
[ "def", "absolute_magnitude", "(", "distance_modulus", ",", "g", ",", "r", ",", "prob", "=", "None", ")", ":", "V", "=", "g", "-", "0.487", "*", "(", "g", "-", "r", ")", "-", "0.0249", "flux", "=", "np", ".", "sum", "(", "10", "**", "(", "-", ...
Calculate the absolute magnitude from a set of bands
[ "Calculate", "the", "absolute", "magnitude", "from", "a", "set", "of", "bands" ]
21e890b4117fc810afb6fb058e8055d564f03382
https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/isochrone/model.py#L1208-L1214
train
DarkEnergySurvey/ugali
ugali/isochrone/model.py
IsochroneModel.observableFractionCDF
def observableFractionCDF(self, mask, distance_modulus, mass_min=0.1): """ Compute observable fraction of stars with masses greater than mass_min in each pixel in the interior region of the mask. Incorporates simplistic photometric errors. ADW: Careful, this function is fragile...
python
def observableFractionCDF(self, mask, distance_modulus, mass_min=0.1): """ Compute observable fraction of stars with masses greater than mass_min in each pixel in the interior region of the mask. Incorporates simplistic photometric errors. ADW: Careful, this function is fragile...
[ "def", "observableFractionCDF", "(", "self", ",", "mask", ",", "distance_modulus", ",", "mass_min", "=", "0.1", ")", ":", "method", "=", "'step'", "mass_init", ",", "mass_pdf", ",", "mass_act", ",", "mag_1", ",", "mag_2", "=", "self", ".", "sample", "(", ...
Compute observable fraction of stars with masses greater than mass_min in each pixel in the interior region of the mask. Incorporates simplistic photometric errors. ADW: Careful, this function is fragile! The selection here should be the same as mask.restrictCatalogToObservable sp...
[ "Compute", "observable", "fraction", "of", "stars", "with", "masses", "greater", "than", "mass_min", "in", "each", "pixel", "in", "the", "interior", "region", "of", "the", "mask", ".", "Incorporates", "simplistic", "photometric", "errors", "." ]
21e890b4117fc810afb6fb058e8055d564f03382
https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/isochrone/model.py#L544-L595
train
DarkEnergySurvey/ugali
ugali/isochrone/model.py
IsochroneModel.histogram2d
def histogram2d(self,distance_modulus=None,delta_mag=0.03,steps=10000): """ Return a 2D histogram the isochrone in mag-mag space. Parameters: ----------- distance_modulus : distance modulus to calculate histogram at delta_mag : magnitude bin size mass_steps : num...
python
def histogram2d(self,distance_modulus=None,delta_mag=0.03,steps=10000): """ Return a 2D histogram the isochrone in mag-mag space. Parameters: ----------- distance_modulus : distance modulus to calculate histogram at delta_mag : magnitude bin size mass_steps : num...
[ "def", "histogram2d", "(", "self", ",", "distance_modulus", "=", "None", ",", "delta_mag", "=", "0.03", ",", "steps", "=", "10000", ")", ":", "if", "distance_modulus", "is", "not", "None", ":", "self", ".", "distance_modulus", "=", "distance_modulus", "# Iso...
Return a 2D histogram the isochrone in mag-mag space. Parameters: ----------- distance_modulus : distance modulus to calculate histogram at delta_mag : magnitude bin size mass_steps : number of steps to sample isochrone at Returns: -------- bins_mag_1 : ...
[ "Return", "a", "2D", "histogram", "the", "isochrone", "in", "mag", "-", "mag", "space", "." ]
21e890b4117fc810afb6fb058e8055d564f03382
https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/isochrone/model.py#L746-L786
train
DarkEnergySurvey/ugali
ugali/isochrone/model.py
IsochroneModel.pdf_mmd
def pdf_mmd(self, lon, lat, mag_1, mag_2, distance_modulus, mask, delta_mag=0.03, steps=1000): """ Ok, now here comes the beauty of having the signal MMD. """ logger.info('Running MMD pdf') roi = mask.roi mmd = self.signalMMD(mask,distance_modulus,delta_mag=delta_mag,ma...
python
def pdf_mmd(self, lon, lat, mag_1, mag_2, distance_modulus, mask, delta_mag=0.03, steps=1000): """ Ok, now here comes the beauty of having the signal MMD. """ logger.info('Running MMD pdf') roi = mask.roi mmd = self.signalMMD(mask,distance_modulus,delta_mag=delta_mag,ma...
[ "def", "pdf_mmd", "(", "self", ",", "lon", ",", "lat", ",", "mag_1", ",", "mag_2", ",", "distance_modulus", ",", "mask", ",", "delta_mag", "=", "0.03", ",", "steps", "=", "1000", ")", ":", "logger", ".", "info", "(", "'Running MMD pdf'", ")", "roi", ...
Ok, now here comes the beauty of having the signal MMD.
[ "Ok", "now", "here", "comes", "the", "beauty", "of", "having", "the", "signal", "MMD", "." ]
21e890b4117fc810afb6fb058e8055d564f03382
https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/isochrone/model.py#L788-L817
train
DarkEnergySurvey/ugali
ugali/isochrone/model.py
IsochroneModel.raw_separation
def raw_separation(self,mag_1,mag_2,steps=10000): """ Calculate the separation in magnitude-magnitude space between points and isochrone. Uses a dense sampling of the isochrone and calculates the metric distance from any isochrone sample point. Parameters: ----------- mag_1 : T...
python
def raw_separation(self,mag_1,mag_2,steps=10000): """ Calculate the separation in magnitude-magnitude space between points and isochrone. Uses a dense sampling of the isochrone and calculates the metric distance from any isochrone sample point. Parameters: ----------- mag_1 : T...
[ "def", "raw_separation", "(", "self", ",", "mag_1", ",", "mag_2", ",", "steps", "=", "10000", ")", ":", "# http://stackoverflow.com/q/12653120/", "mag_1", "=", "np", ".", "array", "(", "mag_1", ",", "copy", "=", "False", ",", "ndmin", "=", "1", ")", "mag...
Calculate the separation in magnitude-magnitude space between points and isochrone. Uses a dense sampling of the isochrone and calculates the metric distance from any isochrone sample point. Parameters: ----------- mag_1 : The magnitude of the test points in the first band mag_2 : The m...
[ "Calculate", "the", "separation", "in", "magnitude", "-", "magnitude", "space", "between", "points", "and", "isochrone", ".", "Uses", "a", "dense", "sampling", "of", "the", "isochrone", "and", "calculates", "the", "metric", "distance", "from", "any", "isochrone"...
21e890b4117fc810afb6fb058e8055d564f03382
https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/isochrone/model.py#L929-L960
train
DarkEnergySurvey/ugali
ugali/isochrone/model.py
IsochroneModel.separation
def separation(self, mag_1, mag_2): """ Calculate the separation between a specific point and the isochrone in magnitude-magnitude space. Uses an interpolation ADW: Could speed this up... Parameters: ----------- mag_1 : The magnitude of the test points in the f...
python
def separation(self, mag_1, mag_2): """ Calculate the separation between a specific point and the isochrone in magnitude-magnitude space. Uses an interpolation ADW: Could speed this up... Parameters: ----------- mag_1 : The magnitude of the test points in the f...
[ "def", "separation", "(", "self", ",", "mag_1", ",", "mag_2", ")", ":", "iso_mag_1", "=", "self", ".", "mag_1", "+", "self", ".", "distance_modulus", "iso_mag_2", "=", "self", ".", "mag_2", "+", "self", ".", "distance_modulus", "def", "interp_iso", "(", ...
Calculate the separation between a specific point and the isochrone in magnitude-magnitude space. Uses an interpolation ADW: Could speed this up... Parameters: ----------- mag_1 : The magnitude of the test points in the first band mag_2 : The magnitude of the test point...
[ "Calculate", "the", "separation", "between", "a", "specific", "point", "and", "the", "isochrone", "in", "magnitude", "-", "magnitude", "space", ".", "Uses", "an", "interpolation" ]
21e890b4117fc810afb6fb058e8055d564f03382
https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/isochrone/model.py#L963-L1017
train
akx/lepo
lepo/router.py
Router.get_handler
def get_handler(self, operation_id): """ Get the handler function for a given operation. To remain Pythonic, both the original and the snake_cased version of the operation ID are supported. This could be overridden in a subclass. :param operation_id: Operation ID. ...
python
def get_handler(self, operation_id): """ Get the handler function for a given operation. To remain Pythonic, both the original and the snake_cased version of the operation ID are supported. This could be overridden in a subclass. :param operation_id: Operation ID. ...
[ "def", "get_handler", "(", "self", ",", "operation_id", ")", ":", "handler", "=", "(", "self", ".", "handlers", ".", "get", "(", "operation_id", ")", "or", "self", ".", "handlers", ".", "get", "(", "snake_case", "(", "operation_id", ")", ")", ")", "if"...
Get the handler function for a given operation. To remain Pythonic, both the original and the snake_cased version of the operation ID are supported. This could be overridden in a subclass. :param operation_id: Operation ID. :return: Handler function :rtype: function
[ "Get", "the", "handler", "function", "for", "a", "given", "operation", "." ]
34cfb24a40f18ea40f672c1ea9a0734ee1816b7d
https://github.com/akx/lepo/blob/34cfb24a40f18ea40f672c1ea9a0734ee1816b7d/lepo/router.py#L105-L126
train
akx/lepo
lepo/router.py
Router.add_handlers
def add_handlers(self, namespace): """ Add handler functions from the given `namespace`, for instance a module. The namespace may be a string, in which case it is expected to be a name of a module. It may also be a dictionary mapping names to functions. Only non-underscore-pref...
python
def add_handlers(self, namespace): """ Add handler functions from the given `namespace`, for instance a module. The namespace may be a string, in which case it is expected to be a name of a module. It may also be a dictionary mapping names to functions. Only non-underscore-pref...
[ "def", "add_handlers", "(", "self", ",", "namespace", ")", ":", "if", "isinstance", "(", "namespace", ",", "str", ")", ":", "namespace", "=", "import_module", "(", "namespace", ")", "if", "isinstance", "(", "namespace", ",", "dict", ")", ":", "namespace", ...
Add handler functions from the given `namespace`, for instance a module. The namespace may be a string, in which case it is expected to be a name of a module. It may also be a dictionary mapping names to functions. Only non-underscore-prefixed functions and methods are imported. :para...
[ "Add", "handler", "functions", "from", "the", "given", "namespace", "for", "instance", "a", "module", "." ]
34cfb24a40f18ea40f672c1ea9a0734ee1816b7d
https://github.com/akx/lepo/blob/34cfb24a40f18ea40f672c1ea9a0734ee1816b7d/lepo/router.py#L128-L152
train
consbio/ncdjango
ncdjango/geoprocessing/tasks/raster.py
SingleArrayExpressionBase.get_context
def get_context(self, arr, expr, context): """ Returns a context dictionary for use in evaluating the expression. :param arr: The input array. :param expr: The input expression. :param context: Evaluation context. """ expression_names = [x for x in self.get_expr...
python
def get_context(self, arr, expr, context): """ Returns a context dictionary for use in evaluating the expression. :param arr: The input array. :param expr: The input expression. :param context: Evaluation context. """ expression_names = [x for x in self.get_expr...
[ "def", "get_context", "(", "self", ",", "arr", ",", "expr", ",", "context", ")", ":", "expression_names", "=", "[", "x", "for", "x", "in", "self", ".", "get_expression_names", "(", "expr", ")", "if", "x", "not", "in", "set", "(", "context", ".", "key...
Returns a context dictionary for use in evaluating the expression. :param arr: The input array. :param expr: The input expression. :param context: Evaluation context.
[ "Returns", "a", "context", "dictionary", "for", "use", "in", "evaluating", "the", "expression", "." ]
f807bfd1e4083ab29fbc3c4d4418be108383a710
https://github.com/consbio/ncdjango/blob/f807bfd1e4083ab29fbc3c4d4418be108383a710/ncdjango/geoprocessing/tasks/raster.py#L82-L96
train
consbio/ncdjango
ncdjango/geoprocessing/tasks/raster.py
MaskByExpression.execute
def execute(self, array_in, expression, **kwargs): """Creates and returns a masked view of the input array.""" context = self.get_context(array_in, expression, kwargs) context.update(kwargs) return ma.masked_where(self.evaluate_expression(expression, context), array_in)
python
def execute(self, array_in, expression, **kwargs): """Creates and returns a masked view of the input array.""" context = self.get_context(array_in, expression, kwargs) context.update(kwargs) return ma.masked_where(self.evaluate_expression(expression, context), array_in)
[ "def", "execute", "(", "self", ",", "array_in", ",", "expression", ",", "*", "*", "kwargs", ")", ":", "context", "=", "self", ".", "get_context", "(", "array_in", ",", "expression", ",", "kwargs", ")", "context", ".", "update", "(", "kwargs", ")", "ret...
Creates and returns a masked view of the input array.
[ "Creates", "and", "returns", "a", "masked", "view", "of", "the", "input", "array", "." ]
f807bfd1e4083ab29fbc3c4d4418be108383a710
https://github.com/consbio/ncdjango/blob/f807bfd1e4083ab29fbc3c4d4418be108383a710/ncdjango/geoprocessing/tasks/raster.py#L104-L109
train
juju/theblues
theblues/errors.py
timeout_error
def timeout_error(url, timeout): """Raise a server error indicating a request timeout to the given URL.""" msg = 'Request timed out: {} timeout: {}s'.format(url, timeout) log.warning(msg) return ServerError(msg)
python
def timeout_error(url, timeout): """Raise a server error indicating a request timeout to the given URL.""" msg = 'Request timed out: {} timeout: {}s'.format(url, timeout) log.warning(msg) return ServerError(msg)
[ "def", "timeout_error", "(", "url", ",", "timeout", ")", ":", "msg", "=", "'Request timed out: {} timeout: {}s'", ".", "format", "(", "url", ",", "timeout", ")", "log", ".", "warning", "(", "msg", ")", "return", "ServerError", "(", "msg", ")" ]
Raise a server error indicating a request timeout to the given URL.
[ "Raise", "a", "server", "error", "indicating", "a", "request", "timeout", "to", "the", "given", "URL", "." ]
f4431f29e43d04fc32f38f4f86cea45cd4e6ae98
https://github.com/juju/theblues/blob/f4431f29e43d04fc32f38f4f86cea45cd4e6ae98/theblues/errors.py#L19-L23
train
DarkEnergySurvey/ugali
ugali/utils/plotting.py
histogram
def histogram(title, title_x, title_y, x, bins_x): """ Plot a basic histogram. """ plt.figure() plt.hist(x, bins_x) plt.xlabel(title_x) plt.ylabel(title_y) plt.title(title)
python
def histogram(title, title_x, title_y, x, bins_x): """ Plot a basic histogram. """ plt.figure() plt.hist(x, bins_x) plt.xlabel(title_x) plt.ylabel(title_y) plt.title(title)
[ "def", "histogram", "(", "title", ",", "title_x", ",", "title_y", ",", "x", ",", "bins_x", ")", ":", "plt", ".", "figure", "(", ")", "plt", ".", "hist", "(", "x", ",", "bins_x", ")", "plt", ".", "xlabel", "(", "title_x", ")", "plt", ".", "ylabel"...
Plot a basic histogram.
[ "Plot", "a", "basic", "histogram", "." ]
21e890b4117fc810afb6fb058e8055d564f03382
https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/utils/plotting.py#L61-L70
train
DarkEnergySurvey/ugali
ugali/utils/plotting.py
twoDimensionalHistogram
def twoDimensionalHistogram(title, title_x, title_y, z, bins_x, bins_y, lim_x=None, lim_y=None, vmin=None, vmax=None): """ Create a two-dimension histogram plot or binned map. If using the outputs of np.histogram2d, remembe...
python
def twoDimensionalHistogram(title, title_x, title_y, z, bins_x, bins_y, lim_x=None, lim_y=None, vmin=None, vmax=None): """ Create a two-dimension histogram plot or binned map. If using the outputs of np.histogram2d, remembe...
[ "def", "twoDimensionalHistogram", "(", "title", ",", "title_x", ",", "title_y", ",", "z", ",", "bins_x", ",", "bins_y", ",", "lim_x", "=", "None", ",", "lim_y", "=", "None", ",", "vmin", "=", "None", ",", "vmax", "=", "None", ")", ":", "plt", ".", ...
Create a two-dimension histogram plot or binned map. If using the outputs of np.histogram2d, remember to transpose the histogram. INPUTS
[ "Create", "a", "two", "-", "dimension", "histogram", "plot", "or", "binned", "map", "." ]
21e890b4117fc810afb6fb058e8055d564f03382
https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/utils/plotting.py#L74-L101
train
DarkEnergySurvey/ugali
ugali/utils/plotting.py
twoDimensionalScatter
def twoDimensionalScatter(title, title_x, title_y, x, y, lim_x = None, lim_y = None, color = 'b', size = 20, alpha=None): """ Create a two-dimensional scatter plot. INPUTS """ plt.figure() plt.scatter(x, y, c=color, ...
python
def twoDimensionalScatter(title, title_x, title_y, x, y, lim_x = None, lim_y = None, color = 'b', size = 20, alpha=None): """ Create a two-dimensional scatter plot. INPUTS """ plt.figure() plt.scatter(x, y, c=color, ...
[ "def", "twoDimensionalScatter", "(", "title", ",", "title_x", ",", "title_y", ",", "x", ",", "y", ",", "lim_x", "=", "None", ",", "lim_y", "=", "None", ",", "color", "=", "'b'", ",", "size", "=", "20", ",", "alpha", "=", "None", ")", ":", "plt", ...
Create a two-dimensional scatter plot. INPUTS
[ "Create", "a", "two", "-", "dimensional", "scatter", "plot", "." ]
21e890b4117fc810afb6fb058e8055d564f03382
https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/utils/plotting.py#L105-L127
train
DarkEnergySurvey/ugali
ugali/utils/plotting.py
drawHealpixMap
def drawHealpixMap(hpxmap, lon, lat, size=1.0, xsize=501, coord='GC', **kwargs): """ Draw local projection of healpix map. """ ax = plt.gca() x = np.linspace(-size,size,xsize) y = np.linspace(-size,size,xsize) xx, yy = np.meshgrid(x,y) coord = coord.upper() if coord == ...
python
def drawHealpixMap(hpxmap, lon, lat, size=1.0, xsize=501, coord='GC', **kwargs): """ Draw local projection of healpix map. """ ax = plt.gca() x = np.linspace(-size,size,xsize) y = np.linspace(-size,size,xsize) xx, yy = np.meshgrid(x,y) coord = coord.upper() if coord == ...
[ "def", "drawHealpixMap", "(", "hpxmap", ",", "lon", ",", "lat", ",", "size", "=", "1.0", ",", "xsize", "=", "501", ",", "coord", "=", "'GC'", ",", "*", "*", "kwargs", ")", ":", "ax", "=", "plt", ".", "gca", "(", ")", "x", "=", "np", ".", "lin...
Draw local projection of healpix map.
[ "Draw", "local", "projection", "of", "healpix", "map", "." ]
21e890b4117fc810afb6fb058e8055d564f03382
https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/utils/plotting.py#L162-L189
train
DarkEnergySurvey/ugali
ugali/utils/plotting.py
getDSSImage
def getDSSImage(ra,dec,radius=1.0,xsize=800,**kwargs): """ Download Digitized Sky Survey images https://archive.stsci.edu/cgi-bin/dss_form https://archive.stsci.edu/cgi-bin/dss_search Image is in celestial orientation (RA increases to the right) https://archive.stsci.edu/dss/script_usage.h...
python
def getDSSImage(ra,dec,radius=1.0,xsize=800,**kwargs): """ Download Digitized Sky Survey images https://archive.stsci.edu/cgi-bin/dss_form https://archive.stsci.edu/cgi-bin/dss_search Image is in celestial orientation (RA increases to the right) https://archive.stsci.edu/dss/script_usage.h...
[ "def", "getDSSImage", "(", "ra", ",", "dec", ",", "radius", "=", "1.0", ",", "xsize", "=", "800", ",", "*", "*", "kwargs", ")", ":", "import", "subprocess", "import", "tempfile", "service", "=", "'skyview'", "if", "service", "==", "'stsci'", ":", "url"...
Download Digitized Sky Survey images https://archive.stsci.edu/cgi-bin/dss_form https://archive.stsci.edu/cgi-bin/dss_search Image is in celestial orientation (RA increases to the right) https://archive.stsci.edu/dss/script_usage.html ra (r) - right ascension dec (d) - declination equ...
[ "Download", "Digitized", "Sky", "Survey", "images" ]
21e890b4117fc810afb6fb058e8055d564f03382
https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/utils/plotting.py#L241-L298
train
DarkEnergySurvey/ugali
ugali/utils/plotting.py
draw_slices
def draw_slices(hist, func=np.sum, **kwargs): """ Draw horizontal and vertical slices through histogram """ from mpl_toolkits.axes_grid1 import make_axes_locatable kwargs.setdefault('ls','-') ax = plt.gca() data = hist # Slices vslice = func(data,axis=0) hslice = func(data,axis=1) ...
python
def draw_slices(hist, func=np.sum, **kwargs): """ Draw horizontal and vertical slices through histogram """ from mpl_toolkits.axes_grid1 import make_axes_locatable kwargs.setdefault('ls','-') ax = plt.gca() data = hist # Slices vslice = func(data,axis=0) hslice = func(data,axis=1) ...
[ "def", "draw_slices", "(", "hist", ",", "func", "=", "np", ".", "sum", ",", "*", "*", "kwargs", ")", ":", "from", "mpl_toolkits", ".", "axes_grid1", "import", "make_axes_locatable", "kwargs", ".", "setdefault", "(", "'ls'", ",", "'-'", ")", "ax", "=", ...
Draw horizontal and vertical slices through histogram
[ "Draw", "horizontal", "and", "vertical", "slices", "through", "histogram" ]
21e890b4117fc810afb6fb058e8055d564f03382
https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/utils/plotting.py#L1035-L1077
train
DarkEnergySurvey/ugali
ugali/utils/plotting.py
plotSkymapCatalog
def plotSkymapCatalog(lon,lat,**kwargs): """ Plot a catalog of coordinates on a full-sky map. """ fig = plt.figure() ax = plt.subplot(111,projection=projection) drawSkymapCatalog(ax,lon,lat,**kwargs)
python
def plotSkymapCatalog(lon,lat,**kwargs): """ Plot a catalog of coordinates on a full-sky map. """ fig = plt.figure() ax = plt.subplot(111,projection=projection) drawSkymapCatalog(ax,lon,lat,**kwargs)
[ "def", "plotSkymapCatalog", "(", "lon", ",", "lat", ",", "*", "*", "kwargs", ")", ":", "fig", "=", "plt", ".", "figure", "(", ")", "ax", "=", "plt", ".", "subplot", "(", "111", ",", "projection", "=", "projection", ")", "drawSkymapCatalog", "(", "ax"...
Plot a catalog of coordinates on a full-sky map.
[ "Plot", "a", "catalog", "of", "coordinates", "on", "a", "full", "-", "sky", "map", "." ]
21e890b4117fc810afb6fb058e8055d564f03382
https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/utils/plotting.py#L1409-L1415
train
DarkEnergySurvey/ugali
ugali/utils/plotting.py
makePath
def makePath(x_path, y_path, epsilon=1.e-10): """ Create closed path. """ x_path_closed = np.concatenate([x_path, x_path[::-1]]) y_path_closed = np.concatenate([y_path, epsilon + y_path[::-1]]) path = matplotlib.path.Path(list(zip(x_path_closed, y_path_closed))) return path
python
def makePath(x_path, y_path, epsilon=1.e-10): """ Create closed path. """ x_path_closed = np.concatenate([x_path, x_path[::-1]]) y_path_closed = np.concatenate([y_path, epsilon + y_path[::-1]]) path = matplotlib.path.Path(list(zip(x_path_closed, y_path_closed))) return path
[ "def", "makePath", "(", "x_path", ",", "y_path", ",", "epsilon", "=", "1.e-10", ")", ":", "x_path_closed", "=", "np", ".", "concatenate", "(", "[", "x_path", ",", "x_path", "[", ":", ":", "-", "1", "]", "]", ")", "y_path_closed", "=", "np", ".", "c...
Create closed path.
[ "Create", "closed", "path", "." ]
21e890b4117fc810afb6fb058e8055d564f03382
https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/utils/plotting.py#L1499-L1506
train
DarkEnergySurvey/ugali
ugali/utils/plotting.py
BasePlotter.drawMask
def drawMask(self,ax=None, mask=None, mtype='maglim'): """ Draw the maglim from the mask. """ if not ax: ax = plt.gca() if mask is None: mask = ugali.analysis.loglike.createMask(self.config,roi=self.roi) mask_map = hp.UNSEEN*np.ones(hp.nside2npix(self.nside)) if mtyp...
python
def drawMask(self,ax=None, mask=None, mtype='maglim'): """ Draw the maglim from the mask. """ if not ax: ax = plt.gca() if mask is None: mask = ugali.analysis.loglike.createMask(self.config,roi=self.roi) mask_map = hp.UNSEEN*np.ones(hp.nside2npix(self.nside)) if mtyp...
[ "def", "drawMask", "(", "self", ",", "ax", "=", "None", ",", "mask", "=", "None", ",", "mtype", "=", "'maglim'", ")", ":", "if", "not", "ax", ":", "ax", "=", "plt", ".", "gca", "(", ")", "if", "mask", "is", "None", ":", "mask", "=", "ugali", ...
Draw the maglim from the mask.
[ "Draw", "the", "maglim", "from", "the", "mask", "." ]
21e890b4117fc810afb6fb058e8055d564f03382
https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/utils/plotting.py#L458-L480
train
warrenspe/hconf
hconf/subparsers/ini.py
INI.parse
def parse(self, configManager, config): """ Parse configuration options out of an .ini configuration file. Inputs: configManager - Our parent ConfigManager instance which is constructing the Config object. config - The _Config object containing configuration options popul...
python
def parse(self, configManager, config): """ Parse configuration options out of an .ini configuration file. Inputs: configManager - Our parent ConfigManager instance which is constructing the Config object. config - The _Config object containing configuration options popul...
[ "def", "parse", "(", "self", ",", "configManager", ",", "config", ")", ":", "parser", "=", "ConfigParser", ".", "RawConfigParser", "(", ")", "configOptions", "=", "dict", "(", ")", "configFile", "=", "self", ".", "_getConfigFile", "(", "config", ")", "if",...
Parse configuration options out of an .ini configuration file. Inputs: configManager - Our parent ConfigManager instance which is constructing the Config object. config - The _Config object containing configuration options populated thus far. Outputs: A dictionary of new configu...
[ "Parse", "configuration", "options", "out", "of", "an", ".", "ini", "configuration", "file", "." ]
12074d15dc3641d3903488c95d89a507386a32d5
https://github.com/warrenspe/hconf/blob/12074d15dc3641d3903488c95d89a507386a32d5/hconf/subparsers/ini.py#L46-L67
train
accraze/python-markov-novel
src/markov_novel/chapter.py
Chapter.write_chapter
def write_chapter(self): """ Create a chapter that contains a random number of paragraphs """ self.paragraphs = [] self.paragraphs.append('\n') for x in range(randint(0, 50)): p = Paragraph(self.model) self.paragraphs.append(p.get_p...
python
def write_chapter(self): """ Create a chapter that contains a random number of paragraphs """ self.paragraphs = [] self.paragraphs.append('\n') for x in range(randint(0, 50)): p = Paragraph(self.model) self.paragraphs.append(p.get_p...
[ "def", "write_chapter", "(", "self", ")", ":", "self", ".", "paragraphs", "=", "[", "]", "self", ".", "paragraphs", ".", "append", "(", "'\\n'", ")", "for", "x", "in", "range", "(", "randint", "(", "0", ",", "50", ")", ")", ":", "p", "=", "Paragr...
Create a chapter that contains a random number of paragraphs
[ "Create", "a", "chapter", "that", "contains", "a", "random", "number", "of", "paragraphs" ]
ff451639e93a3ac11fb0268b92bc0cffc00bfdbe
https://github.com/accraze/python-markov-novel/blob/ff451639e93a3ac11fb0268b92bc0cffc00bfdbe/src/markov_novel/chapter.py#L20-L32
train
kallimachos/sphinxmark
sphinxmark/__init__.py
buildcss
def buildcss(app, buildpath, imagefile): """Create CSS file.""" # set default values div = 'body' repeat = 'repeat-y' position = 'center' attachment = 'scroll' if app.config.sphinxmark_div != 'default': div = app.config.sphinxmark_div if app.config.sphinxmark_repeat is False: ...
python
def buildcss(app, buildpath, imagefile): """Create CSS file.""" # set default values div = 'body' repeat = 'repeat-y' position = 'center' attachment = 'scroll' if app.config.sphinxmark_div != 'default': div = app.config.sphinxmark_div if app.config.sphinxmark_repeat is False: ...
[ "def", "buildcss", "(", "app", ",", "buildpath", ",", "imagefile", ")", ":", "# set default values", "div", "=", "'body'", "repeat", "=", "'repeat-y'", "position", "=", "'center'", "attachment", "=", "'scroll'", "if", "app", ".", "config", ".", "sphinxmark_div...
Create CSS file.
[ "Create", "CSS", "file", "." ]
f7b17d9dabf1fff448bb38d90474498f0d203990
https://github.com/kallimachos/sphinxmark/blob/f7b17d9dabf1fff448bb38d90474498f0d203990/sphinxmark/__init__.py#L34-L64
train
kallimachos/sphinxmark
sphinxmark/__init__.py
createimage
def createimage(app, srcdir, buildpath): """Create PNG image from string.""" text = app.config.sphinxmark_text # draw transparent background width = app.config.sphinxmark_text_width height = app.config.sphinxmark_text_spacing img = Image.new('RGBA', (width, height), (255, 255, 255, 0)) d = ...
python
def createimage(app, srcdir, buildpath): """Create PNG image from string.""" text = app.config.sphinxmark_text # draw transparent background width = app.config.sphinxmark_text_width height = app.config.sphinxmark_text_spacing img = Image.new('RGBA', (width, height), (255, 255, 255, 0)) d = ...
[ "def", "createimage", "(", "app", ",", "srcdir", ",", "buildpath", ")", ":", "text", "=", "app", ".", "config", ".", "sphinxmark_text", "# draw transparent background", "width", "=", "app", ".", "config", ".", "sphinxmark_text_width", "height", "=", "app", "."...
Create PNG image from string.
[ "Create", "PNG", "image", "from", "string", "." ]
f7b17d9dabf1fff448bb38d90474498f0d203990
https://github.com/kallimachos/sphinxmark/blob/f7b17d9dabf1fff448bb38d90474498f0d203990/sphinxmark/__init__.py#L67-L103
train
kallimachos/sphinxmark
sphinxmark/__init__.py
getimage
def getimage(app): """Get image file.""" # append source directory to TEMPLATE_PATH so template is found srcdir = os.path.abspath(os.path.dirname(__file__)) TEMPLATE_PATH.append(srcdir) staticbase = '_static' buildpath = os.path.join(app.outdir, staticbase) try: os.makedirs(buildpath...
python
def getimage(app): """Get image file.""" # append source directory to TEMPLATE_PATH so template is found srcdir = os.path.abspath(os.path.dirname(__file__)) TEMPLATE_PATH.append(srcdir) staticbase = '_static' buildpath = os.path.join(app.outdir, staticbase) try: os.makedirs(buildpath...
[ "def", "getimage", "(", "app", ")", ":", "# append source directory to TEMPLATE_PATH so template is found", "srcdir", "=", "os", ".", "path", ".", "abspath", "(", "os", ".", "path", ".", "dirname", "(", "__file__", ")", ")", "TEMPLATE_PATH", ".", "append", "(", ...
Get image file.
[ "Get", "image", "file", "." ]
f7b17d9dabf1fff448bb38d90474498f0d203990
https://github.com/kallimachos/sphinxmark/blob/f7b17d9dabf1fff448bb38d90474498f0d203990/sphinxmark/__init__.py#L106-L149
train
kallimachos/sphinxmark
sphinxmark/__init__.py
watermark
def watermark(app, env): """Add watermark.""" if app.config.sphinxmark_enable is True: LOG.info('adding watermark...', nonl=True) buildpath, imagefile = getimage(app) cssname = buildcss(app, buildpath, imagefile) app.add_css_file(cssname) LOG.info(' done')
python
def watermark(app, env): """Add watermark.""" if app.config.sphinxmark_enable is True: LOG.info('adding watermark...', nonl=True) buildpath, imagefile = getimage(app) cssname = buildcss(app, buildpath, imagefile) app.add_css_file(cssname) LOG.info(' done')
[ "def", "watermark", "(", "app", ",", "env", ")", ":", "if", "app", ".", "config", ".", "sphinxmark_enable", "is", "True", ":", "LOG", ".", "info", "(", "'adding watermark...'", ",", "nonl", "=", "True", ")", "buildpath", ",", "imagefile", "=", "getimage"...
Add watermark.
[ "Add", "watermark", "." ]
f7b17d9dabf1fff448bb38d90474498f0d203990
https://github.com/kallimachos/sphinxmark/blob/f7b17d9dabf1fff448bb38d90474498f0d203990/sphinxmark/__init__.py#L152-L159
train
kallimachos/sphinxmark
sphinxmark/__init__.py
setup
def setup(app): """ Configure setup for Sphinx extension. :param app: Sphinx application context. """ app.add_config_value('sphinxmark_enable', False, 'html') app.add_config_value('sphinxmark_div', 'default', 'html') app.add_config_value('sphinxmark_border', None, 'html') app.add_config...
python
def setup(app): """ Configure setup for Sphinx extension. :param app: Sphinx application context. """ app.add_config_value('sphinxmark_enable', False, 'html') app.add_config_value('sphinxmark_div', 'default', 'html') app.add_config_value('sphinxmark_border', None, 'html') app.add_config...
[ "def", "setup", "(", "app", ")", ":", "app", ".", "add_config_value", "(", "'sphinxmark_enable'", ",", "False", ",", "'html'", ")", "app", ".", "add_config_value", "(", "'sphinxmark_div'", ",", "'default'", ",", "'html'", ")", "app", ".", "add_config_value", ...
Configure setup for Sphinx extension. :param app: Sphinx application context.
[ "Configure", "setup", "for", "Sphinx", "extension", "." ]
f7b17d9dabf1fff448bb38d90474498f0d203990
https://github.com/kallimachos/sphinxmark/blob/f7b17d9dabf1fff448bb38d90474498f0d203990/sphinxmark/__init__.py#L162-L187
train
DarkEnergySurvey/ugali
ugali/utils/bayesian_efficiency.py
gammalnStirling
def gammalnStirling(z): """ Uses Stirling's approximation for the log-gamma function suitable for large arguments. """ return (0.5 * (np.log(2. * np.pi) - np.log(z))) \ + (z * (np.log(z + (1. / ((12. * z) - (1. / (10. * z))))) - 1.))
python
def gammalnStirling(z): """ Uses Stirling's approximation for the log-gamma function suitable for large arguments. """ return (0.5 * (np.log(2. * np.pi) - np.log(z))) \ + (z * (np.log(z + (1. / ((12. * z) - (1. / (10. * z))))) - 1.))
[ "def", "gammalnStirling", "(", "z", ")", ":", "return", "(", "0.5", "*", "(", "np", ".", "log", "(", "2.", "*", "np", ".", "pi", ")", "-", "np", ".", "log", "(", "z", ")", ")", ")", "+", "(", "z", "*", "(", "np", ".", "log", "(", "z", "...
Uses Stirling's approximation for the log-gamma function suitable for large arguments.
[ "Uses", "Stirling", "s", "approximation", "for", "the", "log", "-", "gamma", "function", "suitable", "for", "large", "arguments", "." ]
21e890b4117fc810afb6fb058e8055d564f03382
https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/utils/bayesian_efficiency.py#L15-L20
train
DarkEnergySurvey/ugali
ugali/simulation/simulator.py
satellite
def satellite(isochrone, kernel, stellar_mass, distance_modulus,**kwargs): """ Wrapping the isochrone and kernel simulate functions. """ mag_1, mag_2 = isochrone.simulate(stellar_mass, distance_modulus) lon, lat = kernel.simulate(len(mag_1)) return mag_1, mag_2, lon, lat
python
def satellite(isochrone, kernel, stellar_mass, distance_modulus,**kwargs): """ Wrapping the isochrone and kernel simulate functions. """ mag_1, mag_2 = isochrone.simulate(stellar_mass, distance_modulus) lon, lat = kernel.simulate(len(mag_1)) return mag_1, mag_2, lon, lat
[ "def", "satellite", "(", "isochrone", ",", "kernel", ",", "stellar_mass", ",", "distance_modulus", ",", "*", "*", "kwargs", ")", ":", "mag_1", ",", "mag_2", "=", "isochrone", ".", "simulate", "(", "stellar_mass", ",", "distance_modulus", ")", "lon", ",", "...
Wrapping the isochrone and kernel simulate functions.
[ "Wrapping", "the", "isochrone", "and", "kernel", "simulate", "functions", "." ]
21e890b4117fc810afb6fb058e8055d564f03382
https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/simulation/simulator.py#L811-L818
train
DarkEnergySurvey/ugali
ugali/simulation/simulator.py
Generator.detectability
def detectability(self,**kwargs): """ An a priori detectability proxy. """ distance_modulus = kwargs.get('distance_modulus') distance = mod2dist(distance_modulus) stellar_mass = kwargs.get('stellar_mass') extension = kwargs.get('extension') # Normalized t...
python
def detectability(self,**kwargs): """ An a priori detectability proxy. """ distance_modulus = kwargs.get('distance_modulus') distance = mod2dist(distance_modulus) stellar_mass = kwargs.get('stellar_mass') extension = kwargs.get('extension') # Normalized t...
[ "def", "detectability", "(", "self", ",", "*", "*", "kwargs", ")", ":", "distance_modulus", "=", "kwargs", ".", "get", "(", "'distance_modulus'", ")", "distance", "=", "mod2dist", "(", "distance_modulus", ")", "stellar_mass", "=", "kwargs", ".", "get", "(", ...
An a priori detectability proxy.
[ "An", "a", "priori", "detectability", "proxy", "." ]
21e890b4117fc810afb6fb058e8055d564f03382
https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/simulation/simulator.py#L76-L88
train
DarkEnergySurvey/ugali
ugali/simulation/simulator.py
Simulator._create_catalog
def _create_catalog(self,catalog=None): """ Bundle it. """ if catalog is None: catalog = ugali.analysis.loglike.createCatalog(self.config,self.roi) cut = self.mask.restrictCatalogToObservableSpace(catalog) self.catalog = catalog.applyCut(cut)
python
def _create_catalog(self,catalog=None): """ Bundle it. """ if catalog is None: catalog = ugali.analysis.loglike.createCatalog(self.config,self.roi) cut = self.mask.restrictCatalogToObservableSpace(catalog) self.catalog = catalog.applyCut(cut)
[ "def", "_create_catalog", "(", "self", ",", "catalog", "=", "None", ")", ":", "if", "catalog", "is", "None", ":", "catalog", "=", "ugali", ".", "analysis", ".", "loglike", ".", "createCatalog", "(", "self", ".", "config", ",", "self", ".", "roi", ")", ...
Bundle it.
[ "Bundle", "it", "." ]
21e890b4117fc810afb6fb058e8055d564f03382
https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/simulation/simulator.py#L228-L235
train
DarkEnergySurvey/ugali
ugali/simulation/simulator.py
Simulator._setup_subpix
def _setup_subpix(self,nside=2**16): """ Subpixels for random position generation. """ # Only setup once... if hasattr(self,'subpix'): return # Simulate over full ROI self.roi_radius = self.config['coords']['roi_radius'] # Setup background spatial stuff...
python
def _setup_subpix(self,nside=2**16): """ Subpixels for random position generation. """ # Only setup once... if hasattr(self,'subpix'): return # Simulate over full ROI self.roi_radius = self.config['coords']['roi_radius'] # Setup background spatial stuff...
[ "def", "_setup_subpix", "(", "self", ",", "nside", "=", "2", "**", "16", ")", ":", "# Only setup once...", "if", "hasattr", "(", "self", ",", "'subpix'", ")", ":", "return", "# Simulate over full ROI", "self", ".", "roi_radius", "=", "self", ".", "config", ...
Subpixels for random position generation.
[ "Subpixels", "for", "random", "position", "generation", "." ]
21e890b4117fc810afb6fb058e8055d564f03382
https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/simulation/simulator.py#L289-L306
train
DarkEnergySurvey/ugali
ugali/simulation/simulator.py
Simulator._setup_cmd
def _setup_cmd(self,mode='cloud-in-cells'): """ The purpose here is to create a more finely binned background CMD to sample from. """ # Only setup once... if hasattr(self,'bkg_lambda'): return logger.info("Setup color...") # In the limit theta->0: 2*pi*(1...
python
def _setup_cmd(self,mode='cloud-in-cells'): """ The purpose here is to create a more finely binned background CMD to sample from. """ # Only setup once... if hasattr(self,'bkg_lambda'): return logger.info("Setup color...") # In the limit theta->0: 2*pi*(1...
[ "def", "_setup_cmd", "(", "self", ",", "mode", "=", "'cloud-in-cells'", ")", ":", "# Only setup once...", "if", "hasattr", "(", "self", ",", "'bkg_lambda'", ")", ":", "return", "logger", ".", "info", "(", "\"Setup color...\"", ")", "# In the limit theta->0: 2*pi*(...
The purpose here is to create a more finely binned background CMD to sample from.
[ "The", "purpose", "here", "is", "to", "create", "a", "more", "finely", "binned", "background", "CMD", "to", "sample", "from", "." ]
21e890b4117fc810afb6fb058e8055d564f03382
https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/simulation/simulator.py#L308-L340
train
DarkEnergySurvey/ugali
ugali/simulation/simulator.py
Simulator.toy_background
def toy_background(self,mc_source_id=2,seed=None): """ Quick uniform background generation. """ logger.info("Running toy background simulation...") size = 20000 nstar = np.random.poisson(size) #np.random.seed(0) logger.info("Simulating %i background stars...
python
def toy_background(self,mc_source_id=2,seed=None): """ Quick uniform background generation. """ logger.info("Running toy background simulation...") size = 20000 nstar = np.random.poisson(size) #np.random.seed(0) logger.info("Simulating %i background stars...
[ "def", "toy_background", "(", "self", ",", "mc_source_id", "=", "2", ",", "seed", "=", "None", ")", ":", "logger", ".", "info", "(", "\"Running toy background simulation...\"", ")", "size", "=", "20000", "nstar", "=", "np", ".", "random", ".", "poisson", "...
Quick uniform background generation.
[ "Quick", "uniform", "background", "generation", "." ]
21e890b4117fc810afb6fb058e8055d564f03382
https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/simulation/simulator.py#L343-L397
train
DarkEnergySurvey/ugali
ugali/simulation/simulator.py
Simulator.satellite
def satellite(self,stellar_mass,distance_modulus,mc_source_id=1,seed=None,**kwargs): """ Create a simulated satellite. Returns a catalog object. """ if seed is not None: np.random.seed(seed) isochrone = kwargs.pop('isochrone',self.isochrone) kernel = kwargs.pop('kerne...
python
def satellite(self,stellar_mass,distance_modulus,mc_source_id=1,seed=None,**kwargs): """ Create a simulated satellite. Returns a catalog object. """ if seed is not None: np.random.seed(seed) isochrone = kwargs.pop('isochrone',self.isochrone) kernel = kwargs.pop('kerne...
[ "def", "satellite", "(", "self", ",", "stellar_mass", ",", "distance_modulus", ",", "mc_source_id", "=", "1", ",", "seed", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "seed", "is", "not", "None", ":", "np", ".", "random", ".", "seed", "(", ...
Create a simulated satellite. Returns a catalog object.
[ "Create", "a", "simulated", "satellite", ".", "Returns", "a", "catalog", "object", "." ]
21e890b4117fc810afb6fb058e8055d564f03382
https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/simulation/simulator.py#L495-L544
train
DarkEnergySurvey/ugali
ugali/simulation/simulator.py
Simulator.makeHDU
def makeHDU(self, mag_1, mag_err_1, mag_2, mag_err_2, lon, lat, mc_source_id): """ Create a catalog fits file object based on input data. ADW: This should be combined with the write_membership function of loglike. """ if self.config['catalog']['coordsys'].lower() == 'cel...
python
def makeHDU(self, mag_1, mag_err_1, mag_2, mag_err_2, lon, lat, mc_source_id): """ Create a catalog fits file object based on input data. ADW: This should be combined with the write_membership function of loglike. """ if self.config['catalog']['coordsys'].lower() == 'cel...
[ "def", "makeHDU", "(", "self", ",", "mag_1", ",", "mag_err_1", ",", "mag_2", ",", "mag_err_2", ",", "lon", ",", "lat", ",", "mc_source_id", ")", ":", "if", "self", ".", "config", "[", "'catalog'", "]", "[", "'coordsys'", "]", ".", "lower", "(", ")", ...
Create a catalog fits file object based on input data. ADW: This should be combined with the write_membership function of loglike.
[ "Create", "a", "catalog", "fits", "file", "object", "based", "on", "input", "data", "." ]
21e890b4117fc810afb6fb058e8055d564f03382
https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/simulation/simulator.py#L628-L662
train
totalgood/pugnlp
src/pugnlp/util.py
inverted_dict
def inverted_dict(d): """Return a dict with swapped keys and values >>> inverted_dict({0: ('a', 'b'), 1: 'cd'}) == {'cd': 1, ('a', 'b'): 0} True """ return dict((force_hashable(v), k) for (k, v) in viewitems(dict(d)))
python
def inverted_dict(d): """Return a dict with swapped keys and values >>> inverted_dict({0: ('a', 'b'), 1: 'cd'}) == {'cd': 1, ('a', 'b'): 0} True """ return dict((force_hashable(v), k) for (k, v) in viewitems(dict(d)))
[ "def", "inverted_dict", "(", "d", ")", ":", "return", "dict", "(", "(", "force_hashable", "(", "v", ")", ",", "k", ")", "for", "(", "k", ",", "v", ")", "in", "viewitems", "(", "dict", "(", "d", ")", ")", ")" ]
Return a dict with swapped keys and values >>> inverted_dict({0: ('a', 'b'), 1: 'cd'}) == {'cd': 1, ('a', 'b'): 0} True
[ "Return", "a", "dict", "with", "swapped", "keys", "and", "values" ]
c43445b14afddfdeadc5f3076675c9e8fc1ee67c
https://github.com/totalgood/pugnlp/blob/c43445b14afddfdeadc5f3076675c9e8fc1ee67c/src/pugnlp/util.py#L167-L173
train
totalgood/pugnlp
src/pugnlp/util.py
inverted_dict_of_lists
def inverted_dict_of_lists(d): """Return a dict where the keys are all the values listed in the values of the original dict >>> inverted_dict_of_lists({0: ['a', 'b'], 1: 'cd'}) == {'a': 0, 'b': 0, 'cd': 1} True """ new_dict = {} for (old_key, old_value_list) in viewitems(dict(d)): for n...
python
def inverted_dict_of_lists(d): """Return a dict where the keys are all the values listed in the values of the original dict >>> inverted_dict_of_lists({0: ['a', 'b'], 1: 'cd'}) == {'a': 0, 'b': 0, 'cd': 1} True """ new_dict = {} for (old_key, old_value_list) in viewitems(dict(d)): for n...
[ "def", "inverted_dict_of_lists", "(", "d", ")", ":", "new_dict", "=", "{", "}", "for", "(", "old_key", ",", "old_value_list", ")", "in", "viewitems", "(", "dict", "(", "d", ")", ")", ":", "for", "new_key", "in", "listify", "(", "old_value_list", ")", "...
Return a dict where the keys are all the values listed in the values of the original dict >>> inverted_dict_of_lists({0: ['a', 'b'], 1: 'cd'}) == {'a': 0, 'b': 0, 'cd': 1} True
[ "Return", "a", "dict", "where", "the", "keys", "are", "all", "the", "values", "listed", "in", "the", "values", "of", "the", "original", "dict" ]
c43445b14afddfdeadc5f3076675c9e8fc1ee67c
https://github.com/totalgood/pugnlp/blob/c43445b14afddfdeadc5f3076675c9e8fc1ee67c/src/pugnlp/util.py#L176-L186
train