code
stringlengths
1
18.2k
def leaves(value, prefix=None): """ LIKE items() BUT RECURSIVE, AND ONLY FOR THE LEAVES (non dict) VALUES SEE wrap_leaves FOR THE INVERSE :param value: THE Mapping TO TRAVERSE :param prefix: OPTIONAL PREFIX GIVEN TO EACH KEY :return: Data, WHICH EACH KEY BEING A PATH INTO value TREE """ prefix = coalesce(prefix, "") ou...
def _str(value, depth): """ FOR DEBUGGING POSSIBLY RECURSIVE STRUCTURES """ output = [] if depth >0 and _get(value, CLASS) in data_types: for k, v in value.items(): output.append(str(k) + "=" + _str(v, depth - 1)) return "{" + ",\n".join(output) + "}" elif depth >0 and is_list(value): for v in value: output.append(_str...
def leaves(self, prefix=None): """ LIKE items() BUT RECURSIVE, AND ONLY FOR THE LEAVES (non dict) VALUES """ prefix = coalesce(prefix, "") output = [] for k, v in self.items(): if _get(v, CLASS) in data_types: output.extend(wrap(v).leaves(prefix=prefix + literal_field(k) + ".")) else: output.append((prefix + literal_fi...
def serialize_value(self, value): """ Given a value, ensure that it is serialized properly :param value: :return: """ # Create a list of serialize methods to run the value through serialize_methods = [ self.serialize_model, self.serialize_json_string, self.serialize_list, self.serialize_dict ] # Run all of our serializ...
def serialize_model(self, value): """ Serializes a model and all of its prefetched foreign keys :param value: :return: """ # Check if the context value is a model if not isinstance(value, models.Model): return value # Serialize the model serialized_model = model_to_dict(value) # Check the model for cached foreign keys ...
def serialize_json_string(self, value): """ Tries to load an encoded json string back into an object :param json_string: :return: """ # Check if the value might be a json string if not isinstance(value, six.string_types): return value # Make sure it starts with a brace if not value.startswith('{') or value.startswith('...
def serialize_list(self, value): """ Ensure that all values of a list or tuple are serialized :return: """ # Check if this is a list or a tuple if not isinstance(value, (list, tuple)): return value # Loop over all the values and serialize the values return [ self.serialize_value(list_value) for list_value in value ]
def serialize_dict(self, value): """ Ensure that all values of a dictionary are properly serialized :param value: :return: """ # Check if this is a dict if not isinstance(value, dict): return value # Loop over all the values and serialize them return { dict_key: self.serialize_value(dict_value) for dict_key, dict_value...
def cache(self): """Return a cache instance.""" cache = self._cache or self.app.config.get('COLLECTIONS_CACHE') return import_string(cache) if isinstance(cache, six.string_types) \ else cache
def collections(self): """Get list of collections.""" # if cache server is configured, load collection from there if self.cache: return self.cache.get( self.app.config['COLLECTIONS_CACHE_KEY'])
def collections(self, values): """Set list of collections.""" # if cache server is configured, save collection list if self.cache: self.cache.set( self.app.config['COLLECTIONS_CACHE_KEY'], values)
def register_signals(self): """Register signals.""" from .models import Collection from .receivers import CollectionUpdater if self.app.config['COLLECTIONS_USE_PERCOLATOR']: from .percolator import collection_inserted_percolator, \ collection_removed_percolator, \ collection_updated_percolator # Register collection sig...
def unregister_signals(self): """Unregister signals.""" from .models import Collection from .percolator import collection_inserted_percolator, \ collection_removed_percolator, collection_updated_percolator # Unregister Record signals if hasattr(self, 'update_function'): signals.before_record_insert.disconnect(self.upda...
def init_app(self, app, **kwargs): """Flask application initialization.""" self.init_config(app) state = _AppState(app=app, cache=kwargs.get('cache')) app.extensions['invenio-collections'] = state return state
def _post_vote(user_bingo_board, field, vote): """ change vote on a field @param user_bingo_board: the user's bingo board or None @param field: the BingoField to vote on @param vote: the vote property from the HTTP POST @raises: VoteException: if user_bingo_board is None or the field does not belong to the user's bingo...
USE_SSE: try: votes = field.num_votes() redis.publish("word_votes", json.dumps({ 'site_id': game.site.id, 'word_id': field.word.id, 'vote_count': votes, })) redis.publish("field_vote", json.dumps({ 'site_id': game.site.id, 'field_id': field.id, 'vote': vote, })) except RedisConnectionError: # redis server not available...
def translate_exception(exc_info, initial_skip=0): """If passed an exc_info it will automatically rewrite the exceptions all the way down to the correct line numbers and frames. """ tb = exc_info[2] frames = [] # skip some internal frames if wanted for x in range(initial_skip): if tb is not None: tb = tb.tb_next initia...
fake_exc_info(exc_info[:2] + (tb,), template.filename, lineno)[2] frames.append(make_frame_proxy(tb)) tb = next # if we don't have any exceptions in the frames left, we have to reraise it unchanged. XXX: can we backup here? when could this happen? if not frames: reraise(exc_info[0], exc_info[1], exc_info[2]) return Pro...
def fake_exc_info(exc_info, filename, lineno): """Helper for `translate_exception`.""" exc_type, exc_value, tb = exc_info # figure the real context out if tb is not None: # if there is a local called __tonnikala_exception__, we get # rid of it to not break the debug functionality. locals = tb.tb_frame.f_locals.copy() l...
the code. This won't work # on some python environments such as google appengine try: if tb is None: location = 'template' else: function = tb.tb_frame.f_code.co_name if function == '__main__': location = 'top-level template code' elif function.startswith('__TK__block__'): location = 'block "%s"' % function[13:] elif f...
= sys.exc_info() new_tb = exc_info[2].tb_next # return without this frame return exc_info[:2] + (new_tb,)
def split_qs(string, delimiter='&'): """Split a string by the specified unquoted, not enclosed delimiter""" open_list = '[<{(' close_list = ']>})' quote_chars = '"\'' level = index = last_index = 0 quoted = False result = [] for index, letter in enumerate(string): if letter in quote_chars: if not quoted: quoted = True ...
def parse_qs(string): """Intelligently parse the query string""" result = {} for item in split_qs(string): # Split the query string by unquotes ampersants ('&') try: # Split the item by unquotes equal signs key, value = split_qs(item, delimiter='=') except ValueError: # Single value without equals sign result[item] = '...
def round(value, decimal=7, digits=None): """ ROUND TO GIVEN NUMBER OF DIGITS, OR GIVEN NUMBER OF DECIMAL PLACES decimal - NUMBER OF DIGITS AFTER DECIMAL POINT (NEGATIVE IS VALID) digits - NUMBER OF SIGNIFICANT DIGITS (LESS THAN 1 IS INVALID) """ if value == None: return None else: value = float(value) if digits != Non...
_round(value, decimal)
def floor(value, mod=1): """ x == floor(x, a) + mod(x, a) FOR ALL a, x RETURN None WHEN GIVEN INVALID ARGUMENTS """ if value == None: return None elif mod <= 0: return None elif mod == 1: return int(math_floor(value)) elif is_integer(mod): return int(math_floor(value / mod)) * mod else: return math_floor(value / mod) *...
def mod(value, mod=1): """ RETURN NON-NEGATIVE MODULO RETURN None WHEN GIVEN INVALID ARGUMENTS """ if value == None: return None elif mod <= 0: return None elif value < 0: return (value % mod + mod) % mod else: return value % mod
def ceiling(value, mod=1): """ RETURN SMALLEST INTEGER GREATER THAN value """ if value == None: return None mod = int(mod) v = int(math_floor(value + mod)) return v - (v % mod)
def MAX(values, *others): """ DECISIVE MAX :param values: :param others: :return: """ if others: from mo_logs import Log Log.warning("Calling wrong") return MAX([values] + list(others)) output = Null for v in values: if v == None: continue elif output == None or v > output: output = v else: pass return output
def DataLookup(fieldVal, db, lookupType, fieldName, histObj={}): """ Return new field value based on single-value lookup against MongoDB :param string fieldVal: input value to lookup :param MongoClient db: MongoClient instance connected to MongoDB :param string lookupType: Type of lookup to perform/MongoDB collection n...
def IncludesLookup(fieldVal, lookupType, db, fieldName, deriveFieldName='', deriveInput={}, histObj={}, overwrite=False, blankIfNoMatch=False): """ Return new field value based on whether or not original value includes AND excludes all words in a comma-delimited list queried from MongoDB :param string fieldVal: input v...
lookup_dict = { 'fieldName': fieldName } if lookupType == 'normIncludes': field_val_clean = _DataClean_(fieldVal) elif lookupType == 'deriveIncludes': if deriveFieldName == '' or deriveInput == {}: raise ValueError("for 'deriveIncludes' must specify both \ 'deriveFieldName' and 'deriveInput'") lookup_dict['deriveFieldN...
field_val_new = row['replace'] if lookupType == 'deriveIncludes': using[deriveFieldName] = deriveInput using['includes'] = row['includes'] using['excludes'] = row['excludes'] using['begins'] = row['begins'] using['ends'] = row['ends'] check_match = True break except KeyError as Key_error_obj: warnings.warn('schema erro...
def RegexLookup(fieldVal, db, fieldName, lookupType, histObj={}): """ Return a new field value based on match against regex queried from MongoDB :param string fieldVal: input value to lookup :param MongoClient db: MongoClient instance connected to MongoDB :param string lookupType: Type of lookup to perform/MongoDB coll...
= re.sub(row['pattern'], '', _DataClean_(field_val_new), flags=re.IGNORECASE) pattern = row['pattern'] break except KeyError as Key_error_obj: warnings.warn('schema error', Key_error_obj) if re_val: re_val.close() change = _CollectHistory_(lookupType=lookupType, fromVal=fieldVal, toVal=field_val_new, pattern=pattern) h...
def DeriveDataLookup(fieldName, db, deriveInput, overwrite=True, fieldVal='', histObj={}, blankIfNoMatch=False): """ Return new field value based on single or multi-value lookup against MongoDB :param string fieldName: Field name to query against :param MongoClient db: MongoClient instance connected to MongoDB :param d...
True else False check_match = True if l_val else False if l_val and (overwrite or (fieldVal == '')): try: field_val_new = l_val['value'] except KeyError as Key_error_obj: warnings.warn('schema error', Key_error_obj) elif blankIfNoMatch and not l_val: field_val_new = '' derive_using = {'blankIfNoMatch': 'no match found'...
def DeriveDataCopyValue(fieldName, deriveInput, overwrite, fieldVal, histObj={}): """ Return new value based on value from another field :param string fieldName: Field name to query against :param dict deriveInput: Values to perform lookup against: {"copyField1": "copyVal1"} :param bool overwrite: Should an existing fi...
def DeriveDataRegex(fieldName, db, deriveInput, overwrite, fieldVal, histObj={}, blankIfNoMatch=False): """ Return a new field value based on match (of another field) against regex queried from MongoDB :param string fieldName: Field name to query against :param MongoClient db: MongoClient instance connected to MongoDB ...
(fieldVal == '')): lookup_dict = { 'deriveFieldName': row, 'fieldName': fieldName } coll = db['deriveRegex'] re_val = coll.find(lookup_dict, ['pattern', 'replace']) for l_val in re_val: try: match = re.match(l_val['pattern'], _DataClean_(deriveInput[row]), flags=re.IGNORECASE) if match: field_val_new = re.sub(l_val['pa...
def _normalize_select(select, frum, schema=None): """ :param select: ONE SELECT COLUMN :param frum: TABLE TO get_columns() :param schema: SCHEMA TO LOOKUP NAMES FOR DEFINITIONS :return: AN ARRAY OF SELECT COLUMNS """ if not _Column: _late_import() if is_text(select): canonical = select = Data(value=select) else: select...
in frum.get_columns() if c.jx_type not in STRUCT ]) else: Log.error("do not know what to do") else: canonical.name = coalesce(select.name, select.value, select.aggregate) canonical.value = jx_expression(select.value, schema=schema) output.append(canonical) output = wrap(output) if any(n==None for n in output.name): Log...
def _normalize_select_no_context(select, schema=None): """ SAME NORMALIZE, BUT NO SOURCE OF COLUMNS """ if not _Column: _late_import() if is_text(select): select = Data(value=select) else: select = wrap(select) output = select.copy() if not select.value: output.name = coalesce(select.name, select.aggregate) if output.n...
is invalid select", name=output.name) output.aggregate = coalesce(canonical_aggregates[select.aggregate].name, select.aggregate, "none") output.default = coalesce(select.default, canonical_aggregates[output.aggregate].default) return output
def _normalize_edge(edge, dim_index, limit, schema=None): """ :param edge: Not normalized edge :param dim_index: Dimensions are ordered; this is this edge's index into that order :param schema: for context :return: a normalized edge """ if not _Column: _late_import() if not edge: Log.error("Edge has no value, or expres...
and not is_text(edge.value): Log.error("You must name compound and complex edges: {{edge}}", edge=edge) if is_container(edge.value) and not edge.domain: # COMPLEX EDGE IS SHORT HAND domain = _normalize_domain(schema=schema) domain.dimension = Data(fields=edge.value) return [Data( name=edge.name, value=jx_expression(edg...
def _normalize_group(edge, dim_index, limit, schema=None): """ :param edge: Not normalized groupby :param dim_index: Dimensions are ordered; this is this groupby's index into that order :param schema: for context :return: a normalized groupby """ if is_text(edge): if edge.endswith(".*"): prefix = edge[:-2] if schema: o...
Log.error("groupby does not accept complicated domains") if not edge.name and not is_text(edge.value): Log.error("You must name compound edges: {{edge}}", edge= edge) return wrap([{ "name": coalesce(edge.name, edge.value), "value": jx_expression(edge.value, schema=schema), "allowNulls": True, "dim":dim_index, "domain":...
def _map_term_using_schema(master, path, term, schema_edges): """ IF THE WHERE CLAUSE REFERS TO FIELDS IN THE SCHEMA, THEN EXPAND THEM """ output = FlatList() for k, v in term.items(): dimension = schema_edges[k] if isinstance(dimension, Dimension): domain = dimension.getDomain() if dimension.fields: if is_data(dimensi...
{f: vv}}) continue if len(dimension.fields) == 1 and is_variable_name(dimension.fields[0]): if domain.getPartByKey(v) is domain.NULL: output.append({"missing": {"field": dimension.fields[0]}}) else: output.append({"term": {dimension.fields[0]: v}}) continue if domain.partitions: part = domain.getPartByKey(v) if part is...
def _where_terms(master, where, schema): """ USE THE SCHEMA TO CONVERT DIMENSION NAMES TO ES FILTERS master - TOP LEVEL WHERE (FOR PLACING NESTED FILTERS) """ if is_data(where): if where.term: # MAP TERM try: output = _map_term_using_schema(master, [], where.term, schema.edges) return output except Exception as e: Log....
and_agg.append({"term": {es_field: vvv}}) or_agg.append({"and": and_agg}) output.append({"or": or_agg}) elif is_list(fields) and len(fields) == 1 and is_variable_name(fields[0]): output.append({"terms": {fields[0]: v}}) elif domain.partitions: output.append({"or": [domain.getPartByKey(vv).esfilter for vv in v]}) return...
def _normalize_sort(sort=None): """ CONVERT SORT PARAMETERS TO A NORMAL FORM SO EASIER TO USE """ if sort==None: return FlatList.EMPTY output = FlatList() for s in listwrap(sort): if is_text(s): output.append({"value": jx_expression(s), "sort": 1}) elif is_expression(s): output.append({"value": s, "sort": 1}) elif mo_m...
def vars(self, exclude_where=False, exclude_select=False): """ :return: variables in query """ def edges_get_all_vars(e): output = set() if is_text(e.value): output.add(e.value) if is_expression(e.value): output |= e.value.vars() if e.domain.key: output.add(e.domain.key) if e.domain.where: output |= e.domain.where.vars...
def wrap(query, container, namespace): """ NORMALIZE QUERY SO IT CAN STILL BE JSON """ if is_op(query, QueryOp) or query == None: return query query = wrap(query) table = container.get_table(query['from']) schema = table.schema output = QueryOp( frum=table, format=query.format, limit=mo_math.min(MAX_LIMIT, coalesce(que...
not mo_math.is_integer(output.limit) or output.limit < 0: Log.error("Expecting limit >= 0") output.isLean = query.isLean return output
def register_cache(self, cache_group): """ Register a cache_group with this manager. Use this method to register more complicated groups that you create yourself. Such as if you need to register several models each with different parameters. :param cache_group: The group to register. \ The group is registered with the ...
def register_model(self, key, *models, **kwargs): """ Register a cache_group with this manager. Use this method to register more simple groups where all models share the same parameters. Any arguments are treated as models that you would like to register. Any keyword arguments received are passed to the register method...
def invalidate_cache(self, klass, extra=None, **kwargs): """ Invalidate a cache for a specific class. This will loop through all registered groups that have registered the given model class and call their invalidate_cache method. All keyword arguments will be directly passed through to the group's invalidate_cache meth...
kwargs.pop('extra', {}) for group in self._registry.values(): if klass in group.models: e = extra.get(group.key) group.invalidate_cache(klass, extra=e, **kwargs)
def create_store_prompt(name): """Create a prompt which implements the `store` feature. :param name: name of the generator :return: prompt """ def _prompt(questions, answers=None, **kwargs): stored_answers = _read_stored_answers(name) to_store = [] for q in questions: if 'store' in q: if q.pop('store'): # remove it so ...
def memoize(function): """Memoizing function. Potentially not thread-safe, since it will return resuts across threads. Make sure this is okay with callers.""" _cache = {} @wraps(function) def wrapper(*args, **kwargs): key = str(args) + str(kwargs) if key not in _cache: _cache[key] = function(*args, **kwargs) return _ca...
def get_inflators_bdf_to_cn(data_year): ''' Calcule les ratios de calage (bdf sur cn pour année de données) à partir des masses de comptabilité nationale et des masses de consommation de bdf. ''' data_cn = get_cn_aggregates(data_year) data_bdf = get_bdf_aggregates(data_year) masses = data_cn.merge( data_bdf, left_index...
def get_inflators_cn_to_cn(target_year): ''' Calcule l'inflateur de vieillissement à partir des masses de comptabilité nationale. ''' data_year = find_nearest_inferior(data_years, target_year) data_year_cn_aggregates = get_cn_aggregates(data_year)['consoCN_COICOP_{}'.format(data_year)].to_dict() target_year_cn_aggregat...
def get_inflators(target_year): ''' Fonction qui calcule les ratios de calage (bdf sur cn pour année de données) et de vieillissement à partir des masses de comptabilité nationale et des masses de consommation de bdf. ''' data_year = find_nearest_inferior(data_years, target_year) inflators_bdf_to_cn = get_inflators_bdf...
def map_to_array(pairs): """ MAP THE (tuid, line) PAIRS TO A SINGLE ARRAY OF TUIDS :param pairs: :return: """ if pairs: pairs = [TuidMap(*p) for p in pairs] max_line = max(p.line for p in pairs) tuids = [None] * max_line for p in pairs: if p.line: # line==0 IS A PLACEHOLDER FOR FILES THAT DO NOT EXIST tuids[p.line-1] =...
def dwmAll(data, db, configName='', config={}, udfNamespace=__name__, verbose=False): """ Return list of dictionaries after cleaning rules have been applied; optionally with a history record ID appended. :param list data: list of dictionaries (records) to which cleaning rules should be applied :param MongoClient db: Mo...
if not config: raise Exception("configName '" + configName + "' not found in collection 'config'") writeContactHistory = config["history"]["writeContactHistory"] returnHistoryId = config["history"]["returnHistoryId"] returnHistoryField = config["history"]["returnHistoryField"] histIdField = config["history"]["histIdFie...
def dwmOne(data, db, config, writeContactHistory=True, returnHistoryId=True, histIdField={"name": "emailAddress", "value": "emailAddress"}, udfNamespace=__name__): """ Return a single dictionary (record) after cleaning rules have been applied; optionally insert history record to collection 'contactHistory' :param dict ...
= config['fields'] ## Run user-defined functions data, history = _RunUserDefinedFunctions_(config=config, data=data, histObj=history, position="beforeGenericValidation", namespace=udfNamespace) # Run generic validation lookup data, history = lookupAll(data=data, configFields=fieldConfig, lookupType='genericLookup', db=...
user-defined functions data, history = _RunUserDefinedFunctions_(config=config, data=data, histObj=history, position="beforeNormalizationRegex", namespace=udfNamespace) # Run normalization regex data, history = lookupAll(data=data, configFields=fieldConfig, lookupType='normRegex', db=db, histObj=history) ## Run user-de...
DB historyId = db['contactHistory'].insert_one(history).inserted_id if writeContactHistory and returnHistoryId: return data, historyId else: return data, None
def wait(self): """ PUT THREAD IN WAIT STATE UNTIL SIGNAL IS ACTIVATED """ if self._go: return True with self.lock: if self._go: return True stopper = _allocate_lock() stopper.acquire() if not self.waiting_threads: self.waiting_threads = [stopper] else: self.waiting_threads.append(stopper) DEBUG and self._name and Log....
def go(self): """ ACTIVATE SIGNAL (DOES NOTHING IF SIGNAL IS ALREADY ACTIVATED) """ DEBUG and self._name and Log.note("GO! {{name|quote}}", name=self.name) if self._go: return with self.lock: if self._go: return self._go = True DEBUG and self._name and Log.note("internal GO! {{name|quote}}", name=self.name) jobs, self....
def on_go(self, target): """ RUN target WHEN SIGNALED """ if not target: Log.error("expecting target") with self.lock: if not self._go: DEBUG and self._name and Log.note("Adding target to signal {{name|quote}}", name=self.name) if not self.job_queue: self.job_queue = [target] else: self.job_queue.append(target) return ...
def remove_go(self, target): """ FOR SAVING MEMORY """ with self.lock: if not self._go: try: self.job_queue.remove(target) except ValueError: pass
def _jx_expression(expr, lang): """ WRAP A JSON EXPRESSION WITH OBJECT REPRESENTATION """ if is_expression(expr): # CONVERT TO lang new_op = lang[expr.id] if not new_op: # CAN NOT BE FOUND, TRY SOME PARTIAL EVAL return language[expr.id].partial_eval() return expr # return new_op(expr.args) # THIS CAN BE DONE, BUT IT NE...
THIS LANGUAGE DOES NOT SUPPORT THIS OPERATOR, GOTO BASE LANGUAGE AND GET THE MACRO class_ = language[op.id] output = class_.define(expr).partial_eval() return _jx_expression(output, lang) else: if not items: return NULL raise Log.error("{{instruction|json}} is not known", instruction=items) except Exception as e: Log.e...
def define(cls, expr): """ GENERAL SUPPORT FOR BUILDING EXPRESSIONS FROM JSON EXPRESSIONS OVERRIDE THIS IF AN OPERATOR EXPECTS COMPLICATED PARAMETERS :param expr: Data representing a JSON Expression :return: parse tree """ try: lang = cls.lang items = items_(expr) for item in items: op, term = item full_op = operators....
items}, **clauses) else: return class_(_jx_expression(term, lang), **clauses) else: if op in ["literal", "date", "offset"]: return class_(term, **clauses) else: return class_(_jx_expression(term, lang), **clauses) except Exception as e: Log.error("programmer error expr = {{value|quote}}", value=expr, cause=e)
def missing(self): """ THERE IS PLENTY OF OPPORTUNITY TO SIMPLIFY missing EXPRESSIONS OVERRIDE THIS METHOD TO SIMPLIFY :return: """ if self.type == BOOLEAN: Log.error("programmer error") return self.lang[MissingOp(self)]
def wait(self, till=None): """ THE ASSUMPTION IS wait() WILL ALWAYS RETURN WITH THE LOCK ACQUIRED :param till: WHEN TO GIVE UP WAITING FOR ANOTHER THREAD TO SIGNAL :return: True IF SIGNALED TO GO, False IF till WAS SIGNALED """ waiter = Signal() if self.waiting: DEBUG and _Log.note("waiting with {{num}} others on {{nam...
def setup(self): """ Defers loading until needed. Compares the existing mapping for each language with the current codebase. If they differ, it automatically updates the index. """ # Get the existing mapping & cache it. We'll compare it # during the ``update`` & if it doesn't match, we'll put the new # mapping. for lan...
self.silently_fail: raise self.setup_complete = True
def clear(self, models=None, commit=True): """ Clears all indexes for the current project. :param models: if specified, only deletes the entries for the given models. :param commit: This is ignored by Haystack (maybe a bug?) """ for language in self.languages: self.log.debug('clearing index for {0}'.format(language)) s...
def update(self, index, iterable, commit=True): """ Updates the index with current data. :param index: The search_indexes.Index object :param iterable: The queryset :param commit: commit to the backend. """ parler = False # setup here because self.existing_mappings are overridden. if not self.setup_complete: try: self....
def build_schema(self, fields, language): """ Build the index schema for the given field. New argument language. :param fields: :param language: the language code :return: a dictionary wit the field name (string) and the mapping configuration (dictionary) """ content_field_name = '' mapping = { DJANGO_CT: {'type': 'str...
def search(self, query_string, **kwargs): """ The main search method :param query_string: The string to pass to Elasticsearch. e.g. '*:*' :param kwargs: start_offset, end_offset, result_class :return: result_class instance """ self.index_name = self._index_name_for_language(translation.get_language()) # self.log.debug(...
def remove(self, obj_or_string, commit=True): """ Removes an object from the index. :param obj_or_string: :param commit: """ if not self.setup_complete: try: self.setup() except elasticsearch.TransportError as e: if not self.silently_fail: raise doc_id = get_identifier(obj_or_string) self.log.error("Failed to remove do...
def get(): """Returns the current version without importing pymds.""" pkgnames = find_packages() if len(pkgnames) == 0: raise ValueError("Can't find any packages") pkgname = pkgnames[0] content = open(join(pkgname, '__init__.py')).read() c = re.compile(r"__version__ *= *('[^']+'|\"[^\"]+\")") m = c.search(content) if m...
def store_integers(items, allow_zero=True): """Store integers from the given list in a storage. This is an example function to show autodoc style. Return :class:`Storage` instance with integers from the given list. Examples:: >>> storage = store_integers([1, 'foo', 2, 'bar', 0]) >>> storage.items [1, 2, 0] >>> storage ...
def add_item(self, item): """Append item to the list. :attr:`last_updated` will be set to :py:meth:`datetime.datetime.now`. :param item: Something to append to :attr:`items`. """ self.items.append(item) self.last_updated = datetime.datetime.now()
def map_http_status_to_exception(http_code): """ Bind a HTTP status to an HttpError. :param http_code: The HTTP code :type http_code: int :return The HttpError that fits to the http_code or HttpError. :rtype Any subclass of HttpError or HttpError """ http_exceptions = HttpError.__subclasses__() for http_exception in ht...
def Lomb_Scargle(data, precision, min_period, max_period, period_jobs=1): """ Returns the period of *data* according to the `Lomb-Scargle periodogram <https://en.wikipedia.org/wiki/Least-squares_spectral_analysis#The_Lomb.E2.80.93Scargle_periodogram>`_. **Parameters** data : array-like, shape = [n_samples, 2] or [n_sam...
def conditional_entropy(data, precision, min_period, max_period, xbins=10, ybins=5, period_jobs=1): """ Returns the period of *data* by minimizing conditional entropy. See `link <http://arxiv.org/pdf/1306.6664v2.pdf>`_ [GDDMD] for details. **Parameters** data : array-like, shape = [n_samples, 2] or [n_samples, 3] Array...
: number The period of *data*. **Citations** .. [GDDMD] Graham, Matthew J. ; Drake, Andrew J. ; Djorgovski, S. G. ; Mahabal, Ashish A. ; Donalek, Ciro, 2013, Monthly Notices of the Royal Astronomical Society, Volume 434, Issue 3, p.2629-2635 """ periods = np.arange(min_period, max_period, precision) copy = np.ma.copy(d...
def CE(period, data, xbins=10, ybins=5): """ Returns the conditional entropy of *data* rephased with *period*. **Parameters** period : number The period to rephase *data* by. data : array-like, shape = [n_samples, 2] or [n_samples, 3] Array containing columns *time*, *mag*, and (optional) *error*. xbins : int, optional...
# for i in np.arange(0, xbins) # for j in np.arange(0, ybins)) if size > 0 else np.PINF # ----------------------------------------------------------------------- # TODO: replace this comment with something that's not old code if size > 0: # bins[i,j] / size divided_bins = bins / size # indices where that is positive # ...
initialize the result array A = np.empty((xbins, ybins), dtype=float) # store at every index [i,j] in A which corresponds to a positive bin: # bins[i,j]/size * log(bins[i,:] / size / (bins[i,j]/size)) A[ arg_positive] = select_divided_bins \ * np.log(select_column_sums / select_divided_bins) # store 0 at every index in...
def find_period(data, min_period=0.2, max_period=32.0, coarse_precision=1e-5, fine_precision=1e-9, periodogram=Lomb_Scargle, period_jobs=1): """find_period(data, min_period=0.2, max_period=32.0, coarse_precision=1e-5, fine_precision=1e-9, periodogram=Lomb_Scargle, period_jobs=1) Returns the period of *data* according t...