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
sequence
docstring
stringlengths
3
17.3k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
consbio/ncdjango
ncdjango/views.py
GetImageViewBase.create_response
def create_response(self, request, image, content_type): """Returns a response object for the given image. Can be overridden to return different responses.""" return HttpResponse(content=image, content_type=content_type)
python
def create_response(self, request, image, content_type): """Returns a response object for the given image. Can be overridden to return different responses.""" return HttpResponse(content=image, content_type=content_type)
[ "def", "create_response", "(", "self", ",", "request", ",", "image", ",", "content_type", ")", ":", "return", "HttpResponse", "(", "content", "=", "image", ",", "content_type", "=", "content_type", ")" ]
Returns a response object for the given image. Can be overridden to return different responses.
[ "Returns", "a", "response", "object", "for", "the", "given", "image", ".", "Can", "be", "overridden", "to", "return", "different", "responses", "." ]
f807bfd1e4083ab29fbc3c4d4418be108383a710
https://github.com/consbio/ncdjango/blob/f807bfd1e4083ab29fbc3c4d4418be108383a710/ncdjango/views.py#L198-L201
train
consbio/ncdjango
ncdjango/views.py
IdentifyViewBase.create_response
def create_response(self, request, content, content_type): """Returns a response object for the request. Can be overridden to return different responses.""" return HttpResponse(content=content, content_type=content_type)
python
def create_response(self, request, content, content_type): """Returns a response object for the request. Can be overridden to return different responses.""" return HttpResponse(content=content, content_type=content_type)
[ "def", "create_response", "(", "self", ",", "request", ",", "content", ",", "content_type", ")", ":", "return", "HttpResponse", "(", "content", "=", "content", ",", "content_type", "=", "content_type", ")" ]
Returns a response object for the request. Can be overridden to return different responses.
[ "Returns", "a", "response", "object", "for", "the", "request", ".", "Can", "be", "overridden", "to", "return", "different", "responses", "." ]
f807bfd1e4083ab29fbc3c4d4418be108383a710
https://github.com/consbio/ncdjango/blob/f807bfd1e4083ab29fbc3c4d4418be108383a710/ncdjango/views.py#L324-L327
train
consbio/ncdjango
ncdjango/views.py
TemporaryFileUploadViewBase.process_temporary_file
def process_temporary_file(self, tmp_file): """Truncates the filename if necessary, saves the model, and returns a response""" #Truncate filename if necessary if len(tmp_file.filename) > 100: base_filename = tmp_file.filename[:tmp_file.filename.rfind(".")] tmp_file.filename = "%s.%s" % (base_filename[:99-len(tmp_file.extension)], tmp_file.extension) tmp_file.save() data = { 'uuid': str(tmp_file.uuid) } response = HttpResponse(json.dumps(data), status=201) response['Content-type'] = "text/plain" return response
python
def process_temporary_file(self, tmp_file): """Truncates the filename if necessary, saves the model, and returns a response""" #Truncate filename if necessary if len(tmp_file.filename) > 100: base_filename = tmp_file.filename[:tmp_file.filename.rfind(".")] tmp_file.filename = "%s.%s" % (base_filename[:99-len(tmp_file.extension)], tmp_file.extension) tmp_file.save() data = { 'uuid': str(tmp_file.uuid) } response = HttpResponse(json.dumps(data), status=201) response['Content-type'] = "text/plain" return response
[ "def", "process_temporary_file", "(", "self", ",", "tmp_file", ")", ":", "#Truncate filename if necessary", "if", "len", "(", "tmp_file", ".", "filename", ")", ">", "100", ":", "base_filename", "=", "tmp_file", ".", "filename", "[", ":", "tmp_file", ".", "filename", ".", "rfind", "(", "\".\"", ")", "]", "tmp_file", ".", "filename", "=", "\"%s.%s\"", "%", "(", "base_filename", "[", ":", "99", "-", "len", "(", "tmp_file", ".", "extension", ")", "]", ",", "tmp_file", ".", "extension", ")", "tmp_file", ".", "save", "(", ")", "data", "=", "{", "'uuid'", ":", "str", "(", "tmp_file", ".", "uuid", ")", "}", "response", "=", "HttpResponse", "(", "json", ".", "dumps", "(", "data", ")", ",", "status", "=", "201", ")", "response", "[", "'Content-type'", "]", "=", "\"text/plain\"", "return", "response" ]
Truncates the filename if necessary, saves the model, and returns a response
[ "Truncates", "the", "filename", "if", "necessary", "saves", "the", "model", "and", "returns", "a", "response" ]
f807bfd1e4083ab29fbc3c4d4418be108383a710
https://github.com/consbio/ncdjango/blob/f807bfd1e4083ab29fbc3c4d4418be108383a710/ncdjango/views.py#L438-L455
train
DarkEnergySurvey/ugali
ugali/analysis/search.py
CandidateSearch.createLabels2D
def createLabels2D(self): """ 2D labeling at zmax """ logger.debug(" Creating 2D labels...") self.zmax = np.argmax(self.values,axis=1) self.vmax = self.values[np.arange(len(self.pixels),dtype=int),self.zmax] kwargs=dict(pixels=self.pixels,values=self.vmax,nside=self.nside, threshold=self.threshold,xsize=self.xsize) labels,nlabels = CandidateSearch.labelHealpix(**kwargs) self.nlabels = nlabels self.labels = np.repeat(labels,len(self.distances)).reshape(len(labels),len(self.distances)) return self.labels, self.nlabels
python
def createLabels2D(self): """ 2D labeling at zmax """ logger.debug(" Creating 2D labels...") self.zmax = np.argmax(self.values,axis=1) self.vmax = self.values[np.arange(len(self.pixels),dtype=int),self.zmax] kwargs=dict(pixels=self.pixels,values=self.vmax,nside=self.nside, threshold=self.threshold,xsize=self.xsize) labels,nlabels = CandidateSearch.labelHealpix(**kwargs) self.nlabels = nlabels self.labels = np.repeat(labels,len(self.distances)).reshape(len(labels),len(self.distances)) return self.labels, self.nlabels
[ "def", "createLabels2D", "(", "self", ")", ":", "logger", ".", "debug", "(", "\" Creating 2D labels...\"", ")", "self", ".", "zmax", "=", "np", ".", "argmax", "(", "self", ".", "values", ",", "axis", "=", "1", ")", "self", ".", "vmax", "=", "self", ".", "values", "[", "np", ".", "arange", "(", "len", "(", "self", ".", "pixels", ")", ",", "dtype", "=", "int", ")", ",", "self", ".", "zmax", "]", "kwargs", "=", "dict", "(", "pixels", "=", "self", ".", "pixels", ",", "values", "=", "self", ".", "vmax", ",", "nside", "=", "self", ".", "nside", ",", "threshold", "=", "self", ".", "threshold", ",", "xsize", "=", "self", ".", "xsize", ")", "labels", ",", "nlabels", "=", "CandidateSearch", ".", "labelHealpix", "(", "*", "*", "kwargs", ")", "self", ".", "nlabels", "=", "nlabels", "self", ".", "labels", "=", "np", ".", "repeat", "(", "labels", ",", "len", "(", "self", ".", "distances", ")", ")", ".", "reshape", "(", "len", "(", "labels", ")", ",", "len", "(", "self", ".", "distances", ")", ")", "return", "self", ".", "labels", ",", "self", ".", "nlabels" ]
2D labeling at zmax
[ "2D", "labeling", "at", "zmax" ]
21e890b4117fc810afb6fb058e8055d564f03382
https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/analysis/search.py#L73-L84
train
alphagov/performanceplatform-collector
performanceplatform/collector/gcloud/sales_parser.py
process_csv
def process_csv(f): """ Take a file-like object and yield OrderedDicts to be inserted into raw spending database. """ reader = unicodecsv.DictReader(f, encoding=_ENCODING) for row in reader: month, year = parse_month_year(row['Return Month']) yield OrderedDict([ ('customer_name', row['CustomerName']), ('supplier_name', row['SupplierName']), ('month', month), ('year', year), ('date', datetime.date(year, month, 1)), ('total_ex_vat', parse_price(row['EvidencedSpend'])), ('lot', parse_lot_name(row['LotDescription'])), ('customer_sector', parse_customer_sector(row['Sector'])), ('supplier_type', parse_sme_or_large(row['SME or Large'])), ])
python
def process_csv(f): """ Take a file-like object and yield OrderedDicts to be inserted into raw spending database. """ reader = unicodecsv.DictReader(f, encoding=_ENCODING) for row in reader: month, year = parse_month_year(row['Return Month']) yield OrderedDict([ ('customer_name', row['CustomerName']), ('supplier_name', row['SupplierName']), ('month', month), ('year', year), ('date', datetime.date(year, month, 1)), ('total_ex_vat', parse_price(row['EvidencedSpend'])), ('lot', parse_lot_name(row['LotDescription'])), ('customer_sector', parse_customer_sector(row['Sector'])), ('supplier_type', parse_sme_or_large(row['SME or Large'])), ])
[ "def", "process_csv", "(", "f", ")", ":", "reader", "=", "unicodecsv", ".", "DictReader", "(", "f", ",", "encoding", "=", "_ENCODING", ")", "for", "row", "in", "reader", ":", "month", ",", "year", "=", "parse_month_year", "(", "row", "[", "'Return Month'", "]", ")", "yield", "OrderedDict", "(", "[", "(", "'customer_name'", ",", "row", "[", "'CustomerName'", "]", ")", ",", "(", "'supplier_name'", ",", "row", "[", "'SupplierName'", "]", ")", ",", "(", "'month'", ",", "month", ")", ",", "(", "'year'", ",", "year", ")", ",", "(", "'date'", ",", "datetime", ".", "date", "(", "year", ",", "month", ",", "1", ")", ")", ",", "(", "'total_ex_vat'", ",", "parse_price", "(", "row", "[", "'EvidencedSpend'", "]", ")", ")", ",", "(", "'lot'", ",", "parse_lot_name", "(", "row", "[", "'LotDescription'", "]", ")", ")", ",", "(", "'customer_sector'", ",", "parse_customer_sector", "(", "row", "[", "'Sector'", "]", ")", ")", ",", "(", "'supplier_type'", ",", "parse_sme_or_large", "(", "row", "[", "'SME or Large'", "]", ")", ")", ",", "]", ")" ]
Take a file-like object and yield OrderedDicts to be inserted into raw spending database.
[ "Take", "a", "file", "-", "like", "object", "and", "yield", "OrderedDicts", "to", "be", "inserted", "into", "raw", "spending", "database", "." ]
de68ab4aa500c31e436e050fa1268fa928c522a5
https://github.com/alphagov/performanceplatform-collector/blob/de68ab4aa500c31e436e050fa1268fa928c522a5/performanceplatform/collector/gcloud/sales_parser.py#L71-L90
train
alphagov/performanceplatform-collector
performanceplatform/collector/ga/core.py
try_number
def try_number(value): """ Attempt to cast the string `value` to an int, and failing that, a float, failing that, raise a ValueError. """ for cast_function in [int, float]: try: return cast_function(value) except ValueError: pass raise ValueError("Unable to use value as int or float: {0!r}" .format(value))
python
def try_number(value): """ Attempt to cast the string `value` to an int, and failing that, a float, failing that, raise a ValueError. """ for cast_function in [int, float]: try: return cast_function(value) except ValueError: pass raise ValueError("Unable to use value as int or float: {0!r}" .format(value))
[ "def", "try_number", "(", "value", ")", ":", "for", "cast_function", "in", "[", "int", ",", "float", "]", ":", "try", ":", "return", "cast_function", "(", "value", ")", "except", "ValueError", ":", "pass", "raise", "ValueError", "(", "\"Unable to use value as int or float: {0!r}\"", ".", "format", "(", "value", ")", ")" ]
Attempt to cast the string `value` to an int, and failing that, a float, failing that, raise a ValueError.
[ "Attempt", "to", "cast", "the", "string", "value", "to", "an", "int", "and", "failing", "that", "a", "float", "failing", "that", "raise", "a", "ValueError", "." ]
de68ab4aa500c31e436e050fa1268fa928c522a5
https://github.com/alphagov/performanceplatform-collector/blob/de68ab4aa500c31e436e050fa1268fa928c522a5/performanceplatform/collector/ga/core.py#L37-L50
train
alphagov/performanceplatform-collector
performanceplatform/collector/ga/core.py
convert_durations
def convert_durations(metric): """ Convert session duration metrics from seconds to milliseconds. """ if metric[0] == 'avgSessionDuration' and metric[1]: new_metric = (metric[0], metric[1] * 1000) else: new_metric = metric return new_metric
python
def convert_durations(metric): """ Convert session duration metrics from seconds to milliseconds. """ if metric[0] == 'avgSessionDuration' and metric[1]: new_metric = (metric[0], metric[1] * 1000) else: new_metric = metric return new_metric
[ "def", "convert_durations", "(", "metric", ")", ":", "if", "metric", "[", "0", "]", "==", "'avgSessionDuration'", "and", "metric", "[", "1", "]", ":", "new_metric", "=", "(", "metric", "[", "0", "]", ",", "metric", "[", "1", "]", "*", "1000", ")", "else", ":", "new_metric", "=", "metric", "return", "new_metric" ]
Convert session duration metrics from seconds to milliseconds.
[ "Convert", "session", "duration", "metrics", "from", "seconds", "to", "milliseconds", "." ]
de68ab4aa500c31e436e050fa1268fa928c522a5
https://github.com/alphagov/performanceplatform-collector/blob/de68ab4aa500c31e436e050fa1268fa928c522a5/performanceplatform/collector/ga/core.py#L53-L61
train
alphagov/performanceplatform-collector
performanceplatform/collector/piwik/core.py
Parser.to_datetime
def to_datetime(date_key): ''' Extract the first date from 'key' matching YYYY-MM-DD or YYYY-MM, and convert to datetime. ''' match = re.search(r'\d{4}-\d{2}(-\d{2})?', date_key) formatter = '%Y-%m' if len(match.group()) == 10: formatter += '-%d' return datetime.strptime( match.group(), formatter).replace(tzinfo=pytz.UTC)
python
def to_datetime(date_key): ''' Extract the first date from 'key' matching YYYY-MM-DD or YYYY-MM, and convert to datetime. ''' match = re.search(r'\d{4}-\d{2}(-\d{2})?', date_key) formatter = '%Y-%m' if len(match.group()) == 10: formatter += '-%d' return datetime.strptime( match.group(), formatter).replace(tzinfo=pytz.UTC)
[ "def", "to_datetime", "(", "date_key", ")", ":", "match", "=", "re", ".", "search", "(", "r'\\d{4}-\\d{2}(-\\d{2})?'", ",", "date_key", ")", "formatter", "=", "'%Y-%m'", "if", "len", "(", "match", ".", "group", "(", ")", ")", "==", "10", ":", "formatter", "+=", "'-%d'", "return", "datetime", ".", "strptime", "(", "match", ".", "group", "(", ")", ",", "formatter", ")", ".", "replace", "(", "tzinfo", "=", "pytz", ".", "UTC", ")" ]
Extract the first date from 'key' matching YYYY-MM-DD or YYYY-MM, and convert to datetime.
[ "Extract", "the", "first", "date", "from", "key", "matching", "YYYY", "-", "MM", "-", "DD", "or", "YYYY", "-", "MM", "and", "convert", "to", "datetime", "." ]
de68ab4aa500c31e436e050fa1268fa928c522a5
https://github.com/alphagov/performanceplatform-collector/blob/de68ab4aa500c31e436e050fa1268fa928c522a5/performanceplatform/collector/piwik/core.py#L77-L87
train
stevearc/dynamo3
dynamo3/types.py
float_to_decimal
def float_to_decimal(f): """ Convert a float to a 38-precision Decimal """ n, d = f.as_integer_ratio() numerator, denominator = Decimal(n), Decimal(d) return DECIMAL_CONTEXT.divide(numerator, denominator)
python
def float_to_decimal(f): """ Convert a float to a 38-precision Decimal """ n, d = f.as_integer_ratio() numerator, denominator = Decimal(n), Decimal(d) return DECIMAL_CONTEXT.divide(numerator, denominator)
[ "def", "float_to_decimal", "(", "f", ")", ":", "n", ",", "d", "=", "f", ".", "as_integer_ratio", "(", ")", "numerator", ",", "denominator", "=", "Decimal", "(", "n", ")", ",", "Decimal", "(", "d", ")", "return", "DECIMAL_CONTEXT", ".", "divide", "(", "numerator", ",", "denominator", ")" ]
Convert a float to a 38-precision Decimal
[ "Convert", "a", "float", "to", "a", "38", "-", "precision", "Decimal" ]
f897c40ece28586272dbcab8f0d99a14a1831dda
https://github.com/stevearc/dynamo3/blob/f897c40ece28586272dbcab8f0d99a14a1831dda/dynamo3/types.py#L13-L17
train
stevearc/dynamo3
dynamo3/types.py
is_dynamo_value
def is_dynamo_value(value): """ Returns True if the value is a Dynamo-formatted value """ if not isinstance(value, dict) or len(value) != 1: return False subkey = six.next(six.iterkeys(value)) return subkey in TYPES_REV
python
def is_dynamo_value(value): """ Returns True if the value is a Dynamo-formatted value """ if not isinstance(value, dict) or len(value) != 1: return False subkey = six.next(six.iterkeys(value)) return subkey in TYPES_REV
[ "def", "is_dynamo_value", "(", "value", ")", ":", "if", "not", "isinstance", "(", "value", ",", "dict", ")", "or", "len", "(", "value", ")", "!=", "1", ":", "return", "False", "subkey", "=", "six", ".", "next", "(", "six", ".", "iterkeys", "(", "value", ")", ")", "return", "subkey", "in", "TYPES_REV" ]
Returns True if the value is a Dynamo-formatted value
[ "Returns", "True", "if", "the", "value", "is", "a", "Dynamo", "-", "formatted", "value" ]
f897c40ece28586272dbcab8f0d99a14a1831dda
https://github.com/stevearc/dynamo3/blob/f897c40ece28586272dbcab8f0d99a14a1831dda/dynamo3/types.py#L35-L40
train
stevearc/dynamo3
dynamo3/types.py
encode_set
def encode_set(dynamizer, value): """ Encode a set for the DynamoDB format """ inner_value = next(iter(value)) inner_type = dynamizer.raw_encode(inner_value)[0] return inner_type + 'S', [dynamizer.raw_encode(v)[1] for v in value]
python
def encode_set(dynamizer, value): """ Encode a set for the DynamoDB format """ inner_value = next(iter(value)) inner_type = dynamizer.raw_encode(inner_value)[0] return inner_type + 'S', [dynamizer.raw_encode(v)[1] for v in value]
[ "def", "encode_set", "(", "dynamizer", ",", "value", ")", ":", "inner_value", "=", "next", "(", "iter", "(", "value", ")", ")", "inner_type", "=", "dynamizer", ".", "raw_encode", "(", "inner_value", ")", "[", "0", "]", "return", "inner_type", "+", "'S'", ",", "[", "dynamizer", ".", "raw_encode", "(", "v", ")", "[", "1", "]", "for", "v", "in", "value", "]" ]
Encode a set for the DynamoDB format
[ "Encode", "a", "set", "for", "the", "DynamoDB", "format" ]
f897c40ece28586272dbcab8f0d99a14a1831dda
https://github.com/stevearc/dynamo3/blob/f897c40ece28586272dbcab8f0d99a14a1831dda/dynamo3/types.py#L77-L81
train
stevearc/dynamo3
dynamo3/types.py
encode_list
def encode_list(dynamizer, value): """ Encode a list for the DynamoDB format """ encoded_list = [] dict(map(dynamizer.raw_encode, value)) for v in value: encoded_type, encoded_value = dynamizer.raw_encode(v) encoded_list.append({ encoded_type: encoded_value, }) return 'L', encoded_list
python
def encode_list(dynamizer, value): """ Encode a list for the DynamoDB format """ encoded_list = [] dict(map(dynamizer.raw_encode, value)) for v in value: encoded_type, encoded_value = dynamizer.raw_encode(v) encoded_list.append({ encoded_type: encoded_value, }) return 'L', encoded_list
[ "def", "encode_list", "(", "dynamizer", ",", "value", ")", ":", "encoded_list", "=", "[", "]", "dict", "(", "map", "(", "dynamizer", ".", "raw_encode", ",", "value", ")", ")", "for", "v", "in", "value", ":", "encoded_type", ",", "encoded_value", "=", "dynamizer", ".", "raw_encode", "(", "v", ")", "encoded_list", ".", "append", "(", "{", "encoded_type", ":", "encoded_value", ",", "}", ")", "return", "'L'", ",", "encoded_list" ]
Encode a list for the DynamoDB format
[ "Encode", "a", "list", "for", "the", "DynamoDB", "format" ]
f897c40ece28586272dbcab8f0d99a14a1831dda
https://github.com/stevearc/dynamo3/blob/f897c40ece28586272dbcab8f0d99a14a1831dda/dynamo3/types.py#L84-L93
train
stevearc/dynamo3
dynamo3/types.py
encode_dict
def encode_dict(dynamizer, value): """ Encode a dict for the DynamoDB format """ encoded_dict = {} for k, v in six.iteritems(value): encoded_type, encoded_value = dynamizer.raw_encode(v) encoded_dict[k] = { encoded_type: encoded_value, } return 'M', encoded_dict
python
def encode_dict(dynamizer, value): """ Encode a dict for the DynamoDB format """ encoded_dict = {} for k, v in six.iteritems(value): encoded_type, encoded_value = dynamizer.raw_encode(v) encoded_dict[k] = { encoded_type: encoded_value, } return 'M', encoded_dict
[ "def", "encode_dict", "(", "dynamizer", ",", "value", ")", ":", "encoded_dict", "=", "{", "}", "for", "k", ",", "v", "in", "six", ".", "iteritems", "(", "value", ")", ":", "encoded_type", ",", "encoded_value", "=", "dynamizer", ".", "raw_encode", "(", "v", ")", "encoded_dict", "[", "k", "]", "=", "{", "encoded_type", ":", "encoded_value", ",", "}", "return", "'M'", ",", "encoded_dict" ]
Encode a dict for the DynamoDB format
[ "Encode", "a", "dict", "for", "the", "DynamoDB", "format" ]
f897c40ece28586272dbcab8f0d99a14a1831dda
https://github.com/stevearc/dynamo3/blob/f897c40ece28586272dbcab8f0d99a14a1831dda/dynamo3/types.py#L96-L104
train
stevearc/dynamo3
dynamo3/types.py
Dynamizer.raw_encode
def raw_encode(self, value): """ Run the encoder on a value """ if type(value) in self.encoders: encoder = self.encoders[type(value)] return encoder(self, value) raise ValueError("No encoder for value '%s' of type '%s'" % (value, type(value)))
python
def raw_encode(self, value): """ Run the encoder on a value """ if type(value) in self.encoders: encoder = self.encoders[type(value)] return encoder(self, value) raise ValueError("No encoder for value '%s' of type '%s'" % (value, type(value)))
[ "def", "raw_encode", "(", "self", ",", "value", ")", ":", "if", "type", "(", "value", ")", "in", "self", ".", "encoders", ":", "encoder", "=", "self", ".", "encoders", "[", "type", "(", "value", ")", "]", "return", "encoder", "(", "self", ",", "value", ")", "raise", "ValueError", "(", "\"No encoder for value '%s' of type '%s'\"", "%", "(", "value", ",", "type", "(", "value", ")", ")", ")" ]
Run the encoder on a value
[ "Run", "the", "encoder", "on", "a", "value" ]
f897c40ece28586272dbcab8f0d99a14a1831dda
https://github.com/stevearc/dynamo3/blob/f897c40ece28586272dbcab8f0d99a14a1831dda/dynamo3/types.py#L150-L156
train
stevearc/dynamo3
dynamo3/types.py
Dynamizer.encode_keys
def encode_keys(self, keys): """ Run the encoder on a dict of values """ return dict(((k, self.encode(v)) for k, v in six.iteritems(keys) if not is_null(v)))
python
def encode_keys(self, keys): """ Run the encoder on a dict of values """ return dict(((k, self.encode(v)) for k, v in six.iteritems(keys) if not is_null(v)))
[ "def", "encode_keys", "(", "self", ",", "keys", ")", ":", "return", "dict", "(", "(", "(", "k", ",", "self", ".", "encode", "(", "v", ")", ")", "for", "k", ",", "v", "in", "six", ".", "iteritems", "(", "keys", ")", "if", "not", "is_null", "(", "v", ")", ")", ")" ]
Run the encoder on a dict of values
[ "Run", "the", "encoder", "on", "a", "dict", "of", "values" ]
f897c40ece28586272dbcab8f0d99a14a1831dda
https://github.com/stevearc/dynamo3/blob/f897c40ece28586272dbcab8f0d99a14a1831dda/dynamo3/types.py#L158-L161
train
stevearc/dynamo3
dynamo3/types.py
Dynamizer.maybe_encode_keys
def maybe_encode_keys(self, keys): """ Same as encode_keys but a no-op if already in Dynamo format """ ret = {} for k, v in six.iteritems(keys): if is_dynamo_value(v): return keys elif not is_null(v): ret[k] = self.encode(v) return ret
python
def maybe_encode_keys(self, keys): """ Same as encode_keys but a no-op if already in Dynamo format """ ret = {} for k, v in six.iteritems(keys): if is_dynamo_value(v): return keys elif not is_null(v): ret[k] = self.encode(v) return ret
[ "def", "maybe_encode_keys", "(", "self", ",", "keys", ")", ":", "ret", "=", "{", "}", "for", "k", ",", "v", "in", "six", ".", "iteritems", "(", "keys", ")", ":", "if", "is_dynamo_value", "(", "v", ")", ":", "return", "keys", "elif", "not", "is_null", "(", "v", ")", ":", "ret", "[", "k", "]", "=", "self", ".", "encode", "(", "v", ")", "return", "ret" ]
Same as encode_keys but a no-op if already in Dynamo format
[ "Same", "as", "encode_keys", "but", "a", "no", "-", "op", "if", "already", "in", "Dynamo", "format" ]
f897c40ece28586272dbcab8f0d99a14a1831dda
https://github.com/stevearc/dynamo3/blob/f897c40ece28586272dbcab8f0d99a14a1831dda/dynamo3/types.py#L163-L171
train
stevearc/dynamo3
dynamo3/types.py
Dynamizer.decode_keys
def decode_keys(self, keys): """ Run the decoder on a dict of values """ return dict(((k, self.decode(v)) for k, v in six.iteritems(keys)))
python
def decode_keys(self, keys): """ Run the decoder on a dict of values """ return dict(((k, self.decode(v)) for k, v in six.iteritems(keys)))
[ "def", "decode_keys", "(", "self", ",", "keys", ")", ":", "return", "dict", "(", "(", "(", "k", ",", "self", ".", "decode", "(", "v", ")", ")", "for", "k", ",", "v", "in", "six", ".", "iteritems", "(", "keys", ")", ")", ")" ]
Run the decoder on a dict of values
[ "Run", "the", "decoder", "on", "a", "dict", "of", "values" ]
f897c40ece28586272dbcab8f0d99a14a1831dda
https://github.com/stevearc/dynamo3/blob/f897c40ece28586272dbcab8f0d99a14a1831dda/dynamo3/types.py#L177-L179
train
stevearc/dynamo3
dynamo3/types.py
Dynamizer.decode
def decode(self, dynamo_value): """ Decode a dynamo value into a python value """ type, value = next(six.iteritems(dynamo_value)) if type == STRING: return value elif type == BINARY: return Binary(value) elif type == NUMBER: return Decimal(value) elif type == STRING_SET: return set(value) elif type == BINARY_SET: return set((Binary(v) for v in value)) elif type == NUMBER_SET: return set((Decimal(v) for v in value)) elif type == BOOL: return value elif type == LIST: return [self.decode(v) for v in value] elif type == MAP: decoded_dict = {} for k, v in six.iteritems(value): decoded_dict[k] = self.decode(v) return decoded_dict elif type == NULL: return None else: raise TypeError("Received unrecognized type %r from dynamo", type)
python
def decode(self, dynamo_value): """ Decode a dynamo value into a python value """ type, value = next(six.iteritems(dynamo_value)) if type == STRING: return value elif type == BINARY: return Binary(value) elif type == NUMBER: return Decimal(value) elif type == STRING_SET: return set(value) elif type == BINARY_SET: return set((Binary(v) for v in value)) elif type == NUMBER_SET: return set((Decimal(v) for v in value)) elif type == BOOL: return value elif type == LIST: return [self.decode(v) for v in value] elif type == MAP: decoded_dict = {} for k, v in six.iteritems(value): decoded_dict[k] = self.decode(v) return decoded_dict elif type == NULL: return None else: raise TypeError("Received unrecognized type %r from dynamo", type)
[ "def", "decode", "(", "self", ",", "dynamo_value", ")", ":", "type", ",", "value", "=", "next", "(", "six", ".", "iteritems", "(", "dynamo_value", ")", ")", "if", "type", "==", "STRING", ":", "return", "value", "elif", "type", "==", "BINARY", ":", "return", "Binary", "(", "value", ")", "elif", "type", "==", "NUMBER", ":", "return", "Decimal", "(", "value", ")", "elif", "type", "==", "STRING_SET", ":", "return", "set", "(", "value", ")", "elif", "type", "==", "BINARY_SET", ":", "return", "set", "(", "(", "Binary", "(", "v", ")", "for", "v", "in", "value", ")", ")", "elif", "type", "==", "NUMBER_SET", ":", "return", "set", "(", "(", "Decimal", "(", "v", ")", "for", "v", "in", "value", ")", ")", "elif", "type", "==", "BOOL", ":", "return", "value", "elif", "type", "==", "LIST", ":", "return", "[", "self", ".", "decode", "(", "v", ")", "for", "v", "in", "value", "]", "elif", "type", "==", "MAP", ":", "decoded_dict", "=", "{", "}", "for", "k", ",", "v", "in", "six", ".", "iteritems", "(", "value", ")", ":", "decoded_dict", "[", "k", "]", "=", "self", ".", "decode", "(", "v", ")", "return", "decoded_dict", "elif", "type", "==", "NULL", ":", "return", "None", "else", ":", "raise", "TypeError", "(", "\"Received unrecognized type %r from dynamo\"", ",", "type", ")" ]
Decode a dynamo value into a python value
[ "Decode", "a", "dynamo", "value", "into", "a", "python", "value" ]
f897c40ece28586272dbcab8f0d99a14a1831dda
https://github.com/stevearc/dynamo3/blob/f897c40ece28586272dbcab8f0d99a14a1831dda/dynamo3/types.py#L181-L208
train
accraze/python-markov-novel
src/markov_novel/paragraph.py
Paragraph.get_paragraph
def get_paragraph(self): """ Write a paragraph of 5 sentences. """ self.text = '' for x in range(randint(5, 12)): sentence = self._write_sentence() self.text = self.text + sentence return self.text
python
def get_paragraph(self): """ Write a paragraph of 5 sentences. """ self.text = '' for x in range(randint(5, 12)): sentence = self._write_sentence() self.text = self.text + sentence return self.text
[ "def", "get_paragraph", "(", "self", ")", ":", "self", ".", "text", "=", "''", "for", "x", "in", "range", "(", "randint", "(", "5", ",", "12", ")", ")", ":", "sentence", "=", "self", ".", "_write_sentence", "(", ")", "self", ".", "text", "=", "self", ".", "text", "+", "sentence", "return", "self", ".", "text" ]
Write a paragraph of 5 sentences.
[ "Write", "a", "paragraph", "of", "5", "sentences", "." ]
ff451639e93a3ac11fb0268b92bc0cffc00bfdbe
https://github.com/accraze/python-markov-novel/blob/ff451639e93a3ac11fb0268b92bc0cffc00bfdbe/src/markov_novel/paragraph.py#L18-L27
train
alphagov/performanceplatform-collector
performanceplatform/collector/crontab.py
skip_job
def skip_job(counter): """ Should we skip the job based on its number If the machine has a number at the end of its hostname (n), and we have m machines in the pool - on machine 1, run job 1, 1 + m, 1+2m etc on machine 2, run job 2, 2 + m , 2 + 2m etc Else run all the jobs """ try: host_number = int(socket.gethostname().split('-')[-1]) except ValueError: return False if (counter + host_number - (NUMBER_OF_HOSTS - 1)) % NUMBER_OF_HOSTS == 0: return False return True
python
def skip_job(counter): """ Should we skip the job based on its number If the machine has a number at the end of its hostname (n), and we have m machines in the pool - on machine 1, run job 1, 1 + m, 1+2m etc on machine 2, run job 2, 2 + m , 2 + 2m etc Else run all the jobs """ try: host_number = int(socket.gethostname().split('-')[-1]) except ValueError: return False if (counter + host_number - (NUMBER_OF_HOSTS - 1)) % NUMBER_OF_HOSTS == 0: return False return True
[ "def", "skip_job", "(", "counter", ")", ":", "try", ":", "host_number", "=", "int", "(", "socket", ".", "gethostname", "(", ")", ".", "split", "(", "'-'", ")", "[", "-", "1", "]", ")", "except", "ValueError", ":", "return", "False", "if", "(", "counter", "+", "host_number", "-", "(", "NUMBER_OF_HOSTS", "-", "1", ")", ")", "%", "NUMBER_OF_HOSTS", "==", "0", ":", "return", "False", "return", "True" ]
Should we skip the job based on its number If the machine has a number at the end of its hostname (n), and we have m machines in the pool - on machine 1, run job 1, 1 + m, 1+2m etc on machine 2, run job 2, 2 + m , 2 + 2m etc Else run all the jobs
[ "Should", "we", "skip", "the", "job", "based", "on", "its", "number" ]
de68ab4aa500c31e436e050fa1268fa928c522a5
https://github.com/alphagov/performanceplatform-collector/blob/de68ab4aa500c31e436e050fa1268fa928c522a5/performanceplatform/collector/crontab.py#L57-L75
train
alphagov/performanceplatform-collector
performanceplatform/collector/crontab.py
generate_crontab
def generate_crontab(current_crontab, path_to_jobs, path_to_app, unique_id): """Returns a crontab with jobs from job path It replaces jobs previously generated by this function It preserves jobs not generated by this function """ set_disable_envar = '' if os.environ.get('DISABLE_COLLECTORS') == 'true': set_disable_envar = 'DISABLE_COLLECTORS={} '.format( os.environ.get('DISABLE_COLLECTORS')) job_template = '{schedule} ' \ '{set_disable_envar}' \ '{app_path}/venv/bin/pp-collector ' \ '-l {collector_slug} ' \ '-c {app_path}/config/{credentials} ' \ '-t {app_path}/config/{token} ' \ '-b {app_path}/config/{performanceplatform} ' \ '>> {app_path}/log/out.log 2>> {app_path}/log/error.log' crontab = [line.strip() for line in current_crontab] crontab = remove_existing_crontab_for_app(crontab, unique_id) additional_crontab = [] job_number = 0 with open(path_to_jobs) as jobs: try: for job in jobs: parsed = parse_job_line(job) if parsed is not None: job_number += 1 if skip_job(job_number): continue schedule, collector_slug, credentials, \ token, performanceplatform = parsed cronjob = job_template.format( schedule=schedule, set_disable_envar=set_disable_envar, app_path=path_to_app, collector_slug=collector_slug, credentials=credentials, token=token, performanceplatform=performanceplatform ) additional_crontab.append(cronjob) except ValueError as e: raise ParseError(str(e)) if additional_crontab: crontab.append(crontab_begin_comment(unique_id)) crontab.extend(additional_crontab) crontab.append(crontab_end_comment(unique_id)) return crontab
python
def generate_crontab(current_crontab, path_to_jobs, path_to_app, unique_id): """Returns a crontab with jobs from job path It replaces jobs previously generated by this function It preserves jobs not generated by this function """ set_disable_envar = '' if os.environ.get('DISABLE_COLLECTORS') == 'true': set_disable_envar = 'DISABLE_COLLECTORS={} '.format( os.environ.get('DISABLE_COLLECTORS')) job_template = '{schedule} ' \ '{set_disable_envar}' \ '{app_path}/venv/bin/pp-collector ' \ '-l {collector_slug} ' \ '-c {app_path}/config/{credentials} ' \ '-t {app_path}/config/{token} ' \ '-b {app_path}/config/{performanceplatform} ' \ '>> {app_path}/log/out.log 2>> {app_path}/log/error.log' crontab = [line.strip() for line in current_crontab] crontab = remove_existing_crontab_for_app(crontab, unique_id) additional_crontab = [] job_number = 0 with open(path_to_jobs) as jobs: try: for job in jobs: parsed = parse_job_line(job) if parsed is not None: job_number += 1 if skip_job(job_number): continue schedule, collector_slug, credentials, \ token, performanceplatform = parsed cronjob = job_template.format( schedule=schedule, set_disable_envar=set_disable_envar, app_path=path_to_app, collector_slug=collector_slug, credentials=credentials, token=token, performanceplatform=performanceplatform ) additional_crontab.append(cronjob) except ValueError as e: raise ParseError(str(e)) if additional_crontab: crontab.append(crontab_begin_comment(unique_id)) crontab.extend(additional_crontab) crontab.append(crontab_end_comment(unique_id)) return crontab
[ "def", "generate_crontab", "(", "current_crontab", ",", "path_to_jobs", ",", "path_to_app", ",", "unique_id", ")", ":", "set_disable_envar", "=", "''", "if", "os", ".", "environ", ".", "get", "(", "'DISABLE_COLLECTORS'", ")", "==", "'true'", ":", "set_disable_envar", "=", "'DISABLE_COLLECTORS={} '", ".", "format", "(", "os", ".", "environ", ".", "get", "(", "'DISABLE_COLLECTORS'", ")", ")", "job_template", "=", "'{schedule} '", "'{set_disable_envar}'", "'{app_path}/venv/bin/pp-collector '", "'-l {collector_slug} '", "'-c {app_path}/config/{credentials} '", "'-t {app_path}/config/{token} '", "'-b {app_path}/config/{performanceplatform} '", "'>> {app_path}/log/out.log 2>> {app_path}/log/error.log'", "crontab", "=", "[", "line", ".", "strip", "(", ")", "for", "line", "in", "current_crontab", "]", "crontab", "=", "remove_existing_crontab_for_app", "(", "crontab", ",", "unique_id", ")", "additional_crontab", "=", "[", "]", "job_number", "=", "0", "with", "open", "(", "path_to_jobs", ")", "as", "jobs", ":", "try", ":", "for", "job", "in", "jobs", ":", "parsed", "=", "parse_job_line", "(", "job", ")", "if", "parsed", "is", "not", "None", ":", "job_number", "+=", "1", "if", "skip_job", "(", "job_number", ")", ":", "continue", "schedule", ",", "collector_slug", ",", "credentials", ",", "token", ",", "performanceplatform", "=", "parsed", "cronjob", "=", "job_template", ".", "format", "(", "schedule", "=", "schedule", ",", "set_disable_envar", "=", "set_disable_envar", ",", "app_path", "=", "path_to_app", ",", "collector_slug", "=", "collector_slug", ",", "credentials", "=", "credentials", ",", "token", "=", "token", ",", "performanceplatform", "=", "performanceplatform", ")", "additional_crontab", ".", "append", "(", "cronjob", ")", "except", "ValueError", "as", "e", ":", "raise", "ParseError", "(", "str", "(", "e", ")", ")", "if", "additional_crontab", ":", "crontab", ".", "append", "(", "crontab_begin_comment", "(", "unique_id", ")", ")", "crontab", ".", "extend", "(", "additional_crontab", ")", "crontab", ".", "append", "(", "crontab_end_comment", "(", "unique_id", ")", ")", "return", "crontab" ]
Returns a crontab with jobs from job path It replaces jobs previously generated by this function It preserves jobs not generated by this function
[ "Returns", "a", "crontab", "with", "jobs", "from", "job", "path" ]
de68ab4aa500c31e436e050fa1268fa928c522a5
https://github.com/alphagov/performanceplatform-collector/blob/de68ab4aa500c31e436e050fa1268fa928c522a5/performanceplatform/collector/crontab.py#L78-L135
train
consbio/ncdjango
ncdjango/interfaces/arcgis/forms.py
ArcGisFormBase.map_parameters
def map_parameters(cls, params): """Maps parameters to form field names""" d = {} for k, v in six.iteritems(params): d[cls.FIELD_MAP.get(k.lower(), k)] = v return d
python
def map_parameters(cls, params): """Maps parameters to form field names""" d = {} for k, v in six.iteritems(params): d[cls.FIELD_MAP.get(k.lower(), k)] = v return d
[ "def", "map_parameters", "(", "cls", ",", "params", ")", ":", "d", "=", "{", "}", "for", "k", ",", "v", "in", "six", ".", "iteritems", "(", "params", ")", ":", "d", "[", "cls", ".", "FIELD_MAP", ".", "get", "(", "k", ".", "lower", "(", ")", ",", "k", ")", "]", "=", "v", "return", "d" ]
Maps parameters to form field names
[ "Maps", "parameters", "to", "form", "field", "names" ]
f807bfd1e4083ab29fbc3c4d4418be108383a710
https://github.com/consbio/ncdjango/blob/f807bfd1e4083ab29fbc3c4d4418be108383a710/ncdjango/interfaces/arcgis/forms.py#L21-L27
train
consbio/ncdjango
ncdjango/geoimage.py
world_to_image
def world_to_image(bbox, size): """Function generator to create functions for converting from world coordinates to image coordinates""" px_per_unit = (float(size[0])/bbox.width, float(size[1])/bbox.height) return lambda x,y: ((x-bbox.xmin) * px_per_unit[0], size[1] - (y-bbox.ymin)*px_per_unit[1])
python
def world_to_image(bbox, size): """Function generator to create functions for converting from world coordinates to image coordinates""" px_per_unit = (float(size[0])/bbox.width, float(size[1])/bbox.height) return lambda x,y: ((x-bbox.xmin) * px_per_unit[0], size[1] - (y-bbox.ymin)*px_per_unit[1])
[ "def", "world_to_image", "(", "bbox", ",", "size", ")", ":", "px_per_unit", "=", "(", "float", "(", "size", "[", "0", "]", ")", "/", "bbox", ".", "width", ",", "float", "(", "size", "[", "1", "]", ")", "/", "bbox", ".", "height", ")", "return", "lambda", "x", ",", "y", ":", "(", "(", "x", "-", "bbox", ".", "xmin", ")", "*", "px_per_unit", "[", "0", "]", ",", "size", "[", "1", "]", "-", "(", "y", "-", "bbox", ".", "ymin", ")", "*", "px_per_unit", "[", "1", "]", ")" ]
Function generator to create functions for converting from world coordinates to image coordinates
[ "Function", "generator", "to", "create", "functions", "for", "converting", "from", "world", "coordinates", "to", "image", "coordinates" ]
f807bfd1e4083ab29fbc3c4d4418be108383a710
https://github.com/consbio/ncdjango/blob/f807bfd1e4083ab29fbc3c4d4418be108383a710/ncdjango/geoimage.py#L173-L177
train
consbio/ncdjango
ncdjango/geoimage.py
GeoImage.warp
def warp(self, target_bbox, target_size=None): """Returns a copy of this image warped to a target size and bounding box""" # Determine target size based on pixels per unit of the source image and the target bounding box reprojected # to the source projection. if not target_size: px_per_unit = (float(self.image.size[0])/self.bbox.width, float(self.image.size[1])/self.bbox.height) src_bbox = target_bbox.project(self.bbox.projection) target_size = (int(round(src_bbox.width*px_per_unit[0])), int(round(src_bbox.height*px_per_unit[1]))) canvas_size = ( max(target_size[0], self.image.size[0]), max(target_size[1], self.image.size[1]) ) # If target and source bounds are the same and source and target sizes are the same, return a reference to # this image. if self.bbox == target_bbox and self.image.size == target_size: return self # If target and source projections are the same, perform a simple resize elif self.bbox.projection.srs == target_bbox.projection.srs: to_source_image = world_to_image(self.bbox, self.image.size) upper_left = to_source_image(*(target_bbox.xmin, target_bbox.ymax)) lower_right = to_source_image(*(target_bbox.xmax, target_bbox.ymin)) if canvas_size == self.image.size: im = self.image else: im = Image.new("RGBA", canvas_size, (0, 0, 0, 0)) im.paste(self.image, (0, 0)) new_image = im.transform( target_size, Image.EXTENT, (upper_left[0], upper_left[1], lower_right[0], lower_right[1]), Image.NEAREST ) # Full warp else: if canvas_size == self.image.size: im = self.image else: im = Image.new("RGBA", canvas_size, (0, 0, 0, 0)) im.paste(self.image, (0, 0)) new_image = im.transform( target_size, Image.MESH, self._create_mesh(target_bbox, target_size), Image.NEAREST ) return GeoImage(new_image, target_bbox)
python
def warp(self, target_bbox, target_size=None): """Returns a copy of this image warped to a target size and bounding box""" # Determine target size based on pixels per unit of the source image and the target bounding box reprojected # to the source projection. if not target_size: px_per_unit = (float(self.image.size[0])/self.bbox.width, float(self.image.size[1])/self.bbox.height) src_bbox = target_bbox.project(self.bbox.projection) target_size = (int(round(src_bbox.width*px_per_unit[0])), int(round(src_bbox.height*px_per_unit[1]))) canvas_size = ( max(target_size[0], self.image.size[0]), max(target_size[1], self.image.size[1]) ) # If target and source bounds are the same and source and target sizes are the same, return a reference to # this image. if self.bbox == target_bbox and self.image.size == target_size: return self # If target and source projections are the same, perform a simple resize elif self.bbox.projection.srs == target_bbox.projection.srs: to_source_image = world_to_image(self.bbox, self.image.size) upper_left = to_source_image(*(target_bbox.xmin, target_bbox.ymax)) lower_right = to_source_image(*(target_bbox.xmax, target_bbox.ymin)) if canvas_size == self.image.size: im = self.image else: im = Image.new("RGBA", canvas_size, (0, 0, 0, 0)) im.paste(self.image, (0, 0)) new_image = im.transform( target_size, Image.EXTENT, (upper_left[0], upper_left[1], lower_right[0], lower_right[1]), Image.NEAREST ) # Full warp else: if canvas_size == self.image.size: im = self.image else: im = Image.new("RGBA", canvas_size, (0, 0, 0, 0)) im.paste(self.image, (0, 0)) new_image = im.transform( target_size, Image.MESH, self._create_mesh(target_bbox, target_size), Image.NEAREST ) return GeoImage(new_image, target_bbox)
[ "def", "warp", "(", "self", ",", "target_bbox", ",", "target_size", "=", "None", ")", ":", "# Determine target size based on pixels per unit of the source image and the target bounding box reprojected", "# to the source projection.", "if", "not", "target_size", ":", "px_per_unit", "=", "(", "float", "(", "self", ".", "image", ".", "size", "[", "0", "]", ")", "/", "self", ".", "bbox", ".", "width", ",", "float", "(", "self", ".", "image", ".", "size", "[", "1", "]", ")", "/", "self", ".", "bbox", ".", "height", ")", "src_bbox", "=", "target_bbox", ".", "project", "(", "self", ".", "bbox", ".", "projection", ")", "target_size", "=", "(", "int", "(", "round", "(", "src_bbox", ".", "width", "*", "px_per_unit", "[", "0", "]", ")", ")", ",", "int", "(", "round", "(", "src_bbox", ".", "height", "*", "px_per_unit", "[", "1", "]", ")", ")", ")", "canvas_size", "=", "(", "max", "(", "target_size", "[", "0", "]", ",", "self", ".", "image", ".", "size", "[", "0", "]", ")", ",", "max", "(", "target_size", "[", "1", "]", ",", "self", ".", "image", ".", "size", "[", "1", "]", ")", ")", "# If target and source bounds are the same and source and target sizes are the same, return a reference to", "# this image.", "if", "self", ".", "bbox", "==", "target_bbox", "and", "self", ".", "image", ".", "size", "==", "target_size", ":", "return", "self", "# If target and source projections are the same, perform a simple resize", "elif", "self", ".", "bbox", ".", "projection", ".", "srs", "==", "target_bbox", ".", "projection", ".", "srs", ":", "to_source_image", "=", "world_to_image", "(", "self", ".", "bbox", ",", "self", ".", "image", ".", "size", ")", "upper_left", "=", "to_source_image", "(", "*", "(", "target_bbox", ".", "xmin", ",", "target_bbox", ".", "ymax", ")", ")", "lower_right", "=", "to_source_image", "(", "*", "(", "target_bbox", ".", "xmax", ",", "target_bbox", ".", "ymin", ")", ")", "if", "canvas_size", "==", "self", ".", "image", ".", "size", ":", "im", "=", "self", ".", "image", "else", ":", "im", "=", "Image", ".", "new", "(", "\"RGBA\"", ",", "canvas_size", ",", "(", "0", ",", "0", ",", "0", ",", "0", ")", ")", "im", ".", "paste", "(", "self", ".", "image", ",", "(", "0", ",", "0", ")", ")", "new_image", "=", "im", ".", "transform", "(", "target_size", ",", "Image", ".", "EXTENT", ",", "(", "upper_left", "[", "0", "]", ",", "upper_left", "[", "1", "]", ",", "lower_right", "[", "0", "]", ",", "lower_right", "[", "1", "]", ")", ",", "Image", ".", "NEAREST", ")", "# Full warp", "else", ":", "if", "canvas_size", "==", "self", ".", "image", ".", "size", ":", "im", "=", "self", ".", "image", "else", ":", "im", "=", "Image", ".", "new", "(", "\"RGBA\"", ",", "canvas_size", ",", "(", "0", ",", "0", ",", "0", ",", "0", ")", ")", "im", ".", "paste", "(", "self", ".", "image", ",", "(", "0", ",", "0", ")", ")", "new_image", "=", "im", ".", "transform", "(", "target_size", ",", "Image", ".", "MESH", ",", "self", ".", "_create_mesh", "(", "target_bbox", ",", "target_size", ")", ",", "Image", ".", "NEAREST", ")", "return", "GeoImage", "(", "new_image", ",", "target_bbox", ")" ]
Returns a copy of this image warped to a target size and bounding box
[ "Returns", "a", "copy", "of", "this", "image", "warped", "to", "a", "target", "size", "and", "bounding", "box" ]
f807bfd1e4083ab29fbc3c4d4418be108383a710
https://github.com/consbio/ncdjango/blob/f807bfd1e4083ab29fbc3c4d4418be108383a710/ncdjango/geoimage.py#L121-L170
train
alphagov/performanceplatform-collector
performanceplatform/collector/ga/plugins/department.py
try_get_department
def try_get_department(department_or_code): """ Try to take the first department code, or fall back to string as passed """ try: value = take_first_department_code(department_or_code) except AssertionError: value = department_or_code if value in DEPARTMENT_MAPPING: value = DEPARTMENT_MAPPING[value] return value
python
def try_get_department(department_or_code): """ Try to take the first department code, or fall back to string as passed """ try: value = take_first_department_code(department_or_code) except AssertionError: value = department_or_code if value in DEPARTMENT_MAPPING: value = DEPARTMENT_MAPPING[value] return value
[ "def", "try_get_department", "(", "department_or_code", ")", ":", "try", ":", "value", "=", "take_first_department_code", "(", "department_or_code", ")", "except", "AssertionError", ":", "value", "=", "department_or_code", "if", "value", "in", "DEPARTMENT_MAPPING", ":", "value", "=", "DEPARTMENT_MAPPING", "[", "value", "]", "return", "value" ]
Try to take the first department code, or fall back to string as passed
[ "Try", "to", "take", "the", "first", "department", "code", "or", "fall", "back", "to", "string", "as", "passed" ]
de68ab4aa500c31e436e050fa1268fa928c522a5
https://github.com/alphagov/performanceplatform-collector/blob/de68ab4aa500c31e436e050fa1268fa928c522a5/performanceplatform/collector/ga/plugins/department.py#L62-L74
train
juju/theblues
theblues/identity_manager.py
IdentityManager.debug
def debug(self): """Retrieve the debug information from the identity manager.""" url = '{}debug/status'.format(self.url) try: return make_request(url, timeout=self.timeout) except ServerError as err: return {"error": str(err)}
python
def debug(self): """Retrieve the debug information from the identity manager.""" url = '{}debug/status'.format(self.url) try: return make_request(url, timeout=self.timeout) except ServerError as err: return {"error": str(err)}
[ "def", "debug", "(", "self", ")", ":", "url", "=", "'{}debug/status'", ".", "format", "(", "self", ".", "url", ")", "try", ":", "return", "make_request", "(", "url", ",", "timeout", "=", "self", ".", "timeout", ")", "except", "ServerError", "as", "err", ":", "return", "{", "\"error\"", ":", "str", "(", "err", ")", "}" ]
Retrieve the debug information from the identity manager.
[ "Retrieve", "the", "debug", "information", "from", "the", "identity", "manager", "." ]
f4431f29e43d04fc32f38f4f86cea45cd4e6ae98
https://github.com/juju/theblues/blob/f4431f29e43d04fc32f38f4f86cea45cd4e6ae98/theblues/identity_manager.py#L44-L50
train
juju/theblues
theblues/identity_manager.py
IdentityManager.login
def login(self, username, json_document): """Send user identity information to the identity manager. Raise a ServerError if an error occurs in the request process. @param username The logged in user. @param json_document The JSON payload for login. """ url = '{}u/{}'.format(self.url, username) make_request( url, method='PUT', body=json_document, timeout=self.timeout)
python
def login(self, username, json_document): """Send user identity information to the identity manager. Raise a ServerError if an error occurs in the request process. @param username The logged in user. @param json_document The JSON payload for login. """ url = '{}u/{}'.format(self.url, username) make_request( url, method='PUT', body=json_document, timeout=self.timeout)
[ "def", "login", "(", "self", ",", "username", ",", "json_document", ")", ":", "url", "=", "'{}u/{}'", ".", "format", "(", "self", ".", "url", ",", "username", ")", "make_request", "(", "url", ",", "method", "=", "'PUT'", ",", "body", "=", "json_document", ",", "timeout", "=", "self", ".", "timeout", ")" ]
Send user identity information to the identity manager. Raise a ServerError if an error occurs in the request process. @param username The logged in user. @param json_document The JSON payload for login.
[ "Send", "user", "identity", "information", "to", "the", "identity", "manager", "." ]
f4431f29e43d04fc32f38f4f86cea45cd4e6ae98
https://github.com/juju/theblues/blob/f4431f29e43d04fc32f38f4f86cea45cd4e6ae98/theblues/identity_manager.py#L52-L62
train
juju/theblues
theblues/identity_manager.py
IdentityManager.discharge
def discharge(self, username, macaroon): """Discharge the macarooon for the identity. Raise a ServerError if an error occurs in the request process. @param username The logged in user. @param macaroon The macaroon returned from the charm store. @return The resulting base64 encoded macaroon. @raises ServerError when making request to the discharge endpoint InvalidMacaroon when the macaroon passedin or discharged is invalid """ caveats = macaroon.third_party_caveats() if len(caveats) != 1: raise InvalidMacaroon( 'Invalid number of third party caveats (1 != {})' ''.format(len(caveats))) url = '{}discharger/discharge?discharge-for-user={}&id={}'.format( self.url, quote(username), caveats[0][1]) logging.debug('Sending identity info to {}'.format(url)) logging.debug('data is {}'.format(caveats[0][1])) response = make_request(url, method='POST', timeout=self.timeout) try: macaroon = response['Macaroon'] json_macaroon = json.dumps(macaroon) except (KeyError, UnicodeDecodeError) as err: raise InvalidMacaroon( 'Invalid macaroon from discharger: {}'.format(err.message)) return base64.urlsafe_b64encode(json_macaroon.encode('utf-8'))
python
def discharge(self, username, macaroon): """Discharge the macarooon for the identity. Raise a ServerError if an error occurs in the request process. @param username The logged in user. @param macaroon The macaroon returned from the charm store. @return The resulting base64 encoded macaroon. @raises ServerError when making request to the discharge endpoint InvalidMacaroon when the macaroon passedin or discharged is invalid """ caveats = macaroon.third_party_caveats() if len(caveats) != 1: raise InvalidMacaroon( 'Invalid number of third party caveats (1 != {})' ''.format(len(caveats))) url = '{}discharger/discharge?discharge-for-user={}&id={}'.format( self.url, quote(username), caveats[0][1]) logging.debug('Sending identity info to {}'.format(url)) logging.debug('data is {}'.format(caveats[0][1])) response = make_request(url, method='POST', timeout=self.timeout) try: macaroon = response['Macaroon'] json_macaroon = json.dumps(macaroon) except (KeyError, UnicodeDecodeError) as err: raise InvalidMacaroon( 'Invalid macaroon from discharger: {}'.format(err.message)) return base64.urlsafe_b64encode(json_macaroon.encode('utf-8'))
[ "def", "discharge", "(", "self", ",", "username", ",", "macaroon", ")", ":", "caveats", "=", "macaroon", ".", "third_party_caveats", "(", ")", "if", "len", "(", "caveats", ")", "!=", "1", ":", "raise", "InvalidMacaroon", "(", "'Invalid number of third party caveats (1 != {})'", "''", ".", "format", "(", "len", "(", "caveats", ")", ")", ")", "url", "=", "'{}discharger/discharge?discharge-for-user={}&id={}'", ".", "format", "(", "self", ".", "url", ",", "quote", "(", "username", ")", ",", "caveats", "[", "0", "]", "[", "1", "]", ")", "logging", ".", "debug", "(", "'Sending identity info to {}'", ".", "format", "(", "url", ")", ")", "logging", ".", "debug", "(", "'data is {}'", ".", "format", "(", "caveats", "[", "0", "]", "[", "1", "]", ")", ")", "response", "=", "make_request", "(", "url", ",", "method", "=", "'POST'", ",", "timeout", "=", "self", ".", "timeout", ")", "try", ":", "macaroon", "=", "response", "[", "'Macaroon'", "]", "json_macaroon", "=", "json", ".", "dumps", "(", "macaroon", ")", "except", "(", "KeyError", ",", "UnicodeDecodeError", ")", "as", "err", ":", "raise", "InvalidMacaroon", "(", "'Invalid macaroon from discharger: {}'", ".", "format", "(", "err", ".", "message", ")", ")", "return", "base64", ".", "urlsafe_b64encode", "(", "json_macaroon", ".", "encode", "(", "'utf-8'", ")", ")" ]
Discharge the macarooon for the identity. Raise a ServerError if an error occurs in the request process. @param username The logged in user. @param macaroon The macaroon returned from the charm store. @return The resulting base64 encoded macaroon. @raises ServerError when making request to the discharge endpoint InvalidMacaroon when the macaroon passedin or discharged is invalid
[ "Discharge", "the", "macarooon", "for", "the", "identity", "." ]
f4431f29e43d04fc32f38f4f86cea45cd4e6ae98
https://github.com/juju/theblues/blob/f4431f29e43d04fc32f38f4f86cea45cd4e6ae98/theblues/identity_manager.py#L64-L92
train
juju/theblues
theblues/identity_manager.py
IdentityManager.discharge_token
def discharge_token(self, username): """Discharge token for a user. Raise a ServerError if an error occurs in the request process. @param username The logged in user. @return The resulting base64 encoded discharged token. """ url = '{}discharge-token-for-user?username={}'.format( self.url, quote(username)) logging.debug('Sending identity info to {}'.format(url)) response = make_request(url, method='GET', timeout=self.timeout) try: macaroon = response['DischargeToken'] json_macaroon = json.dumps(macaroon) except (KeyError, UnicodeDecodeError) as err: raise InvalidMacaroon( 'Invalid macaroon from discharger: {}'.format(err.message)) return base64.urlsafe_b64encode("[{}]".format( json_macaroon).encode('utf-8'))
python
def discharge_token(self, username): """Discharge token for a user. Raise a ServerError if an error occurs in the request process. @param username The logged in user. @return The resulting base64 encoded discharged token. """ url = '{}discharge-token-for-user?username={}'.format( self.url, quote(username)) logging.debug('Sending identity info to {}'.format(url)) response = make_request(url, method='GET', timeout=self.timeout) try: macaroon = response['DischargeToken'] json_macaroon = json.dumps(macaroon) except (KeyError, UnicodeDecodeError) as err: raise InvalidMacaroon( 'Invalid macaroon from discharger: {}'.format(err.message)) return base64.urlsafe_b64encode("[{}]".format( json_macaroon).encode('utf-8'))
[ "def", "discharge_token", "(", "self", ",", "username", ")", ":", "url", "=", "'{}discharge-token-for-user?username={}'", ".", "format", "(", "self", ".", "url", ",", "quote", "(", "username", ")", ")", "logging", ".", "debug", "(", "'Sending identity info to {}'", ".", "format", "(", "url", ")", ")", "response", "=", "make_request", "(", "url", ",", "method", "=", "'GET'", ",", "timeout", "=", "self", ".", "timeout", ")", "try", ":", "macaroon", "=", "response", "[", "'DischargeToken'", "]", "json_macaroon", "=", "json", ".", "dumps", "(", "macaroon", ")", "except", "(", "KeyError", ",", "UnicodeDecodeError", ")", "as", "err", ":", "raise", "InvalidMacaroon", "(", "'Invalid macaroon from discharger: {}'", ".", "format", "(", "err", ".", "message", ")", ")", "return", "base64", ".", "urlsafe_b64encode", "(", "\"[{}]\"", ".", "format", "(", "json_macaroon", ")", ".", "encode", "(", "'utf-8'", ")", ")" ]
Discharge token for a user. Raise a ServerError if an error occurs in the request process. @param username The logged in user. @return The resulting base64 encoded discharged token.
[ "Discharge", "token", "for", "a", "user", "." ]
f4431f29e43d04fc32f38f4f86cea45cd4e6ae98
https://github.com/juju/theblues/blob/f4431f29e43d04fc32f38f4f86cea45cd4e6ae98/theblues/identity_manager.py#L94-L113
train
juju/theblues
theblues/identity_manager.py
IdentityManager.set_extra_info
def set_extra_info(self, username, extra_info): """Set extra info for the given user. Raise a ServerError if an error occurs in the request process. @param username The username for the user to update. @param info The extra info as a JSON encoded string, or as a Python dictionary like object. """ url = self._get_extra_info_url(username) make_request(url, method='PUT', body=extra_info, timeout=self.timeout)
python
def set_extra_info(self, username, extra_info): """Set extra info for the given user. Raise a ServerError if an error occurs in the request process. @param username The username for the user to update. @param info The extra info as a JSON encoded string, or as a Python dictionary like object. """ url = self._get_extra_info_url(username) make_request(url, method='PUT', body=extra_info, timeout=self.timeout)
[ "def", "set_extra_info", "(", "self", ",", "username", ",", "extra_info", ")", ":", "url", "=", "self", ".", "_get_extra_info_url", "(", "username", ")", "make_request", "(", "url", ",", "method", "=", "'PUT'", ",", "body", "=", "extra_info", ",", "timeout", "=", "self", ".", "timeout", ")" ]
Set extra info for the given user. Raise a ServerError if an error occurs in the request process. @param username The username for the user to update. @param info The extra info as a JSON encoded string, or as a Python dictionary like object.
[ "Set", "extra", "info", "for", "the", "given", "user", "." ]
f4431f29e43d04fc32f38f4f86cea45cd4e6ae98
https://github.com/juju/theblues/blob/f4431f29e43d04fc32f38f4f86cea45cd4e6ae98/theblues/identity_manager.py#L122-L132
train
juju/theblues
theblues/identity_manager.py
IdentityManager.get_extra_info
def get_extra_info(self, username): """Get extra info for the given user. Raise a ServerError if an error occurs in the request process. @param username The username for the user who's info is being accessed. """ url = self._get_extra_info_url(username) return make_request(url, timeout=self.timeout)
python
def get_extra_info(self, username): """Get extra info for the given user. Raise a ServerError if an error occurs in the request process. @param username The username for the user who's info is being accessed. """ url = self._get_extra_info_url(username) return make_request(url, timeout=self.timeout)
[ "def", "get_extra_info", "(", "self", ",", "username", ")", ":", "url", "=", "self", ".", "_get_extra_info_url", "(", "username", ")", "return", "make_request", "(", "url", ",", "timeout", "=", "self", ".", "timeout", ")" ]
Get extra info for the given user. Raise a ServerError if an error occurs in the request process. @param username The username for the user who's info is being accessed.
[ "Get", "extra", "info", "for", "the", "given", "user", "." ]
f4431f29e43d04fc32f38f4f86cea45cd4e6ae98
https://github.com/juju/theblues/blob/f4431f29e43d04fc32f38f4f86cea45cd4e6ae98/theblues/identity_manager.py#L134-L142
train
consbio/ncdjango
ncdjango/geoprocessing/params.py
ParameterCollection.is_complete
def is_complete(self): """Do all required parameters have values?""" return all(p.name in self.values for p in self.parameters if p.required)
python
def is_complete(self): """Do all required parameters have values?""" return all(p.name in self.values for p in self.parameters if p.required)
[ "def", "is_complete", "(", "self", ")", ":", "return", "all", "(", "p", ".", "name", "in", "self", ".", "values", "for", "p", "in", "self", ".", "parameters", "if", "p", ".", "required", ")" ]
Do all required parameters have values?
[ "Do", "all", "required", "parameters", "have", "values?" ]
f807bfd1e4083ab29fbc3c4d4418be108383a710
https://github.com/consbio/ncdjango/blob/f807bfd1e4083ab29fbc3c4d4418be108383a710/ncdjango/geoprocessing/params.py#L95-L98
train
stevearc/dynamo3
dynamo3/batch.py
_encode_write
def _encode_write(dynamizer, data, action, key): """ Encode an item write command """ # Strip null values out of data data = dict(((k, dynamizer.encode(v)) for k, v in six.iteritems(data) if not is_null(v))) return { action: { key: data, } }
python
def _encode_write(dynamizer, data, action, key): """ Encode an item write command """ # Strip null values out of data data = dict(((k, dynamizer.encode(v)) for k, v in six.iteritems(data) if not is_null(v))) return { action: { key: data, } }
[ "def", "_encode_write", "(", "dynamizer", ",", "data", ",", "action", ",", "key", ")", ":", "# Strip null values out of data", "data", "=", "dict", "(", "(", "(", "k", ",", "dynamizer", ".", "encode", "(", "v", ")", ")", "for", "k", ",", "v", "in", "six", ".", "iteritems", "(", "data", ")", "if", "not", "is_null", "(", "v", ")", ")", ")", "return", "{", "action", ":", "{", "key", ":", "data", ",", "}", "}" ]
Encode an item write command
[ "Encode", "an", "item", "write", "command" ]
f897c40ece28586272dbcab8f0d99a14a1831dda
https://github.com/stevearc/dynamo3/blob/f897c40ece28586272dbcab8f0d99a14a1831dda/dynamo3/batch.py#L148-L157
train
stevearc/dynamo3
dynamo3/batch.py
encode_query_kwargs
def encode_query_kwargs(dynamizer, kwargs): """ Encode query constraints in Dynamo format """ ret = {} for k, v in six.iteritems(kwargs): if '__' not in k: raise TypeError("Invalid query argument '%s'" % k) name, condition_key = k.split('__') # Convert ==None to IS_NULL if condition_key == 'eq' and is_null(v): condition_key = 'null' v = True # null is a special case if condition_key == 'null': ret[name] = { 'ComparisonOperator': 'NULL' if v else 'NOT_NULL' } continue elif condition_key not in ('in', 'between'): v = (v,) ret[name] = { 'AttributeValueList': [dynamizer.encode(value) for value in v], 'ComparisonOperator': CONDITIONS[condition_key], } return ret
python
def encode_query_kwargs(dynamizer, kwargs): """ Encode query constraints in Dynamo format """ ret = {} for k, v in six.iteritems(kwargs): if '__' not in k: raise TypeError("Invalid query argument '%s'" % k) name, condition_key = k.split('__') # Convert ==None to IS_NULL if condition_key == 'eq' and is_null(v): condition_key = 'null' v = True # null is a special case if condition_key == 'null': ret[name] = { 'ComparisonOperator': 'NULL' if v else 'NOT_NULL' } continue elif condition_key not in ('in', 'between'): v = (v,) ret[name] = { 'AttributeValueList': [dynamizer.encode(value) for value in v], 'ComparisonOperator': CONDITIONS[condition_key], } return ret
[ "def", "encode_query_kwargs", "(", "dynamizer", ",", "kwargs", ")", ":", "ret", "=", "{", "}", "for", "k", ",", "v", "in", "six", ".", "iteritems", "(", "kwargs", ")", ":", "if", "'__'", "not", "in", "k", ":", "raise", "TypeError", "(", "\"Invalid query argument '%s'\"", "%", "k", ")", "name", ",", "condition_key", "=", "k", ".", "split", "(", "'__'", ")", "# Convert ==None to IS_NULL", "if", "condition_key", "==", "'eq'", "and", "is_null", "(", "v", ")", ":", "condition_key", "=", "'null'", "v", "=", "True", "# null is a special case", "if", "condition_key", "==", "'null'", ":", "ret", "[", "name", "]", "=", "{", "'ComparisonOperator'", ":", "'NULL'", "if", "v", "else", "'NOT_NULL'", "}", "continue", "elif", "condition_key", "not", "in", "(", "'in'", ",", "'between'", ")", ":", "v", "=", "(", "v", ",", ")", "ret", "[", "name", "]", "=", "{", "'AttributeValueList'", ":", "[", "dynamizer", ".", "encode", "(", "value", ")", "for", "value", "in", "v", "]", ",", "'ComparisonOperator'", ":", "CONDITIONS", "[", "condition_key", "]", ",", "}", "return", "ret" ]
Encode query constraints in Dynamo format
[ "Encode", "query", "constraints", "in", "Dynamo", "format" ]
f897c40ece28586272dbcab8f0d99a14a1831dda
https://github.com/stevearc/dynamo3/blob/f897c40ece28586272dbcab8f0d99a14a1831dda/dynamo3/batch.py#L165-L188
train
stevearc/dynamo3
dynamo3/batch.py
ItemUpdate.attrs
def attrs(self, dynamizer): """ Get the attributes for the update """ ret = { self.key: { 'Action': self.action, } } if not is_null(self.value): ret[self.key]['Value'] = dynamizer.encode(self.value) return ret
python
def attrs(self, dynamizer): """ Get the attributes for the update """ ret = { self.key: { 'Action': self.action, } } if not is_null(self.value): ret[self.key]['Value'] = dynamizer.encode(self.value) return ret
[ "def", "attrs", "(", "self", ",", "dynamizer", ")", ":", "ret", "=", "{", "self", ".", "key", ":", "{", "'Action'", ":", "self", ".", "action", ",", "}", "}", "if", "not", "is_null", "(", "self", ".", "value", ")", ":", "ret", "[", "self", ".", "key", "]", "[", "'Value'", "]", "=", "dynamizer", ".", "encode", "(", "self", ".", "value", ")", "return", "ret" ]
Get the attributes for the update
[ "Get", "the", "attributes", "for", "the", "update" ]
f897c40ece28586272dbcab8f0d99a14a1831dda
https://github.com/stevearc/dynamo3/blob/f897c40ece28586272dbcab8f0d99a14a1831dda/dynamo3/batch.py#L109-L118
train
stevearc/dynamo3
dynamo3/batch.py
ItemUpdate.expected
def expected(self, dynamizer): """ Get the expected values for the update """ if self._expect_kwargs: return encode_query_kwargs(dynamizer, self._expect_kwargs) if self._expected is not NO_ARG: ret = {} if is_null(self._expected): ret['Exists'] = False else: ret['Value'] = dynamizer.encode(self._expected) ret['Exists'] = True return {self.key: ret} return {}
python
def expected(self, dynamizer): """ Get the expected values for the update """ if self._expect_kwargs: return encode_query_kwargs(dynamizer, self._expect_kwargs) if self._expected is not NO_ARG: ret = {} if is_null(self._expected): ret['Exists'] = False else: ret['Value'] = dynamizer.encode(self._expected) ret['Exists'] = True return {self.key: ret} return {}
[ "def", "expected", "(", "self", ",", "dynamizer", ")", ":", "if", "self", ".", "_expect_kwargs", ":", "return", "encode_query_kwargs", "(", "dynamizer", ",", "self", ".", "_expect_kwargs", ")", "if", "self", ".", "_expected", "is", "not", "NO_ARG", ":", "ret", "=", "{", "}", "if", "is_null", "(", "self", ".", "_expected", ")", ":", "ret", "[", "'Exists'", "]", "=", "False", "else", ":", "ret", "[", "'Value'", "]", "=", "dynamizer", ".", "encode", "(", "self", ".", "_expected", ")", "ret", "[", "'Exists'", "]", "=", "True", "return", "{", "self", ".", "key", ":", "ret", "}", "return", "{", "}" ]
Get the expected values for the update
[ "Get", "the", "expected", "values", "for", "the", "update" ]
f897c40ece28586272dbcab8f0d99a14a1831dda
https://github.com/stevearc/dynamo3/blob/f897c40ece28586272dbcab8f0d99a14a1831dda/dynamo3/batch.py#L120-L132
train
stevearc/dynamo3
dynamo3/batch.py
BatchWriter.flush
def flush(self): """ Flush pending items to Dynamo """ items = [] for data in self._to_put: items.append(encode_put(self.connection.dynamizer, data)) for data in self._to_delete: items.append(encode_delete(self.connection.dynamizer, data)) self._write(items) self._to_put = [] self._to_delete = []
python
def flush(self): """ Flush pending items to Dynamo """ items = [] for data in self._to_put: items.append(encode_put(self.connection.dynamizer, data)) for data in self._to_delete: items.append(encode_delete(self.connection.dynamizer, data)) self._write(items) self._to_put = [] self._to_delete = []
[ "def", "flush", "(", "self", ")", ":", "items", "=", "[", "]", "for", "data", "in", "self", ".", "_to_put", ":", "items", ".", "append", "(", "encode_put", "(", "self", ".", "connection", ".", "dynamizer", ",", "data", ")", ")", "for", "data", "in", "self", ".", "_to_delete", ":", "items", ".", "append", "(", "encode_delete", "(", "self", ".", "connection", ".", "dynamizer", ",", "data", ")", ")", "self", ".", "_write", "(", "items", ")", "self", ".", "_to_put", "=", "[", "]", "self", ".", "_to_delete", "=", "[", "]" ]
Flush pending items to Dynamo
[ "Flush", "pending", "items", "to", "Dynamo" ]
f897c40ece28586272dbcab8f0d99a14a1831dda
https://github.com/stevearc/dynamo3/blob/f897c40ece28586272dbcab8f0d99a14a1831dda/dynamo3/batch.py#L261-L272
train
stevearc/dynamo3
dynamo3/batch.py
BatchWriter._write
def _write(self, items): """ Perform a batch write and handle the response """ response = self._batch_write_item(items) if 'consumed_capacity' in response: # Comes back as a list from BatchWriteItem self.consumed_capacity = \ sum(response['consumed_capacity'], self.consumed_capacity) if response.get('UnprocessedItems'): unprocessed = response['UnprocessedItems'].get(self.tablename, []) # Some items have not been processed. Stow them for now & # re-attempt processing on ``__exit__``. LOG.info("%d items were unprocessed. Storing for later.", len(unprocessed)) self._unprocessed.extend(unprocessed) # Getting UnprocessedItems indicates that we are exceeding our # throughput. So sleep for a bit. self._attempt += 1 self.connection.exponential_sleep(self._attempt) else: # No UnprocessedItems means our request rate is fine, so we can # reset the attempt number. self._attempt = 0 return response
python
def _write(self, items): """ Perform a batch write and handle the response """ response = self._batch_write_item(items) if 'consumed_capacity' in response: # Comes back as a list from BatchWriteItem self.consumed_capacity = \ sum(response['consumed_capacity'], self.consumed_capacity) if response.get('UnprocessedItems'): unprocessed = response['UnprocessedItems'].get(self.tablename, []) # Some items have not been processed. Stow them for now & # re-attempt processing on ``__exit__``. LOG.info("%d items were unprocessed. Storing for later.", len(unprocessed)) self._unprocessed.extend(unprocessed) # Getting UnprocessedItems indicates that we are exceeding our # throughput. So sleep for a bit. self._attempt += 1 self.connection.exponential_sleep(self._attempt) else: # No UnprocessedItems means our request rate is fine, so we can # reset the attempt number. self._attempt = 0 return response
[ "def", "_write", "(", "self", ",", "items", ")", ":", "response", "=", "self", ".", "_batch_write_item", "(", "items", ")", "if", "'consumed_capacity'", "in", "response", ":", "# Comes back as a list from BatchWriteItem", "self", ".", "consumed_capacity", "=", "sum", "(", "response", "[", "'consumed_capacity'", "]", ",", "self", ".", "consumed_capacity", ")", "if", "response", ".", "get", "(", "'UnprocessedItems'", ")", ":", "unprocessed", "=", "response", "[", "'UnprocessedItems'", "]", ".", "get", "(", "self", ".", "tablename", ",", "[", "]", ")", "# Some items have not been processed. Stow them for now &", "# re-attempt processing on ``__exit__``.", "LOG", ".", "info", "(", "\"%d items were unprocessed. Storing for later.\"", ",", "len", "(", "unprocessed", ")", ")", "self", ".", "_unprocessed", ".", "extend", "(", "unprocessed", ")", "# Getting UnprocessedItems indicates that we are exceeding our", "# throughput. So sleep for a bit.", "self", ".", "_attempt", "+=", "1", "self", ".", "connection", ".", "exponential_sleep", "(", "self", ".", "_attempt", ")", "else", ":", "# No UnprocessedItems means our request rate is fine, so we can", "# reset the attempt number.", "self", ".", "_attempt", "=", "0", "return", "response" ]
Perform a batch write and handle the response
[ "Perform", "a", "batch", "write", "and", "handle", "the", "response" ]
f897c40ece28586272dbcab8f0d99a14a1831dda
https://github.com/stevearc/dynamo3/blob/f897c40ece28586272dbcab8f0d99a14a1831dda/dynamo3/batch.py#L274-L299
train
stevearc/dynamo3
dynamo3/batch.py
BatchWriter.resend_unprocessed
def resend_unprocessed(self): """ Resend all unprocessed items """ LOG.info("Re-sending %d unprocessed items.", len(self._unprocessed)) while self._unprocessed: to_resend = self._unprocessed[:MAX_WRITE_BATCH] self._unprocessed = self._unprocessed[MAX_WRITE_BATCH:] LOG.info("Sending %d items", len(to_resend)) self._write(to_resend) LOG.info("%d unprocessed items left", len(self._unprocessed))
python
def resend_unprocessed(self): """ Resend all unprocessed items """ LOG.info("Re-sending %d unprocessed items.", len(self._unprocessed)) while self._unprocessed: to_resend = self._unprocessed[:MAX_WRITE_BATCH] self._unprocessed = self._unprocessed[MAX_WRITE_BATCH:] LOG.info("Sending %d items", len(to_resend)) self._write(to_resend) LOG.info("%d unprocessed items left", len(self._unprocessed))
[ "def", "resend_unprocessed", "(", "self", ")", ":", "LOG", ".", "info", "(", "\"Re-sending %d unprocessed items.\"", ",", "len", "(", "self", ".", "_unprocessed", ")", ")", "while", "self", ".", "_unprocessed", ":", "to_resend", "=", "self", ".", "_unprocessed", "[", ":", "MAX_WRITE_BATCH", "]", "self", ".", "_unprocessed", "=", "self", ".", "_unprocessed", "[", "MAX_WRITE_BATCH", ":", "]", "LOG", ".", "info", "(", "\"Sending %d items\"", ",", "len", "(", "to_resend", ")", ")", "self", ".", "_write", "(", "to_resend", ")", "LOG", ".", "info", "(", "\"%d unprocessed items left\"", ",", "len", "(", "self", ".", "_unprocessed", ")", ")" ]
Resend all unprocessed items
[ "Resend", "all", "unprocessed", "items" ]
f897c40ece28586272dbcab8f0d99a14a1831dda
https://github.com/stevearc/dynamo3/blob/f897c40ece28586272dbcab8f0d99a14a1831dda/dynamo3/batch.py#L301-L310
train
stevearc/dynamo3
dynamo3/batch.py
BatchWriter._batch_write_item
def _batch_write_item(self, items): """ Make a BatchWriteItem call to Dynamo """ kwargs = { 'RequestItems': { self.tablename: items, }, 'ReturnConsumedCapacity': self.return_capacity, 'ReturnItemCollectionMetrics': self.return_item_collection_metrics, } return self.connection.call('batch_write_item', **kwargs)
python
def _batch_write_item(self, items): """ Make a BatchWriteItem call to Dynamo """ kwargs = { 'RequestItems': { self.tablename: items, }, 'ReturnConsumedCapacity': self.return_capacity, 'ReturnItemCollectionMetrics': self.return_item_collection_metrics, } return self.connection.call('batch_write_item', **kwargs)
[ "def", "_batch_write_item", "(", "self", ",", "items", ")", ":", "kwargs", "=", "{", "'RequestItems'", ":", "{", "self", ".", "tablename", ":", "items", ",", "}", ",", "'ReturnConsumedCapacity'", ":", "self", ".", "return_capacity", ",", "'ReturnItemCollectionMetrics'", ":", "self", ".", "return_item_collection_metrics", ",", "}", "return", "self", ".", "connection", ".", "call", "(", "'batch_write_item'", ",", "*", "*", "kwargs", ")" ]
Make a BatchWriteItem call to Dynamo
[ "Make", "a", "BatchWriteItem", "call", "to", "Dynamo" ]
f897c40ece28586272dbcab8f0d99a14a1831dda
https://github.com/stevearc/dynamo3/blob/f897c40ece28586272dbcab8f0d99a14a1831dda/dynamo3/batch.py#L312-L321
train
juju/theblues
theblues/charmstore.py
_get_path
def _get_path(entity_id): '''Get the entity_id as a string if it is a Reference. @param entity_id The ID either a reference or a string of the entity to get. @return entity_id as a string ''' try: path = entity_id.path() except AttributeError: path = entity_id if path.startswith('cs:'): path = path[3:] return path
python
def _get_path(entity_id): '''Get the entity_id as a string if it is a Reference. @param entity_id The ID either a reference or a string of the entity to get. @return entity_id as a string ''' try: path = entity_id.path() except AttributeError: path = entity_id if path.startswith('cs:'): path = path[3:] return path
[ "def", "_get_path", "(", "entity_id", ")", ":", "try", ":", "path", "=", "entity_id", ".", "path", "(", ")", "except", "AttributeError", ":", "path", "=", "entity_id", "if", "path", ".", "startswith", "(", "'cs:'", ")", ":", "path", "=", "path", "[", "3", ":", "]", "return", "path" ]
Get the entity_id as a string if it is a Reference. @param entity_id The ID either a reference or a string of the entity to get. @return entity_id as a string
[ "Get", "the", "entity_id", "as", "a", "string", "if", "it", "is", "a", "Reference", "." ]
f4431f29e43d04fc32f38f4f86cea45cd4e6ae98
https://github.com/juju/theblues/blob/f4431f29e43d04fc32f38f4f86cea45cd4e6ae98/theblues/charmstore.py#L482-L495
train
juju/theblues
theblues/charmstore.py
CharmStore._get
def _get(self, url): """Make a get request against the charmstore. This method is used by other API methods to standardize querying. @param url The full url to query (e.g. https://api.jujucharms.com/charmstore/v4/macaroon) """ try: response = requests.get(url, verify=self.verify, cookies=self.cookies, timeout=self.timeout, auth=self._client.auth()) response.raise_for_status() return response except HTTPError as exc: if exc.response.status_code in (404, 407): raise EntityNotFound(url) else: message = ('Error during request: {url} ' 'status code:({code}) ' 'message: {message}').format( url=url, code=exc.response.status_code, message=exc.response.text) logging.error(message) raise ServerError(exc.response.status_code, exc.response.text, message) except Timeout: message = 'Request timed out: {url} timeout: {timeout}' message = message.format(url=url, timeout=self.timeout) logging.error(message) raise ServerError(message) except RequestException as exc: message = ('Error during request: {url} ' 'message: {message}').format( url=url, message=exc) logging.error(message) raise ServerError(exc.args[0][1].errno, exc.args[0][1].strerror, message)
python
def _get(self, url): """Make a get request against the charmstore. This method is used by other API methods to standardize querying. @param url The full url to query (e.g. https://api.jujucharms.com/charmstore/v4/macaroon) """ try: response = requests.get(url, verify=self.verify, cookies=self.cookies, timeout=self.timeout, auth=self._client.auth()) response.raise_for_status() return response except HTTPError as exc: if exc.response.status_code in (404, 407): raise EntityNotFound(url) else: message = ('Error during request: {url} ' 'status code:({code}) ' 'message: {message}').format( url=url, code=exc.response.status_code, message=exc.response.text) logging.error(message) raise ServerError(exc.response.status_code, exc.response.text, message) except Timeout: message = 'Request timed out: {url} timeout: {timeout}' message = message.format(url=url, timeout=self.timeout) logging.error(message) raise ServerError(message) except RequestException as exc: message = ('Error during request: {url} ' 'message: {message}').format( url=url, message=exc) logging.error(message) raise ServerError(exc.args[0][1].errno, exc.args[0][1].strerror, message)
[ "def", "_get", "(", "self", ",", "url", ")", ":", "try", ":", "response", "=", "requests", ".", "get", "(", "url", ",", "verify", "=", "self", ".", "verify", ",", "cookies", "=", "self", ".", "cookies", ",", "timeout", "=", "self", ".", "timeout", ",", "auth", "=", "self", ".", "_client", ".", "auth", "(", ")", ")", "response", ".", "raise_for_status", "(", ")", "return", "response", "except", "HTTPError", "as", "exc", ":", "if", "exc", ".", "response", ".", "status_code", "in", "(", "404", ",", "407", ")", ":", "raise", "EntityNotFound", "(", "url", ")", "else", ":", "message", "=", "(", "'Error during request: {url} '", "'status code:({code}) '", "'message: {message}'", ")", ".", "format", "(", "url", "=", "url", ",", "code", "=", "exc", ".", "response", ".", "status_code", ",", "message", "=", "exc", ".", "response", ".", "text", ")", "logging", ".", "error", "(", "message", ")", "raise", "ServerError", "(", "exc", ".", "response", ".", "status_code", ",", "exc", ".", "response", ".", "text", ",", "message", ")", "except", "Timeout", ":", "message", "=", "'Request timed out: {url} timeout: {timeout}'", "message", "=", "message", ".", "format", "(", "url", "=", "url", ",", "timeout", "=", "self", ".", "timeout", ")", "logging", ".", "error", "(", "message", ")", "raise", "ServerError", "(", "message", ")", "except", "RequestException", "as", "exc", ":", "message", "=", "(", "'Error during request: {url} '", "'message: {message}'", ")", ".", "format", "(", "url", "=", "url", ",", "message", "=", "exc", ")", "logging", ".", "error", "(", "message", ")", "raise", "ServerError", "(", "exc", ".", "args", "[", "0", "]", "[", "1", "]", ".", "errno", ",", "exc", ".", "args", "[", "0", "]", "[", "1", "]", ".", "strerror", ",", "message", ")" ]
Make a get request against the charmstore. This method is used by other API methods to standardize querying. @param url The full url to query (e.g. https://api.jujucharms.com/charmstore/v4/macaroon)
[ "Make", "a", "get", "request", "against", "the", "charmstore", "." ]
f4431f29e43d04fc32f38f4f86cea45cd4e6ae98
https://github.com/juju/theblues/blob/f4431f29e43d04fc32f38f4f86cea45cd4e6ae98/theblues/charmstore.py#L66-L106
train
juju/theblues
theblues/charmstore.py
CharmStore._meta
def _meta(self, entity_id, includes, channel=None): '''Retrieve metadata about an entity in the charmstore. @param entity_id The ID either a reference or a string of the entity to get. @param includes Which metadata fields to include in the response. @param channel Optional channel name, e.g. `stable`. ''' queries = [] if includes is not None: queries.extend([('include', include) for include in includes]) if channel is not None: queries.append(('channel', channel)) if len(queries): url = '{}/{}/meta/any?{}'.format(self.url, _get_path(entity_id), urlencode(queries)) else: url = '{}/{}/meta/any'.format(self.url, _get_path(entity_id)) data = self._get(url) return data.json()
python
def _meta(self, entity_id, includes, channel=None): '''Retrieve metadata about an entity in the charmstore. @param entity_id The ID either a reference or a string of the entity to get. @param includes Which metadata fields to include in the response. @param channel Optional channel name, e.g. `stable`. ''' queries = [] if includes is not None: queries.extend([('include', include) for include in includes]) if channel is not None: queries.append(('channel', channel)) if len(queries): url = '{}/{}/meta/any?{}'.format(self.url, _get_path(entity_id), urlencode(queries)) else: url = '{}/{}/meta/any'.format(self.url, _get_path(entity_id)) data = self._get(url) return data.json()
[ "def", "_meta", "(", "self", ",", "entity_id", ",", "includes", ",", "channel", "=", "None", ")", ":", "queries", "=", "[", "]", "if", "includes", "is", "not", "None", ":", "queries", ".", "extend", "(", "[", "(", "'include'", ",", "include", ")", "for", "include", "in", "includes", "]", ")", "if", "channel", "is", "not", "None", ":", "queries", ".", "append", "(", "(", "'channel'", ",", "channel", ")", ")", "if", "len", "(", "queries", ")", ":", "url", "=", "'{}/{}/meta/any?{}'", ".", "format", "(", "self", ".", "url", ",", "_get_path", "(", "entity_id", ")", ",", "urlencode", "(", "queries", ")", ")", "else", ":", "url", "=", "'{}/{}/meta/any'", ".", "format", "(", "self", ".", "url", ",", "_get_path", "(", "entity_id", ")", ")", "data", "=", "self", ".", "_get", "(", "url", ")", "return", "data", ".", "json", "(", ")" ]
Retrieve metadata about an entity in the charmstore. @param entity_id The ID either a reference or a string of the entity to get. @param includes Which metadata fields to include in the response. @param channel Optional channel name, e.g. `stable`.
[ "Retrieve", "metadata", "about", "an", "entity", "in", "the", "charmstore", "." ]
f4431f29e43d04fc32f38f4f86cea45cd4e6ae98
https://github.com/juju/theblues/blob/f4431f29e43d04fc32f38f4f86cea45cd4e6ae98/theblues/charmstore.py#L108-L127
train
juju/theblues
theblues/charmstore.py
CharmStore.entities
def entities(self, entity_ids): '''Get the default data for entities. @param entity_ids A list of entity ids either as strings or references. ''' url = '%s/meta/any?include=id&' % self.url for entity_id in entity_ids: url += 'id=%s&' % _get_path(entity_id) # Remove the trailing '&' from the URL. url = url[:-1] data = self._get(url) return data.json()
python
def entities(self, entity_ids): '''Get the default data for entities. @param entity_ids A list of entity ids either as strings or references. ''' url = '%s/meta/any?include=id&' % self.url for entity_id in entity_ids: url += 'id=%s&' % _get_path(entity_id) # Remove the trailing '&' from the URL. url = url[:-1] data = self._get(url) return data.json()
[ "def", "entities", "(", "self", ",", "entity_ids", ")", ":", "url", "=", "'%s/meta/any?include=id&'", "%", "self", ".", "url", "for", "entity_id", "in", "entity_ids", ":", "url", "+=", "'id=%s&'", "%", "_get_path", "(", "entity_id", ")", "# Remove the trailing '&' from the URL.", "url", "=", "url", "[", ":", "-", "1", "]", "data", "=", "self", ".", "_get", "(", "url", ")", "return", "data", ".", "json", "(", ")" ]
Get the default data for entities. @param entity_ids A list of entity ids either as strings or references.
[ "Get", "the", "default", "data", "for", "entities", "." ]
f4431f29e43d04fc32f38f4f86cea45cd4e6ae98
https://github.com/juju/theblues/blob/f4431f29e43d04fc32f38f4f86cea45cd4e6ae98/theblues/charmstore.py#L148-L159
train
juju/theblues
theblues/charmstore.py
CharmStore.bundle
def bundle(self, bundle_id, channel=None): '''Get the default data for a bundle. @param bundle_id The bundle's id. @param channel Optional channel name. ''' return self.entity(bundle_id, get_files=True, channel=channel)
python
def bundle(self, bundle_id, channel=None): '''Get the default data for a bundle. @param bundle_id The bundle's id. @param channel Optional channel name. ''' return self.entity(bundle_id, get_files=True, channel=channel)
[ "def", "bundle", "(", "self", ",", "bundle_id", ",", "channel", "=", "None", ")", ":", "return", "self", ".", "entity", "(", "bundle_id", ",", "get_files", "=", "True", ",", "channel", "=", "channel", ")" ]
Get the default data for a bundle. @param bundle_id The bundle's id. @param channel Optional channel name.
[ "Get", "the", "default", "data", "for", "a", "bundle", "." ]
f4431f29e43d04fc32f38f4f86cea45cd4e6ae98
https://github.com/juju/theblues/blob/f4431f29e43d04fc32f38f4f86cea45cd4e6ae98/theblues/charmstore.py#L161-L167
train
juju/theblues
theblues/charmstore.py
CharmStore.charm
def charm(self, charm_id, channel=None): '''Get the default data for a charm. @param charm_id The charm's id. @param channel Optional channel name. ''' return self.entity(charm_id, get_files=True, channel=channel)
python
def charm(self, charm_id, channel=None): '''Get the default data for a charm. @param charm_id The charm's id. @param channel Optional channel name. ''' return self.entity(charm_id, get_files=True, channel=channel)
[ "def", "charm", "(", "self", ",", "charm_id", ",", "channel", "=", "None", ")", ":", "return", "self", ".", "entity", "(", "charm_id", ",", "get_files", "=", "True", ",", "channel", "=", "channel", ")" ]
Get the default data for a charm. @param charm_id The charm's id. @param channel Optional channel name.
[ "Get", "the", "default", "data", "for", "a", "charm", "." ]
f4431f29e43d04fc32f38f4f86cea45cd4e6ae98
https://github.com/juju/theblues/blob/f4431f29e43d04fc32f38f4f86cea45cd4e6ae98/theblues/charmstore.py#L169-L175
train
juju/theblues
theblues/charmstore.py
CharmStore.charm_icon_url
def charm_icon_url(self, charm_id, channel=None): '''Generate the path to the icon for charms. @param charm_id The ID of the charm. @param channel Optional channel name. @return The url to the icon. ''' url = '{}/{}/icon.svg'.format(self.url, _get_path(charm_id)) return _add_channel(url, channel)
python
def charm_icon_url(self, charm_id, channel=None): '''Generate the path to the icon for charms. @param charm_id The ID of the charm. @param channel Optional channel name. @return The url to the icon. ''' url = '{}/{}/icon.svg'.format(self.url, _get_path(charm_id)) return _add_channel(url, channel)
[ "def", "charm_icon_url", "(", "self", ",", "charm_id", ",", "channel", "=", "None", ")", ":", "url", "=", "'{}/{}/icon.svg'", ".", "format", "(", "self", ".", "url", ",", "_get_path", "(", "charm_id", ")", ")", "return", "_add_channel", "(", "url", ",", "channel", ")" ]
Generate the path to the icon for charms. @param charm_id The ID of the charm. @param channel Optional channel name. @return The url to the icon.
[ "Generate", "the", "path", "to", "the", "icon", "for", "charms", "." ]
f4431f29e43d04fc32f38f4f86cea45cd4e6ae98
https://github.com/juju/theblues/blob/f4431f29e43d04fc32f38f4f86cea45cd4e6ae98/theblues/charmstore.py#L177-L185
train
juju/theblues
theblues/charmstore.py
CharmStore.charm_icon
def charm_icon(self, charm_id, channel=None): '''Get the charm icon. @param charm_id The ID of the charm. @param channel Optional channel name. ''' url = self.charm_icon_url(charm_id, channel=channel) response = self._get(url) return response.content
python
def charm_icon(self, charm_id, channel=None): '''Get the charm icon. @param charm_id The ID of the charm. @param channel Optional channel name. ''' url = self.charm_icon_url(charm_id, channel=channel) response = self._get(url) return response.content
[ "def", "charm_icon", "(", "self", ",", "charm_id", ",", "channel", "=", "None", ")", ":", "url", "=", "self", ".", "charm_icon_url", "(", "charm_id", ",", "channel", "=", "channel", ")", "response", "=", "self", ".", "_get", "(", "url", ")", "return", "response", ".", "content" ]
Get the charm icon. @param charm_id The ID of the charm. @param channel Optional channel name.
[ "Get", "the", "charm", "icon", "." ]
f4431f29e43d04fc32f38f4f86cea45cd4e6ae98
https://github.com/juju/theblues/blob/f4431f29e43d04fc32f38f4f86cea45cd4e6ae98/theblues/charmstore.py#L187-L195
train
juju/theblues
theblues/charmstore.py
CharmStore.bundle_visualization
def bundle_visualization(self, bundle_id, channel=None): '''Get the bundle visualization. @param bundle_id The ID of the bundle. @param channel Optional channel name. ''' url = self.bundle_visualization_url(bundle_id, channel=channel) response = self._get(url) return response.content
python
def bundle_visualization(self, bundle_id, channel=None): '''Get the bundle visualization. @param bundle_id The ID of the bundle. @param channel Optional channel name. ''' url = self.bundle_visualization_url(bundle_id, channel=channel) response = self._get(url) return response.content
[ "def", "bundle_visualization", "(", "self", ",", "bundle_id", ",", "channel", "=", "None", ")", ":", "url", "=", "self", ".", "bundle_visualization_url", "(", "bundle_id", ",", "channel", "=", "channel", ")", "response", "=", "self", ".", "_get", "(", "url", ")", "return", "response", ".", "content" ]
Get the bundle visualization. @param bundle_id The ID of the bundle. @param channel Optional channel name.
[ "Get", "the", "bundle", "visualization", "." ]
f4431f29e43d04fc32f38f4f86cea45cd4e6ae98
https://github.com/juju/theblues/blob/f4431f29e43d04fc32f38f4f86cea45cd4e6ae98/theblues/charmstore.py#L197-L205
train
juju/theblues
theblues/charmstore.py
CharmStore.bundle_visualization_url
def bundle_visualization_url(self, bundle_id, channel=None): '''Generate the path to the visualization for bundles. @param charm_id The ID of the bundle. @param channel Optional channel name. @return The url to the visualization. ''' url = '{}/{}/diagram.svg'.format(self.url, _get_path(bundle_id)) return _add_channel(url, channel)
python
def bundle_visualization_url(self, bundle_id, channel=None): '''Generate the path to the visualization for bundles. @param charm_id The ID of the bundle. @param channel Optional channel name. @return The url to the visualization. ''' url = '{}/{}/diagram.svg'.format(self.url, _get_path(bundle_id)) return _add_channel(url, channel)
[ "def", "bundle_visualization_url", "(", "self", ",", "bundle_id", ",", "channel", "=", "None", ")", ":", "url", "=", "'{}/{}/diagram.svg'", ".", "format", "(", "self", ".", "url", ",", "_get_path", "(", "bundle_id", ")", ")", "return", "_add_channel", "(", "url", ",", "channel", ")" ]
Generate the path to the visualization for bundles. @param charm_id The ID of the bundle. @param channel Optional channel name. @return The url to the visualization.
[ "Generate", "the", "path", "to", "the", "visualization", "for", "bundles", "." ]
f4431f29e43d04fc32f38f4f86cea45cd4e6ae98
https://github.com/juju/theblues/blob/f4431f29e43d04fc32f38f4f86cea45cd4e6ae98/theblues/charmstore.py#L207-L215
train
juju/theblues
theblues/charmstore.py
CharmStore.entity_readme_url
def entity_readme_url(self, entity_id, channel=None): '''Generate the url path for the readme of an entity. @entity_id The id of the entity (i.e. charm, bundle). @param channel Optional channel name. ''' url = '{}/{}/readme'.format(self.url, _get_path(entity_id)) return _add_channel(url, channel)
python
def entity_readme_url(self, entity_id, channel=None): '''Generate the url path for the readme of an entity. @entity_id The id of the entity (i.e. charm, bundle). @param channel Optional channel name. ''' url = '{}/{}/readme'.format(self.url, _get_path(entity_id)) return _add_channel(url, channel)
[ "def", "entity_readme_url", "(", "self", ",", "entity_id", ",", "channel", "=", "None", ")", ":", "url", "=", "'{}/{}/readme'", ".", "format", "(", "self", ".", "url", ",", "_get_path", "(", "entity_id", ")", ")", "return", "_add_channel", "(", "url", ",", "channel", ")" ]
Generate the url path for the readme of an entity. @entity_id The id of the entity (i.e. charm, bundle). @param channel Optional channel name.
[ "Generate", "the", "url", "path", "for", "the", "readme", "of", "an", "entity", "." ]
f4431f29e43d04fc32f38f4f86cea45cd4e6ae98
https://github.com/juju/theblues/blob/f4431f29e43d04fc32f38f4f86cea45cd4e6ae98/theblues/charmstore.py#L217-L224
train
juju/theblues
theblues/charmstore.py
CharmStore.entity_readme_content
def entity_readme_content(self, entity_id, channel=None): '''Get the readme for an entity. @entity_id The id of the entity (i.e. charm, bundle). @param channel Optional channel name. ''' readme_url = self.entity_readme_url(entity_id, channel=channel) response = self._get(readme_url) return response.text
python
def entity_readme_content(self, entity_id, channel=None): '''Get the readme for an entity. @entity_id The id of the entity (i.e. charm, bundle). @param channel Optional channel name. ''' readme_url = self.entity_readme_url(entity_id, channel=channel) response = self._get(readme_url) return response.text
[ "def", "entity_readme_content", "(", "self", ",", "entity_id", ",", "channel", "=", "None", ")", ":", "readme_url", "=", "self", ".", "entity_readme_url", "(", "entity_id", ",", "channel", "=", "channel", ")", "response", "=", "self", ".", "_get", "(", "readme_url", ")", "return", "response", ".", "text" ]
Get the readme for an entity. @entity_id The id of the entity (i.e. charm, bundle). @param channel Optional channel name.
[ "Get", "the", "readme", "for", "an", "entity", "." ]
f4431f29e43d04fc32f38f4f86cea45cd4e6ae98
https://github.com/juju/theblues/blob/f4431f29e43d04fc32f38f4f86cea45cd4e6ae98/theblues/charmstore.py#L226-L234
train
juju/theblues
theblues/charmstore.py
CharmStore.archive_url
def archive_url(self, entity_id, channel=None): '''Generate a URL for the archive of an entity.. @param entity_id The ID of the entity to look up as a string or reference. @param channel Optional channel name. ''' url = '{}/{}/archive'.format(self.url, _get_path(entity_id)) return _add_channel(url, channel)
python
def archive_url(self, entity_id, channel=None): '''Generate a URL for the archive of an entity.. @param entity_id The ID of the entity to look up as a string or reference. @param channel Optional channel name. ''' url = '{}/{}/archive'.format(self.url, _get_path(entity_id)) return _add_channel(url, channel)
[ "def", "archive_url", "(", "self", ",", "entity_id", ",", "channel", "=", "None", ")", ":", "url", "=", "'{}/{}/archive'", ".", "format", "(", "self", ".", "url", ",", "_get_path", "(", "entity_id", ")", ")", "return", "_add_channel", "(", "url", ",", "channel", ")" ]
Generate a URL for the archive of an entity.. @param entity_id The ID of the entity to look up as a string or reference. @param channel Optional channel name.
[ "Generate", "a", "URL", "for", "the", "archive", "of", "an", "entity", ".." ]
f4431f29e43d04fc32f38f4f86cea45cd4e6ae98
https://github.com/juju/theblues/blob/f4431f29e43d04fc32f38f4f86cea45cd4e6ae98/theblues/charmstore.py#L236-L244
train
juju/theblues
theblues/charmstore.py
CharmStore.file_url
def file_url(self, entity_id, filename, channel=None): '''Generate a URL for a file in an archive without requesting it. @param entity_id The ID of the entity to look up. @param filename The name of the file in the archive. @param channel Optional channel name. ''' url = '{}/{}/archive/{}'.format(self.url, _get_path(entity_id), filename) return _add_channel(url, channel)
python
def file_url(self, entity_id, filename, channel=None): '''Generate a URL for a file in an archive without requesting it. @param entity_id The ID of the entity to look up. @param filename The name of the file in the archive. @param channel Optional channel name. ''' url = '{}/{}/archive/{}'.format(self.url, _get_path(entity_id), filename) return _add_channel(url, channel)
[ "def", "file_url", "(", "self", ",", "entity_id", ",", "filename", ",", "channel", "=", "None", ")", ":", "url", "=", "'{}/{}/archive/{}'", ".", "format", "(", "self", ".", "url", ",", "_get_path", "(", "entity_id", ")", ",", "filename", ")", "return", "_add_channel", "(", "url", ",", "channel", ")" ]
Generate a URL for a file in an archive without requesting it. @param entity_id The ID of the entity to look up. @param filename The name of the file in the archive. @param channel Optional channel name.
[ "Generate", "a", "URL", "for", "a", "file", "in", "an", "archive", "without", "requesting", "it", "." ]
f4431f29e43d04fc32f38f4f86cea45cd4e6ae98
https://github.com/juju/theblues/blob/f4431f29e43d04fc32f38f4f86cea45cd4e6ae98/theblues/charmstore.py#L246-L255
train
juju/theblues
theblues/charmstore.py
CharmStore.files
def files(self, entity_id, manifest=None, filename=None, read_file=False, channel=None): ''' Get the files or file contents of a file for an entity. If all files are requested, a dictionary of filenames and urls for the files in the archive are returned. If filename is provided, the url of just that file is returned, if it exists. If filename is provided and read_file is true, the *contents* of the file are returned, if the file exists. @param entity_id The id of the entity to get files for @param manifest The manifest of files for the entity. Providing this reduces queries; if not provided, the manifest is looked up in the charmstore. @param filename The name of the file in the archive to get. @param read_file Whether to get the url for the file or the file contents. @param channel Optional channel name. ''' if manifest is None: manifest_url = '{}/{}/meta/manifest'.format(self.url, _get_path(entity_id)) manifest_url = _add_channel(manifest_url, channel) manifest = self._get(manifest_url) manifest = manifest.json() files = {} for f in manifest: manifest_name = f['Name'] file_url = self.file_url(_get_path(entity_id), manifest_name, channel=channel) files[manifest_name] = file_url if filename: file_url = files.get(filename, None) if file_url is None: raise EntityNotFound(entity_id, filename) if read_file: data = self._get(file_url) return data.text else: return file_url else: return files
python
def files(self, entity_id, manifest=None, filename=None, read_file=False, channel=None): ''' Get the files or file contents of a file for an entity. If all files are requested, a dictionary of filenames and urls for the files in the archive are returned. If filename is provided, the url of just that file is returned, if it exists. If filename is provided and read_file is true, the *contents* of the file are returned, if the file exists. @param entity_id The id of the entity to get files for @param manifest The manifest of files for the entity. Providing this reduces queries; if not provided, the manifest is looked up in the charmstore. @param filename The name of the file in the archive to get. @param read_file Whether to get the url for the file or the file contents. @param channel Optional channel name. ''' if manifest is None: manifest_url = '{}/{}/meta/manifest'.format(self.url, _get_path(entity_id)) manifest_url = _add_channel(manifest_url, channel) manifest = self._get(manifest_url) manifest = manifest.json() files = {} for f in manifest: manifest_name = f['Name'] file_url = self.file_url(_get_path(entity_id), manifest_name, channel=channel) files[manifest_name] = file_url if filename: file_url = files.get(filename, None) if file_url is None: raise EntityNotFound(entity_id, filename) if read_file: data = self._get(file_url) return data.text else: return file_url else: return files
[ "def", "files", "(", "self", ",", "entity_id", ",", "manifest", "=", "None", ",", "filename", "=", "None", ",", "read_file", "=", "False", ",", "channel", "=", "None", ")", ":", "if", "manifest", "is", "None", ":", "manifest_url", "=", "'{}/{}/meta/manifest'", ".", "format", "(", "self", ".", "url", ",", "_get_path", "(", "entity_id", ")", ")", "manifest_url", "=", "_add_channel", "(", "manifest_url", ",", "channel", ")", "manifest", "=", "self", ".", "_get", "(", "manifest_url", ")", "manifest", "=", "manifest", ".", "json", "(", ")", "files", "=", "{", "}", "for", "f", "in", "manifest", ":", "manifest_name", "=", "f", "[", "'Name'", "]", "file_url", "=", "self", ".", "file_url", "(", "_get_path", "(", "entity_id", ")", ",", "manifest_name", ",", "channel", "=", "channel", ")", "files", "[", "manifest_name", "]", "=", "file_url", "if", "filename", ":", "file_url", "=", "files", ".", "get", "(", "filename", ",", "None", ")", "if", "file_url", "is", "None", ":", "raise", "EntityNotFound", "(", "entity_id", ",", "filename", ")", "if", "read_file", ":", "data", "=", "self", ".", "_get", "(", "file_url", ")", "return", "data", ".", "text", "else", ":", "return", "file_url", "else", ":", "return", "files" ]
Get the files or file contents of a file for an entity. If all files are requested, a dictionary of filenames and urls for the files in the archive are returned. If filename is provided, the url of just that file is returned, if it exists. If filename is provided and read_file is true, the *contents* of the file are returned, if the file exists. @param entity_id The id of the entity to get files for @param manifest The manifest of files for the entity. Providing this reduces queries; if not provided, the manifest is looked up in the charmstore. @param filename The name of the file in the archive to get. @param read_file Whether to get the url for the file or the file contents. @param channel Optional channel name.
[ "Get", "the", "files", "or", "file", "contents", "of", "a", "file", "for", "an", "entity", "." ]
f4431f29e43d04fc32f38f4f86cea45cd4e6ae98
https://github.com/juju/theblues/blob/f4431f29e43d04fc32f38f4f86cea45cd4e6ae98/theblues/charmstore.py#L257-L303
train
juju/theblues
theblues/charmstore.py
CharmStore.resource_url
def resource_url(self, entity_id, name, revision): ''' Return the resource url for a given resource on an entity. @param entity_id The id of the entity to get resource for. @param name The name of the resource. @param revision The revision of the resource. ''' return '{}/{}/resource/{}/{}'.format(self.url, _get_path(entity_id), name, revision)
python
def resource_url(self, entity_id, name, revision): ''' Return the resource url for a given resource on an entity. @param entity_id The id of the entity to get resource for. @param name The name of the resource. @param revision The revision of the resource. ''' return '{}/{}/resource/{}/{}'.format(self.url, _get_path(entity_id), name, revision)
[ "def", "resource_url", "(", "self", ",", "entity_id", ",", "name", ",", "revision", ")", ":", "return", "'{}/{}/resource/{}/{}'", ".", "format", "(", "self", ".", "url", ",", "_get_path", "(", "entity_id", ")", ",", "name", ",", "revision", ")" ]
Return the resource url for a given resource on an entity. @param entity_id The id of the entity to get resource for. @param name The name of the resource. @param revision The revision of the resource.
[ "Return", "the", "resource", "url", "for", "a", "given", "resource", "on", "an", "entity", "." ]
f4431f29e43d04fc32f38f4f86cea45cd4e6ae98
https://github.com/juju/theblues/blob/f4431f29e43d04fc32f38f4f86cea45cd4e6ae98/theblues/charmstore.py#L305-L316
train
juju/theblues
theblues/charmstore.py
CharmStore.config
def config(self, charm_id, channel=None): '''Get the config data for a charm. @param charm_id The charm's id. @param channel Optional channel name. ''' url = '{}/{}/meta/charm-config'.format(self.url, _get_path(charm_id)) data = self._get(_add_channel(url, channel)) return data.json()
python
def config(self, charm_id, channel=None): '''Get the config data for a charm. @param charm_id The charm's id. @param channel Optional channel name. ''' url = '{}/{}/meta/charm-config'.format(self.url, _get_path(charm_id)) data = self._get(_add_channel(url, channel)) return data.json()
[ "def", "config", "(", "self", ",", "charm_id", ",", "channel", "=", "None", ")", ":", "url", "=", "'{}/{}/meta/charm-config'", ".", "format", "(", "self", ".", "url", ",", "_get_path", "(", "charm_id", ")", ")", "data", "=", "self", ".", "_get", "(", "_add_channel", "(", "url", ",", "channel", ")", ")", "return", "data", ".", "json", "(", ")" ]
Get the config data for a charm. @param charm_id The charm's id. @param channel Optional channel name.
[ "Get", "the", "config", "data", "for", "a", "charm", "." ]
f4431f29e43d04fc32f38f4f86cea45cd4e6ae98
https://github.com/juju/theblues/blob/f4431f29e43d04fc32f38f4f86cea45cd4e6ae98/theblues/charmstore.py#L318-L326
train
juju/theblues
theblues/charmstore.py
CharmStore.entityId
def entityId(self, partial, channel=None): '''Get an entity's full id provided a partial one. Raises EntityNotFound if partial cannot be resolved. @param partial The partial id (e.g. mysql, precise/mysql). @param channel Optional channel name. ''' url = '{}/{}/meta/any'.format(self.url, _get_path(partial)) data = self._get(_add_channel(url, channel)) return data.json()['Id']
python
def entityId(self, partial, channel=None): '''Get an entity's full id provided a partial one. Raises EntityNotFound if partial cannot be resolved. @param partial The partial id (e.g. mysql, precise/mysql). @param channel Optional channel name. ''' url = '{}/{}/meta/any'.format(self.url, _get_path(partial)) data = self._get(_add_channel(url, channel)) return data.json()['Id']
[ "def", "entityId", "(", "self", ",", "partial", ",", "channel", "=", "None", ")", ":", "url", "=", "'{}/{}/meta/any'", ".", "format", "(", "self", ".", "url", ",", "_get_path", "(", "partial", ")", ")", "data", "=", "self", ".", "_get", "(", "_add_channel", "(", "url", ",", "channel", ")", ")", "return", "data", ".", "json", "(", ")", "[", "'Id'", "]" ]
Get an entity's full id provided a partial one. Raises EntityNotFound if partial cannot be resolved. @param partial The partial id (e.g. mysql, precise/mysql). @param channel Optional channel name.
[ "Get", "an", "entity", "s", "full", "id", "provided", "a", "partial", "one", "." ]
f4431f29e43d04fc32f38f4f86cea45cd4e6ae98
https://github.com/juju/theblues/blob/f4431f29e43d04fc32f38f4f86cea45cd4e6ae98/theblues/charmstore.py#L328-L337
train
juju/theblues
theblues/charmstore.py
CharmStore.search
def search(self, text, includes=None, doc_type=None, limit=None, autocomplete=False, promulgated_only=False, tags=None, sort=None, owner=None, series=None): ''' Search for entities in the charmstore. @param text The text to search for. @param includes What metadata to return in results (e.g. charm-config). @param doc_type Filter to this type: bundle or charm. @param limit Maximum number of results to return. @param autocomplete Whether to prefix/suffix match search terms. @param promulgated_only Whether to filter to only promulgated charms. @param tags The tags to filter; can be a list of tags or a single tag. @param sort Sorting the result based on the sort string provided which can be name, author, series and - in front for descending. @param owner Optional owner. If provided, search results will only include entities that owner can view. @param series The series to filter; can be a list of series or a single series. ''' queries = self._common_query_parameters(doc_type, includes, owner, promulgated_only, series, sort) if len(text): queries.append(('text', text)) if limit is not None: queries.append(('limit', limit)) if autocomplete: queries.append(('autocomplete', 1)) if tags is not None: if type(tags) is list: tags = ','.join(tags) queries.append(('tags', tags)) if len(queries): url = '{}/search?{}'.format(self.url, urlencode(queries)) else: url = '{}/search'.format(self.url) data = self._get(url) return data.json()['Results']
python
def search(self, text, includes=None, doc_type=None, limit=None, autocomplete=False, promulgated_only=False, tags=None, sort=None, owner=None, series=None): ''' Search for entities in the charmstore. @param text The text to search for. @param includes What metadata to return in results (e.g. charm-config). @param doc_type Filter to this type: bundle or charm. @param limit Maximum number of results to return. @param autocomplete Whether to prefix/suffix match search terms. @param promulgated_only Whether to filter to only promulgated charms. @param tags The tags to filter; can be a list of tags or a single tag. @param sort Sorting the result based on the sort string provided which can be name, author, series and - in front for descending. @param owner Optional owner. If provided, search results will only include entities that owner can view. @param series The series to filter; can be a list of series or a single series. ''' queries = self._common_query_parameters(doc_type, includes, owner, promulgated_only, series, sort) if len(text): queries.append(('text', text)) if limit is not None: queries.append(('limit', limit)) if autocomplete: queries.append(('autocomplete', 1)) if tags is not None: if type(tags) is list: tags = ','.join(tags) queries.append(('tags', tags)) if len(queries): url = '{}/search?{}'.format(self.url, urlencode(queries)) else: url = '{}/search'.format(self.url) data = self._get(url) return data.json()['Results']
[ "def", "search", "(", "self", ",", "text", ",", "includes", "=", "None", ",", "doc_type", "=", "None", ",", "limit", "=", "None", ",", "autocomplete", "=", "False", ",", "promulgated_only", "=", "False", ",", "tags", "=", "None", ",", "sort", "=", "None", ",", "owner", "=", "None", ",", "series", "=", "None", ")", ":", "queries", "=", "self", ".", "_common_query_parameters", "(", "doc_type", ",", "includes", ",", "owner", ",", "promulgated_only", ",", "series", ",", "sort", ")", "if", "len", "(", "text", ")", ":", "queries", ".", "append", "(", "(", "'text'", ",", "text", ")", ")", "if", "limit", "is", "not", "None", ":", "queries", ".", "append", "(", "(", "'limit'", ",", "limit", ")", ")", "if", "autocomplete", ":", "queries", ".", "append", "(", "(", "'autocomplete'", ",", "1", ")", ")", "if", "tags", "is", "not", "None", ":", "if", "type", "(", "tags", ")", "is", "list", ":", "tags", "=", "','", ".", "join", "(", "tags", ")", "queries", ".", "append", "(", "(", "'tags'", ",", "tags", ")", ")", "if", "len", "(", "queries", ")", ":", "url", "=", "'{}/search?{}'", ".", "format", "(", "self", ".", "url", ",", "urlencode", "(", "queries", ")", ")", "else", ":", "url", "=", "'{}/search'", ".", "format", "(", "self", ".", "url", ")", "data", "=", "self", ".", "_get", "(", "url", ")", "return", "data", ".", "json", "(", ")", "[", "'Results'", "]" ]
Search for entities in the charmstore. @param text The text to search for. @param includes What metadata to return in results (e.g. charm-config). @param doc_type Filter to this type: bundle or charm. @param limit Maximum number of results to return. @param autocomplete Whether to prefix/suffix match search terms. @param promulgated_only Whether to filter to only promulgated charms. @param tags The tags to filter; can be a list of tags or a single tag. @param sort Sorting the result based on the sort string provided which can be name, author, series and - in front for descending. @param owner Optional owner. If provided, search results will only include entities that owner can view. @param series The series to filter; can be a list of series or a single series.
[ "Search", "for", "entities", "in", "the", "charmstore", "." ]
f4431f29e43d04fc32f38f4f86cea45cd4e6ae98
https://github.com/juju/theblues/blob/f4431f29e43d04fc32f38f4f86cea45cd4e6ae98/theblues/charmstore.py#L339-L376
train
juju/theblues
theblues/charmstore.py
CharmStore.list
def list(self, includes=None, doc_type=None, promulgated_only=False, sort=None, owner=None, series=None): ''' List entities in the charmstore. @param includes What metadata to return in results (e.g. charm-config). @param doc_type Filter to this type: bundle or charm. @param promulgated_only Whether to filter to only promulgated charms. @param sort Sorting the result based on the sort string provided which can be name, author, series and - in front for descending. @param owner Optional owner. If provided, search results will only include entities that owner can view. @param series The series to filter; can be a list of series or a single series. ''' queries = self._common_query_parameters(doc_type, includes, owner, promulgated_only, series, sort) if len(queries): url = '{}/list?{}'.format(self.url, urlencode(queries)) else: url = '{}/list'.format(self.url) data = self._get(url) return data.json()['Results']
python
def list(self, includes=None, doc_type=None, promulgated_only=False, sort=None, owner=None, series=None): ''' List entities in the charmstore. @param includes What metadata to return in results (e.g. charm-config). @param doc_type Filter to this type: bundle or charm. @param promulgated_only Whether to filter to only promulgated charms. @param sort Sorting the result based on the sort string provided which can be name, author, series and - in front for descending. @param owner Optional owner. If provided, search results will only include entities that owner can view. @param series The series to filter; can be a list of series or a single series. ''' queries = self._common_query_parameters(doc_type, includes, owner, promulgated_only, series, sort) if len(queries): url = '{}/list?{}'.format(self.url, urlencode(queries)) else: url = '{}/list'.format(self.url) data = self._get(url) return data.json()['Results']
[ "def", "list", "(", "self", ",", "includes", "=", "None", ",", "doc_type", "=", "None", ",", "promulgated_only", "=", "False", ",", "sort", "=", "None", ",", "owner", "=", "None", ",", "series", "=", "None", ")", ":", "queries", "=", "self", ".", "_common_query_parameters", "(", "doc_type", ",", "includes", ",", "owner", ",", "promulgated_only", ",", "series", ",", "sort", ")", "if", "len", "(", "queries", ")", ":", "url", "=", "'{}/list?{}'", ".", "format", "(", "self", ".", "url", ",", "urlencode", "(", "queries", ")", ")", "else", ":", "url", "=", "'{}/list'", ".", "format", "(", "self", ".", "url", ")", "data", "=", "self", ".", "_get", "(", "url", ")", "return", "data", ".", "json", "(", ")", "[", "'Results'", "]" ]
List entities in the charmstore. @param includes What metadata to return in results (e.g. charm-config). @param doc_type Filter to this type: bundle or charm. @param promulgated_only Whether to filter to only promulgated charms. @param sort Sorting the result based on the sort string provided which can be name, author, series and - in front for descending. @param owner Optional owner. If provided, search results will only include entities that owner can view. @param series The series to filter; can be a list of series or a single series.
[ "List", "entities", "in", "the", "charmstore", "." ]
f4431f29e43d04fc32f38f4f86cea45cd4e6ae98
https://github.com/juju/theblues/blob/f4431f29e43d04fc32f38f4f86cea45cd4e6ae98/theblues/charmstore.py#L378-L400
train
juju/theblues
theblues/charmstore.py
CharmStore._common_query_parameters
def _common_query_parameters(self, doc_type, includes, owner, promulgated_only, series, sort): ''' Extract common query parameters between search and list into slice. @param includes What metadata to return in results (e.g. charm-config). @param doc_type Filter to this type: bundle or charm. @param promulgated_only Whether to filter to only promulgated charms. @param sort Sorting the result based on the sort string provided which can be name, author, series and - in front for descending. @param owner Optional owner. If provided, search results will only include entities that owner can view. @param series The series to filter; can be a list of series or a single series. ''' queries = [] if includes is not None: queries.extend([('include', include) for include in includes]) if doc_type is not None: queries.append(('type', doc_type)) if promulgated_only: queries.append(('promulgated', 1)) if owner is not None: queries.append(('owner', owner)) if series is not None: if type(series) is list: series = ','.join(series) queries.append(('series', series)) if sort is not None: queries.append(('sort', sort)) return queries
python
def _common_query_parameters(self, doc_type, includes, owner, promulgated_only, series, sort): ''' Extract common query parameters between search and list into slice. @param includes What metadata to return in results (e.g. charm-config). @param doc_type Filter to this type: bundle or charm. @param promulgated_only Whether to filter to only promulgated charms. @param sort Sorting the result based on the sort string provided which can be name, author, series and - in front for descending. @param owner Optional owner. If provided, search results will only include entities that owner can view. @param series The series to filter; can be a list of series or a single series. ''' queries = [] if includes is not None: queries.extend([('include', include) for include in includes]) if doc_type is not None: queries.append(('type', doc_type)) if promulgated_only: queries.append(('promulgated', 1)) if owner is not None: queries.append(('owner', owner)) if series is not None: if type(series) is list: series = ','.join(series) queries.append(('series', series)) if sort is not None: queries.append(('sort', sort)) return queries
[ "def", "_common_query_parameters", "(", "self", ",", "doc_type", ",", "includes", ",", "owner", ",", "promulgated_only", ",", "series", ",", "sort", ")", ":", "queries", "=", "[", "]", "if", "includes", "is", "not", "None", ":", "queries", ".", "extend", "(", "[", "(", "'include'", ",", "include", ")", "for", "include", "in", "includes", "]", ")", "if", "doc_type", "is", "not", "None", ":", "queries", ".", "append", "(", "(", "'type'", ",", "doc_type", ")", ")", "if", "promulgated_only", ":", "queries", ".", "append", "(", "(", "'promulgated'", ",", "1", ")", ")", "if", "owner", "is", "not", "None", ":", "queries", ".", "append", "(", "(", "'owner'", ",", "owner", ")", ")", "if", "series", "is", "not", "None", ":", "if", "type", "(", "series", ")", "is", "list", ":", "series", "=", "','", ".", "join", "(", "series", ")", "queries", ".", "append", "(", "(", "'series'", ",", "series", ")", ")", "if", "sort", "is", "not", "None", ":", "queries", ".", "append", "(", "(", "'sort'", ",", "sort", ")", ")", "return", "queries" ]
Extract common query parameters between search and list into slice. @param includes What metadata to return in results (e.g. charm-config). @param doc_type Filter to this type: bundle or charm. @param promulgated_only Whether to filter to only promulgated charms. @param sort Sorting the result based on the sort string provided which can be name, author, series and - in front for descending. @param owner Optional owner. If provided, search results will only include entities that owner can view. @param series The series to filter; can be a list of series or a single series.
[ "Extract", "common", "query", "parameters", "between", "search", "and", "list", "into", "slice", "." ]
f4431f29e43d04fc32f38f4f86cea45cd4e6ae98
https://github.com/juju/theblues/blob/f4431f29e43d04fc32f38f4f86cea45cd4e6ae98/theblues/charmstore.py#L402-L432
train
juju/theblues
theblues/charmstore.py
CharmStore.fetch_related
def fetch_related(self, ids): """Fetch related entity information. Fetches metadata, stats and extra-info for the supplied entities. @param ids The entity ids to fetch related information for. A list of entity id dicts from the charmstore. """ if not ids: return [] meta = '&id='.join(id['Id'] for id in ids) url = ('{url}/meta/any?id={meta}' '&include=bundle-metadata&include=stats' '&include=supported-series&include=extra-info' '&include=bundle-unit-count&include=owner').format( url=self.url, meta=meta) data = self._get(url) return data.json().values()
python
def fetch_related(self, ids): """Fetch related entity information. Fetches metadata, stats and extra-info for the supplied entities. @param ids The entity ids to fetch related information for. A list of entity id dicts from the charmstore. """ if not ids: return [] meta = '&id='.join(id['Id'] for id in ids) url = ('{url}/meta/any?id={meta}' '&include=bundle-metadata&include=stats' '&include=supported-series&include=extra-info' '&include=bundle-unit-count&include=owner').format( url=self.url, meta=meta) data = self._get(url) return data.json().values()
[ "def", "fetch_related", "(", "self", ",", "ids", ")", ":", "if", "not", "ids", ":", "return", "[", "]", "meta", "=", "'&id='", ".", "join", "(", "id", "[", "'Id'", "]", "for", "id", "in", "ids", ")", "url", "=", "(", "'{url}/meta/any?id={meta}'", "'&include=bundle-metadata&include=stats'", "'&include=supported-series&include=extra-info'", "'&include=bundle-unit-count&include=owner'", ")", ".", "format", "(", "url", "=", "self", ".", "url", ",", "meta", "=", "meta", ")", "data", "=", "self", ".", "_get", "(", "url", ")", "return", "data", ".", "json", "(", ")", ".", "values", "(", ")" ]
Fetch related entity information. Fetches metadata, stats and extra-info for the supplied entities. @param ids The entity ids to fetch related information for. A list of entity id dicts from the charmstore.
[ "Fetch", "related", "entity", "information", "." ]
f4431f29e43d04fc32f38f4f86cea45cd4e6ae98
https://github.com/juju/theblues/blob/f4431f29e43d04fc32f38f4f86cea45cd4e6ae98/theblues/charmstore.py#L436-L453
train
juju/theblues
theblues/charmstore.py
CharmStore.fetch_interfaces
def fetch_interfaces(self, interface, way): """Get the list of charms that provides or requires this interface. @param interface The interface for the charm relation. @param way The type of relation, either "provides" or "requires". @return List of charms """ if not interface: return [] if way == 'requires': request = '&requires=' + interface else: request = '&provides=' + interface url = (self.url + '/search?' + 'include=charm-metadata&include=stats&include=supported-series' '&include=extra-info&include=bundle-unit-count' '&limit=1000&include=owner' + request) data = self._get(url) return data.json().values()
python
def fetch_interfaces(self, interface, way): """Get the list of charms that provides or requires this interface. @param interface The interface for the charm relation. @param way The type of relation, either "provides" or "requires". @return List of charms """ if not interface: return [] if way == 'requires': request = '&requires=' + interface else: request = '&provides=' + interface url = (self.url + '/search?' + 'include=charm-metadata&include=stats&include=supported-series' '&include=extra-info&include=bundle-unit-count' '&limit=1000&include=owner' + request) data = self._get(url) return data.json().values()
[ "def", "fetch_interfaces", "(", "self", ",", "interface", ",", "way", ")", ":", "if", "not", "interface", ":", "return", "[", "]", "if", "way", "==", "'requires'", ":", "request", "=", "'&requires='", "+", "interface", "else", ":", "request", "=", "'&provides='", "+", "interface", "url", "=", "(", "self", ".", "url", "+", "'/search?'", "+", "'include=charm-metadata&include=stats&include=supported-series'", "'&include=extra-info&include=bundle-unit-count'", "'&limit=1000&include=owner'", "+", "request", ")", "data", "=", "self", ".", "_get", "(", "url", ")", "return", "data", ".", "json", "(", ")", ".", "values", "(", ")" ]
Get the list of charms that provides or requires this interface. @param interface The interface for the charm relation. @param way The type of relation, either "provides" or "requires". @return List of charms
[ "Get", "the", "list", "of", "charms", "that", "provides", "or", "requires", "this", "interface", "." ]
f4431f29e43d04fc32f38f4f86cea45cd4e6ae98
https://github.com/juju/theblues/blob/f4431f29e43d04fc32f38f4f86cea45cd4e6ae98/theblues/charmstore.py#L455-L473
train
juju/theblues
theblues/charmstore.py
CharmStore.debug
def debug(self): '''Retrieve the debug information from the charmstore.''' url = '{}/debug/status'.format(self.url) data = self._get(url) return data.json()
python
def debug(self): '''Retrieve the debug information from the charmstore.''' url = '{}/debug/status'.format(self.url) data = self._get(url) return data.json()
[ "def", "debug", "(", "self", ")", ":", "url", "=", "'{}/debug/status'", ".", "format", "(", "self", ".", "url", ")", "data", "=", "self", ".", "_get", "(", "url", ")", "return", "data", ".", "json", "(", ")" ]
Retrieve the debug information from the charmstore.
[ "Retrieve", "the", "debug", "information", "from", "the", "charmstore", "." ]
f4431f29e43d04fc32f38f4f86cea45cd4e6ae98
https://github.com/juju/theblues/blob/f4431f29e43d04fc32f38f4f86cea45cd4e6ae98/theblues/charmstore.py#L475-L479
train
DarkEnergySurvey/ugali
ugali/isochrone/parsec.py
ParsecIsochrone.query_server
def query_server(self,outfile,age,metallicity): """ Server query for the isochrone file. Parameters: ----------- outfile : name of output isochrone file age : isochrone age metallicity : isochrone metallicity Returns: -------- outfile : name of output isochrone file """ params = copy.deepcopy(self.download_defaults) epsilon = 1e-4 lage = np.log10(age*1e9) lage_min,lage_max = params['isoc_lage0'],params['isoc_lage1'] if not (lage_min-epsilon < lage <lage_max+epsilon): msg = 'Age outside of valid range: %g [%g < log(age) < %g]'%(lage,lage_min,lage_max) raise RuntimeError(msg) z_min,z_max = params['isoc_z0'],params['isoc_z1'] if not (z_min <= metallicity <= z_max): msg = 'Metallicity outside of valid range: %g [%g < z < %g]'%(metallicity,z_min,z_max) raise RuntimeError(msg) params['photsys_file'] = photsys_dict[self.survey] params['isoc_age'] = age * 1e9 params['isoc_zeta'] = metallicity server = self.download_url url = server + '/cgi-bin/cmd_%s'%params['cmd_version'] # First check that the server is alive logger.debug("Accessing %s..."%url) urlopen(url,timeout=2) q = urlencode(params).encode('utf-8') logger.debug(url+'?'+q) c = str(urlopen(url, q).read()) aa = re.compile('output\d+') fname = aa.findall(c) if len(fname) == 0: msg = "Output filename not found" raise RuntimeError(msg) out = '{0}/tmp/{1}.dat'.format(server, fname[0]) cmd = 'wget --progress dot:binary %s -O %s'%(out,outfile) logger.debug(cmd) stdout = subprocess.check_output(cmd,shell=True,stderr=subprocess.STDOUT) logger.debug(stdout) return outfile
python
def query_server(self,outfile,age,metallicity): """ Server query for the isochrone file. Parameters: ----------- outfile : name of output isochrone file age : isochrone age metallicity : isochrone metallicity Returns: -------- outfile : name of output isochrone file """ params = copy.deepcopy(self.download_defaults) epsilon = 1e-4 lage = np.log10(age*1e9) lage_min,lage_max = params['isoc_lage0'],params['isoc_lage1'] if not (lage_min-epsilon < lage <lage_max+epsilon): msg = 'Age outside of valid range: %g [%g < log(age) < %g]'%(lage,lage_min,lage_max) raise RuntimeError(msg) z_min,z_max = params['isoc_z0'],params['isoc_z1'] if not (z_min <= metallicity <= z_max): msg = 'Metallicity outside of valid range: %g [%g < z < %g]'%(metallicity,z_min,z_max) raise RuntimeError(msg) params['photsys_file'] = photsys_dict[self.survey] params['isoc_age'] = age * 1e9 params['isoc_zeta'] = metallicity server = self.download_url url = server + '/cgi-bin/cmd_%s'%params['cmd_version'] # First check that the server is alive logger.debug("Accessing %s..."%url) urlopen(url,timeout=2) q = urlencode(params).encode('utf-8') logger.debug(url+'?'+q) c = str(urlopen(url, q).read()) aa = re.compile('output\d+') fname = aa.findall(c) if len(fname) == 0: msg = "Output filename not found" raise RuntimeError(msg) out = '{0}/tmp/{1}.dat'.format(server, fname[0]) cmd = 'wget --progress dot:binary %s -O %s'%(out,outfile) logger.debug(cmd) stdout = subprocess.check_output(cmd,shell=True,stderr=subprocess.STDOUT) logger.debug(stdout) return outfile
[ "def", "query_server", "(", "self", ",", "outfile", ",", "age", ",", "metallicity", ")", ":", "params", "=", "copy", ".", "deepcopy", "(", "self", ".", "download_defaults", ")", "epsilon", "=", "1e-4", "lage", "=", "np", ".", "log10", "(", "age", "*", "1e9", ")", "lage_min", ",", "lage_max", "=", "params", "[", "'isoc_lage0'", "]", ",", "params", "[", "'isoc_lage1'", "]", "if", "not", "(", "lage_min", "-", "epsilon", "<", "lage", "<", "lage_max", "+", "epsilon", ")", ":", "msg", "=", "'Age outside of valid range: %g [%g < log(age) < %g]'", "%", "(", "lage", ",", "lage_min", ",", "lage_max", ")", "raise", "RuntimeError", "(", "msg", ")", "z_min", ",", "z_max", "=", "params", "[", "'isoc_z0'", "]", ",", "params", "[", "'isoc_z1'", "]", "if", "not", "(", "z_min", "<=", "metallicity", "<=", "z_max", ")", ":", "msg", "=", "'Metallicity outside of valid range: %g [%g < z < %g]'", "%", "(", "metallicity", ",", "z_min", ",", "z_max", ")", "raise", "RuntimeError", "(", "msg", ")", "params", "[", "'photsys_file'", "]", "=", "photsys_dict", "[", "self", ".", "survey", "]", "params", "[", "'isoc_age'", "]", "=", "age", "*", "1e9", "params", "[", "'isoc_zeta'", "]", "=", "metallicity", "server", "=", "self", ".", "download_url", "url", "=", "server", "+", "'/cgi-bin/cmd_%s'", "%", "params", "[", "'cmd_version'", "]", "# First check that the server is alive", "logger", ".", "debug", "(", "\"Accessing %s...\"", "%", "url", ")", "urlopen", "(", "url", ",", "timeout", "=", "2", ")", "q", "=", "urlencode", "(", "params", ")", ".", "encode", "(", "'utf-8'", ")", "logger", ".", "debug", "(", "url", "+", "'?'", "+", "q", ")", "c", "=", "str", "(", "urlopen", "(", "url", ",", "q", ")", ".", "read", "(", ")", ")", "aa", "=", "re", ".", "compile", "(", "'output\\d+'", ")", "fname", "=", "aa", ".", "findall", "(", "c", ")", "if", "len", "(", "fname", ")", "==", "0", ":", "msg", "=", "\"Output filename not found\"", "raise", "RuntimeError", "(", "msg", ")", "out", "=", "'{0}/tmp/{1}.dat'", ".", "format", "(", "server", ",", "fname", "[", "0", "]", ")", "cmd", "=", "'wget --progress dot:binary %s -O %s'", "%", "(", "out", ",", "outfile", ")", "logger", ".", "debug", "(", "cmd", ")", "stdout", "=", "subprocess", ".", "check_output", "(", "cmd", ",", "shell", "=", "True", ",", "stderr", "=", "subprocess", ".", "STDOUT", ")", "logger", ".", "debug", "(", "stdout", ")", "return", "outfile" ]
Server query for the isochrone file. Parameters: ----------- outfile : name of output isochrone file age : isochrone age metallicity : isochrone metallicity Returns: -------- outfile : name of output isochrone file
[ "Server", "query", "for", "the", "isochrone", "file", "." ]
21e890b4117fc810afb6fb058e8055d564f03382
https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/isochrone/parsec.py#L138-L192
train
DarkEnergySurvey/ugali
ugali/analysis/scan.py
Scan.run
def run(self, coords=None, debug=False): """ Run the likelihood grid search """ #self.grid.precompute() self.grid.search(coords=coords) return self.grid
python
def run(self, coords=None, debug=False): """ Run the likelihood grid search """ #self.grid.precompute() self.grid.search(coords=coords) return self.grid
[ "def", "run", "(", "self", ",", "coords", "=", "None", ",", "debug", "=", "False", ")", ":", "#self.grid.precompute()", "self", ".", "grid", ".", "search", "(", "coords", "=", "coords", ")", "return", "self", ".", "grid" ]
Run the likelihood grid search
[ "Run", "the", "likelihood", "grid", "search" ]
21e890b4117fc810afb6fb058e8055d564f03382
https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/analysis/scan.py#L52-L58
train
DarkEnergySurvey/ugali
ugali/analysis/scan.py
GridSearch.write
def write(self, outfile): """ Save the likelihood results as a sparse HEALPix map. """ data = odict() data['PIXEL']=self.roi.pixels_target # Full data output (too large for survey) if self.config['scan']['full_pdf']: data['LOG_LIKELIHOOD']=self.log_likelihood_sparse_array.T data['RICHNESS']=self.richness_sparse_array.T data['RICHNESS_LOWER']=self.richness_lower_sparse_array.T data['RICHNESS_UPPER']=self.richness_upper_sparse_array.T data['RICHNESS_LIMIT']=self.richness_upper_limit_sparse_array.T #data['STELLAR_MASS']=self.stellar_mass_sparse_array.T data['FRACTION_OBSERVABLE']=self.fraction_observable_sparse_array.T else: data['LOG_LIKELIHOOD']=self.log_likelihood_sparse_array.T data['RICHNESS']=self.richness_sparse_array.T data['FRACTION_OBSERVABLE']=self.fraction_observable_sparse_array.T # Convert to 32bit float for k in list(data.keys())[1:]: data[k] = data[k].astype('f4',copy=False) # Stellar mass can be calculated from STELLAR * RICHNESS header = odict() header['STELLAR']=round(self.stellar_mass_conversion,8) header['LKDNSIDE']=self.config['coords']['nside_likelihood'] header['LKDPIX']=ang2pix(self.config['coords']['nside_likelihood'], self.roi.lon,self.roi.lat) header['NROI']=self.roi.inROI(self.loglike.catalog_roi.lon, self.loglike.catalog_roi.lat).sum() header['NANNULUS']=self.roi.inAnnulus(self.loglike.catalog_roi.lon, self.loglike.catalog_roi.lat).sum() header['NINSIDE']=self.roi.inInterior(self.loglike.catalog_roi.lon, self.loglike.catalog_roi.lat).sum() header['NTARGET']=self.roi.inTarget(self.loglike.catalog_roi.lon, self.loglike.catalog_roi.lat).sum() # Flatten if there is only a single distance modulus # ADW: Is this really what we want to do? if len(self.distance_modulus_array) == 1: for key in data: data[key] = data[key].flatten() logger.info("Writing %s..."%outfile) write_partial_map(outfile,data, nside=self.config['coords']['nside_pixel'], header=header, clobber=True ) fitsio.write(outfile, dict(DISTANCE_MODULUS=self.distance_modulus_array.astype('f4',copy=False)), extname='DISTANCE_MODULUS', clobber=False)
python
def write(self, outfile): """ Save the likelihood results as a sparse HEALPix map. """ data = odict() data['PIXEL']=self.roi.pixels_target # Full data output (too large for survey) if self.config['scan']['full_pdf']: data['LOG_LIKELIHOOD']=self.log_likelihood_sparse_array.T data['RICHNESS']=self.richness_sparse_array.T data['RICHNESS_LOWER']=self.richness_lower_sparse_array.T data['RICHNESS_UPPER']=self.richness_upper_sparse_array.T data['RICHNESS_LIMIT']=self.richness_upper_limit_sparse_array.T #data['STELLAR_MASS']=self.stellar_mass_sparse_array.T data['FRACTION_OBSERVABLE']=self.fraction_observable_sparse_array.T else: data['LOG_LIKELIHOOD']=self.log_likelihood_sparse_array.T data['RICHNESS']=self.richness_sparse_array.T data['FRACTION_OBSERVABLE']=self.fraction_observable_sparse_array.T # Convert to 32bit float for k in list(data.keys())[1:]: data[k] = data[k].astype('f4',copy=False) # Stellar mass can be calculated from STELLAR * RICHNESS header = odict() header['STELLAR']=round(self.stellar_mass_conversion,8) header['LKDNSIDE']=self.config['coords']['nside_likelihood'] header['LKDPIX']=ang2pix(self.config['coords']['nside_likelihood'], self.roi.lon,self.roi.lat) header['NROI']=self.roi.inROI(self.loglike.catalog_roi.lon, self.loglike.catalog_roi.lat).sum() header['NANNULUS']=self.roi.inAnnulus(self.loglike.catalog_roi.lon, self.loglike.catalog_roi.lat).sum() header['NINSIDE']=self.roi.inInterior(self.loglike.catalog_roi.lon, self.loglike.catalog_roi.lat).sum() header['NTARGET']=self.roi.inTarget(self.loglike.catalog_roi.lon, self.loglike.catalog_roi.lat).sum() # Flatten if there is only a single distance modulus # ADW: Is this really what we want to do? if len(self.distance_modulus_array) == 1: for key in data: data[key] = data[key].flatten() logger.info("Writing %s..."%outfile) write_partial_map(outfile,data, nside=self.config['coords']['nside_pixel'], header=header, clobber=True ) fitsio.write(outfile, dict(DISTANCE_MODULUS=self.distance_modulus_array.astype('f4',copy=False)), extname='DISTANCE_MODULUS', clobber=False)
[ "def", "write", "(", "self", ",", "outfile", ")", ":", "data", "=", "odict", "(", ")", "data", "[", "'PIXEL'", "]", "=", "self", ".", "roi", ".", "pixels_target", "# Full data output (too large for survey)", "if", "self", ".", "config", "[", "'scan'", "]", "[", "'full_pdf'", "]", ":", "data", "[", "'LOG_LIKELIHOOD'", "]", "=", "self", ".", "log_likelihood_sparse_array", ".", "T", "data", "[", "'RICHNESS'", "]", "=", "self", ".", "richness_sparse_array", ".", "T", "data", "[", "'RICHNESS_LOWER'", "]", "=", "self", ".", "richness_lower_sparse_array", ".", "T", "data", "[", "'RICHNESS_UPPER'", "]", "=", "self", ".", "richness_upper_sparse_array", ".", "T", "data", "[", "'RICHNESS_LIMIT'", "]", "=", "self", ".", "richness_upper_limit_sparse_array", ".", "T", "#data['STELLAR_MASS']=self.stellar_mass_sparse_array.T", "data", "[", "'FRACTION_OBSERVABLE'", "]", "=", "self", ".", "fraction_observable_sparse_array", ".", "T", "else", ":", "data", "[", "'LOG_LIKELIHOOD'", "]", "=", "self", ".", "log_likelihood_sparse_array", ".", "T", "data", "[", "'RICHNESS'", "]", "=", "self", ".", "richness_sparse_array", ".", "T", "data", "[", "'FRACTION_OBSERVABLE'", "]", "=", "self", ".", "fraction_observable_sparse_array", ".", "T", "# Convert to 32bit float", "for", "k", "in", "list", "(", "data", ".", "keys", "(", ")", ")", "[", "1", ":", "]", ":", "data", "[", "k", "]", "=", "data", "[", "k", "]", ".", "astype", "(", "'f4'", ",", "copy", "=", "False", ")", "# Stellar mass can be calculated from STELLAR * RICHNESS", "header", "=", "odict", "(", ")", "header", "[", "'STELLAR'", "]", "=", "round", "(", "self", ".", "stellar_mass_conversion", ",", "8", ")", "header", "[", "'LKDNSIDE'", "]", "=", "self", ".", "config", "[", "'coords'", "]", "[", "'nside_likelihood'", "]", "header", "[", "'LKDPIX'", "]", "=", "ang2pix", "(", "self", ".", "config", "[", "'coords'", "]", "[", "'nside_likelihood'", "]", ",", "self", ".", "roi", ".", "lon", ",", "self", ".", "roi", ".", "lat", ")", "header", "[", "'NROI'", "]", "=", "self", ".", "roi", ".", "inROI", "(", "self", ".", "loglike", ".", "catalog_roi", ".", "lon", ",", "self", ".", "loglike", ".", "catalog_roi", ".", "lat", ")", ".", "sum", "(", ")", "header", "[", "'NANNULUS'", "]", "=", "self", ".", "roi", ".", "inAnnulus", "(", "self", ".", "loglike", ".", "catalog_roi", ".", "lon", ",", "self", ".", "loglike", ".", "catalog_roi", ".", "lat", ")", ".", "sum", "(", ")", "header", "[", "'NINSIDE'", "]", "=", "self", ".", "roi", ".", "inInterior", "(", "self", ".", "loglike", ".", "catalog_roi", ".", "lon", ",", "self", ".", "loglike", ".", "catalog_roi", ".", "lat", ")", ".", "sum", "(", ")", "header", "[", "'NTARGET'", "]", "=", "self", ".", "roi", ".", "inTarget", "(", "self", ".", "loglike", ".", "catalog_roi", ".", "lon", ",", "self", ".", "loglike", ".", "catalog_roi", ".", "lat", ")", ".", "sum", "(", ")", "# Flatten if there is only a single distance modulus", "# ADW: Is this really what we want to do?", "if", "len", "(", "self", ".", "distance_modulus_array", ")", "==", "1", ":", "for", "key", "in", "data", ":", "data", "[", "key", "]", "=", "data", "[", "key", "]", ".", "flatten", "(", ")", "logger", ".", "info", "(", "\"Writing %s...\"", "%", "outfile", ")", "write_partial_map", "(", "outfile", ",", "data", ",", "nside", "=", "self", ".", "config", "[", "'coords'", "]", "[", "'nside_pixel'", "]", ",", "header", "=", "header", ",", "clobber", "=", "True", ")", "fitsio", ".", "write", "(", "outfile", ",", "dict", "(", "DISTANCE_MODULUS", "=", "self", ".", "distance_modulus_array", ".", "astype", "(", "'f4'", ",", "copy", "=", "False", ")", ")", ",", "extname", "=", "'DISTANCE_MODULUS'", ",", "clobber", "=", "False", ")" ]
Save the likelihood results as a sparse HEALPix map.
[ "Save", "the", "likelihood", "results", "as", "a", "sparse", "HEALPix", "map", "." ]
21e890b4117fc810afb6fb058e8055d564f03382
https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/analysis/scan.py#L326-L381
train
EasyPost/pystalk
pystalk/client.py
BeanstalkClient.from_uri
def from_uri(cls, uri, socket_timeout=None, auto_decode=False): """Construct a synchronous Beanstalk Client from a URI. The URI may be of the form beanstalk://host:port or beanstalkd://host:port IPv6 literals must be wrapped in brackets as per RFC 2732. """ parts = six.moves.urllib.parse.urlparse(uri) if parts.scheme.lower() not in ('beanstalk', 'beanstalkd'): raise ValueError('Invalid scheme %s' % parts.scheme) ipv6_md = re.match(r'^\[([0-9a-fA-F:]+)\](:[0-9]+)?$', parts.netloc) if ipv6_md: host = ipv6_md.group(1) port = ipv6_md.group(2) or '11300' port = port.lstrip(':') elif ':' in parts.netloc: host, port = parts.netloc.rsplit(':', 1) else: host = parts.netloc port = 11300 port = int(port) return cls(host, port, socket_timeout=socket_timeout, auto_decode=auto_decode)
python
def from_uri(cls, uri, socket_timeout=None, auto_decode=False): """Construct a synchronous Beanstalk Client from a URI. The URI may be of the form beanstalk://host:port or beanstalkd://host:port IPv6 literals must be wrapped in brackets as per RFC 2732. """ parts = six.moves.urllib.parse.urlparse(uri) if parts.scheme.lower() not in ('beanstalk', 'beanstalkd'): raise ValueError('Invalid scheme %s' % parts.scheme) ipv6_md = re.match(r'^\[([0-9a-fA-F:]+)\](:[0-9]+)?$', parts.netloc) if ipv6_md: host = ipv6_md.group(1) port = ipv6_md.group(2) or '11300' port = port.lstrip(':') elif ':' in parts.netloc: host, port = parts.netloc.rsplit(':', 1) else: host = parts.netloc port = 11300 port = int(port) return cls(host, port, socket_timeout=socket_timeout, auto_decode=auto_decode)
[ "def", "from_uri", "(", "cls", ",", "uri", ",", "socket_timeout", "=", "None", ",", "auto_decode", "=", "False", ")", ":", "parts", "=", "six", ".", "moves", ".", "urllib", ".", "parse", ".", "urlparse", "(", "uri", ")", "if", "parts", ".", "scheme", ".", "lower", "(", ")", "not", "in", "(", "'beanstalk'", ",", "'beanstalkd'", ")", ":", "raise", "ValueError", "(", "'Invalid scheme %s'", "%", "parts", ".", "scheme", ")", "ipv6_md", "=", "re", ".", "match", "(", "r'^\\[([0-9a-fA-F:]+)\\](:[0-9]+)?$'", ",", "parts", ".", "netloc", ")", "if", "ipv6_md", ":", "host", "=", "ipv6_md", ".", "group", "(", "1", ")", "port", "=", "ipv6_md", ".", "group", "(", "2", ")", "or", "'11300'", "port", "=", "port", ".", "lstrip", "(", "':'", ")", "elif", "':'", "in", "parts", ".", "netloc", ":", "host", ",", "port", "=", "parts", ".", "netloc", ".", "rsplit", "(", "':'", ",", "1", ")", "else", ":", "host", "=", "parts", ".", "netloc", "port", "=", "11300", "port", "=", "int", "(", "port", ")", "return", "cls", "(", "host", ",", "port", ",", "socket_timeout", "=", "socket_timeout", ",", "auto_decode", "=", "auto_decode", ")" ]
Construct a synchronous Beanstalk Client from a URI. The URI may be of the form beanstalk://host:port or beanstalkd://host:port IPv6 literals must be wrapped in brackets as per RFC 2732.
[ "Construct", "a", "synchronous", "Beanstalk", "Client", "from", "a", "URI", "." ]
96759ad1fda264b9897ee5346eef7926892a3a4c
https://github.com/EasyPost/pystalk/blob/96759ad1fda264b9897ee5346eef7926892a3a4c/pystalk/client.py#L96-L117
train
EasyPost/pystalk
pystalk/client.py
BeanstalkClient.list_tubes
def list_tubes(self): """Return a list of tubes that this beanstalk instance knows about :rtype: list of tubes """ with self._sock_ctx() as sock: self._send_message('list-tubes', sock) body = self._receive_data_with_prefix(b'OK', sock) tubes = yaml_load(body) return tubes
python
def list_tubes(self): """Return a list of tubes that this beanstalk instance knows about :rtype: list of tubes """ with self._sock_ctx() as sock: self._send_message('list-tubes', sock) body = self._receive_data_with_prefix(b'OK', sock) tubes = yaml_load(body) return tubes
[ "def", "list_tubes", "(", "self", ")", ":", "with", "self", ".", "_sock_ctx", "(", ")", "as", "sock", ":", "self", ".", "_send_message", "(", "'list-tubes'", ",", "sock", ")", "body", "=", "self", ".", "_receive_data_with_prefix", "(", "b'OK'", ",", "sock", ")", "tubes", "=", "yaml_load", "(", "body", ")", "return", "tubes" ]
Return a list of tubes that this beanstalk instance knows about :rtype: list of tubes
[ "Return", "a", "list", "of", "tubes", "that", "this", "beanstalk", "instance", "knows", "about" ]
96759ad1fda264b9897ee5346eef7926892a3a4c
https://github.com/EasyPost/pystalk/blob/96759ad1fda264b9897ee5346eef7926892a3a4c/pystalk/client.py#L246-L255
train
EasyPost/pystalk
pystalk/client.py
BeanstalkClient.stats
def stats(self): """Return a dictionary with a bunch of instance-wide statistics :rtype: dict """ with self._sock_ctx() as socket: self._send_message('stats', socket) body = self._receive_data_with_prefix(b'OK', socket) stats = yaml_load(body) return stats
python
def stats(self): """Return a dictionary with a bunch of instance-wide statistics :rtype: dict """ with self._sock_ctx() as socket: self._send_message('stats', socket) body = self._receive_data_with_prefix(b'OK', socket) stats = yaml_load(body) return stats
[ "def", "stats", "(", "self", ")", ":", "with", "self", ".", "_sock_ctx", "(", ")", "as", "socket", ":", "self", ".", "_send_message", "(", "'stats'", ",", "socket", ")", "body", "=", "self", ".", "_receive_data_with_prefix", "(", "b'OK'", ",", "socket", ")", "stats", "=", "yaml_load", "(", "body", ")", "return", "stats" ]
Return a dictionary with a bunch of instance-wide statistics :rtype: dict
[ "Return", "a", "dictionary", "with", "a", "bunch", "of", "instance", "-", "wide", "statistics" ]
96759ad1fda264b9897ee5346eef7926892a3a4c
https://github.com/EasyPost/pystalk/blob/96759ad1fda264b9897ee5346eef7926892a3a4c/pystalk/client.py#L257-L266
train
EasyPost/pystalk
pystalk/client.py
BeanstalkClient.put_job
def put_job(self, data, pri=65536, delay=0, ttr=120): """Insert a new job into whatever queue is currently USEd :param data: Job body :type data: Text (either str which will be encoded as utf-8, or bytes which are already utf-8 :param pri: Priority for the job :type pri: int :param delay: Delay in seconds before the job should be placed on the ready queue :type delay: int :param ttr: Time to reserve (how long a worker may work on this job before we assume the worker is blocked and give the job to another worker :type ttr: int .. seealso:: :func:`put_job_into()` Put a job into a specific tube :func:`using()` Insert a job using an external guard """ with self._sock_ctx() as socket: message = 'put {pri} {delay} {ttr} {datalen}\r\n'.format( pri=pri, delay=delay, ttr=ttr, datalen=len(data), data=data ).encode('utf-8') if not isinstance(data, bytes): data = data.encode('utf-8') message += data message += b'\r\n' self._send_message(message, socket) return self._receive_id(socket)
python
def put_job(self, data, pri=65536, delay=0, ttr=120): """Insert a new job into whatever queue is currently USEd :param data: Job body :type data: Text (either str which will be encoded as utf-8, or bytes which are already utf-8 :param pri: Priority for the job :type pri: int :param delay: Delay in seconds before the job should be placed on the ready queue :type delay: int :param ttr: Time to reserve (how long a worker may work on this job before we assume the worker is blocked and give the job to another worker :type ttr: int .. seealso:: :func:`put_job_into()` Put a job into a specific tube :func:`using()` Insert a job using an external guard """ with self._sock_ctx() as socket: message = 'put {pri} {delay} {ttr} {datalen}\r\n'.format( pri=pri, delay=delay, ttr=ttr, datalen=len(data), data=data ).encode('utf-8') if not isinstance(data, bytes): data = data.encode('utf-8') message += data message += b'\r\n' self._send_message(message, socket) return self._receive_id(socket)
[ "def", "put_job", "(", "self", ",", "data", ",", "pri", "=", "65536", ",", "delay", "=", "0", ",", "ttr", "=", "120", ")", ":", "with", "self", ".", "_sock_ctx", "(", ")", "as", "socket", ":", "message", "=", "'put {pri} {delay} {ttr} {datalen}\\r\\n'", ".", "format", "(", "pri", "=", "pri", ",", "delay", "=", "delay", ",", "ttr", "=", "ttr", ",", "datalen", "=", "len", "(", "data", ")", ",", "data", "=", "data", ")", ".", "encode", "(", "'utf-8'", ")", "if", "not", "isinstance", "(", "data", ",", "bytes", ")", ":", "data", "=", "data", ".", "encode", "(", "'utf-8'", ")", "message", "+=", "data", "message", "+=", "b'\\r\\n'", "self", ".", "_send_message", "(", "message", ",", "socket", ")", "return", "self", ".", "_receive_id", "(", "socket", ")" ]
Insert a new job into whatever queue is currently USEd :param data: Job body :type data: Text (either str which will be encoded as utf-8, or bytes which are already utf-8 :param pri: Priority for the job :type pri: int :param delay: Delay in seconds before the job should be placed on the ready queue :type delay: int :param ttr: Time to reserve (how long a worker may work on this job before we assume the worker is blocked and give the job to another worker :type ttr: int .. seealso:: :func:`put_job_into()` Put a job into a specific tube :func:`using()` Insert a job using an external guard
[ "Insert", "a", "new", "job", "into", "whatever", "queue", "is", "currently", "USEd" ]
96759ad1fda264b9897ee5346eef7926892a3a4c
https://github.com/EasyPost/pystalk/blob/96759ad1fda264b9897ee5346eef7926892a3a4c/pystalk/client.py#L268-L298
train
EasyPost/pystalk
pystalk/client.py
BeanstalkClient.watchlist
def watchlist(self, tubes): """Set the watchlist to the given tubes :param tubes: A list of tubes to watch Automatically un-watches any tubes that are not on the target list """ tubes = set(tubes) for tube in tubes - self._watchlist: self.watch(tube) for tube in self._watchlist - tubes: self.ignore(tube)
python
def watchlist(self, tubes): """Set the watchlist to the given tubes :param tubes: A list of tubes to watch Automatically un-watches any tubes that are not on the target list """ tubes = set(tubes) for tube in tubes - self._watchlist: self.watch(tube) for tube in self._watchlist - tubes: self.ignore(tube)
[ "def", "watchlist", "(", "self", ",", "tubes", ")", ":", "tubes", "=", "set", "(", "tubes", ")", "for", "tube", "in", "tubes", "-", "self", ".", "_watchlist", ":", "self", ".", "watch", "(", "tube", ")", "for", "tube", "in", "self", ".", "_watchlist", "-", "tubes", ":", "self", ".", "ignore", "(", "tube", ")" ]
Set the watchlist to the given tubes :param tubes: A list of tubes to watch Automatically un-watches any tubes that are not on the target list
[ "Set", "the", "watchlist", "to", "the", "given", "tubes" ]
96759ad1fda264b9897ee5346eef7926892a3a4c
https://github.com/EasyPost/pystalk/blob/96759ad1fda264b9897ee5346eef7926892a3a4c/pystalk/client.py#L331-L342
train
EasyPost/pystalk
pystalk/client.py
BeanstalkClient.watch
def watch(self, tube): """Add the given tube to the watchlist. :param tube: Name of the tube to add to the watchlist Note: Initially, all connections are watching a tube named "default". If you manually call :func:`watch()`, we will un-watch the "default" tube. To keep it in your list, first call :func:`watch()` with the other tubes, then call :func:`watch()` with "default". """ with self._sock_ctx() as socket: self.desired_watchlist.add(tube) if tube not in self._watchlist: self._send_message('watch {0}'.format(tube), socket) self._receive_id(socket) self._watchlist.add(tube) if self.initial_watch: if tube != 'default': self.ignore('default') self.initial_watch = False
python
def watch(self, tube): """Add the given tube to the watchlist. :param tube: Name of the tube to add to the watchlist Note: Initially, all connections are watching a tube named "default". If you manually call :func:`watch()`, we will un-watch the "default" tube. To keep it in your list, first call :func:`watch()` with the other tubes, then call :func:`watch()` with "default". """ with self._sock_ctx() as socket: self.desired_watchlist.add(tube) if tube not in self._watchlist: self._send_message('watch {0}'.format(tube), socket) self._receive_id(socket) self._watchlist.add(tube) if self.initial_watch: if tube != 'default': self.ignore('default') self.initial_watch = False
[ "def", "watch", "(", "self", ",", "tube", ")", ":", "with", "self", ".", "_sock_ctx", "(", ")", "as", "socket", ":", "self", ".", "desired_watchlist", ".", "add", "(", "tube", ")", "if", "tube", "not", "in", "self", ".", "_watchlist", ":", "self", ".", "_send_message", "(", "'watch {0}'", ".", "format", "(", "tube", ")", ",", "socket", ")", "self", ".", "_receive_id", "(", "socket", ")", "self", ".", "_watchlist", ".", "add", "(", "tube", ")", "if", "self", ".", "initial_watch", ":", "if", "tube", "!=", "'default'", ":", "self", ".", "ignore", "(", "'default'", ")", "self", ".", "initial_watch", "=", "False" ]
Add the given tube to the watchlist. :param tube: Name of the tube to add to the watchlist Note: Initially, all connections are watching a tube named "default". If you manually call :func:`watch()`, we will un-watch the "default" tube. To keep it in your list, first call :func:`watch()` with the other tubes, then call :func:`watch()` with "default".
[ "Add", "the", "given", "tube", "to", "the", "watchlist", "." ]
96759ad1fda264b9897ee5346eef7926892a3a4c
https://github.com/EasyPost/pystalk/blob/96759ad1fda264b9897ee5346eef7926892a3a4c/pystalk/client.py#L344-L363
train
EasyPost/pystalk
pystalk/client.py
BeanstalkClient.ignore
def ignore(self, tube): """Remove the given tube from the watchlist. :param tube: Name of tube to remove from the watchlist If all tubes are :func:`ignore()` d, beanstalk will auto-add "default" to the watchlist to prevent the list from being empty. See :func:`watch()` for more unformation. """ with self._sock_ctx() as socket: if tube not in self._watchlist: raise KeyError(tube) if tube != 'default': self.desired_watchlist.remove(tube) if tube in self._watchlist: self._send_message('ignore {0}'.format(tube), socket) self._receive_id(socket) self._watchlist.remove(tube) if not self._watchlist: self._watchlist.add('default')
python
def ignore(self, tube): """Remove the given tube from the watchlist. :param tube: Name of tube to remove from the watchlist If all tubes are :func:`ignore()` d, beanstalk will auto-add "default" to the watchlist to prevent the list from being empty. See :func:`watch()` for more unformation. """ with self._sock_ctx() as socket: if tube not in self._watchlist: raise KeyError(tube) if tube != 'default': self.desired_watchlist.remove(tube) if tube in self._watchlist: self._send_message('ignore {0}'.format(tube), socket) self._receive_id(socket) self._watchlist.remove(tube) if not self._watchlist: self._watchlist.add('default')
[ "def", "ignore", "(", "self", ",", "tube", ")", ":", "with", "self", ".", "_sock_ctx", "(", ")", "as", "socket", ":", "if", "tube", "not", "in", "self", ".", "_watchlist", ":", "raise", "KeyError", "(", "tube", ")", "if", "tube", "!=", "'default'", ":", "self", ".", "desired_watchlist", ".", "remove", "(", "tube", ")", "if", "tube", "in", "self", ".", "_watchlist", ":", "self", ".", "_send_message", "(", "'ignore {0}'", ".", "format", "(", "tube", ")", ",", "socket", ")", "self", ".", "_receive_id", "(", "socket", ")", "self", ".", "_watchlist", ".", "remove", "(", "tube", ")", "if", "not", "self", ".", "_watchlist", ":", "self", ".", "_watchlist", ".", "add", "(", "'default'", ")" ]
Remove the given tube from the watchlist. :param tube: Name of tube to remove from the watchlist If all tubes are :func:`ignore()` d, beanstalk will auto-add "default" to the watchlist to prevent the list from being empty. See :func:`watch()` for more unformation.
[ "Remove", "the", "given", "tube", "from", "the", "watchlist", "." ]
96759ad1fda264b9897ee5346eef7926892a3a4c
https://github.com/EasyPost/pystalk/blob/96759ad1fda264b9897ee5346eef7926892a3a4c/pystalk/client.py#L365-L383
train
EasyPost/pystalk
pystalk/client.py
BeanstalkClient.stats_job
def stats_job(self, job_id): """Fetch statistics about a single job :rtype: dict """ with self._sock_ctx() as socket: if hasattr(job_id, 'job_id'): job_id = job_id.job_id self._send_message('stats-job {0}'.format(job_id), socket) body = self._receive_data_with_prefix(b'OK', socket) job_status = yaml_load(body) return job_status
python
def stats_job(self, job_id): """Fetch statistics about a single job :rtype: dict """ with self._sock_ctx() as socket: if hasattr(job_id, 'job_id'): job_id = job_id.job_id self._send_message('stats-job {0}'.format(job_id), socket) body = self._receive_data_with_prefix(b'OK', socket) job_status = yaml_load(body) return job_status
[ "def", "stats_job", "(", "self", ",", "job_id", ")", ":", "with", "self", ".", "_sock_ctx", "(", ")", "as", "socket", ":", "if", "hasattr", "(", "job_id", ",", "'job_id'", ")", ":", "job_id", "=", "job_id", ".", "job_id", "self", ".", "_send_message", "(", "'stats-job {0}'", ".", "format", "(", "job_id", ")", ",", "socket", ")", "body", "=", "self", ".", "_receive_data_with_prefix", "(", "b'OK'", ",", "socket", ")", "job_status", "=", "yaml_load", "(", "body", ")", "return", "job_status" ]
Fetch statistics about a single job :rtype: dict
[ "Fetch", "statistics", "about", "a", "single", "job" ]
96759ad1fda264b9897ee5346eef7926892a3a4c
https://github.com/EasyPost/pystalk/blob/96759ad1fda264b9897ee5346eef7926892a3a4c/pystalk/client.py#L385-L396
train
EasyPost/pystalk
pystalk/client.py
BeanstalkClient.stats_tube
def stats_tube(self, tube_name): """Fetch statistics about a single tube :param tube_name: Tube to fetch stats about :rtype: dict """ with self._sock_ctx() as socket: self._send_message('stats-tube {0}'.format(tube_name), socket) body = self._receive_data_with_prefix(b'OK', socket) return yaml_load(body)
python
def stats_tube(self, tube_name): """Fetch statistics about a single tube :param tube_name: Tube to fetch stats about :rtype: dict """ with self._sock_ctx() as socket: self._send_message('stats-tube {0}'.format(tube_name), socket) body = self._receive_data_with_prefix(b'OK', socket) return yaml_load(body)
[ "def", "stats_tube", "(", "self", ",", "tube_name", ")", ":", "with", "self", ".", "_sock_ctx", "(", ")", "as", "socket", ":", "self", ".", "_send_message", "(", "'stats-tube {0}'", ".", "format", "(", "tube_name", ")", ",", "socket", ")", "body", "=", "self", ".", "_receive_data_with_prefix", "(", "b'OK'", ",", "socket", ")", "return", "yaml_load", "(", "body", ")" ]
Fetch statistics about a single tube :param tube_name: Tube to fetch stats about :rtype: dict
[ "Fetch", "statistics", "about", "a", "single", "tube" ]
96759ad1fda264b9897ee5346eef7926892a3a4c
https://github.com/EasyPost/pystalk/blob/96759ad1fda264b9897ee5346eef7926892a3a4c/pystalk/client.py#L398-L407
train
EasyPost/pystalk
pystalk/client.py
BeanstalkClient.reserve_job
def reserve_job(self, timeout=5): """Reserve a job for this connection. Blocks for TIMEOUT secionds and raises TIMED_OUT if no job was available :param timeout: Time to wait for a job, in seconds. :type timeout: int """ timeout = int(timeout) if self.socket_timeout is not None: if timeout >= self.socket_timeout: raise ValueError('reserve_job timeout must be < socket timeout') if not self._watchlist: raise ValueError('Select a tube or two before reserving a job') with self._sock_ctx() as socket: self._send_message('reserve-with-timeout {0}'.format(timeout), socket) job_id, job_data = self._receive_id_and_data_with_prefix(b'RESERVED', socket) return Job(job_id, job_data)
python
def reserve_job(self, timeout=5): """Reserve a job for this connection. Blocks for TIMEOUT secionds and raises TIMED_OUT if no job was available :param timeout: Time to wait for a job, in seconds. :type timeout: int """ timeout = int(timeout) if self.socket_timeout is not None: if timeout >= self.socket_timeout: raise ValueError('reserve_job timeout must be < socket timeout') if not self._watchlist: raise ValueError('Select a tube or two before reserving a job') with self._sock_ctx() as socket: self._send_message('reserve-with-timeout {0}'.format(timeout), socket) job_id, job_data = self._receive_id_and_data_with_prefix(b'RESERVED', socket) return Job(job_id, job_data)
[ "def", "reserve_job", "(", "self", ",", "timeout", "=", "5", ")", ":", "timeout", "=", "int", "(", "timeout", ")", "if", "self", ".", "socket_timeout", "is", "not", "None", ":", "if", "timeout", ">=", "self", ".", "socket_timeout", ":", "raise", "ValueError", "(", "'reserve_job timeout must be < socket timeout'", ")", "if", "not", "self", ".", "_watchlist", ":", "raise", "ValueError", "(", "'Select a tube or two before reserving a job'", ")", "with", "self", ".", "_sock_ctx", "(", ")", "as", "socket", ":", "self", ".", "_send_message", "(", "'reserve-with-timeout {0}'", ".", "format", "(", "timeout", ")", ",", "socket", ")", "job_id", ",", "job_data", "=", "self", ".", "_receive_id_and_data_with_prefix", "(", "b'RESERVED'", ",", "socket", ")", "return", "Job", "(", "job_id", ",", "job_data", ")" ]
Reserve a job for this connection. Blocks for TIMEOUT secionds and raises TIMED_OUT if no job was available :param timeout: Time to wait for a job, in seconds. :type timeout: int
[ "Reserve", "a", "job", "for", "this", "connection", ".", "Blocks", "for", "TIMEOUT", "secionds", "and", "raises", "TIMED_OUT", "if", "no", "job", "was", "available" ]
96759ad1fda264b9897ee5346eef7926892a3a4c
https://github.com/EasyPost/pystalk/blob/96759ad1fda264b9897ee5346eef7926892a3a4c/pystalk/client.py#L409-L424
train
EasyPost/pystalk
pystalk/client.py
BeanstalkClient.delete_job
def delete_job(self, job_id): """Delete the given job id. The job must have been previously reserved by this connection""" if hasattr(job_id, 'job_id'): job_id = job_id.job_id with self._sock_ctx() as socket: self._send_message('delete {0}'.format(job_id), socket) self._receive_word(socket, b'DELETED')
python
def delete_job(self, job_id): """Delete the given job id. The job must have been previously reserved by this connection""" if hasattr(job_id, 'job_id'): job_id = job_id.job_id with self._sock_ctx() as socket: self._send_message('delete {0}'.format(job_id), socket) self._receive_word(socket, b'DELETED')
[ "def", "delete_job", "(", "self", ",", "job_id", ")", ":", "if", "hasattr", "(", "job_id", ",", "'job_id'", ")", ":", "job_id", "=", "job_id", ".", "job_id", "with", "self", ".", "_sock_ctx", "(", ")", "as", "socket", ":", "self", ".", "_send_message", "(", "'delete {0}'", ".", "format", "(", "job_id", ")", ",", "socket", ")", "self", ".", "_receive_word", "(", "socket", ",", "b'DELETED'", ")" ]
Delete the given job id. The job must have been previously reserved by this connection
[ "Delete", "the", "given", "job", "id", ".", "The", "job", "must", "have", "been", "previously", "reserved", "by", "this", "connection" ]
96759ad1fda264b9897ee5346eef7926892a3a4c
https://github.com/EasyPost/pystalk/blob/96759ad1fda264b9897ee5346eef7926892a3a4c/pystalk/client.py#L474-L480
train
EasyPost/pystalk
pystalk/client.py
BeanstalkClient.bury_job
def bury_job(self, job_id, pri=65536): """Mark the given job_id as buried. The job must have been previously reserved by this connection :param job_id: Job to bury :param pri: Priority for the newly-buried job. If not passed, will keep its current priority :type pri: int """ if hasattr(job_id, 'job_id'): job_id = job_id.job_id with self._sock_ctx() as socket: self._send_message('bury {0} {1}'.format(job_id, pri), socket) return self._receive_word(socket, b'BURIED')
python
def bury_job(self, job_id, pri=65536): """Mark the given job_id as buried. The job must have been previously reserved by this connection :param job_id: Job to bury :param pri: Priority for the newly-buried job. If not passed, will keep its current priority :type pri: int """ if hasattr(job_id, 'job_id'): job_id = job_id.job_id with self._sock_ctx() as socket: self._send_message('bury {0} {1}'.format(job_id, pri), socket) return self._receive_word(socket, b'BURIED')
[ "def", "bury_job", "(", "self", ",", "job_id", ",", "pri", "=", "65536", ")", ":", "if", "hasattr", "(", "job_id", ",", "'job_id'", ")", ":", "job_id", "=", "job_id", ".", "job_id", "with", "self", ".", "_sock_ctx", "(", ")", "as", "socket", ":", "self", ".", "_send_message", "(", "'bury {0} {1}'", ".", "format", "(", "job_id", ",", "pri", ")", ",", "socket", ")", "return", "self", ".", "_receive_word", "(", "socket", ",", "b'BURIED'", ")" ]
Mark the given job_id as buried. The job must have been previously reserved by this connection :param job_id: Job to bury :param pri: Priority for the newly-buried job. If not passed, will keep its current priority :type pri: int
[ "Mark", "the", "given", "job_id", "as", "buried", ".", "The", "job", "must", "have", "been", "previously", "reserved", "by", "this", "connection" ]
96759ad1fda264b9897ee5346eef7926892a3a4c
https://github.com/EasyPost/pystalk/blob/96759ad1fda264b9897ee5346eef7926892a3a4c/pystalk/client.py#L482-L493
train
EasyPost/pystalk
pystalk/client.py
BeanstalkClient.kick_job
def kick_job(self, job_id): """Kick the given job id. The job must either be in the DELAYED or BURIED state and will be immediately moved to the READY state.""" if hasattr(job_id, 'job_id'): job_id = job_id.job_id with self._sock_ctx() as socket: self._send_message('kick-job {0}'.format(job_id), socket) self._receive_word(socket, b'KICKED')
python
def kick_job(self, job_id): """Kick the given job id. The job must either be in the DELAYED or BURIED state and will be immediately moved to the READY state.""" if hasattr(job_id, 'job_id'): job_id = job_id.job_id with self._sock_ctx() as socket: self._send_message('kick-job {0}'.format(job_id), socket) self._receive_word(socket, b'KICKED')
[ "def", "kick_job", "(", "self", ",", "job_id", ")", ":", "if", "hasattr", "(", "job_id", ",", "'job_id'", ")", ":", "job_id", "=", "job_id", ".", "job_id", "with", "self", ".", "_sock_ctx", "(", ")", "as", "socket", ":", "self", ".", "_send_message", "(", "'kick-job {0}'", ".", "format", "(", "job_id", ")", ",", "socket", ")", "self", ".", "_receive_word", "(", "socket", ",", "b'KICKED'", ")" ]
Kick the given job id. The job must either be in the DELAYED or BURIED state and will be immediately moved to the READY state.
[ "Kick", "the", "given", "job", "id", ".", "The", "job", "must", "either", "be", "in", "the", "DELAYED", "or", "BURIED", "state", "and", "will", "be", "immediately", "moved", "to", "the", "READY", "state", "." ]
96759ad1fda264b9897ee5346eef7926892a3a4c
https://github.com/EasyPost/pystalk/blob/96759ad1fda264b9897ee5346eef7926892a3a4c/pystalk/client.py#L512-L519
train
EasyPost/pystalk
pystalk/client.py
BeanstalkClient.use
def use(self, tube): """Start producing jobs into the given tube. :param tube: Name of the tube to USE Subsequent calls to :func:`put_job` insert jobs into this tube. """ with self._sock_ctx() as socket: if self.current_tube != tube: self.desired_tube = tube self._send_message('use {0}'.format(tube), socket) self._receive_name(socket) self.current_tube = tube
python
def use(self, tube): """Start producing jobs into the given tube. :param tube: Name of the tube to USE Subsequent calls to :func:`put_job` insert jobs into this tube. """ with self._sock_ctx() as socket: if self.current_tube != tube: self.desired_tube = tube self._send_message('use {0}'.format(tube), socket) self._receive_name(socket) self.current_tube = tube
[ "def", "use", "(", "self", ",", "tube", ")", ":", "with", "self", ".", "_sock_ctx", "(", ")", "as", "socket", ":", "if", "self", ".", "current_tube", "!=", "tube", ":", "self", ".", "desired_tube", "=", "tube", "self", ".", "_send_message", "(", "'use {0}'", ".", "format", "(", "tube", ")", ",", "socket", ")", "self", ".", "_receive_name", "(", "socket", ")", "self", ".", "current_tube", "=", "tube" ]
Start producing jobs into the given tube. :param tube: Name of the tube to USE Subsequent calls to :func:`put_job` insert jobs into this tube.
[ "Start", "producing", "jobs", "into", "the", "given", "tube", "." ]
96759ad1fda264b9897ee5346eef7926892a3a4c
https://github.com/EasyPost/pystalk/blob/96759ad1fda264b9897ee5346eef7926892a3a4c/pystalk/client.py#L521-L533
train
EasyPost/pystalk
pystalk/client.py
BeanstalkClient.using
def using(self, tube): """Context-manager to insert jobs into a specific tube :param tube: Tube to insert to Yields out an instance of :class:`BeanstalkInsertingProxy` to insert items into that tube .. seealso:: :func:`use()` Change the default tube :func:`put_job()` Put a job into whatever the current tube is :func:`put_job_into()` Put a job into a specific tube """ try: current_tube = self.current_tube self.use(tube) yield BeanstalkInsertingProxy(self, tube) finally: self.use(current_tube)
python
def using(self, tube): """Context-manager to insert jobs into a specific tube :param tube: Tube to insert to Yields out an instance of :class:`BeanstalkInsertingProxy` to insert items into that tube .. seealso:: :func:`use()` Change the default tube :func:`put_job()` Put a job into whatever the current tube is :func:`put_job_into()` Put a job into a specific tube """ try: current_tube = self.current_tube self.use(tube) yield BeanstalkInsertingProxy(self, tube) finally: self.use(current_tube)
[ "def", "using", "(", "self", ",", "tube", ")", ":", "try", ":", "current_tube", "=", "self", ".", "current_tube", "self", ".", "use", "(", "tube", ")", "yield", "BeanstalkInsertingProxy", "(", "self", ",", "tube", ")", "finally", ":", "self", ".", "use", "(", "current_tube", ")" ]
Context-manager to insert jobs into a specific tube :param tube: Tube to insert to Yields out an instance of :class:`BeanstalkInsertingProxy` to insert items into that tube .. seealso:: :func:`use()` Change the default tube :func:`put_job()` Put a job into whatever the current tube is :func:`put_job_into()` Put a job into a specific tube
[ "Context", "-", "manager", "to", "insert", "jobs", "into", "a", "specific", "tube" ]
96759ad1fda264b9897ee5346eef7926892a3a4c
https://github.com/EasyPost/pystalk/blob/96759ad1fda264b9897ee5346eef7926892a3a4c/pystalk/client.py#L536-L559
train
EasyPost/pystalk
pystalk/client.py
BeanstalkClient.kick_jobs
def kick_jobs(self, num_jobs): """Kick some number of jobs from the buried queue onto the ready queue. :param num_jobs: Number of jobs to kick :type num_jobs: int If not that many jobs are in the buried queue, it will kick as many as it can.""" with self._sock_ctx() as socket: self._send_message('kick {0}'.format(num_jobs), socket) return self._receive_id(socket)
python
def kick_jobs(self, num_jobs): """Kick some number of jobs from the buried queue onto the ready queue. :param num_jobs: Number of jobs to kick :type num_jobs: int If not that many jobs are in the buried queue, it will kick as many as it can.""" with self._sock_ctx() as socket: self._send_message('kick {0}'.format(num_jobs), socket) return self._receive_id(socket)
[ "def", "kick_jobs", "(", "self", ",", "num_jobs", ")", ":", "with", "self", ".", "_sock_ctx", "(", ")", "as", "socket", ":", "self", ".", "_send_message", "(", "'kick {0}'", ".", "format", "(", "num_jobs", ")", ",", "socket", ")", "return", "self", ".", "_receive_id", "(", "socket", ")" ]
Kick some number of jobs from the buried queue onto the ready queue. :param num_jobs: Number of jobs to kick :type num_jobs: int If not that many jobs are in the buried queue, it will kick as many as it can.
[ "Kick", "some", "number", "of", "jobs", "from", "the", "buried", "queue", "onto", "the", "ready", "queue", "." ]
96759ad1fda264b9897ee5346eef7926892a3a4c
https://github.com/EasyPost/pystalk/blob/96759ad1fda264b9897ee5346eef7926892a3a4c/pystalk/client.py#L561-L570
train
EasyPost/pystalk
pystalk/client.py
BeanstalkClient.pause_tube
def pause_tube(self, tube, delay=3600): """Pause a tube for some number of seconds, preventing it from issuing jobs. :param delay: Time to pause for, in seconds :type delay: int There is no way to permanently pause a tube; passing 0 for delay actually un-pauses the tube. .. seealso:: :func:`unpause_tube()` """ with self._sock_ctx() as socket: delay = int(delay) self._send_message('pause-tube {0} {1}'.format(tube, delay), socket) return self._receive_word(socket, b'PAUSED')
python
def pause_tube(self, tube, delay=3600): """Pause a tube for some number of seconds, preventing it from issuing jobs. :param delay: Time to pause for, in seconds :type delay: int There is no way to permanently pause a tube; passing 0 for delay actually un-pauses the tube. .. seealso:: :func:`unpause_tube()` """ with self._sock_ctx() as socket: delay = int(delay) self._send_message('pause-tube {0} {1}'.format(tube, delay), socket) return self._receive_word(socket, b'PAUSED')
[ "def", "pause_tube", "(", "self", ",", "tube", ",", "delay", "=", "3600", ")", ":", "with", "self", ".", "_sock_ctx", "(", ")", "as", "socket", ":", "delay", "=", "int", "(", "delay", ")", "self", ".", "_send_message", "(", "'pause-tube {0} {1}'", ".", "format", "(", "tube", ",", "delay", ")", ",", "socket", ")", "return", "self", ".", "_receive_word", "(", "socket", ",", "b'PAUSED'", ")" ]
Pause a tube for some number of seconds, preventing it from issuing jobs. :param delay: Time to pause for, in seconds :type delay: int There is no way to permanently pause a tube; passing 0 for delay actually un-pauses the tube. .. seealso:: :func:`unpause_tube()`
[ "Pause", "a", "tube", "for", "some", "number", "of", "seconds", "preventing", "it", "from", "issuing", "jobs", "." ]
96759ad1fda264b9897ee5346eef7926892a3a4c
https://github.com/EasyPost/pystalk/blob/96759ad1fda264b9897ee5346eef7926892a3a4c/pystalk/client.py#L572-L587
train
DarkEnergySurvey/ugali
ugali/utils/stats.py
interval
def interval(best,lo=np.nan,hi=np.nan): """ Pythonized interval for easy output to yaml """ return [float(best),[float(lo),float(hi)]]
python
def interval(best,lo=np.nan,hi=np.nan): """ Pythonized interval for easy output to yaml """ return [float(best),[float(lo),float(hi)]]
[ "def", "interval", "(", "best", ",", "lo", "=", "np", ".", "nan", ",", "hi", "=", "np", ".", "nan", ")", ":", "return", "[", "float", "(", "best", ")", ",", "[", "float", "(", "lo", ")", ",", "float", "(", "hi", ")", "]", "]" ]
Pythonized interval for easy output to yaml
[ "Pythonized", "interval", "for", "easy", "output", "to", "yaml" ]
21e890b4117fc810afb6fb058e8055d564f03382
https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/utils/stats.py#L28-L32
train
DarkEnergySurvey/ugali
ugali/utils/stats.py
peak_interval
def peak_interval(data, alpha=_alpha, npoints=_npoints): """ Identify interval using Gaussian kernel density estimator. """ peak = kde_peak(data,npoints) x = np.sort(data.flat); n = len(x) # The number of entries in the interval window = int(np.rint((1.0-alpha)*n)) # The start, stop, and width of all possible intervals starts = x[:n-window]; ends = x[window:] widths = ends - starts # Just the intervals containing the peak select = (peak >= starts) & (peak <= ends) widths = widths[select] if len(widths) == 0: raise ValueError('Too few elements for interval calculation') min_idx = np.argmin(widths) lo = x[min_idx] hi = x[min_idx+window] return interval(peak,lo,hi)
python
def peak_interval(data, alpha=_alpha, npoints=_npoints): """ Identify interval using Gaussian kernel density estimator. """ peak = kde_peak(data,npoints) x = np.sort(data.flat); n = len(x) # The number of entries in the interval window = int(np.rint((1.0-alpha)*n)) # The start, stop, and width of all possible intervals starts = x[:n-window]; ends = x[window:] widths = ends - starts # Just the intervals containing the peak select = (peak >= starts) & (peak <= ends) widths = widths[select] if len(widths) == 0: raise ValueError('Too few elements for interval calculation') min_idx = np.argmin(widths) lo = x[min_idx] hi = x[min_idx+window] return interval(peak,lo,hi)
[ "def", "peak_interval", "(", "data", ",", "alpha", "=", "_alpha", ",", "npoints", "=", "_npoints", ")", ":", "peak", "=", "kde_peak", "(", "data", ",", "npoints", ")", "x", "=", "np", ".", "sort", "(", "data", ".", "flat", ")", "n", "=", "len", "(", "x", ")", "# The number of entries in the interval", "window", "=", "int", "(", "np", ".", "rint", "(", "(", "1.0", "-", "alpha", ")", "*", "n", ")", ")", "# The start, stop, and width of all possible intervals", "starts", "=", "x", "[", ":", "n", "-", "window", "]", "ends", "=", "x", "[", "window", ":", "]", "widths", "=", "ends", "-", "starts", "# Just the intervals containing the peak", "select", "=", "(", "peak", ">=", "starts", ")", "&", "(", "peak", "<=", "ends", ")", "widths", "=", "widths", "[", "select", "]", "if", "len", "(", "widths", ")", "==", "0", ":", "raise", "ValueError", "(", "'Too few elements for interval calculation'", ")", "min_idx", "=", "np", ".", "argmin", "(", "widths", ")", "lo", "=", "x", "[", "min_idx", "]", "hi", "=", "x", "[", "min_idx", "+", "window", "]", "return", "interval", "(", "peak", ",", "lo", ",", "hi", ")" ]
Identify interval using Gaussian kernel density estimator.
[ "Identify", "interval", "using", "Gaussian", "kernel", "density", "estimator", "." ]
21e890b4117fc810afb6fb058e8055d564f03382
https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/utils/stats.py#L82-L101
train
DarkEnergySurvey/ugali
ugali/utils/stats.py
Samples.supplement
def supplement(self,coordsys='gal'): """ Add some supplemental columns """ from ugali.utils.projector import gal2cel, gal2cel_angle from ugali.utils.projector import cel2gal, cel2gal_angle coordsys = coordsys.lower() kwargs = dict(usemask=False, asrecarray=True) out = copy.deepcopy(self) if ('lon' in out.names) and ('lat' in out.names): # Ignore entries that are all zero zeros = np.all(self.ndarray==0,axis=1) if coordsys == 'gal': ra,dec = gal2cel(out.lon,out.lat) glon,glat = out.lon,out.lat else: ra,dec = out.lon,out.lat glon,glat = cel2gal(out.lon,out.lat) ra[zeros] = 0; dec[zeros] = 0 glon[zeros] = 0; glat[zeros] = 0 names = ['ra','dec','glon','glat'] arrs = [ra,dec,glon,glat] out = mlab.rec_append_fields(out,names,arrs).view(Samples) #out = recfuncs.append_fields(out,names,arrs,**kwargs).view(Samples) if 'position_angle' in out.names: if coordsys == 'gal': pa_gal = out.position_angle pa_cel = gal2cel_angle(out.lon,out.lat,out.position_angle) pa_cel = pa_cel - 180.*(pa_cel > 180.) else: pa_gal = cel2gal_angle(out.lon,out.lat,out.position_angle) pa_cel = out.position_angle pa_gal = pa_gal - 180.*(pa_gal > 180.) pa_gal[zeros] = 0; pa_cel[zeros] = 0 names = ['position_angle_gal','position_angle_cel'] arrs = [pa_gal,pa_cel] out = recfuncs.append_fields(out,names,arrs,**kwargs).view(Samples) return out
python
def supplement(self,coordsys='gal'): """ Add some supplemental columns """ from ugali.utils.projector import gal2cel, gal2cel_angle from ugali.utils.projector import cel2gal, cel2gal_angle coordsys = coordsys.lower() kwargs = dict(usemask=False, asrecarray=True) out = copy.deepcopy(self) if ('lon' in out.names) and ('lat' in out.names): # Ignore entries that are all zero zeros = np.all(self.ndarray==0,axis=1) if coordsys == 'gal': ra,dec = gal2cel(out.lon,out.lat) glon,glat = out.lon,out.lat else: ra,dec = out.lon,out.lat glon,glat = cel2gal(out.lon,out.lat) ra[zeros] = 0; dec[zeros] = 0 glon[zeros] = 0; glat[zeros] = 0 names = ['ra','dec','glon','glat'] arrs = [ra,dec,glon,glat] out = mlab.rec_append_fields(out,names,arrs).view(Samples) #out = recfuncs.append_fields(out,names,arrs,**kwargs).view(Samples) if 'position_angle' in out.names: if coordsys == 'gal': pa_gal = out.position_angle pa_cel = gal2cel_angle(out.lon,out.lat,out.position_angle) pa_cel = pa_cel - 180.*(pa_cel > 180.) else: pa_gal = cel2gal_angle(out.lon,out.lat,out.position_angle) pa_cel = out.position_angle pa_gal = pa_gal - 180.*(pa_gal > 180.) pa_gal[zeros] = 0; pa_cel[zeros] = 0 names = ['position_angle_gal','position_angle_cel'] arrs = [pa_gal,pa_cel] out = recfuncs.append_fields(out,names,arrs,**kwargs).view(Samples) return out
[ "def", "supplement", "(", "self", ",", "coordsys", "=", "'gal'", ")", ":", "from", "ugali", ".", "utils", ".", "projector", "import", "gal2cel", ",", "gal2cel_angle", "from", "ugali", ".", "utils", ".", "projector", "import", "cel2gal", ",", "cel2gal_angle", "coordsys", "=", "coordsys", ".", "lower", "(", ")", "kwargs", "=", "dict", "(", "usemask", "=", "False", ",", "asrecarray", "=", "True", ")", "out", "=", "copy", ".", "deepcopy", "(", "self", ")", "if", "(", "'lon'", "in", "out", ".", "names", ")", "and", "(", "'lat'", "in", "out", ".", "names", ")", ":", "# Ignore entries that are all zero", "zeros", "=", "np", ".", "all", "(", "self", ".", "ndarray", "==", "0", ",", "axis", "=", "1", ")", "if", "coordsys", "==", "'gal'", ":", "ra", ",", "dec", "=", "gal2cel", "(", "out", ".", "lon", ",", "out", ".", "lat", ")", "glon", ",", "glat", "=", "out", ".", "lon", ",", "out", ".", "lat", "else", ":", "ra", ",", "dec", "=", "out", ".", "lon", ",", "out", ".", "lat", "glon", ",", "glat", "=", "cel2gal", "(", "out", ".", "lon", ",", "out", ".", "lat", ")", "ra", "[", "zeros", "]", "=", "0", "dec", "[", "zeros", "]", "=", "0", "glon", "[", "zeros", "]", "=", "0", "glat", "[", "zeros", "]", "=", "0", "names", "=", "[", "'ra'", ",", "'dec'", ",", "'glon'", ",", "'glat'", "]", "arrs", "=", "[", "ra", ",", "dec", ",", "glon", ",", "glat", "]", "out", "=", "mlab", ".", "rec_append_fields", "(", "out", ",", "names", ",", "arrs", ")", ".", "view", "(", "Samples", ")", "#out = recfuncs.append_fields(out,names,arrs,**kwargs).view(Samples)", "if", "'position_angle'", "in", "out", ".", "names", ":", "if", "coordsys", "==", "'gal'", ":", "pa_gal", "=", "out", ".", "position_angle", "pa_cel", "=", "gal2cel_angle", "(", "out", ".", "lon", ",", "out", ".", "lat", ",", "out", ".", "position_angle", ")", "pa_cel", "=", "pa_cel", "-", "180.", "*", "(", "pa_cel", ">", "180.", ")", "else", ":", "pa_gal", "=", "cel2gal_angle", "(", "out", ".", "lon", ",", "out", ".", "lat", ",", "out", ".", "position_angle", ")", "pa_cel", "=", "out", ".", "position_angle", "pa_gal", "=", "pa_gal", "-", "180.", "*", "(", "pa_gal", ">", "180.", ")", "pa_gal", "[", "zeros", "]", "=", "0", "pa_cel", "[", "zeros", "]", "=", "0", "names", "=", "[", "'position_angle_gal'", ",", "'position_angle_cel'", "]", "arrs", "=", "[", "pa_gal", ",", "pa_cel", "]", "out", "=", "recfuncs", ".", "append_fields", "(", "out", ",", "names", ",", "arrs", ",", "*", "*", "kwargs", ")", ".", "view", "(", "Samples", ")", "return", "out" ]
Add some supplemental columns
[ "Add", "some", "supplemental", "columns" ]
21e890b4117fc810afb6fb058e8055d564f03382
https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/utils/stats.py#L201-L244
train
DarkEnergySurvey/ugali
ugali/utils/stats.py
Samples.median
def median(self, name, **kwargs): """ Median of the distribution. """ data = self.get(name,**kwargs) return np.percentile(data,[50])
python
def median(self, name, **kwargs): """ Median of the distribution. """ data = self.get(name,**kwargs) return np.percentile(data,[50])
[ "def", "median", "(", "self", ",", "name", ",", "*", "*", "kwargs", ")", ":", "data", "=", "self", ".", "get", "(", "name", ",", "*", "*", "kwargs", ")", "return", "np", ".", "percentile", "(", "data", ",", "[", "50", "]", ")" ]
Median of the distribution.
[ "Median", "of", "the", "distribution", "." ]
21e890b4117fc810afb6fb058e8055d564f03382
https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/utils/stats.py#L294-L299
train
DarkEnergySurvey/ugali
ugali/utils/stats.py
Samples.kde_peak
def kde_peak(self, name, npoints=_npoints, **kwargs): """ Calculate peak of kernel density estimator """ data = self.get(name,**kwargs) return kde_peak(data,npoints)
python
def kde_peak(self, name, npoints=_npoints, **kwargs): """ Calculate peak of kernel density estimator """ data = self.get(name,**kwargs) return kde_peak(data,npoints)
[ "def", "kde_peak", "(", "self", ",", "name", ",", "npoints", "=", "_npoints", ",", "*", "*", "kwargs", ")", ":", "data", "=", "self", ".", "get", "(", "name", ",", "*", "*", "kwargs", ")", "return", "kde_peak", "(", "data", ",", "npoints", ")" ]
Calculate peak of kernel density estimator
[ "Calculate", "peak", "of", "kernel", "density", "estimator" ]
21e890b4117fc810afb6fb058e8055d564f03382
https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/utils/stats.py#L312-L317
train
DarkEnergySurvey/ugali
ugali/utils/stats.py
Samples.kde
def kde(self, name, npoints=_npoints, **kwargs): """ Calculate kernel density estimator for parameter """ data = self.get(name,**kwargs) return kde(data,npoints)
python
def kde(self, name, npoints=_npoints, **kwargs): """ Calculate kernel density estimator for parameter """ data = self.get(name,**kwargs) return kde(data,npoints)
[ "def", "kde", "(", "self", ",", "name", ",", "npoints", "=", "_npoints", ",", "*", "*", "kwargs", ")", ":", "data", "=", "self", ".", "get", "(", "name", ",", "*", "*", "kwargs", ")", "return", "kde", "(", "data", ",", "npoints", ")" ]
Calculate kernel density estimator for parameter
[ "Calculate", "kernel", "density", "estimator", "for", "parameter" ]
21e890b4117fc810afb6fb058e8055d564f03382
https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/utils/stats.py#L319-L324
train
DarkEnergySurvey/ugali
ugali/utils/stats.py
Samples.peak_interval
def peak_interval(self, name, alpha=_alpha, npoints=_npoints, **kwargs): """ Calculate peak interval for parameter. """ data = self.get(name, **kwargs) return peak_interval(data,alpha,npoints)
python
def peak_interval(self, name, alpha=_alpha, npoints=_npoints, **kwargs): """ Calculate peak interval for parameter. """ data = self.get(name, **kwargs) return peak_interval(data,alpha,npoints)
[ "def", "peak_interval", "(", "self", ",", "name", ",", "alpha", "=", "_alpha", ",", "npoints", "=", "_npoints", ",", "*", "*", "kwargs", ")", ":", "data", "=", "self", ".", "get", "(", "name", ",", "*", "*", "kwargs", ")", "return", "peak_interval", "(", "data", ",", "alpha", ",", "npoints", ")" ]
Calculate peak interval for parameter.
[ "Calculate", "peak", "interval", "for", "parameter", "." ]
21e890b4117fc810afb6fb058e8055d564f03382
https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/utils/stats.py#L326-L331
train
DarkEnergySurvey/ugali
ugali/utils/stats.py
Samples.min_interval
def min_interval(self,name, alpha=_alpha, **kwargs): """ Calculate minimum interval for parameter. """ data = self.get(name, **kwargs) return min_interval(data,alpha)
python
def min_interval(self,name, alpha=_alpha, **kwargs): """ Calculate minimum interval for parameter. """ data = self.get(name, **kwargs) return min_interval(data,alpha)
[ "def", "min_interval", "(", "self", ",", "name", ",", "alpha", "=", "_alpha", ",", "*", "*", "kwargs", ")", ":", "data", "=", "self", ".", "get", "(", "name", ",", "*", "*", "kwargs", ")", "return", "min_interval", "(", "data", ",", "alpha", ")" ]
Calculate minimum interval for parameter.
[ "Calculate", "minimum", "interval", "for", "parameter", "." ]
21e890b4117fc810afb6fb058e8055d564f03382
https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/utils/stats.py#L333-L338
train
DarkEnergySurvey/ugali
ugali/utils/stats.py
Samples.results
def results(self, names=None, alpha=_alpha, mode='peak', **kwargs): """ Calculate the results for a set of parameters. """ if names is None: names = self.names ret = odict() for n in names: ret[n] = getattr(self,'%s_interval'%mode)(n, **kwargs) return ret
python
def results(self, names=None, alpha=_alpha, mode='peak', **kwargs): """ Calculate the results for a set of parameters. """ if names is None: names = self.names ret = odict() for n in names: ret[n] = getattr(self,'%s_interval'%mode)(n, **kwargs) return ret
[ "def", "results", "(", "self", ",", "names", "=", "None", ",", "alpha", "=", "_alpha", ",", "mode", "=", "'peak'", ",", "*", "*", "kwargs", ")", ":", "if", "names", "is", "None", ":", "names", "=", "self", ".", "names", "ret", "=", "odict", "(", ")", "for", "n", "in", "names", ":", "ret", "[", "n", "]", "=", "getattr", "(", "self", ",", "'%s_interval'", "%", "mode", ")", "(", "n", ",", "*", "*", "kwargs", ")", "return", "ret" ]
Calculate the results for a set of parameters.
[ "Calculate", "the", "results", "for", "a", "set", "of", "parameters", "." ]
21e890b4117fc810afb6fb058e8055d564f03382
https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/utils/stats.py#L340-L348
train
DarkEnergySurvey/ugali
ugali/utils/parabola.py
Parabola.densify
def densify(self, factor=10): """ Increase the density of points along the parabolic curve. """ x = [] y = [] for ii in range(0, len(self.x) - 2): p = Parabola(self.x[ii: ii + 3], self.y[ii: ii + 3]) x.append(np.linspace(self.x[ii], self.x[ii + 1], factor)[0: -1]) y.append(p(x[-1])) p = Parabola(self.x[len(self.x) - 3:], self.y[len(self.y) - 3:]) x.append(np.linspace(self.x[-2], self.x[-1], factor)[0: -1]) y.append(p(x[-1])) x.append([self.x[-1]]) y.append([self.y[-1]]) #f = scipy.interpolate.interp1d(np.concatenate(x), np.concatenate(y)) #x = np.linspace(self.x[0], self.x[-1], len(x) * factor) #return x, f(x) return np.concatenate(x), np.concatenate(y)
python
def densify(self, factor=10): """ Increase the density of points along the parabolic curve. """ x = [] y = [] for ii in range(0, len(self.x) - 2): p = Parabola(self.x[ii: ii + 3], self.y[ii: ii + 3]) x.append(np.linspace(self.x[ii], self.x[ii + 1], factor)[0: -1]) y.append(p(x[-1])) p = Parabola(self.x[len(self.x) - 3:], self.y[len(self.y) - 3:]) x.append(np.linspace(self.x[-2], self.x[-1], factor)[0: -1]) y.append(p(x[-1])) x.append([self.x[-1]]) y.append([self.y[-1]]) #f = scipy.interpolate.interp1d(np.concatenate(x), np.concatenate(y)) #x = np.linspace(self.x[0], self.x[-1], len(x) * factor) #return x, f(x) return np.concatenate(x), np.concatenate(y)
[ "def", "densify", "(", "self", ",", "factor", "=", "10", ")", ":", "x", "=", "[", "]", "y", "=", "[", "]", "for", "ii", "in", "range", "(", "0", ",", "len", "(", "self", ".", "x", ")", "-", "2", ")", ":", "p", "=", "Parabola", "(", "self", ".", "x", "[", "ii", ":", "ii", "+", "3", "]", ",", "self", ".", "y", "[", "ii", ":", "ii", "+", "3", "]", ")", "x", ".", "append", "(", "np", ".", "linspace", "(", "self", ".", "x", "[", "ii", "]", ",", "self", ".", "x", "[", "ii", "+", "1", "]", ",", "factor", ")", "[", "0", ":", "-", "1", "]", ")", "y", ".", "append", "(", "p", "(", "x", "[", "-", "1", "]", ")", ")", "p", "=", "Parabola", "(", "self", ".", "x", "[", "len", "(", "self", ".", "x", ")", "-", "3", ":", "]", ",", "self", ".", "y", "[", "len", "(", "self", ".", "y", ")", "-", "3", ":", "]", ")", "x", ".", "append", "(", "np", ".", "linspace", "(", "self", ".", "x", "[", "-", "2", "]", ",", "self", ".", "x", "[", "-", "1", "]", ",", "factor", ")", "[", "0", ":", "-", "1", "]", ")", "y", ".", "append", "(", "p", "(", "x", "[", "-", "1", "]", ")", ")", "x", ".", "append", "(", "[", "self", ".", "x", "[", "-", "1", "]", "]", ")", "y", ".", "append", "(", "[", "self", ".", "y", "[", "-", "1", "]", "]", ")", "#f = scipy.interpolate.interp1d(np.concatenate(x), np.concatenate(y))", "#x = np.linspace(self.x[0], self.x[-1], len(x) * factor) ", "#return x, f(x)", "return", "np", ".", "concatenate", "(", "x", ")", ",", "np", ".", "concatenate", "(", "y", ")" ]
Increase the density of points along the parabolic curve.
[ "Increase", "the", "density", "of", "points", "along", "the", "parabolic", "curve", "." ]
21e890b4117fc810afb6fb058e8055d564f03382
https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/utils/parabola.py#L83-L105
train
DarkEnergySurvey/ugali
ugali/utils/parabola.py
Parabola.profileUpperLimit
def profileUpperLimit(self, delta = 2.71): """ Compute one-sided upperlimit via profile method. """ a = self.p_2 b = self.p_1 if self.vertex_x < 0: c = self.p_0 + delta else: c = self.p_0 - self.vertex_y + delta if b**2 - 4. * a * c < 0.: print('WARNING') print(a, b, c) return 0. return max((np.sqrt(b**2 - 4. * a * c) - b) / (2. * a), (-1. * np.sqrt(b**2 - 4. * a * c) - b) / (2. * a))
python
def profileUpperLimit(self, delta = 2.71): """ Compute one-sided upperlimit via profile method. """ a = self.p_2 b = self.p_1 if self.vertex_x < 0: c = self.p_0 + delta else: c = self.p_0 - self.vertex_y + delta if b**2 - 4. * a * c < 0.: print('WARNING') print(a, b, c) return 0. return max((np.sqrt(b**2 - 4. * a * c) - b) / (2. * a), (-1. * np.sqrt(b**2 - 4. * a * c) - b) / (2. * a))
[ "def", "profileUpperLimit", "(", "self", ",", "delta", "=", "2.71", ")", ":", "a", "=", "self", ".", "p_2", "b", "=", "self", ".", "p_1", "if", "self", ".", "vertex_x", "<", "0", ":", "c", "=", "self", ".", "p_0", "+", "delta", "else", ":", "c", "=", "self", ".", "p_0", "-", "self", ".", "vertex_y", "+", "delta", "if", "b", "**", "2", "-", "4.", "*", "a", "*", "c", "<", "0.", ":", "print", "(", "'WARNING'", ")", "print", "(", "a", ",", "b", ",", "c", ")", "return", "0.", "return", "max", "(", "(", "np", ".", "sqrt", "(", "b", "**", "2", "-", "4.", "*", "a", "*", "c", ")", "-", "b", ")", "/", "(", "2.", "*", "a", ")", ",", "(", "-", "1.", "*", "np", ".", "sqrt", "(", "b", "**", "2", "-", "4.", "*", "a", "*", "c", ")", "-", "b", ")", "/", "(", "2.", "*", "a", ")", ")" ]
Compute one-sided upperlimit via profile method.
[ "Compute", "one", "-", "sided", "upperlimit", "via", "profile", "method", "." ]
21e890b4117fc810afb6fb058e8055d564f03382
https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/utils/parabola.py#L107-L123
train
DarkEnergySurvey/ugali
ugali/utils/parabola.py
Parabola.bayesianUpperLimit
def bayesianUpperLimit(self, alpha, steps=1.e5, plot=False): """ Compute one-sided upper limit using Bayesian Method of Helene. Several methods of increasing numerical stability have been implemented. """ x_dense, y_dense = self.densify() y_dense -= np.max(y_dense) # Numeric stability f = scipy.interpolate.interp1d(x_dense, y_dense, kind='linear') x = np.linspace(0., np.max(x_dense), steps) pdf = np.exp(f(x) / 2.) cut = (pdf / np.max(pdf)) > 1.e-10 x = x[cut] pdf = pdf[cut] #pdf /= pdf[0] #forbidden = np.nonzero(pdf < 1.e-10)[0] #if len(forbidden) > 0: # index = forbidden[0] # Numeric stability # x = x[0: index] # pdf = pdf[0: index] cdf = np.cumsum(pdf) cdf /= cdf[-1] cdf_reflect = scipy.interpolate.interp1d(cdf, x) return cdf_reflect(alpha)
python
def bayesianUpperLimit(self, alpha, steps=1.e5, plot=False): """ Compute one-sided upper limit using Bayesian Method of Helene. Several methods of increasing numerical stability have been implemented. """ x_dense, y_dense = self.densify() y_dense -= np.max(y_dense) # Numeric stability f = scipy.interpolate.interp1d(x_dense, y_dense, kind='linear') x = np.linspace(0., np.max(x_dense), steps) pdf = np.exp(f(x) / 2.) cut = (pdf / np.max(pdf)) > 1.e-10 x = x[cut] pdf = pdf[cut] #pdf /= pdf[0] #forbidden = np.nonzero(pdf < 1.e-10)[0] #if len(forbidden) > 0: # index = forbidden[0] # Numeric stability # x = x[0: index] # pdf = pdf[0: index] cdf = np.cumsum(pdf) cdf /= cdf[-1] cdf_reflect = scipy.interpolate.interp1d(cdf, x) return cdf_reflect(alpha)
[ "def", "bayesianUpperLimit", "(", "self", ",", "alpha", ",", "steps", "=", "1.e5", ",", "plot", "=", "False", ")", ":", "x_dense", ",", "y_dense", "=", "self", ".", "densify", "(", ")", "y_dense", "-=", "np", ".", "max", "(", "y_dense", ")", "# Numeric stability", "f", "=", "scipy", ".", "interpolate", ".", "interp1d", "(", "x_dense", ",", "y_dense", ",", "kind", "=", "'linear'", ")", "x", "=", "np", ".", "linspace", "(", "0.", ",", "np", ".", "max", "(", "x_dense", ")", ",", "steps", ")", "pdf", "=", "np", ".", "exp", "(", "f", "(", "x", ")", "/", "2.", ")", "cut", "=", "(", "pdf", "/", "np", ".", "max", "(", "pdf", ")", ")", ">", "1.e-10", "x", "=", "x", "[", "cut", "]", "pdf", "=", "pdf", "[", "cut", "]", "#pdf /= pdf[0]", "#forbidden = np.nonzero(pdf < 1.e-10)[0]", "#if len(forbidden) > 0:", "# index = forbidden[0] # Numeric stability", "# x = x[0: index]", "# pdf = pdf[0: index]", "cdf", "=", "np", ".", "cumsum", "(", "pdf", ")", "cdf", "/=", "cdf", "[", "-", "1", "]", "cdf_reflect", "=", "scipy", ".", "interpolate", ".", "interp1d", "(", "cdf", ",", "x", ")", "return", "cdf_reflect", "(", "alpha", ")" ]
Compute one-sided upper limit using Bayesian Method of Helene. Several methods of increasing numerical stability have been implemented.
[ "Compute", "one", "-", "sided", "upper", "limit", "using", "Bayesian", "Method", "of", "Helene", ".", "Several", "methods", "of", "increasing", "numerical", "stability", "have", "been", "implemented", "." ]
21e890b4117fc810afb6fb058e8055d564f03382
https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/utils/parabola.py#L125-L148
train
DarkEnergySurvey/ugali
ugali/utils/parabola.py
Parabola.bayesianUpperLimit2
def bayesianUpperLimit2(self, alpha, steps=1.e5, plot=False): """ Compute one-sided upper limit using Bayesian Method of Helene. """ cut = ((self.y / 2.) > -30.) # Numeric stability try: f = scipy.interpolate.interp1d(self.x[cut], self.y[cut], kind='cubic') except: f = scipy.interpolate.interp1d(self.x[cut], self.y[cut], kind='linear') x = np.linspace(0., np.max(self.x[cut]), steps) y = np.exp(f(x) / 2.) #forbidden = np.nonzero((y / np.exp(self.vertex_y / 2.)) < 1.e-10)[0] forbidden = np.nonzero((y / self.vertex_y) < 1.e-10)[0] if len(forbidden) > 0: index = forbidden[0] # Numeric stability x = x[0: index] y = y[0: index] cdf = np.cumsum(y) cdf /= cdf[-1] cdf_reflect = scipy.interpolate.interp1d(cdf, x) return cdf_reflect(alpha)
python
def bayesianUpperLimit2(self, alpha, steps=1.e5, plot=False): """ Compute one-sided upper limit using Bayesian Method of Helene. """ cut = ((self.y / 2.) > -30.) # Numeric stability try: f = scipy.interpolate.interp1d(self.x[cut], self.y[cut], kind='cubic') except: f = scipy.interpolate.interp1d(self.x[cut], self.y[cut], kind='linear') x = np.linspace(0., np.max(self.x[cut]), steps) y = np.exp(f(x) / 2.) #forbidden = np.nonzero((y / np.exp(self.vertex_y / 2.)) < 1.e-10)[0] forbidden = np.nonzero((y / self.vertex_y) < 1.e-10)[0] if len(forbidden) > 0: index = forbidden[0] # Numeric stability x = x[0: index] y = y[0: index] cdf = np.cumsum(y) cdf /= cdf[-1] cdf_reflect = scipy.interpolate.interp1d(cdf, x) return cdf_reflect(alpha)
[ "def", "bayesianUpperLimit2", "(", "self", ",", "alpha", ",", "steps", "=", "1.e5", ",", "plot", "=", "False", ")", ":", "cut", "=", "(", "(", "self", ".", "y", "/", "2.", ")", ">", "-", "30.", ")", "# Numeric stability", "try", ":", "f", "=", "scipy", ".", "interpolate", ".", "interp1d", "(", "self", ".", "x", "[", "cut", "]", ",", "self", ".", "y", "[", "cut", "]", ",", "kind", "=", "'cubic'", ")", "except", ":", "f", "=", "scipy", ".", "interpolate", ".", "interp1d", "(", "self", ".", "x", "[", "cut", "]", ",", "self", ".", "y", "[", "cut", "]", ",", "kind", "=", "'linear'", ")", "x", "=", "np", ".", "linspace", "(", "0.", ",", "np", ".", "max", "(", "self", ".", "x", "[", "cut", "]", ")", ",", "steps", ")", "y", "=", "np", ".", "exp", "(", "f", "(", "x", ")", "/", "2.", ")", "#forbidden = np.nonzero((y / np.exp(self.vertex_y / 2.)) < 1.e-10)[0]", "forbidden", "=", "np", ".", "nonzero", "(", "(", "y", "/", "self", ".", "vertex_y", ")", "<", "1.e-10", ")", "[", "0", "]", "if", "len", "(", "forbidden", ")", ">", "0", ":", "index", "=", "forbidden", "[", "0", "]", "# Numeric stability", "x", "=", "x", "[", "0", ":", "index", "]", "y", "=", "y", "[", "0", ":", "index", "]", "cdf", "=", "np", ".", "cumsum", "(", "y", ")", "cdf", "/=", "cdf", "[", "-", "1", "]", "cdf_reflect", "=", "scipy", ".", "interpolate", ".", "interp1d", "(", "cdf", ",", "x", ")", "return", "cdf_reflect", "(", "alpha", ")" ]
Compute one-sided upper limit using Bayesian Method of Helene.
[ "Compute", "one", "-", "sided", "upper", "limit", "using", "Bayesian", "Method", "of", "Helene", "." ]
21e890b4117fc810afb6fb058e8055d564f03382
https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/utils/parabola.py#L150-L171
train
DarkEnergySurvey/ugali
ugali/utils/parabola.py
Parabola.confidenceInterval
def confidenceInterval(self, alpha=0.6827, steps=1.e5, plot=False): """ Compute two-sided confidence interval by taking x-values corresponding to the largest PDF-values first. """ x_dense, y_dense = self.densify() y_dense -= np.max(y_dense) # Numeric stability f = scipy.interpolate.interp1d(x_dense, y_dense, kind='linear') x = np.linspace(0., np.max(x_dense), steps) # ADW: Why does this start at 0, which often outside the input range? # Wouldn't starting at xmin be better: #x = np.linspace(np.min(x_dense), np.max(x_dense), steps) pdf = np.exp(f(x) / 2.) cut = (pdf / np.max(pdf)) > 1.e-10 x = x[cut] pdf = pdf[cut] sorted_pdf_indices = np.argsort(pdf)[::-1] # Indices of PDF in descending value cdf = np.cumsum(pdf[sorted_pdf_indices]) cdf /= cdf[-1] sorted_pdf_index_max = np.argmin((cdf - alpha)**2) x_select = x[sorted_pdf_indices[0: sorted_pdf_index_max]] return np.min(x_select), np.max(x_select)
python
def confidenceInterval(self, alpha=0.6827, steps=1.e5, plot=False): """ Compute two-sided confidence interval by taking x-values corresponding to the largest PDF-values first. """ x_dense, y_dense = self.densify() y_dense -= np.max(y_dense) # Numeric stability f = scipy.interpolate.interp1d(x_dense, y_dense, kind='linear') x = np.linspace(0., np.max(x_dense), steps) # ADW: Why does this start at 0, which often outside the input range? # Wouldn't starting at xmin be better: #x = np.linspace(np.min(x_dense), np.max(x_dense), steps) pdf = np.exp(f(x) / 2.) cut = (pdf / np.max(pdf)) > 1.e-10 x = x[cut] pdf = pdf[cut] sorted_pdf_indices = np.argsort(pdf)[::-1] # Indices of PDF in descending value cdf = np.cumsum(pdf[sorted_pdf_indices]) cdf /= cdf[-1] sorted_pdf_index_max = np.argmin((cdf - alpha)**2) x_select = x[sorted_pdf_indices[0: sorted_pdf_index_max]] return np.min(x_select), np.max(x_select)
[ "def", "confidenceInterval", "(", "self", ",", "alpha", "=", "0.6827", ",", "steps", "=", "1.e5", ",", "plot", "=", "False", ")", ":", "x_dense", ",", "y_dense", "=", "self", ".", "densify", "(", ")", "y_dense", "-=", "np", ".", "max", "(", "y_dense", ")", "# Numeric stability", "f", "=", "scipy", ".", "interpolate", ".", "interp1d", "(", "x_dense", ",", "y_dense", ",", "kind", "=", "'linear'", ")", "x", "=", "np", ".", "linspace", "(", "0.", ",", "np", ".", "max", "(", "x_dense", ")", ",", "steps", ")", "# ADW: Why does this start at 0, which often outside the input range?", "# Wouldn't starting at xmin be better:", "#x = np.linspace(np.min(x_dense), np.max(x_dense), steps)", "pdf", "=", "np", ".", "exp", "(", "f", "(", "x", ")", "/", "2.", ")", "cut", "=", "(", "pdf", "/", "np", ".", "max", "(", "pdf", ")", ")", ">", "1.e-10", "x", "=", "x", "[", "cut", "]", "pdf", "=", "pdf", "[", "cut", "]", "sorted_pdf_indices", "=", "np", ".", "argsort", "(", "pdf", ")", "[", ":", ":", "-", "1", "]", "# Indices of PDF in descending value", "cdf", "=", "np", ".", "cumsum", "(", "pdf", "[", "sorted_pdf_indices", "]", ")", "cdf", "/=", "cdf", "[", "-", "1", "]", "sorted_pdf_index_max", "=", "np", ".", "argmin", "(", "(", "cdf", "-", "alpha", ")", "**", "2", ")", "x_select", "=", "x", "[", "sorted_pdf_indices", "[", "0", ":", "sorted_pdf_index_max", "]", "]", "return", "np", ".", "min", "(", "x_select", ")", ",", "np", ".", "max", "(", "x_select", ")" ]
Compute two-sided confidence interval by taking x-values corresponding to the largest PDF-values first.
[ "Compute", "two", "-", "sided", "confidence", "interval", "by", "taking", "x", "-", "values", "corresponding", "to", "the", "largest", "PDF", "-", "values", "first", "." ]
21e890b4117fc810afb6fb058e8055d564f03382
https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/utils/parabola.py#L174-L196
train
DarkEnergySurvey/ugali
ugali/utils/projector.py
hms2dec
def hms2dec(hms): """ Convert longitude from hours,minutes,seconds in string or 3-array format to decimal degrees. ADW: This really should be replaced by astropy """ DEGREE = 360. HOUR = 24. MINUTE = 60. SECOND = 3600. if isstring(hms): hour,minute,second = np.array(re.split('[hms]',hms))[:3].astype(float) else: hour,minute,second = hms.T decimal = (hour + minute * 1./MINUTE + second * 1./SECOND)*(DEGREE/HOUR) return decimal
python
def hms2dec(hms): """ Convert longitude from hours,minutes,seconds in string or 3-array format to decimal degrees. ADW: This really should be replaced by astropy """ DEGREE = 360. HOUR = 24. MINUTE = 60. SECOND = 3600. if isstring(hms): hour,minute,second = np.array(re.split('[hms]',hms))[:3].astype(float) else: hour,minute,second = hms.T decimal = (hour + minute * 1./MINUTE + second * 1./SECOND)*(DEGREE/HOUR) return decimal
[ "def", "hms2dec", "(", "hms", ")", ":", "DEGREE", "=", "360.", "HOUR", "=", "24.", "MINUTE", "=", "60.", "SECOND", "=", "3600.", "if", "isstring", "(", "hms", ")", ":", "hour", ",", "minute", ",", "second", "=", "np", ".", "array", "(", "re", ".", "split", "(", "'[hms]'", ",", "hms", ")", ")", "[", ":", "3", "]", ".", "astype", "(", "float", ")", "else", ":", "hour", ",", "minute", ",", "second", "=", "hms", ".", "T", "decimal", "=", "(", "hour", "+", "minute", "*", "1.", "/", "MINUTE", "+", "second", "*", "1.", "/", "SECOND", ")", "*", "(", "DEGREE", "/", "HOUR", ")", "return", "decimal" ]
Convert longitude from hours,minutes,seconds in string or 3-array format to decimal degrees. ADW: This really should be replaced by astropy
[ "Convert", "longitude", "from", "hours", "minutes", "seconds", "in", "string", "or", "3", "-", "array", "format", "to", "decimal", "degrees", "." ]
21e890b4117fc810afb6fb058e8055d564f03382
https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/utils/projector.py#L422-L440
train
DarkEnergySurvey/ugali
ugali/utils/projector.py
dms2dec
def dms2dec(dms): """ Convert latitude from degrees,minutes,seconds in string or 3-array format to decimal degrees. """ DEGREE = 360. HOUR = 24. MINUTE = 60. SECOND = 3600. # Be careful here, degree needs to be a float so that negative zero # can have its signbit set: # http://docs.scipy.org/doc/numpy-1.7.0/reference/c-api.coremath.html#NPY_NZERO if isstring(dms): degree,minute,second = np.array(re.split('[dms]',hms))[:3].astype(float) else: degree,minute,second = dms.T sign = np.copysign(1.0,degree) decimal = np.abs(degree) + minute * 1./MINUTE + second * 1./SECOND decimal *= sign return decimal
python
def dms2dec(dms): """ Convert latitude from degrees,minutes,seconds in string or 3-array format to decimal degrees. """ DEGREE = 360. HOUR = 24. MINUTE = 60. SECOND = 3600. # Be careful here, degree needs to be a float so that negative zero # can have its signbit set: # http://docs.scipy.org/doc/numpy-1.7.0/reference/c-api.coremath.html#NPY_NZERO if isstring(dms): degree,minute,second = np.array(re.split('[dms]',hms))[:3].astype(float) else: degree,minute,second = dms.T sign = np.copysign(1.0,degree) decimal = np.abs(degree) + minute * 1./MINUTE + second * 1./SECOND decimal *= sign return decimal
[ "def", "dms2dec", "(", "dms", ")", ":", "DEGREE", "=", "360.", "HOUR", "=", "24.", "MINUTE", "=", "60.", "SECOND", "=", "3600.", "# Be careful here, degree needs to be a float so that negative zero", "# can have its signbit set:", "# http://docs.scipy.org/doc/numpy-1.7.0/reference/c-api.coremath.html#NPY_NZERO", "if", "isstring", "(", "dms", ")", ":", "degree", ",", "minute", ",", "second", "=", "np", ".", "array", "(", "re", ".", "split", "(", "'[dms]'", ",", "hms", ")", ")", "[", ":", "3", "]", ".", "astype", "(", "float", ")", "else", ":", "degree", ",", "minute", ",", "second", "=", "dms", ".", "T", "sign", "=", "np", ".", "copysign", "(", "1.0", ",", "degree", ")", "decimal", "=", "np", ".", "abs", "(", "degree", ")", "+", "minute", "*", "1.", "/", "MINUTE", "+", "second", "*", "1.", "/", "SECOND", "decimal", "*=", "sign", "return", "decimal" ]
Convert latitude from degrees,minutes,seconds in string or 3-array format to decimal degrees.
[ "Convert", "latitude", "from", "degrees", "minutes", "seconds", "in", "string", "or", "3", "-", "array", "format", "to", "decimal", "degrees", "." ]
21e890b4117fc810afb6fb058e8055d564f03382
https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/utils/projector.py#L442-L464
train