code
stringlengths
1
18.2k
def inverse(d): """ reverse the k:v pairs """ output = {} for k, v in unwrap(d).items(): output[v] = output.get(v, []) output[v].append(k) return output
def zip(keys, values): """ CONVERT LIST OF KEY/VALUE PAIRS TO Data PLEASE `import dot`, AND CALL `dot.zip()` """ output = Data() for i, k in enumerate(keys): if i >= len(values): break output[k] = values[i] return output
def tail_field(field): """ RETURN THE FIRST STEP IN PATH, ALONG WITH THE REMAINING TAIL """ if field == "." or field==None: return ".", "." elif "." in field: if "\\." in field: return tuple(k.replace("\a", ".") for k in field.replace("\\.", "\a").split(".", 1)) else: return field.split(".", 1) else: return field, "."
def split_field(field): """ RETURN field AS ARRAY OF DOT-SEPARATED FIELDS """ if field == "." or field==None: return [] elif is_text(field) and "." in field: if field.startswith(".."): remainder = field.lstrip(".") back = len(field) - len(remainder) - 1 return [-1]*back + [k.replace("\a", ".") for k in remainder.replac...
def join_field(path): """ RETURN field SEQUENCE AS STRING """ output = ".".join([f.replace(".", "\\.") for f in path if f != None]) return output if output else "."
def startswith_field(field, prefix): """ RETURN True IF field PATH STRING STARTS WITH prefix PATH STRING """ if prefix.startswith("."): return True # f_back = len(field) - len(field.strip(".")) # p_back = len(prefix) - len(prefix.strip(".")) # if f_back > p_back: # return False # else: # return True if field.startswith...
def relative_field(field, parent): """ RETURN field PATH WITH RESPECT TO parent """ if parent==".": return field field_path = split_field(field) parent_path = split_field(parent) common = 0 for f, p in _builtin_zip(field_path, parent_path): if f != p: break common += 1 if len(parent_path) == common: return join_field(f...
def _setdefault(obj, key, value): """ DO NOT USE __dict__.setdefault(obj, key, value), IT DOES NOT CHECK FOR obj[key] == None """ v = obj.get(key) if v == None: obj[key] = value return value return v
def set_default(*params): """ INPUT dicts IN PRIORITY ORDER UPDATES FIRST dict WITH THE MERGE RESULT, WHERE MERGE RESULT IS DEFINED AS: FOR EACH LEAF, RETURN THE HIGHEST PRIORITY LEAF VALUE """ p0 = params[0] agg = p0 if p0 or _get(p0, CLASS) in data_types else {} for p in params[1:]: p = unwrap(p) if p is None: contin...
def _all_default(d, default, seen=None): """ ANY VALUE NOT SET WILL BE SET BY THE default THIS IS RECURSIVE """ if default is None: return if _get(default, CLASS) is Data: default = object.__getattribute__(default, SLOT) # REACH IN AND GET THE dict # Log = _late_import() # Log.error("strictly dict (or object) allowed: ...
[k], default_value) except Exception as e: if PATH_NOT_FOUND not in e: get_logger().error("Can not set attribute {{name}}", name=k, cause=e) elif is_list(existing_value) or is_list(default_value): _set_attr(d, [k], None) _set_attr(d, [k], listwrap(existing_value) + listwrap(default_value)) elif (hasattr(existing_value,...
def _getdefault(obj, key): """ obj MUST BE A DICT key IS EXPECTED TO BE LITERAL (NO ESCAPING) TRY BOTH ATTRIBUTE AND ITEM ACCESS, OR RETURN Null """ try: return obj[key] except Exception as f: pass try: return getattr(obj, key) except Exception as f: pass try: if float(key) == round(float(key), 0): return obj[int(key)]...
def set_attr(obj, path, value): """ SAME AS object.__setattr__(), BUT USES DOT-DELIMITED path RETURN OLD VALUE """ try: return _set_attr(obj, split_field(path), value) except Exception as e: Log = get_logger() if PATH_NOT_FOUND in e: Log.warning(PATH_NOT_FOUND + ": {{path}}", path=path, cause=e) else: Log.error("Proble...
def get_attr(obj, path): """ SAME AS object.__getattr__(), BUT USES DOT-DELIMITED path """ try: return _get_attr(obj, split_field(path)) except Exception as e: Log = get_logger() if PATH_NOT_FOUND in e: Log.error(PATH_NOT_FOUND+": {{path}}", path=path, cause=e) else: Log.error("Problem setting value", e)
def wrap(v): """ WRAP AS Data OBJECT FOR DATA PROCESSING: https://github.com/klahnakoski/mo-dots/tree/dev/docs :param v: THE VALUE TO WRAP :return: Data INSTANCE """ type_ = _get(v, CLASS) if type_ is dict: m = object.__new__(Data) _set(m, SLOT, v) return m elif type_ is none_type: return Null elif type_ is list: retur...
def listwrap(value): """ PERFORMS THE FOLLOWING TRANSLATION None -> [] value -> [value] [...] -> [...] (unchanged list) ##MOTIVATION## OFTEN IT IS NICE TO ALLOW FUNCTION PARAMETERS TO BE ASSIGNED A VALUE, OR A list-OF-VALUES, OR NULL. CHECKING FOR WHICH THE CALLER USED IS TEDIOUS. INSTEAD WE CAST FROM THOSE THREE CASES...
def unwraplist(v): """ LISTS WITH ZERO AND ONE element MAP TO None AND element RESPECTIVELY """ if is_list(v): if len(v) == 0: return None elif len(v) == 1: return unwrap(v[0]) else: return unwrap(v) else: return unwrap(v)
def tuplewrap(value): """ INTENDED TO TURN lists INTO tuples FOR USE AS KEYS """ if isinstance(value, (list, set, tuple) + generator_types): return tuple(tuplewrap(v) if is_sequence(v) else v for v in value) return unwrap(value),
def get_slanted_adjacent_coords(x, y): ''' returns the six adjacent coordinates on a standard keyboard, where each row is slanted to the right from the last. adjacencies are clockwise, starting with key to the left, then two keys above, then right key, then two keys below. (that is, only near-diagonal keys are adjacent...
def get_aligned_adjacent_coords(x, y): ''' returns the nine clockwise adjacent coordinates on a keypad, where each row is vertically aligned. ''' return [(x-1, y), (x-1, y-1), (x, y-1), (x+1, y-1), (x+1, y), (x+1, y+1), (x, y+1), (x-1, y+1)]
def build_graph(layout_str, slanted): ''' builds an adjacency graph as a dictionary: {character: [adjacent_characters]}. adjacent characters occur in a clockwise order. for example: * on qwerty layout, 'g' maps to ['fF', 'tT', 'yY', 'hH', 'bB', 'vV'] * on keypad layout, '7' maps to [None, None, None, '=', '8', '5', '4'...
illustrated keys above, each qwerty row is indented one space in from the last for token in line.split(): x, remainder = divmod(line.index(token) - slant, x_unit) assert remainder == 0, 'unexpected x offset for %s in:\n%s' % (token, layout_str) position_table[(x,y)] = token adjacency_graph = {} for (x,y), chars in posi...
def calcul_ratios_calage(year_data, year_calage, data_bdf, data_cn): ''' 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. ''' masses = data_cn.merge( data_bdf, left_index = True, right_in...
def get_bdf_data_frames(depenses, year_data = None): assert year_data is not None ''' Récupère les dépenses de budget des familles et les agrège par poste (en tenant compte des poids respectifs des ménages) ''' depenses_by_grosposte = pandas.DataFrame() for grosposte in range(1, 13): if depenses_by_grosposte is None: d...
def _make_rofr_rdf(app, api_home_dir, api_uri): """ The setup function that creates the Register of Registers. Do not call from outside setup :param app: the Flask app containing this LDAPI :type app: Flask app :param api_uri: URI base of the API :type api_uri: string :return: none :rtype: None """ from time import sle...
app.view_functions[rule.endpoint] except (AttributeError, KeyError): continue try: candidate_register_uri = api_uri + str( rule) + '?_view=reg&_format=_internal' test_context = app.test_request_context(candidate_register_uri) with test_context: resp = endpoint_func() except RegOfRegTtlError: # usually an RofR renderer ...
def get_filtered_register_graph(register_uri, g): """ Gets a filtered version (label, comment, contained item classes & subregisters only) of the each register for the Register of Registers :param register_uri: the public URI of the register :type register_uri: string :param g: the rdf graph to append registers to :typ...
def clear_cache_delete_selected(modeladmin, request, queryset): """ A delete action that will invalidate cache after being called. """ result = delete_selected(modeladmin, request, queryset) # A result of None means that the delete happened. if not result and hasattr(modeladmin, 'invalidate_cache'): modeladmin.invalida...
def invalidate_cache(self, obj=None, queryset=None, extra=None, force_all=False): """ Method that should be called by all tiggers to invalidate the cache for an item(s). Should be overriden by inheriting classes to customize behavior. """ if self.cache_manager: if queryset != None: force_all = True self.cache_manager.i...
def connect(self, host, port): """Connect to a host on a given port. If the hostname ends with a colon (`:') followed by a number, and there is no port specified, that suffix will be stripped off and the number interpreted as the port number to use. """ if not port and (host.find(':') == host.rfind(':')): i = host.rfin...
self.debuglevel > 0: print 'connect fail:', (host, port) self.close() continue break if not self.sock: raise socket.error, msg
def waiting(self, timeout=0): "Return True if data is ready for the client." if self.linebuffer: return True (winput, woutput, wexceptions) = select.select((self.sock,), (), (), timeout) return winput != []
def read(self): "Wait for and read data being streamed from the daemon." if self.verbose > 1: sys.stderr.write("poll: reading from daemon...\n") eol = self.linebuffer.find('\n') if eol == -1: frag = self.sock.recv(4096) self.linebuffer += frag if self.verbose > 1: sys.stderr.write("poll: read complete.\n") if not self....
We got a \n-terminated line return len(self.response)
def send(self, commands): "Ship commands to the daemon." if not commands.endswith("\n"): commands += "\n" self.sock.send(commands)
def stream(self, flags=0, devpath=None): "Control streaming reports from the daemon," if flags & WATCH_DISABLE: arg = '?WATCH={"enable":false' if flags & WATCH_JSON: arg += ',"json":false' if flags & WATCH_NMEA: arg += ',"nmea":false' if flags & WATCH_RARE: arg += ',"raw":1' if flags & WATCH_RAW: arg += ',"raw":2' if f...
def make_app(global_conf, full_stack=True, **app_conf): """ Set tg2-raptorized up with the settings found in the PasteDeploy configuration file used. :param global_conf: The global settings for tg2-raptorized (those defined under the ``[DEFAULT]`` section). :type global_conf: dict :param full_stack: Should the whole TG...
def CalcRad(lat): "Radius of curvature in meters at specified latitude." a = 6378.137 e2 = 0.081082 * 0.081082 # the radius of curvature of an ellipsoidal Earth in the plane of a # meridian of latitude is given by # # R' = a * (1 - e^2) / (1 - e^2 * (sin(lat))^2)^(3/2) # # where a is the equatorial radius, # b is the p...
* sc * sc y = pow(z, 1.5) r = x / y r = r * 1000.0 # Convert to meters return r
def EarthDistance((lat1, lon1), (lat2, lon2)): "Distance in meters between two points specified in degrees." x1 = CalcRad(lat1) * math.cos(Deg2Rad(lon1)) * math.sin(Deg2Rad(90-lat1)) x2 = CalcRad(lat2) * math.cos(Deg2Rad(lon2)) * math.sin(Deg2Rad(90-lat2)) y1 = CalcRad(lat1) * math.sin(Deg2Rad(lon1)) * math.sin(Deg2Rad...
def MeterOffset((lat1, lon1), (lat2, lon2)): "Return offset in meters of second arg from first." dx = EarthDistance((lat1, lon1), (lat1, lon2)) dy = EarthDistance((lat1, lon1), (lat2, lon1)) if lat1 < lat2: dy *= -1 if lon1 < lon2: dx *= -1 return (dx, dy)
def isotime(s): "Convert timestamps in ISO8661 format to and from Unix time." if type(s) == type(1): return time.strftime("%Y-%m-%dT%H:%M:%S", time.gmtime(s)) elif type(s) == type(1.0): date = int(s) msec = s - date date = time.strftime("%Y-%m-%dT%H:%M:%S", time.gmtime(s)) return date + "." + repr(msec)[3:] elif type(s...
def not_found(entity_id=None, message='Entity not found'): """ Build a response to indicate that the requested entity was not found. :param string message: An optional message, defaults to 'Entity not found' :param string entity_id: An option ID of the entity requested and which was not found :return: A flask Response ...
def requires_auth(self, roles=None): """ Used to impose auth constraints on requests which require a logged in user with particular roles. :param list[string] roles: A list of :class:`string` representing roles the logged in user must have to perform this action. The user and password are passed in each request in the ...
@wraps(f) def decorated(*args, **kwargs): auth = request.authorization if not auth: return MeteorApp.authentication_failure(message='No authorization header supplied') user_id = auth.username password = auth.password try: db = self.get_db() user = db.get_user(user_id=user_id, password=password) if user is None: return ...
def switch_charset(characters, target=''): ''' Transforms an iterable of kana characters to its opposite script. For example, it can turn [u'あ', u'い'] into [u'ア', u'イ'], or {u'ホ': u'ボ} into {u'ほ': u'ぼ'}. There are no safety checks--keep in mind that the correct source and target values must be set, otherwise the result...
def _switch_charset_dict(characters, target=''): ''' Switches the character set of the key/value pairs in a dictionary. ''' offset_characters = {} offset = block_offset * offsets[target]['direction'] for char in characters: offset_key = chr(ord(char) + offset) offset_value = chr(ord(characters[char]) + offset) offset_c...
def _switch_charset_list(characters, target=''): ''' Switches the character set of a list. If a character does not have an equivalent in the target script (e.g. ヹ when converting to hiragana), the original character is kept. ''' # Copy the list to avoid modifying the existing one. characters = characters[:] offset = bl...
def kana_romaji_lt(romaji, *kana): ''' Generates a lookup table with the kana characters on the left side and their rōmaji equivalents as the values. For the consonant-vowel (cv) characters, we'll generate: {u'か': ('ka', 'k', 'k', 'ā'), u'が': ('ga', 'g', 'g', 'ā'), [...] Multiple kana character sets can be passed as re...
def fw_romaji_lt(full, regular): ''' Generates a lookup table with the fullwidth rōmaji characters on the left side, and the regular rōmaji characters as the values. ''' lt = {} for n in range(len(full)): fw = full[n] reg = regular[n] lt[fw] = reg return lt
def get_cache_prefix(self, prefix=''): """ Hook for any extra data you would like to prepend to your cache key. The default implementation ensures that ajax not non ajax requests are cached separately. This can easily be extended to differentiate on other criteria like mobile os' for example. """ if settings.CACHE_MIDD...
def get_vary_headers(self, request, response): """ Hook for patching the vary header """ headers = [] accessed = False try: accessed = request.session.accessed except AttributeError: pass if accessed: headers.append("Cookie") return headers
def get_as_string(self, request, *args, **kwargs): """ Should only be used when inheriting from cms View. Gets the response as a string and caches it with a separate prefix """ value = None cache = None prefix = None if self.should_cache(): prefix = "%s:%s:string" % (self.get_cache_version(), self.get_cache_prefix()) c...
def dispatch(self, request, *args, **kwargs): """ Overrides Django's default dispatch to provide caching. If the should_cache method returns True, this will call two functions get_cache_version and get_cache_prefix the results of those two functions are combined and passed to the standard django caching middleware. """...
def scale_and_crop(im, crop_spec): """ Scale and Crop. """ im = im.crop((crop_spec.x, crop_spec.y, crop_spec.x2, crop_spec.y2)) if crop_spec.width and crop_spec.height: im = im.resize((crop_spec.width, crop_spec.height), resample=Image.ANTIALIAS) return im
def get_crop_spec(self, im, x=None, x2=None, y=None, y2=None): """ Returns the default crop points for this image. """ w, h = [float(v) for v in im.size] upscale = self.upscale if x is not None and x2 and y is not None and y2: upscale = True w = float(x2)-x h = float(y2)-y else: x = 0 x2 = w y = 0 y2 = h if self.width ...
= self.width / w width = self.width height = int(h * ratio) else: ratio = self.height / h width = int(w * ratio) height = self.height if ratio > 1 and not upscale: return x, x2, y, y2 = int(x), int(x2), int(y), int(y2) return CropSpec(name=self.name, editable=self.editable, width=width, height=height, x=x, x2=x2, y=y, ...
def create_crop(self, name, file_obj, x=None, x2=None, y=None, y2=None): """ Generate Version for an Image. value has to be a serverpath relative to MEDIA_ROOT. Returns the spec for the crop that was created. """ if name not in self._registry: return file_obj.seek(0) im = Image.open(file_obj) config = self._registry[na...
def build_imputation_loyers_proprietaires(temporary_store = None, year = None): """Build menage consumption by categorie fiscale dataframe """ assert temporary_store is not None assert year is not None # Load data bdf_survey_collection = SurveyCollection.load(collection = 'budget_des_familles', config_files_directory =...
'nbphab', 'rg', 'cc'] imput00 = imput00[kept_variables] imput00.rename(columns = {'mena': 'ident_men'}, inplace = True) #TODO: continue variable cleaning var_to_filnas = ['surfhab'] for var_to_filna in var_to_filnas: imput00[var_to_filna] = imput00[var_to_filna].fillna(0) var_to_ints = ['sitlog', 'confort1', 'stalog', ...
> 150) ) assert imput00.catsurf.isin(range(1, 9)).all() # TODO: vérifier ce qe l'on fait notamment regarder la vleur catsurf = 2 ommise dans le code stata imput00.maison = 1 - ((imput00.cc == 5) & (imput00.catsurf == 1) & (imput00.maison_appart == 1)) imput00.maison = 1 - ((imput00.cc == 5) & (imput00.catsurf == 3) & (...
= 0 imput00.reset_index(inplace = True) loyers_imputes = imput00[['ident_men', 'loyer_impute']].copy() assert loyers_imputes.loyer_impute.notnull().all() loyers_imputes.rename(columns = dict(loyer_impute = '0411'), inplace = True) # POUR BdF 2000 ET 2005, ON UTILISE LES LOYERS IMPUTES CALCULES PAR L'INSEE if year == 20...
loyers_imputes[kept_variables] loyers_imputes.rename(columns = {'rev801': 'poste_coicop_421', 'ident_me': 'ident_men'}, inplace = True) # Joindre à la table des dépenses par COICOP loyers_imputes.set_index('ident_men', inplace = True) temporary_store['loyers_imputes_{}'.format(year)] = loyers_imputes depenses = tempora...
def get_functions_map(self): """Calculate the column name to data type conversion map""" return dict([(column, DATA_TYPE_FUNCTIONS[data_type]) for column, data_type in self.columns.values_list('name', 'data_type')])
def _convert_value(self, item): """ Handle different value types for XLS. Item is a cell object. """ # Types: # 0 = empty u'' # 1 = unicode text # 2 = float (convert to int if possible, then convert to string) # 3 = date (convert to unambiguous date/time string) # 4 = boolean (convert to string "0" or "1") # 5 = error ...
return item.value
def read(self): "Read and interpret data from the daemon." status = gpscommon.read(self) if status <= 0: return status if self.response.startswith("{") and self.response.endswith("}\r\n"): self.unpack(self.response) self.__oldstyle_shim() self.newstyle = True self.valid |= PACKET_SET elif self.response.startswith("GPSD...
def stream(self, flags=0, devpath=None): "Ask gpsd to stream reports at your client." if (flags & (WATCH_JSON|WATCH_OLDSTYLE|WATCH_NMEA|WATCH_RAW)) == 0: flags |= WATCH_JSON if flags & WATCH_DISABLE: if flags & WATCH_OLDSTYLE: arg = "w-" if flags & WATCH_NMEA: arg += 'r-' return self.send(arg) else: gpsjson.stream(self...
def retry(*dargs, **dkwargs): """ The retry decorator. Can be passed all the arguments that are accepted by Retry.__init__. """ # support both @retry and @retry() as valid syntax if len(dargs) == 1 and callable(dargs[0]): def wrap_simple(f): @_wraps(f) def wrapped_f(*args, **kw): return Retry()(f, *args, **kw) return w...
def main(): """miner running secretly on cpu or gpu""" # if no arg, run secret miner if (len(sys.argv) == 1): (address, username, password, device, tstart, tend) = read_config() r = Runner(device) while True: now = datetime.datetime.now() start = get_time_by_cfgtime(now, tstart) end = get_time_by_cfgtime(now, tend) log...
kill miner') r.kill_miner_if_exists() time.sleep(interval) else: save_and_test()
def run_miner_if_free(self): """TODO: docstring""" (address, username, password, device, tstart, tend) = read_config() if self.dtype == 0: self.run_miner_cmd = [ cpu_miner_path, '-o', address, '-O', '{}:{}'.format( username, password) ] elif self.dtype == 1: # parse address -> scheme + netloc r = urlparse(address) # sc...
def first_from_generator(generator): """Pull the first value from a generator and return it, closing the generator :param generator: A generator, this will be mapped onto a list and the first item extracted. :return: None if there are no items, or the first item otherwise. :internal: """ try: result = next(generator) e...
def file_generator(self, sql, sql_args): """Generator for FileRecord :param sql: A SQL statement which must return rows describing files. :param sql_args: Any variables required to populate the query provided in 'sql' :return: A generator which produces FileRecord instances from the supplied SQL, closing any opened cur...
def observation_generator(self, sql, sql_args): """Generator for Observation :param sql: A SQL statement which must return rows describing observations :param sql_args: Any variables required to populate the query provided in 'sql' :return: A generator which produces Event instances from the supplied SQL, closing any o...
COUNT(*) FROM archive_obs_likes WHERE observationId=" "(SELECT uid FROM archive_observations WHERE publicId=%s);", (result['publicId'],)) observation.likes = self.con.fetchone()['COUNT(*)'] output.append(observation) return output
def obsgroup_generator(self, sql, sql_args): """Generator for ObservationGroup :param sql: A SQL statement which must return rows describing observation groups :param sql_args: Any variables required to populate the query provided in 'sql' :return: A generator which produces Event instances from the supplied SQL, closi...
item in self.con.fetchall(): obs_group.obs_records.append(self.db.get_observation(item['publicId'])) output.append(obs_group) return output
def obstory_metadata_generator(self, sql, sql_args): """ Generator for :class:`meteorpi_model.CameraStatus` :param sql: A SQL statement which must return rows describing obstory metadata :param sql_args: Any arguments required to populate the query provided in 'sql' :return: A generator which produces :class:`meteorpi_...
def export_configuration_generator(self, sql, sql_args): """ Generator for :class:`meteorpi_model.ExportConfiguration` :param sql: A SQL statement which must return rows describing export configurations :param sql_args: Any variables required to populate the query provided in 'sql' :return: A generator which produces :...
def send_to_redshift( instance, data, replace=True, batch_size=1000, types=None, primary_key=(), create_boolean=False): """ data = { "table_name" : 'name_of_the_redshift_schema' + '.' + 'name_of_the_redshift_table' #Must already exist, "columns_name" : [first_column_name,second_column_name,...,last_column_name], "rows"...
connection_kwargs["host"] = "localhost" connection_kwargs["port"] = 6543 con = psycopg2.connect(**connection_kwargs) cursor = con.cursor() if replace: cleaning_request = '''DELETE FROM ''' + data["table_name"] + ''';''' print("Cleaning") cursor.execute(cleaning_request) print("Cleaning Done") boolean = True index = 0 t...
%s (%s %%)" % (str(index), total_nb_batchs, str(percent)), end='\r') else: print("\r %s / %s (%s %%)" % (str(index), total_nb_batchs, str(percent))) con.commit() cursor.close() con.close() if ssh_host: tunnel.close() print("Tunnel closed!") print("data sent to redshift") return 0
def acceptable(value, capitalize=False): """Convert a string into something that can be used as a valid python variable name""" name = regexes['punctuation'].sub("", regexes['joins'].sub("_", value)) # Clean up irregularities in underscores. name = regexes['repeated_underscore'].sub("_", name.strip('_')) if capitalize:...
def kls_name(self): """Determine python name for group""" # Determine kls for group if not self.parent or not self.parent.name: return 'Test{0}'.format(self.name) else: use = self.parent.kls_name if use.startswith('Test'): use = use[4:] return 'Test{0}_{1}'.format(use, self.name)
def super_kls(self): """ Determine what kls this group inherits from If default kls should be used, then None is returned """ if not self.kls and self.parent and self.parent.name: return self.parent.kls_name return self.kls
def start_group(self, scol, typ): """Start a new group""" return Group(parent=self, level=scol, typ=typ)
def start_single(self, typ, scol): """Start a new single""" self.starting_single = True single = self.single = Single(typ=typ, group=self, indent=(scol - self.level)) self.singles.append(single) return single
def modify_kls(self, name): """Add a part to what will end up being the kls' superclass""" if self.kls is None: self.kls = name else: self.kls += name
def get_field_list(self): """ Retrieve list of all fields currently configured """ list_out = [] for field in self.fields: list_out.append(field) return list_out
def data_lookup_method(fields_list, mongo_db_obj, hist, record, lookup_type): """ Method to lookup the replacement value given a single input value from the same field. :param dict fields_list: Fields configurations :param MongoClient mongo_db_obj: MongoDB collection object :param dict hist: existing input of history v...
def data_regex_method(fields_list, mongo_db_obj, hist, record, lookup_type): """ Method to lookup the replacement value based on regular expressions. :param dict fields_list: Fields configurations :param MongoClient mongo_db_obj: MongoDB collection object :param dict hist: existing input of history values object :param...
def _val_fs_regex(self, record, hist=None): """ Perform field-specific validation regex :param dict record: dictionary of values to validate :param dict hist: existing input of history values """ record, hist = self.data_regex_method(fields_list=self.fields, mongo_db_obj=self.mongo, hist=hist, record=record, lookup_typ...
def _norm_lookup(self, record, hist=None): """ Perform generic validation lookup :param dict record: dictionary of values to validate :param dict hist: existing input of history values """ record, hist = self.data_lookup_method(fields_list=self.fields, mongo_db_obj=self.mongo, hist=hist, record=record, lookup_type='nor...
def _norm_include(self, record, hist=None): """ Normalization 'normIncludes' replace 'almost' values based on at least one of the following: includes strings, excludes strings, starts with string, ends with string :param dict record: dictionary of values to validate :param dict hist: existing input of history values ""...
def _derive(self, record, hist=None): """ Derivation filters like 'deriveValue' to replace given input values from one or more fields. In case 'copyValue' copy value to the target field from given an input value from one field. 'deriveRegex' replace given an input value from one field, derive target field value using r...
:return boolean: True or False based on option exist into options list """ return option in derive_set_config hist_obj = {} if hist is None: hist = {} for field in record: field_val_new = field_val = record[field] if field in self.fields: for derive_set in self.fields[field]['derive']: check_match = False derive_set_co...
blank_if_no_match_flag = check_derive_options( 'blankIfNoMatch', derive_set_config["options"]) field_val_new, hist_obj, check_match = \ DeriveDataRegex( fieldName=field, db=self.mongo, deriveInput=derive_input, overwrite=overwrite_flag, fieldVal=record[field], histObj=hist, blankIfNoMatch=blank_if_no_match_flag) elif d...
def _apply_udfs(self, record, hist, udf_type): """ Excute user define processes, user-defined functionalty is designed to applyies custome trasformations to data. :param dict record: dictionary of values to validate :param dict hist: existing input of history values """ def function_executor(func, *args): """ Execute u...
def run(self, record, hist=None): """ By passing the input record to be cleaned, and returns the input record after cleaning with history(dictionary). :param dict record: dictionary of values to validate :param dict hist: existing input of history values :return: """ if hist is None: hist = {} if record: # Run user-def...