code stringlengths 1 18.2k |
|---|
def fancy(cls, contains, max_tries, inner=False, keepcase=False): """ Try to create a key with a chosen prefix, by starting with a 26-bit urandom number and appending with 8-byte integers until prefix matches. This function is naive, but has a max_tries argument which will abort when reached with a ValueError. TODO: ma... |
aspect of multiprocessing; mini-clustering? """ contains = contains if keepcase else contains.lower() if not set(contains).issubset(base58.alphabet): raise ValueError("Cannot find contained phrase '{}' as it contains non-b58 characters".format(contains)) basenum = os.urandom(26) for i in range(max_tries): k = nacl.publ... |
def pieces(array, chunk_size): """Yield successive chunks from array/list/string. Final chunk may be truncated if array is not evenly divisible by chunk_size.""" for i in range(0, len(array), chunk_size): yield array[i:i+chunk_size] |
def piece_file(input_f, chunk_size): """ Provides a streaming interface to file data in chunks of even size, which avoids memoryerrors from loading whole files into RAM to pass to `pieces`. """ chunk = input_f.read(chunk_size) total_bytes = 0 while chunk: yield chunk chunk = input_f.read(chunk_size) total_bytes += len(... |
def new(cls, file_info, sender, recipients, version=1): """ Constructs (encrypts) a new MiniLockHeader object. file_info: dict, with 'fileKey', 'fileNonce', 'fileHash' as bytes entries sender: UserLock for sender recipients: list of UserLock for recipients """ ephem_key = UserLock.ephemeral() decryptInfo = {} for recip... |
ephem->recipient box, which obfuscates the sender. ephem_sending_box = nacl.public.Box(ephem_key.private_key, recipient.public_key) crypted_di_entry = ephem_sending_box.encrypt(di_entry, sending_nonce)[24:] decryptInfo[sending_nonce_b64] = b64encode(crypted_di_entry) # Now have a decryptInfo dictionary full of entries ... |
def decrypt(self, recipient_key): """ Attempt decryption of header with a private key; returns decryptInfo. Returns a dictionary, not a new MiniLockHeader! """ ephem = UserLock.from_b64(self.dict['ephemeral']) ephem_box = nacl.public.Box(recipient_key.private_key, ephem.public_key) # Scan available entries in decryptIn... |
fileInfo_raw = b64decode(decryptInfo['fileInfo']) fileInfo_decrypted = senderBox.decrypt(fileInfo_raw, success_nonce).decode('utf8') fileInfo = json.loads(fileInfo_decrypted) # Overwrite decryptInfo's fileInfo key decryptInfo['fileInfo'] = fileInfo return decryptInfo |
def new(cls, file_name, file_or_contents, sender, recipients): """ Constructs (that is, encrypts) a new miniLock file from sender to recipients. """ assert_type_and_length('recipients', recipients, list, minL=1) assert_type_and_length('sender', sender, UserLock) for R in recipients: assert_type_and_length('recipient', ... |
def iter_chunks(self, start_count=0): """ Iterate over the chunks of the file according to their length prefixes. yields: index <int>, encrypted chunks without length prefixes <bytes>, lastchunk <bool> """ ciphertext = self.chunks_block chunknum = start_count idx = 0 lastchunk = False while idx < len(ciphertext): plain... |
def decrypt(self, recipient_key): """ recipient_key: UserLock with a private key part. returns: filename, decrypted file contents """ if recipient_key.private_key is None: raise ValueError("Cannot decrypt with this key; no private key part found.") header = MiniLockHeader(self.header) # Create ephemeral public key for ... |
def to_json(self): """ Returns: str: """ data = dict() for key, value in self.__dict__.items(): if value: if hasattr(value, 'to_dict'): data[key] = value.to_dict() elif isinstance(value, datetime): data[key] = value.strftime('%Y-%m-%d %H:%M:%S') else: data[key] = value return json.dumps(data) |
def to_dict(self): """ Returns: dict: """ data = dict() for key, value in self.__dict__.items(): if value: if hasattr(value, 'to_dict'): data[key] = value.to_dict() else: data[key] = value return data |
def run(query, container=Null): """ THIS FUNCTION IS SIMPLY SWITCHING BASED ON THE query["from"] CONTAINER, BUT IT IS ALSO PROCESSING A list CONTAINER; SEPARATE TO A ListContainer """ if container == None: container = wrap(query)["from"] query_op = QueryOp.wrap(query, container=container, namespace=container.schema) el... |
already_normalized=True) if query_op.select: container = select(container, query_op.select) if query_op.window: if isinstance(container, Cube): container = list(container.values()) for param in query_op.window: window(container, param) # AT THIS POINT frum IS IN LIST FORMAT, NOW PACKAGE RESULT if query_op.format == "cu... |
def unique_index(data, keys=None, fail_on_dup=True): """ RETURN dict THAT USES KEYS TO INDEX DATA ONLY ONE VALUE ALLOWED PER UNIQUE KEY """ o = UniqueIndex(listwrap(keys), fail_on_dup=fail_on_dup) for d in data: try: o.add(d) except Exception as e: o.add(d) Log.error( "index {{index}} is not unique {{key}} maps to both... |
def map2set(data, relation): """ EXPECTING A is_data(relation) THAT MAPS VALUES TO lists THE LISTS ARE EXPECTED TO POINT TO MEMBERS OF A SET A set() IS RETURNED """ if data == None: return Null if isinstance(relation, Data): Log.error("Does not accept a Data") if is_data(relation): try: # relation[d] is expected to be ... |
return output except Exception as e: Log.error("Expecting a dict with lists in codomain", e) return Null |
def tuple(data, field_name): """ RETURN LIST OF TUPLES """ if isinstance(data, Cube): Log.error("not supported yet") if isinstance(data, FlatList): Log.error("not supported yet") if is_data(field_name) and "value" in field_name: # SIMPLIFY {"value":value} AS STRING field_name = field_name["value"] # SIMPLE PYTHON ITERA... |
def _tuple_deep(v, field, depth, record): """ field = {"name":name, "value":["attribute", "path"]} r[field.name]=v[field.value], BUT WE MUST DEAL WITH POSSIBLE LIST IN field.value PATH """ if hasattr(field.value, "__call__"): return 0, None, record + (field.value(v),) for i, f in enumerate(field.value[depth : len(field... |
def select(data, field_name): """ return list with values from field_name """ if isinstance(data, Cube): return data._select(_normalize_selects(field_name)) if isinstance(data, PartFlatList): return data.select(field_name) if isinstance(data, UniqueIndex): data = ( data._data.values() ) # THE SELECT ROUTINE REQUIRES di... |
def _select_deep(v, field, depth, record): """ field = {"name":name, "value":["attribute", "path"]} r[field.name]=v[field.value], BUT WE MUST DEAL WITH POSSIBLE LIST IN field.value PATH """ if hasattr(field.value, "__call__"): try: record[field.name] = field.value(wrap(v)) except Exception as e: record[field.name] = No... |
def _select_deep_meta(field, depth): """ field = {"name":name, "value":["attribute", "path"]} r[field.name]=v[field.value], BUT WE MUST DEAL WITH POSSIBLE LIST IN field.value PATH RETURN FUNCTION THAT PERFORMS THE MAPPING """ name = field.name if hasattr(field.value, "__call__"): try: def assign(source, destination): d... |
property", value=source, field=f, cause=e, ) return 0, None return assign else: f = field.value[0] if not f: # NO NAME FIELD INDICATES SELECT VALUE def assign(source, destination): destination[name] = source return 0, None return assign else: def assign(source, destination): try: destination[name] = source.get(f) excep... |
def sort(data, fieldnames=None, already_normalized=False): """ PASS A FIELD NAME, OR LIST OF FIELD NAMES, OR LIST OF STRUCTS WITH {"field":field_name, "sort":direction} """ try: if data == None: return Null if not fieldnames: return wrap(sort_using_cmp(data, value_compare)) if already_normalized: formal = fieldnames el... |
def filter(data, where): """ where - a function that accepts (record, rownum, rows) and returns boolean """ if len(data) == 0 or where == None or where == TRUE: return data if isinstance(data, Container): return data.filter(where) if is_container(data): temp = jx_expression_to_function(where) dd = wrap(data) return wra... |
def drill_filter(esfilter, data): """ PARTIAL EVALUATE THE FILTER BASED ON DATA GIVEN TODO: FIX THIS MONUMENALLY BAD IDEA """ esfilter = unwrap(esfilter) primary_nested = [] # track if nested, changes if not primary_column = [] # only one path allowed primary_branch = ( [] ) # CONTAINS LISTS OF RECORDS TO ITERATE: cons... |
True primary_column[depth + i] = c primary_branch[depth + i] = d return c, join_field(col[i + 1 :]) else: if len(primary_column) <= depth + i: primary_nested.append(False) primary_column.append(c) primary_branch.append([d]) return fieldname, None def pe_filter(filter, data, depth): """ PARTIAL EVALUATE THE filter BASED... |
{"or": output} else: return False elif filter["not"]: f = pe_filter(filter["not"], data, depth) if f is True: return False elif f is False: return True else: return {"not": f} elif filter.term or filter.eq: eq = coalesce(filter.term, filter.eq) result = True output = {} for col, val in eq.items(): first, rest = parse_f... |
return {"term": {rest_a: val_b}} else: return {"equal": [rest_a, rest_b]} elif filter.terms: result = True output = {} for col, vals in filter["terms"].items(): first, rest = parse_field(col, data, depth) d = data[first] if not rest: if d not in vals: result = False else: output[rest] = vals if result and output: retur... |
result = False else: output[rest] = ranges if result and output: return {"range": output} else: return result elif filter.missing: if is_text(filter.missing): field = filter["missing"] else: field = filter["missing"]["field"] first, rest = parse_field(field, data, depth) d = data[first] if not rest: if d == None: retur... |
return True return False else: return {"exists": rest} else: Log.error("Can not interpret esfilter: {{esfilter}}", {"esfilter": filter}) output = [] # A LIST OF OBJECTS MAKING THROUGH THE FILTER def main(sequence, esfilter, row, depth): """ RETURN A SEQUENCE OF REFERENCES OF OBJECTS DOWN THE TREE SHORT SEQUENCES MEANS ... |
= 0 # EVEN THOUGH A ROW CAN HAVE MANY VALUES, WE ONLY NEED UP TO max for i, n in enumerate(primary_nested): if n: max = i + 1 # OUTPUT IS A LIST OF ROWS, # WHERE EACH ROW IS A LIST OF VALUES SEEN DURING A WALK DOWN A PATH IN THE HIERARCHY uniform_output = FlatList() def recurse(row, depth): if depth == max: uniform_out... |
def wrap_function(func): """ RETURN A THREE-PARAMETER WINDOW FUNCTION TO MATCH """ if is_text(func): return compile_expression(func) numarg = func.__code__.co_argcount if numarg == 0: def temp(row, rownum, rows): return func() return temp elif numarg == 1: def temp(row, rownum, rows): return func(row) return temp elif ... |
def window(data, param): """ MAYBE WE CAN DO THIS WITH NUMPY (no, the edges of windows are not graceful with numpy) data - list of records """ name = param.name # column to assign window function result edges = param.edges # columns to gourp by where = param.where # DO NOT CONSIDER THESE VALUES sortColumns = param.sort... |
r in enumerate(data): try: r[name] = calc_value(r, rownum, data) except Exception as e: raise e return try: edge_values = [e.value.var for e in edges] except Exception as e: raise Log.error("can only support simple variable edges", cause=e) if not aggregate or aggregate == "none": for _, values in groupby(data, edge_va... |
i in range(tail, head): total.add(sequence[i].__temp__) # WINDOW FUNCTION APPLICATION for i, r in enumerate(sequence): r[name] = total.end() total.add(sequence[i + head].__temp__) total.sub(sequence[i + tail].__temp__) for r in data: r["__temp__"] = None |
def intervals(_min, _max=None, size=1): """ RETURN (min, max) PAIRS OF GIVEN SIZE, WHICH COVER THE _min, _max RANGE THE LAST PAIR MAY BE SMALLER Yes! It's just like range(), only cooler! """ if _max == None: _max = _min _min = 0 _max = int(mo_math.ceiling(_max)) _min = int(mo_math.floor(_min)) output = ((x, min(x + siz... |
def get_context_hints_per_source(context_renderers): """ Given a list of context renderers, return a dictionary of context hints per source. """ # Merge the context render hints for each source as there can be multiple context hints for # sources depending on the render target. Merging them together involves combining ... |
def get_querysets_for_context_hints(context_hints_per_source): """ Given a list of context hint dictionaries, return a dictionary of querysets for efficient context loading. The return value is structured as follows: { model: queryset, ... } """ model_select_relateds = defaultdict(set) model_prefetch_relateds = default... |
def dict_find(d, which_key): """ Finds key values in a nested dictionary. Returns a tuple of the dictionary in which the key was found along with the value """ # If the starting point is a list, iterate recursively over all values if isinstance(d, (list, tuple)): for i in d: for result in dict_find(i, which_key): yield... |
def get_model_ids_to_fetch(events, context_hints_per_source): """ Obtains the ids of all models that need to be fetched. Returns a dictionary of models that point to sets of ids that need to be fetched. Return output is as follows: { model: [id1, id2, ...], ... } """ number_types = (complex, float) + six.integer_types ... |
def fetch_model_data(model_querysets, model_ids_to_fetch): """ Given a dictionary of models to querysets and model IDs to models, fetch the IDs for every model and return the objects in the following structure. { model: { id: obj, ... }, ... } """ return { model: id_dict(model_querysets[model].filter(id__in=ids_to_fetc... |
def load_fetched_objects_into_contexts(events, model_data, context_hints_per_source): """ Given the fetched model data and the context hints for each source, go through each event and populate the contexts with the loaded information. """ for event in events: context_hints = context_hints_per_source.get(event.source, {... |
def load_renderers_into_events(events, mediums, context_renderers, default_rendering_style): """ Given the events and the context renderers, load the renderers into the event objects so that they may be able to call the 'render' method later on. """ # Make a mapping of source groups and rendering styles to context rend... |
step 1 doesn't work, look up based on the source and medium rendering style # 3. If step 2 doesn't work, look up based on the source group and default rendering style # 4. if step 3 doesn't work, look up based on the source and default rendering style # If none of those steps work, this event will not be able to be ren... |
def load_contexts_and_renderers(events, mediums): """ Given a list of events and mediums, load the context model data into the contexts of the events. """ sources = {event.source for event in events} rendering_styles = {medium.rendering_style for medium in mediums if medium.rendering_style} # Fetch the default renderin... |
def main(global_config, **settings): """ This function returns a Pyramid WSGI application. """ engine = engine_from_config(settings, 'sqlalchemy.') initialize_sql(engine) config = Configurator(settings=settings) config.add_static_view('static', 'pyramidraptorized:static', cache_max_age=3600) config.add_route('home', '/... |
def get_printer(colors: bool = True, width_limit: bool = True, disabled: bool = False) -> Printer: """ Returns an already initialized instance of the printer. :param colors: If False, no colors will be printed. :param width_limit: If True, printing width will be limited by console width. :param disabled: If True, nothi... |
def _get_windows_console_width() -> int: """ A small utility function for getting the current console window's width, in Windows. :return: The current console window's width. """ from ctypes import byref, windll import pyreadline out = windll.kernel32.GetStdHandle(-11) info = pyreadline.console.CONSOLE_SCREEN_BUFFER_IN... |
def _in_qtconsole() -> bool: """ A small utility function which determines if we're running in QTConsole's context. """ try: from IPython import get_ipython try: from ipykernel.zmqshell import ZMQInteractiveShell shell_object = ZMQInteractiveShell except ImportError: from IPython.kernel.zmq import zmqshell shell_object... |
def get_console_width() -> int: """ A small utility function for getting the current console window's width. :return: The current console window's width. """ # Assigning the value once, as frequent call to this function # causes a major slow down(ImportErrors + isinstance). global _IN_QT if _IN_QT is None: _IN_QT = _in... |
def group(self, indent: int = DEFAULT_INDENT, add_line: bool = True) -> _TextGroup: """ Returns a context manager which adds an indentation before each line. :param indent: Number of spaces to print. :param add_line: If True, a new line will be printed after the group. :return: A TextGroup context manager. """ return _... |
def _split_lines(self, original_lines: List[str]) -> List[str]: """ Splits the original lines list according to the current console width and group indentations. :param original_lines: The original lines list to split. :return: A list of the new width-formatted lines. """ console_width = get_console_width() # We take i... |
it. if self._ANSI_REGEXP.match(current_color): line_index += self._ANSI_COLOR_LENGTH fixed_line.extend(list(current_color)) colors_counter += 1 continue fixed_line.append(line[line_index]) line_index += 1 # Create a new line, if max line is reached. if len(fixed_line) >= max_line_length + (colors_counter * self._ANSI_C... |
self._ANSI_COLOR_LENGTH and self._ANSI_REGEXP.match(fixed_line) is not None and \ len(lines) > 0: lines[-1] = lines[-1][:-1] + fixed_line else: lines.append(fixed_line) return lines |
def write(self, text: str): """ Prints text to the screen. Supports colors by using the color constants. To use colors, add the color before the text you want to print. :param text: The text to print. """ # Default color is NORMAL. last_color = (self._DARK_CODE, 0) # We use splitlines with keepends in order to keep the... |
line starts with a color. If not, we apply the color from the last line. line = self._ANSI_COLOR_CODE % (last_color[0], int(last_color[1])) + line # Print the final line. self._writer.write(line) # Update the in_line status. self._in_line = not line.endswith(self.LINE_SEP) # Update the last color used. if self._colors:... |
def write_aligned(self, key: str, value: str, not_important_keys: Optional[List[str]] = None, is_list: bool = False, align_size: Optional[int] = None, key_color: str = PURPLE, value_color: str = GREEN, dark_key_color: str = DARK_PURPLE, dark_value_color: str = DARK_GREEN, separator: str = SEPARATOR): """ Prints keys an... |
text color for unimportant values (default is dark green). :param separator: The separator to use (default is ':'). """ align_size = align_size or min(32, get_console_width() // 2) not_important_keys = not_important_keys or [] if value is None: return if isinstance(value, bool): value = str(value) if key in not_importa... |
def write_title(self, title: str, title_color: str = YELLOW, hyphen_line_color: str = WHITE): """ Prints title with hyphen line underneath it. :param title: The title to print. :param title_color: The title text color (default is yellow). :param hyphen_line_color: The hyphen line color (default is white). """ self.writ... |
def generate_pos_tagger(check_accuracy=False): """Accuracy is about 0.94 with 90% training data.""" global tagger logging.debug("Reading TIGER corpus") corp = nltk.corpus.ConllCorpusReader(DIR_PATH, TIGER_FILE_NAME, ['ignore', 'words', 'ignore', 'ignore', 'pos'], encoding='utf-8') tagged_sents = list(corp.tagged_sents(... |
def find_holes(db_module, db, table_name, column_name, _range, filter=None): """ FIND HOLES IN A DENSE COLUMN OF INTEGERS RETURNS A LIST OF {"min"min, "max":max} OBJECTS """ if not filter: filter = {"match_all": {}} _range = wrap(_range) params = { "min": _range.min, "max": _range.max - 1, "column_name": db_module.quot... |
_range.max}) else: ranges.append(_range) return ranges |
def values2rows(values, column_names): """ CONVERT LIST OF JSON-IZABLE DATA STRUCTURE TO DATABASE ROW value - THE STRUCTURE TO CONVERT INTO row column_names - FOR ORDERING THE ALLOWED COLUMNS (EXTRA ATTRIBUTES ARE LOST) THE COLUMN NAMES ARE EXPECTED TO HAVE dots (.) FOR DEEPER PROPERTIES """ values = wrap(values) looku... |
def make_lock_securely(email = None, warn_only = False): "Terminal oriented; produces a prompt for user input of email and password. Returns crypto.UserLock." email = email or input("Please provide email address: ") while True: passphrase = getpass.getpass("Please type a secure passphrase (with spaces): ") ok, score = ... |
def encrypt_file(file_path, sender, recipients): "Returns encrypted binary file content if successful" for recipient_key in recipients: crypto.assert_type_and_length('recipient_key', recipient_key, (str, crypto.UserLock)) crypto.assert_type_and_length("sender_key", sender, crypto.UserLock) if (not os.path.exists(file_p... |
def decrypt_file(file_path, recipient_key, *, base64=False): "Returns (filename, file_contents) if successful" crypto.assert_type_and_length('recipient_key', recipient_key, crypto.UserLock) with open(file_path, "rb") as I: contents = I.read() if base64: contents = crypto.b64decode(contents) crypted = crypto.MiniLockFil... |
def encrypt_folder(path, sender, recipients): """ This helper function should zip the contents of a folder and encrypt it as a zip-file. Recipients are responsible for opening the zip-file. """ for recipient_key in recipients: crypto.assert_type_and_length('recipient_key', recipient_key, (str, crypto.UserLock)) crypto.... |
def get_profile(A): "Fail-soft profile getter; if no profile is present assume none and quietly ignore." try: with open(os.path.expanduser(A.profile)) as I: profile = json.load(I) return profile except: return {} |
def main_encrypt(A): "Encrypt to recipient list using primary key OR prompted key. Recipients may be IDs or petnames." profile = get_profile(A) localKeys = profile.get('local keys', []) if not localKeys: localKeys = [make_lock_securely(warn_only = A.ignore_entropy)] else: localKeys = [crypto.UserLock.private_from_b64(k... |
= hex(int.from_bytes(os.urandom(6),'big'))[2:] + ".minilock" print("Saving output to", A.output) with open(A.output, "wb") as O: O.write(crypted) |
def main_decrypt(A): "Get all local keys OR prompt user for key, then attempt to decrypt with each." profile = get_profile(A) localKeys = profile.get('local keys', []) if not localKeys: localKeys = [make_lock_securely(warn_only = A.ignore_entropy)] else: localKeys = [crypto.UserLock.private_from_b64(k['private_key']) f... |
def build_homogeneisation_revenus_menages(temporary_store = None, year = None): assert temporary_store is not None """Build menage consumption by categorie fiscale dataframe """ assert year is not None # Load data bdf_survey_collection = SurveyCollection.load( collection = 'budget_des_familles', config_files_directory ... |
], ) menage = survey.get_values( table = "socioscm", variables = ['exdep', 'exrev', 'mena'] ) menage.set_index('mena') menrev = menrev.merge(menage, left_index = True, right_index = True) # cette étape de ne garder que les données dont on est sûr de la qualité et de la véracité # exdep = 1 si les données sont bien remp... |
menrev['revind'] + menrev['revsec'] menrev.rename( columns = dict( revpat = "revpat", impfon = "impfon", imphab = "imphab", revaid = "somme_obl_recue", ), inplace = True ) menrev['impot_revenu'] = menrev['ir'] + menrev['irbis'] rev_disp = survey.get_values( table = "menrev", variables = ['revtot', 'revret', 'revcho', '... |
= rev_disp['revsal'] + rev_disp['revind'] + rev_disp['revsec'] rev_disp['revtot'] = rev_disp['revact'] + rev_disp['revpat'] + rev_disp['revsoc'] + rev_disp['somme_obl_recue'] rev_disp['revact'] = rev_disp['revsal'] + rev_disp['revind'] + rev_disp['revsec'] rev_disp.rename( columns = dict( ponderr = "pondmen", mena = "i... |
right_index = True) rev_disp['rev_disp_loyerimput'] = rev_disp['rev_disponible'] - rev_dispbis['loyer_impute'] for var in ['somme_obl_recue', 'act_indpt', 'revpat', 'salaires', 'autres_rev', 'rev_disponible', 'impfon', 'imphab', 'revsoc', 'revact', 'impot_revenu', 'revtot', 'rev_disp_loyerimput']: rev_disp[var] = rev_d... |
rev71 = "somme_libre_recue", revt_d = "autres_ress", ident = "ident_men", rev10 = "act_indpt", rev11 = "autoverses", rev20 = "salaires", rev21 = "autres_rev", ), inplace = True ) var_to_ints = ['pondmen', 'impot_autres_res', 'impot_res_ppal', 'pondmenrev_disp', 'c13131'] for var_to_int in var_to_ints: revenus.loc[reven... |
var_to_ints = ['loyer_impute'] for var_to_int in var_to_ints: revenus[var_to_int] = revenus[var_to_int].astype(int) temporary_store["revenus_{}".format(year)] = revenus elif year == 2005: c05d = survey.get_values( table = "c05d", variables = ['c13111', 'c13121', 'c13141', 'pondmen', 'ident_men'], ) rev_disp = c05d.sort... |
= "impot_revenu", c13121 = "impot_autres_res", ), inplace = True ) # * Ces pondérations (0.65 0.35) viennent de l'enquête BdF 1995 qui distingue taxe d'habitation et impôts # fonciers. A partir de BdF 1995, # * on a calculé que la taxe d'habitation représente en moyenne 65% des impôts locaux, et que les impôts # foncie... |
assert set(revenus.index) == set(loyers_imputes.index), '''revenus and loyers_imputes indexes are not equal. In revenus and not in loyers_imputes: {} In loyers_imputes and not in revenus: {} '''.format(set(revenus.index) - set(loyers_imputes.index), set(loyers_imputes.index) - set(revenus.index)) revenus = revenus.merg... |
= ['ident_me']) except: menage = survey.get_values( table = "menage", variables = ['ident_me', 'revtot', 'revact', 'revsoc', 'revpat', 'rev700', 'rev701', 'rev999', 'revindep', 'salaires'], ).sort_values(by = ['ident_me']) rev_disp.index = rev_disp.index.astype(ident_men_dtype) menage.index = menage.index.astype(ident_... |
loyers_imputes.rename( columns = {"poste_coicop_421": "loyer_impute"}, inplace = True, ) temporary_store["loyers_imputes_{}".format(year)] = loyers_imputes revenus = revenus.merge(loyers_imputes, left_index = True, right_index = True) revenus['rev_disponible'] = revenus.revtot - revenus.impot_revenu - revenus.imphab re... |
def collection(name=None): """Render the collection page. It renders it either with a collection specific template (aka collection_{collection_name}.html) or with the default collection template (collection.html). """ if name is None: collection = Collection.query.get_or_404(1) else: collection = Collection.query.filte... |
def url(self): """:class:`str`: The URL to the highscores page on Tibia.com containing the results.""" return self.get_url(self.world, self.category, self.vocation, self.page) |
def url_tibiadata(self): """:class:`str`: The URL to the highscores page on TibiaData.com containing the results.""" return self.get_url_tibiadata(self.world, self.category, self.vocation) |
def from_content(cls, content): """Creates an instance of the class from the html content of a highscores page. Notes ----- Tibia.com only shows up to 25 entries per page, so in order to obtain the full highscores, all 12 pages must be parsed and merged into one. Parameters ---------- content: :class:`str` The HTML con... |
{"selected": True}) vocation = int(vocation_selected["value"]) if vocation_selected else 0 highscores = cls(world, category, vocation=vocation) entries = tables.get("Highscores") if entries is None: return None _, header, *rows = entries info_row = rows.pop() highscores.results_count = int(results_pattern.search(info_r... |
def from_tibiadata(cls, content, vocation=None): """Builds a highscores object from a TibiaData highscores response. Notes ----- Since TibiaData.com's response doesn't contain any indication of the vocation filter applied, :py:attr:`vocation` can't be determined from the response, so the attribute must be assigned manu... |
json_content["highscores"] if "error" in highscores_json["data"]: return None world = highscores_json["world"] category = highscores_json["type"] highscores = cls(world, category) for entry in highscores_json["data"]: value_key = "level" if highscores.category in [Category.ACHIEVEMENTS, Category.LOYALTY_POINTS, Categor... |
def get_url(cls, world, category=Category.EXPERIENCE, vocation=VocationFilter.ALL, page=1): """Gets the Tibia.com URL of the highscores for the given parameters. Parameters ---------- world: :class:`str` The game world of the desired highscores. category: :class:`Category` The desired highscores category. vocation: :cl... |
def get_url_tibiadata(cls, world, category=Category.EXPERIENCE, vocation=VocationFilter.ALL): """Gets the TibiaData.com URL of the highscores for the given parameters. Parameters ---------- world: :class:`str` The game world of the desired highscores. category: :class:`Category` The desired highscores category. vocatio... |
def _parse_entry(self, cols): """Parses an entry's row and adds the result to py:attr:`entries`. Parameters ---------- cols: :class:`bs4.ResultSet` The list of columns for that entry. """ rank, name, vocation, *values = [c.text.replace('\xa0', ' ').strip() for c in cols] rank = int(rank) if self.category == Category.EX... |
def transform(string, transliterations=None): """ Transform the string to "upside-down" writing. Example: >>> import upsidedown >>> print(upsidedown.transform('Hello World!')) ¡pꞁɹoM oꞁꞁǝH For languages with diacritics you might want to supply a transliteration to work around missing (rendering of) upside-down forms: >... |
def main(): """Main method for running upsidedown.py from the command line.""" import sys output = [] line = sys.stdin.readline() while line: line = line.strip("\n") output.append(transform(line)) line = sys.stdin.readline() output.reverse() print("\n".join(output)) |
def capture_termination_signal(please_stop): """ WILL SIGNAL please_stop WHEN THIS AWS INSTANCE IS DUE FOR SHUTDOWN """ def worker(please_stop): seen_problem = False while not please_stop: request_time = (time.time() - timer.START)/60 # MINUTES try: response = requests.get("http://169.254.169.254/latest/meta-data/spot/... |
please_stop).wait() Thread.run("listen for termination", worker) |
def pop_message(self, wait=SECOND, till=None): """ RETURN TUPLE (message, payload) CALLER IS RESPONSIBLE FOR CALLING message.delete() WHEN DONE """ if till is not None and not isinstance(till, Signal): Log.error("Expecting a signal") message = self.queue.read(wait_time_seconds=mo_math.floor(wait.seconds)) if not messag... |
def never(self): """ Inspected function should never be called Return: self """ def check(): #pylint: disable=missing-docstring return not super(SinonExpectation, self).called self.valid_list.append(check) return self |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.