code
stringlengths
1
18.2k
def add_years(self, datetimestr, n, return_date=False): """Returns a time that n years after a time. :param datetimestr: a datetime object or a datetime str :param n: number of years, value can be negative :param return_date: returns a date object instead of datetime **中文文档** 返回给定日期N年之后的时间。 """ a_datetime = self.parse_...
def round_to(self, dt, hour, minute, second, mode="floor"): """Round the given datetime to specified hour, minute and second. :param mode: 'floor' or 'ceiling' **中文文档** 将给定时间对齐到最近的一个指定了小时, 分钟, 秒的时间上。 """ mode = mode.lower() new_dt = datetime(dt.year, dt.month, dt.day, hour, minute, second) if mode == "floor": if new_dt...
def lint(ctx: click.Context, amend: bool = False, stage: bool = False): """ Runs all linters Args: ctx: click context amend: whether or not to commit results stage: whether or not to stage changes """ _lint(ctx, amend, stage)
def callback(self, herald_svc, message): """ Tries to call the callback of the post message. Avoids errors to go outside this method. :param herald_svc: Herald service instance :param message: Received answer message """ if self.__callback is not None: try: # pylint: disable=W0703 self.__callback(herald_svc, message) e...
def errback(self, herald_svc, exception): """ Tries to call the error callback of the post message. Avoids errors to go outside this method. :param herald_svc: Herald service instance :param exception: An exception describing/caused by the error """ if self.__errback is not None: try: # pylint: disable=W0703 self.__err...
def socket_set_hwm(socket, hwm=-1): """libzmq 2/3 compatible sethwm""" try: socket.sndhwm = socket.rcvhwm = hwm except AttributeError: socket.hwm = hwm
def zpipe(ctx): """build inproc pipe for talking to threads mimic pipe used in czmq zthread_fork. Returns a pair of PAIRs connected via inproc """ a = ctx.socket(zmq.PAIR) a.linger = 0 b = ctx.socket(zmq.PAIR) b.linger = 0 socket_set_hwm(a, 1) socket_set_hwm(b, 1) iface = "inproc://%s" % binascii.hexlify(os.urandom(8))...
def get_country(similar=False, **kwargs): """ Get a country for pycountry """ result_country = None try: if similar: for country in countries: if kwargs.get('name', '') in country.name: result_country = country break else: result_country = countries.get(**kwargs) except Exception as ex: msg = ('Country not found in pyc...
def get_location(address=""): """ Retrieve location coordinates from an address introduced. """ coordinates = None try: geolocator = Nominatim() location = geolocator.geocode(address) coordinates = (location.latitude, location.longitude) except Exception as ex: logger.error('Fail get location - {}'.format(ex)) return c...
def get_address(coords=None, **kwargs): """ Retrieve addres from a location in coords format introduced. """ address = None try: if (not coords) and \ ('latitude' in kwargs and 'longitude' in kwargs) or \ ('location' in kwargs): coords = kwargs.get( 'location', (kwargs.get('latitude'), kwargs.get('longitude'))) # trans...
def set_documents(self, documents, fully_formed=False): """ Wrap documents in the correct root tags, add id fields and convert them to xml strings. Args: documents -- If fully_formed is False (default), accepts dict where keys are document ids and values can be ether xml string, etree.ElementTree or dict representation...
of documents. Default is False. """ def add_id(document, id): def make_id_tag(root, rel_path, max_depth): if max_depth < 0: raise ParameterError("document_id_xpath too deep!") if not rel_path: return root else: child = root.find(rel_path[0]) if child is None: child = ET.Element(rel_path[0]) root.append(child) return ma...
same as given xpath, make new root and append to it. for id, document in documents.items(): if document.tag != doc_root_tag: documents[id] = ET.Element(doc_root_tag) documents[id].append(document) # documents is still the old reference # Insert ids in documents and collapse to a list of documents. for id, document in d...
def set_doc_ids(self, doc_ids): """ Build xml documents from a list of document ids. Args: doc_ids -- A document id or a lost of those. """ if isinstance(doc_ids, list): self.set_documents(dict.fromkeys(doc_ids)) else: self.set_documents({doc_ids: None})
def add_property(self, set_property, name, starting_value, tag_name=None): """ Set properies of atributes stored in content using stored common fdel and fget and given fset. Args: set_property -- Function that sets given property. name -- Name of the atribute this property must simulate. Used as key in content dict by ...
def set_query(self, value): """ Convert a dict form of query in a string of needed and store the query string. Args: value -- A query string or a dict with query xpaths as keys and text or nested query dicts as values. """ if isinstance(value, basestring) or value is None: self._content['query'] = value elif hasattr(va...
def get_xml_request(self): """ Make xml request string from stored request information. Returns: A properly formated XMl request string containing all set request fields and wraped in connections envelope. """ def wrap_xml_content(xml_content): """ Wrap XML content string in the correct CPS request envelope.""" fields ...
list faster than incremental concat. xml_request = ''.join(fields) return xml_request xml_content = [] if self._documents: xml_content += self._documents for key, value in self._nested_content.items(): if value: xml_content += ['<{0}>'.format(key)] +\ ['<{0}>{1}</{0}>'.format(sub_key, sub_value) for sub_key, sub_value ...
def send(self): """ Send an XML string version of content through the connection. Returns: Response object. """ xml_request = self.get_xml_request() if(self.connection._debug == 1): print(xml_request) Debug.warn('-' * 25) Debug.warn(self._command) Debug.dump("doc: \n", self._documents) Debug.dump("cont: \n", self._cont...
def _min_timezone_offset(): "time zone offset (minutes)" now = time.time() return (datetime.datetime.fromtimestamp(now) - datetime.datetime.utcfromtimestamp(now)).seconds // 60
def parse_transaction_id(self, data): "return transaction_id" if data[0] == TDS_ERROR_TOKEN: raise self.parse_error('begin()', data) t, data = _parse_byte(data) assert t == TDS_ENVCHANGE_TOKEN _, data = _parse_int(data, 2) # packet length e, data = _parse_byte(data) assert e == TDS_ENV_BEGINTRANS ln, data = _parse_byte...
def format_duration(secs): """ Format a duration in seconds as minutes and seconds. """ secs = int(secs) if abs(secs) > 60: mins = abs(secs) / 60 secs = abs(secs) - (mins * 60) return '%s%im %02is' % ('-' if secs < 0 else '', mins, secs) return '%is' % secs
def learn(self, numEpochs, batchsize): """Train the classifier for a given number of epochs, with a given batchsize""" for epoch in range(numEpochs): print('epoch %d' % epoch) indexes = np.random.permutation(self.trainsize) for i in range(0, self.trainsize, batchsize): x = Variable(self.x_train[indexes[i: i + batchsize...
def evaluate(self, batchsize): """Evaluate how well the classifier is doing. Return mean loss and mean accuracy""" sum_loss, sum_accuracy = 0, 0 for i in range(0, self.testsize, batchsize): x = Variable(self.x_test[i: i + batchsize]) y = Variable(self.y_test[i: i + batchsize]) loss = self.model(x, y) sum_loss += loss.d...
def save(self, model_filename, optimizer_filename): """ Save the state of the model & optimizer to disk """ serializers.save_hdf5(model_filename, self.model) serializers.save_hdf5(optimizer_filename, self.optimizer)
def classify(self, phrase_vector): """ Run this over an input vector and see the result """ x = Variable(np.asarray([phrase_vector])) return self.model.predictor(x).data[0]
def parent_site(self, site): """ Filter to the given site, only give content relevant for that site. """ # Avoid auto filter if site is already set. self._parent_site = site if settings.FLUENTCMS_EMAILTEMPLATES_ENABLE_CROSS_SITE: # Allow content to be shared between all sites: return self.filter(Q(parent_site=site) | Q...
def _single_site(self): """ Make sure the queryset is filtered on a parent site, if that didn't happen already. """ if settings.FLUENTCMS_EMAILTEMPLATES_FILTER_SITE_ID and self._parent_site is None: return self.parent_site(settings.SITE_ID) else: return self
def help(route): r"""Displays help for the given route. Args: route (str): A route that resolves a member. """ help_text = getRouteHelp(route.split('/') if route else []) if help_text is None: err('Can\'t help :(') else: print '\n%s' % help_text
def encode(data: Union[str, bytes]) -> str: """ Return Base58 string from data :param data: Bytes or string data """ return ensure_str(base58.b58encode(ensure_bytes(data)))
def plotOptMod(verNObg3gray, VERgray): """ called from either readTranscar.py or hist-feasibility/plotsnew.py """ if VERgray is None and verNObg3gray is None: return fg = figure() ax2 = fg.gca() # summed (as camera would see) if VERgray is not None: z = VERgray.alt_km Ek = VERgray.energy_ev.values # ax1.semilogx(VERgra...
energies ax = figure().gca() for e in Ek: ax.semilogx(VERgray.loc[:, e], z, marker='', label='{:.0f} eV'.format(e)) ax.set_title('filtered VER/flux') ax.set_xlabel('VER/flux') ax.set_ylabel('altitude [km]') ax.legend(loc='best', fontsize=8) ax.set_xlim((1e-5, 1e5)) ax.grid(True) if verNObg3gray is not None: ax1 = figur...
def deriv(f,c,dx=0.0001): """ deriv(f,c,dx) --> float Returns f'(x), computed as a symmetric difference quotient. """ return (f(c+dx)-f(c-dx))/(2*dx)
def newton(f,c,tol=0.0001,restrict=None): """ newton(f,c) --> float Returns the x closest to c such that f(x) = 0 """ #print(c) if restrict: lo,hi = restrict if c < lo or c > hi: print(c) c = random*(hi-lo)+lo if fuzzyequals(f(c),0,tol): return c else: try: return newton(f,c-f(c)/deriv(f,c,tol),tol,restrict) except: re...
def integrate_box(self,low,high,forcequad=False,**kwargs): """Integrates over a box. Optionally force quad integration, even for non-adaptive. If adaptive mode is not being used, this will just call the `scipy.stats.gaussian_kde` method `integrate_box_1d`. Else, by default, it will call `scipy.integrate.quad`. If the `...
def validate_context(self): """ Make sure there are no duplicate context objects or we might end up with switched data Converting the tuple to a set gets rid of the eventual duplicate objects, comparing the length of the original tuple and set tells us if we have duplicates in the tuple or not """ if self.context and l...
def get_instance_of(self, model_cls): """ Search the data to find a instance of a model specified in the template """ for obj in self.data.values(): if isinstance(obj, model_cls): return obj LOGGER.error('Context Not Found') raise Exception('Context Not Found')
def get_context(self): """ Create a dict with the context data context is not required, but if it is defined it should be a tuple """ if not self.context: return else: assert isinstance(self.context, tuple), 'Expected a Tuple not {0}'.format(type(self.context)) for model in self.context: model_cls = utils.get_model_cla...
def get_context_data(self): """ Context Data is equal to context + extra_context Merge the dicts context_data and extra_context and update state """ self.get_context() self.context_data.update(self.get_extra_context()) return self.context_data
def send(self, to, language=None, **data): """ This is the method to be called """ self.data = data self.get_context_data() if app_settings['SEND_EMAILS']: try: if language: mail.send(to, template=self.template, context=self.context_data, language=language) else: mail.send(to, template=self.template, context=self.conte...
def params(self): """Parameters used in the url of the API call and for authentication. :return: parameters used in the url. :rtype: dict """ params = {} params["access_token"] = self.access_token params["account_id"] = self.account_id return params
def data(self): """Parameters passed to the API containing the details to create a new alert. :return: parameters to create new alert. :rtype: dict """ data = {} data["name"] = self.name data["query"] = self.queryd data["languages"] = self.languages data["countries"] = self.countries if self.countries else "" data["sou...
def params(self): """Parameters used in the url of the API call and for authentication. :return: parameters used in the url. :rtype: dict """ params = {} params["access_token"] = self.access_token params["account_id"] = self.account_id params["alert_id"] = self.alert_id if self.since_id: params["since_id"] = self.since...
if self.source else "" params["countries"] = self.countries if self.countries else "" params["include_children"] = self.include_children if self.include_children else "" params["sort"] = self.sort if self.sort else "" params["languages"] = self.languages if self.languages else "" params["timezone"] = self.timezone if s...
def params(self): """Parameters used in the url of the API call and for authentication. :return: parameters used in the url. :rtype: dict """ params = {} params["access_token"] = self.access_token params["account_id"] = self.account_id params["alert_id"] = self.alert_id params["mention_id"] = self.mention_id params["be...
def url(self): """The concatenation of the `base_url` and `end_url` that make up the resultant url. :return: the `base_url` and the `end_url`. :rtype: str """ end_url = ("/accounts/{account_id}/alerts/{alert_id}/mentions/" "{mention_id}/children?") def without_keys(d, keys): return {x: d[x] for x in d if x not in keys}...
def data(self): """Parameters passed to the API containing the details to update a alert. :return: parameters to create new alert. :rtype: dict """ data = {} data["favorite"] = self.favorite if self.favorite else "" data["trashed"] = self.trashed if self.trashed else "" data["read"] = self.read if self.read else "" dat...
def call(command, collect_missing=False, silent=True): r"""Calls a task, as if it were called from the command line. Args: command (str): A route followed by params (as if it were entered in the shell). collect_missing (bool): Collects any missing argument for the command through the shell. Defaults to False. Returns: ...
def add(TargetGroup, NewMember, Config=None, Args=None): r"""Adds members to an existing group. Args: TargetGroup (Group): The target group for the addition. NewMember (Group / Task): The member to be added. Config (dict): The config for the member. Args (OrderedDict): ArgConfig for the NewMember, if it's a task (optio...
def do_check_pep8(files, status): """ Run the python pep8 tool against the filst of supplied files. Append any linting errors to the returned status list Args: files (str): list of files to run pep8 against status (list): list of pre-receive check failures to eventually print to the user Returns: status list of current...
def do_check(func, files, status): """ Generic do_check helper method Args: func (function): Specific function to call files (list): list of files to run against status (list): list of pre-receive check failures to eventually print to the user Returns: status list of current pre-redeive check failures. Might be an empt...
def check_for_empty_defaults(status): """ Method to check for empty roles structure. When a role is created using ansible-galaxy it creates a default scaffolding structure. Best practice dictates that if any of these are not used then they should be removed. For example a bare main.yml with the following string is crea...
" remove directory".format(dirpath)) if dirpath in dirs_to_check: try: joined_filename = os.path.join(dirpath, 'main.yml') with open(joined_filename, 'r') as f: # try to match: # --- # (tasks|vars|defaults) file for myrole # if re.match(r'^---\n# \S+ file for \S+\n$', f.read()): status.append("Empty file, please remove...
def from_inline(cls: Type[RevocationType], version: int, currency: str, inline: str) -> RevocationType: """ Return Revocation document instance from inline string Only self.pubkey is populated. You must populate self.identity with an Identity instance to use raw/sign/signed_raw methods :param version: Version number :p...
def from_signed_raw(cls: Type[RevocationType], signed_raw: str) -> RevocationType: """ Return Revocation document instance from a signed raw string :param signed_raw: raw document file in duniter format :return: """ lines = signed_raw.splitlines(True) n = 0 version = int(Revocation.parse_field("Version", lines[n])) n +...
def extract_self_cert(signed_raw: str) -> Identity: """ Return self-certified Identity instance from the signed raw Revocation document :param signed_raw: Signed raw document string :return: """ lines = signed_raw.splitlines(True) n = 0 version = int(Revocation.parse_field("Version", lines[n])) n += 1 Revocation.parse_...
def raw(self) -> str: """ Return Revocation raw document string :return: """ if not isinstance(self.identity, Identity): raise MalformedDocumentError("Can not return full revocation document created from inline") return """Version: {version} Type: Revocation Currency: {currency} Issuer: {pubkey} IdtyUniqueID: {uid} Idt...
def sign(self, keys: list) -> None: """ Sign the current document. Warning : current signatures will be replaced with the new ones. :param keys: List of libnacl key instances :return: """ if not isinstance(self.identity, Identity): raise MalformedDocumentError("Can not return full revocation document created from inlin...
def signed_raw(self) -> str: """ Return Revocation signed raw document string :return: """ if not isinstance(self.identity, Identity): raise MalformedDocumentError("Can not return full revocation document created from inline") raw = self.raw() signed = "\n".join(self.signatures) signed_raw = raw + signed + "\n" return ...
def clean_text(text): """ Retrieve clean text without markdown sintax or other things. """ if text: text = html2text.html2text(clean_markdown(text)) return re.sub(r'\s+', ' ', text).strip()
def clean_markdown(text): """ Parse markdown sintaxt to html. """ result = text if isinstance(text, str): result = ''.join( BeautifulSoup(markdown(text), 'lxml').findAll(text=True)) return result
def select_regexp_char(char): """ Select correct regex depending the char """ regexp = '{}'.format(char) if not isinstance(char, str) and not isinstance(char, int): regexp = '' if isinstance(char, str) and not char.isalpha() and not char.isdigit(): regexp = r"\{}".format(char) return regexp
def exclude_chars(text, exclusion=None): """ Clean text string of simbols in exclusion list. """ exclusion = [] if exclusion is None else exclusion regexp = r"|".join([select_regexp_char(x) for x in exclusion]) or r'' return re.sub(regexp, '', text)
def strip_accents(text): """ Strip agents from a string. """ normalized_str = unicodedata.normalize('NFD', text) return ''.join([ c for c in normalized_str if unicodedata.category(c) != 'Mn'])
def normalizer(text, exclusion=OPERATIONS_EXCLUSION, lower=True, separate_char='-', **kwargs): """ Clean text string of simbols only alphanumeric chars. """ clean_str = re.sub(r'[^\w{}]'.format( "".join(exclusion)), separate_char, text.strip()) or '' clean_lowerbar = clean_str_without_accents = strip_accents(clean_str)...
def normalize_dict(dictionary, **kwargs): """ Given an dict, normalize all of their keys using normalize function. """ result = {} if isinstance(dictionary, dict): keys = list(dictionary.keys()) for key in keys: result[normalizer(key, **kwargs)] = normalize_dict(dictionary.get(key), **kwargs) else: result = dictionary ...
def pluralize(data_type): """ adds s to the data type or the correct english plural form """ known = { u"address": u"addresses", u"company": u"companies" } if data_type in known.keys(): return known[data_type] else: return u"%ss" % data_type
def remove_properties_containing_None(properties_dict): """ removes keys from a dict those values == None json schema validation might fail if they are set and the type or format of the property does not match """ # remove empty properties - as validations may fail new_dict = dict() for key in properties_dict.keys(): v...
def dict_to_object(d): """Recursively converts a dict to an object""" top = type('CreateSendModel', (object,), d) seqs = tuple, list, set, frozenset for i, j in d.items(): if isinstance(j, dict): setattr(top, i, dict_to_object(j)) elif isinstance(j, seqs): setattr(top, i, type(j)(dict_to_object(sj) if isinstance(sj, di...
def veq_samples(R_dist,Prot_dist,N=1e4,alpha=0.23,l0=20,sigl=20): """Source for diff rot """ ls = stats.norm(l0,sigl).rvs(N) Prots = Prot_dist.rvs(N) Prots *= diff_Prot_factor(ls,alpha) return R_dist.rvs(N)*2*np.pi*RSUN/(Prots*DAY)/1e5
def fveq(z,R,dR,P,dP): """z=veq in km/s. """ R *= 2*pi*RSUN dR *= 2*pi*RSUN P *= DAY dP *= DAY exp1 = -P**2/(2*dP**2) - R**2/(2*dR**2) exp2 = (dR**2*P + dP**2*R*(z*1e5))**2/(2*dP**2*dR**2*(dR**2 + dP**2*(z*1e5)**2)) nonexp_term = 2*dP*dR*np.sqrt(dR**2 + dP**2*(z*1e5)**2) return 1e5/(4*pi*(dR**2 + dP**2*(z*1e5)**2)**(3/...
def cleanup(): """Clean up the installation directory.""" lib_dir = os.path.join(os.environ['CONTAINER_DIR'], '_lib') if os.path.exists(lib_dir): shutil.rmtree(lib_dir) os.mkdir(lib_dir)
def get_or_create_project_venv(): """ Create a project-level virtualenv (if it does not already exist). :return: ``VirtualEnv`` object """ venv_dir = get_project_venv_dir() if os.path.exists(venv_dir): return VirtualEnv(venv_dir) else: return create_project_venv()
def create_project_venv(): """ Create a project-level virtualenv. :raises: if virtualenv exists already :return: ``VirtualEnv`` object """ print('... creating project-level virtualenv') venv_dir = get_project_venv_dir() if os.path.exists(venv_dir): raise Exception('ERROR: virtualenv already exists!') use_venv_module = ...
def fetch_pool(repo_url, branch='master', reuse_existing=False): """Fetch a git repository from ``repo_url`` and returns a ``FeaturePool`` object.""" repo_name = get_repo_name(repo_url) lib_dir = get_lib_dir() pool_dir = get_pool_dir(repo_name) print('... fetching %s ' % repo_name) if os.path.exists(pool_dir): if not r...
def noglobals(fn): """ decorator for functions that dont get access to globals """ return type(fn)( getattr(fn, 'func_code', getattr(fn, '__code__')), {'__builtins__': builtins}, getattr(fn, 'func_name', getattr(fn, '__name__')), getattr(fn, 'func_defaults', getattr(fn, '__defaults__')), getattr(fn, 'func_closure', get...
def exclude_values(values, args): """ Exclude data with specific value. ============= ============= ======================================= Parameter Type Description ============= ============= ======================================= values list values where exclude elements args list or dict elements to exclude =====...
def get_element(source, path, separator=r'[/.]'): """ Given a dict and path '/' or '.' separated. Digs into de dict to retrieve the specified element. Args: source (dict): set of nested objects in which the data will be searched path (string): '/' or '.' string with attribute names """ return _get_element_by_names(sour...
def _get_element_by_names(source, names): """ Given a dict and path '/' or '.' separated. Digs into de dict to retrieve the specified element. Args: source (dict): set of nested objects in which the data will be searched path (list): list of attribute names """ if source is None: return source else: if names: head, *re...
def add_element(source, path, value, separator=r'[/.]', **kwargs): """ Add element into a list or dict easily using a path. ============= ============= ======================================= Parameter Type Description ============= ============= ======================================= source list or dict element where...
def _add_element_by_names(src, names, value, override=False, digit=True): """ Internal method recursive to Add element into a list or dict easily using a path. ============= ============= ======================================= Parameter Type Description ============= ============= =====================================...
src :( elif isinstance(src, dict): if head not in src: src[head] = [""] * (int(rest[0]) + 1) if rest and force_list(digit)[0] and rest[0].isdigit() else {} # more heads in rest if rest: # Head find but isn't a dict or list to navigate for it. if not isinstance(src[head], (dict, list)): # only could be str for dict or i...
list) and override: src[head] = {} _add_element_by_names(src[head], rest, value, override=override, digit=digit) # it's final head else: if not override: if isinstance(src, list) and isinstance(head, int): if src[head] == '': src[head] = value else: src.append(value) elif isinstance(src[head], list): src[head].append(v...
def format_dict(dic, format_list, separator=',', default_value=str): """ Format dict to string passing a list of keys as order Args: lista: List with elements to clean duplicates. """ dic = collections.defaultdict(default_value, dic) str_format = separator.join(["{" + "{}".format(head) + "}" for head in format_list]) r...
def force_list(element): """ Given an element or a list, concatenates every element and clean it to create a full text """ if element is None: return [] if isinstance(element, (collections.Iterator, list)): return element return [element]
def chunks(lista, size): """Yield successive n-sized chunks from l.""" if not isinstance(lista, list): logger.error('Erron in chunks, arg introduced is not a list.', lista=lista) return lista for i in range(0, len(lista), size): yield lista[i:i + size]
def flatten(data, parent_key='', sep='_'): """ Transform dictionary multilevel values to one level dict, concatenating the keys with sep between them. """ items = [] if isinstance(data, list): logger.debug('Flattening list {}'.format(data)) list_keys = [str(i) for i in range(0, len(data))] items.extend( flatten(dict(zi...
def nested_dict_to_list(path, dic, exclusion=None): """ Transform nested dict to list """ result = [] exclusion = ['__self'] if exclusion is None else exclusion for key, value in dic.items(): if not any([exclude in key for exclude in exclusion]): if isinstance(value, dict): aux = path + key + "/" result.extend(nested_d...
def find_value_in_object(attr, obj): """Return values for any key coincidence with attr in obj or any other nested dict. """ # Carry on inspecting inside the list or tuple if isinstance(obj, (collections.Iterator, list)): for item in obj: yield from find_value_in_object(attr, item) # Final object (dict or entity) inspe...
def remove_list_duplicates(lista, unique=False): """ Remove duplicated elements in a list. Args: lista: List with elements to clean duplicates. """ result = [] allready = [] for elem in lista: if elem not in result: result.append(elem) else: allready.append(elem) if unique: for elem in allready: result = list(filter((e...
def dict2orderedlist(dic, order_list, default='', **kwargs): """ Return a list with dict values ordered by a list of key passed in args. """ result = [] for key_order in order_list: value = get_element(dic, key_order, **kwargs) result.append(value if value is not None else default) return result
def get_dimension(data): """ Get dimension of the data passed by argument independently if it's an arrays or dictionaries """ result = [0, 0] if isinstance(data, list): result = get_dimension_array(data) elif isinstance(data, dict): result = get_dimension_dict(data) return result
def get_dimension_array(array): """ Get dimension of an array getting the number of rows and the max num of columns. """ if all(isinstance(el, list) for el in array): result = [len(array), len(max([x for x in array], key=len,))] # elif array and isinstance(array, list): else: result = [len(array), 1] return result
def get_ldict_keys(ldict, flatten_keys=False, **kwargs): """ Get first level keys from a list of dicts """ result = [] for ddict in ldict: if isinstance(ddict, dict): if flatten_keys: ddict = flatten(ddict, **kwargs) result.extend(ddict.keys()) return list(set(result))
def get_alldictkeys(ddict, parent=None): """ Get all keys in a dict """ parent = [] if parent is None else parent if not isinstance(ddict, dict): return [tuple(parent)] return reduce( list.__add__, [get_alldictkeys(v, parent + [k]) for k, v in ddict.items()], [])
def clean_dictkeys(ddict, exclusions=None): """ Exclude chars in dict keys and return a clean dictionary. """ exclusions = [] if exclusions is None else exclusions if not isinstance(ddict, dict): return {} for key in list(ddict.keys()): if [incl for incl in exclusions if incl in key]: data = ddict.pop(key) clean_key = ...
def authenticate(previous_token = None): """ Authenticate the client to the server """ # if we already have a session token, try to authenticate with it if previous_token != None: headers = server_connection.request("authenticate", { 'session_token' : previous_token, 'repository' : config['repository']})[1] # Only care...
def find_local_changes(): """ Find things that have changed since the last run, applying ignore filters """ manifest = data_store.read_local_manifest() old_state = manifest['files'] current_state = get_file_list(config['data_dir']) current_state = [fle for fle in current_state if not next((True for flter in config['ign...
def update(session_token, testing = False): """ Compare changes on the client to changes on the server and update local files which have changed on the server. """ conflict_comparison_file_dest = cpjoin(config['data_dir'], '.shttpfs', 'conflict_files') conflict_resolution_path = cpjoin(config['data_dir'], '.shttpfs', '...
else: raise SystemExit('Server error') result = json.loads(req_result) changes = result['sorted_changes'] # Are there any changes? if all(v == [] for k,v in changes.iteritems()): print 'Nothing to update' return # Pull and delete from remote to local if changes['client_pull_files'] != []: # Filter out pull ignore files...